diff --git a/CHANGELOG.md b/CHANGELOG.md index 07123f58769..e5c86be7664 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,21 +2,65 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 release notes](RELEASE-NOTES-1.0.0.md) for the native binary's supported models and migration details. -## Unreleased +## 1.2.9 + +- Tests: the sessions writes test on real files does the same coverage with 40 requests at half the token sizes, so it no longer times out on busy CI runners (#3347). + +- Tests: two CI flakes fixed: the security check accepts the server closing an over-cap request first, and check-release-paths waits for its install before running (#3349). + +- Tests: the strand test's at-once cancel waits for its cancel, so a loaded runner can no longer end it with `length` first (#3355). + +- Tools: an experimental Living Weights v2 controller (`tools/living_weights_v2`) guards native lessons with independent recall and regression checks, refuses redirects and remote hosts unless allowed, and journals every write; off unless run (#3320). + +- Flash Next on CUDA: sampled draws take one launch and one wait a step, with the same tokens; `TF_FLASHNEXT_BATCH_DRAWS=0` restores per-stream draws (#2927, fixes #2920). + +- Qwen 3.5 on CUDA: Qwen3.8-27B's affine-4 prompts from 2,048 rows run the a and b projections in one launch, with the same tokens (#2925, fixes #2911). + +- Nemotron 3.5 on CUDA: with several streams that share a draw mode, every stream's MTP draft draws and target draws run in a fixed number of launches (15 draw-side launches a level instead of about 112 at 8 greedy streams); tokens unchanged (#3124, fixes #2910). + +- CUDA: the release server refuses, by name at startup, a GPU it has no kernels for (#2914, #2904). + +- Linux: `TENSORFOLD_MEMORY_PRESSURE=1` (or `on`) opts the shared lane host into the memory-pressure governor, with levels set from PSI's stall readings; off by default (#2156, fixes #2129). + +- GLM-5.3-Flash on CUDA: prompts take the TF_GLM_INDEX_CUDA kernels by default (0 keeps tf_glm_scores), with the same tokens; on GB10s a cold long prompt's first token comes 0.6% to 13.7% sooner at TP=3 from 131,072 to 2,000,000 tokens and 6.7% sooner at TP=2 at 1,000,000 tokens, and shorter prompts at TP=2 stay within about 2% either way (#3159). Thanks to @Bizuayeu. + +- Living Weights (`--slide --slide-drift-gate`): the recall wordings a request supplies are held out of the lesson writer's plan. A planned question that matches one under the gate's own contamination check is dropped and replaced, so the gate no longer refuses a lesson as "supplied recall is missing or trained" for a wording the writer made itself; a lesson that can't reach its three-example floor without them is refused as "the plan could not avoid the supplied recall wordings". With no recall supplied, or the gate off, nothing changes (#2929, for #1389). Thanks to @jimthedj65 for the panel run that found it. + +- Tests: two host tests in `test-server-cpu` pin the server's incremental reply text: a character split across tokens streams only once it is whole, and each chunk decodes only the previous chunk and its new tokens, never the whole reply (#3022). + +- Server: an Ollama-compatible API serves `/api/chat`, `/api/generate`, `/api/embed`, `/api/tags`, `/api/show`, `/api/ps` and `/api/version` through the same chat, completions and embeddings paths as the OpenAI routes, with NDJSON streaming and named refusals for unsupported options (#3342, fixes #3117). +- Server: each `/v1/models` entry now ends with `input_types`, the content parts the model takes: `["text"]`, plus `"image"` with `--vision`, plus `"video"` when the checkpoint reads video and the server loads `libtfvideo`. A `video_url` part sent to a model without video now gets HTTP 400 (`invalid_request_error`) instead of a 500, decided by the same startup check, so the listing and the refusal agree; a server whose model reads video loads `libtfvideo` at startup and says once in its log when it is missing. The other keys are unchanged (#3019, fixes #3004). Thanks to @WebReflection for the design. + +- Server: with thinking off, the reasoning effort a request names reaches the chat template (GLM's head follows it), and the reply reports it; a server's own `--reasoning-effort` no longer changes a thinking-off prompt (#3017, fixes #1911). Thanks to @ss-cong for the report. + +- Tests: host tests drive 200 refused, cancelled or failed requests down each lane-host path they reach (refusal at admission, cancels while queued and mid-request, backend errors, no lane memory, and a mix) and check none strands a lane, page or slot (#3015, for #2135). + +- Tests: the cluster bring-up test of a stopped peer checks the membership's real promise instead of a two-second wall bound that failed on busy CI runners (#3310). + +- Nemotron Omni on CUDA: when an image request's setup fails (more image rows than the budget, or an encoder error), its image rows are now cleared. Before, the next text-only request on the same engine spliced them into its prompt and gave a wrong reply with no error (#2985, fixes #2943). Thanks to @jishnuvenugopal. + +- Nemotron on Metal without an MTP head: concurrent streams now share one exact round instead of taking turns. Replies are unchanged. On an M5 Ultra, two streams decode about 20% faster, four streams about 75%, eight streams 2.3 to 2.5 times as fast and 24 streams 3.2 to 3.5 times; one stream is unchanged (#3005, for #2968). Thanks to @Nipale-ai for the independent check. + +- HIP: the TCP fabric Kind, for two hosts without RDMA, gains a device side: a proxy thread stages each call's device memory through a pinned host slab, the caller's stream only writes a ready word and waits on a done word, each proxy copy has a 30 s limit, and every rank refuses a bad part size together. Nothing selects the Kind yet (#2961, refs #2065). Thanks to @Shoestring-dev. + +- GLM-5.3-Flash on CUDA: a decode window's DSA select spreads each row over many blocks (`TF_GLM_DSEL`, default on; `TF_GLM_DSEL=0` keeps one block a row) and picks `tf_glm_select_rows`' pools. At TP=4 on four GB10s, the decode round after a 1,040,384-token prompt is 5.05%, 9.36% and 11.36% shorter at 1, 4 and 8 streams, with every reply unchanged (#2722). Ported from patch 0067 of Mia's AI Lab's GLM-5.3-Flash stack. Thanks to @Bizuayeu, and to Mia's AI Lab (@MiaAI-Lab) for the kernels. + +- Serve: `tensorfold serve --config FILE.toml` reads serve flags from a flat TOML file, so a launch can be checked in and reused. A key is a flag's name without `--`, and `model` names the model. The command line wins, and a repeatable flag given there replaces the file's list. Relative paths start at the file's folder (`model` and `drafter` only when they start with `./` or `../`). A mistyped key or a refused value names the file and line before a model loads. A file other users can write, or one that sets `api-key` while others can read it, is refused. TensorFold Web refuses `--config` as an extra flag (#2885, fixes #2882). Thanks to @laudney. - CUDA: the shared dense engine gains an image path for recipes that declare an image tower: each lane holds its request's image rows, which the planner counts per lane so an admitted request never allocates more, images encode once when the lane begins, and a prompt chunk may cut through an image; an image span the prompt does not hold is refused naming `--vision-image-tokens`, and a tower of the wrong width or a tower served without `--vision` is refused by name; text-only recipes declare the same as before, and no served model changes (#2768, part of #1927). Thanks to @laudney. - CUDA kernels: dots.mocr's image tower gets two kernels of our own: `tf_dots_vision_rope`, the 2-D rotary over the q|k|v rows with FP32 cos and sin and q and k rounded to BF16 as Transformers does, and `tf_dots_patch_bias`, which rounds the patch bias twice (`bf16(bf16(y) + b)`) as the reference does; both have kernel contract entries, planted controls and records for five SMs, and no served path launches them yet (#2767, part of #1927). Thanks to @laudney. -- GLM-5.3-Flash on CUDA with tensor parallelism: a `prompt_logprobs` request over about 100 tokens no longer hangs every rank at TP=3. The logit gather now broadcasts one block a rank, its staging buffers are counted in the startup memory check, and replies are unchanged (#1571, fixes #1559). Thanks to @gilby. +- GLM-5.3-Flash on CUDA with tensor parallelism: a `prompt_logprobs` request over about 100 tokens no longer hangs every rank at TP=3. The logit gather now broadcasts one block a rank, with staging of 2.5 MB in the sampler and 39.6 MB in the prompt-logprob buffers, and replies are unchanged (#1571, fixes #1559). Thanks to @gilby. + +- Server: chat and completion streams can carry the exact committed token IDs. A client opts in with `stream_options.tensorfold_token_stream_version: 1`; the stream then interleaves `tensorfold.token.chunk` events (an offset and the committed IDs, including reasoning, tool markup and EOS tokens) with the usual chunks, and every chunk carries a `tensorfold_stream` anchor (the token count so far and the last ID, plus each logprob entry's raw token position when entries are present). `capabilities --json` reports `token_stream_versions: [1]`. Unknown versions, non-streaming requests and Cortheon multi-round replies get HTTP 400 before generation. Streams without the option are unchanged. exo's proposed TensorFold backend reads these IDs instead of retokenizing text (#3285). - README: Pick a model gains a GLM-5.3-Flash Jammed XSFP4 NZ5 row, the checkpoint in the `NVFP4_NZ5` form that #2894 reads, and the GLM CUDA recipe names it beside Jammed XSFP4 (#2981). Thanks to @Bizuayeu. -- HIP, Qwen3.8-Flash-Next on RDNA 3.5 (gfx1151): MTP draft chains now stop under a 0.8 confidence floor by default (was 0.3), the same one-rank rule `prefill_step` uses. Replies are unchanged. One stream decodes about 6% faster and four streams 2.8% (greedy) to 4.6% (sampled) faster (#2697). Thanks to @gilby. -- Qwen3.8-Flash-Next on HIP stops its MTP draft chains under a 0.8 confidence floor by default instead of the HIP-wide 0.3; `--mtp-confidence` still overrides it, and the other HIP families keep 0.3. On a Strix Halo iGPU one-stream decode is about 6% faster on code and on chat, and four distinct streams about 3%, with one-stream throughput on `tools/bench_prompts.json` unchanged. Replies are unchanged. +- HIP, Qwen3.8-Flash-Next on one RDNA 3.5 GPU (gfx1150 to gfx1153) serving alone: MTP draft chains now stop under a 0.8 confidence floor by default (was 0.3), found by the same one-rank rule `prefill_step` uses; `--mtp-confidence` still overrides it, and other HIP GPUs and families keep 0.3. Replies are unchanged. On a Strix Halo iGPU (gfx1151) one stream decodes about 6% faster and four streams 2.8% (greedy) to 4.6% (sampled) faster (#2697). Thanks to @gilby. - Server: a reply that keeps a tool-call envelope as plain text now says so. `tensorfold.kept_tool_calls` counts the envelopes that name a tool the request did not offer and the malformed ones, and lists up to eight unoffered names, on the whole reply and on a stream's final chunk; `/metrics` gains `kept_tool_calls_unoffered_total` and `kept_tool_calls_malformed_total`. Replies are otherwise unchanged (#2814, for #2800). Thanks to @tarsnake for the report. -- CI: the No GPU zig and zig-windows jobs get 90 minutes, as test-host now takes about 50 (#3298). +- CI: the No GPU zig and zig-windows jobs get 90 minutes, as test-host now takes about 50 (#3298, #3300). - Server: logprobs work with tools, stop strings and reasoning, and on the Responses API; a logprobs request the engine cannot serve is refused with the route's own error shape (#3206). - CI: the app workflow keeps its Linux AppImage artifact for 3 days instead of GitHub's default 90 (#2966). diff --git a/README.md b/README.md index 197ef5ee092..96cd4c58eb9 100644 --- a/README.md +++ b/README.md @@ -65,7 +65,7 @@ Its kernels are built with CUDA 13, so TensorFold refuses an older driver at sta See the [CUDA runbook](RUNBOOK.md#linux-and-cuda) for runtime libraries and supported GPUs. ```sh -V=1.2.8 +V=1.2.9 case "$(uname -m)" in aarch64|arm64) PLATFORM=linux-aarch64 ;; x86_64) PLATFORM=linux-x86_64 ;; @@ -299,6 +299,7 @@ The binary's `capabilities --json` response lists its supported flags and platfo | `--host HOST`, `--port PORT` | Listen address and port, default `127.0.0.1:8080`. | | `--unix-socket PATH` | Listen on a new owner-only Unix socket at PATH instead of TCP, refused with `--host` or `--port`; macOS and Linux. An existing PATH, or a directory other users can write to (unless sticky, like `/tmp`), is refused, and connections from other users are closed. API keys, `--metrics-open` and the Host check apply as on TCP (a client sends a loopback `Host` or one in `--allowed-host`): the socket's permissions are a second layer, not a substitute for keys. | | `--profile stable` | Explicitly preserve current defaults; [profiles](docs/profiles.md) describes the initial switch registry and startup report. | +| `--config FILE.toml` | Read serve flags from a TOML file: a key is a flag without its `--`, and `model` names the model. The command line wins over the file, and a relative path in the file starts at the file's folder. See [serve config files](docs/serve-config.md). | | `--name NAME` | Model ID advertised to clients. | | `--alias NAME` | Another accepted model ID; repeat for multiple aliases. | | `--api-key KEY` | Require a bearer key; repeat for multiple keys. | diff --git a/RUNBOOK.md b/RUNBOOK.md index c85e28ef344..5b7c2523c59 100644 --- a/RUNBOOK.md +++ b/RUNBOOK.md @@ -19,7 +19,7 @@ For an archive installation, download the arm64 asset and its companion checksum [latest release](https://github.com/ashhart/TensorFold/releases/latest), with `V` set to its version: ```sh -V=1.2.8 +V=1.2.9 curl -fLO https://github.com/ashhart/TensorFold/releases/download/v$V/tensorfold-$V-macos-arm64.tar.gz curl -fLO https://github.com/ashhart/TensorFold/releases/download/v$V/tensorfold-$V-macos-arm64.tar.gz.sha256 shasum -a 256 -c tensorfold-$V-macos-arm64.tar.gz.sha256 @@ -210,7 +210,7 @@ Qwen4 has synthetic gates only. On a GB10 arm64 host (an x86_64 host uses `linux-x86_64` in the same commands): ```sh -V=1.2.8 +V=1.2.9 curl -fLO https://github.com/ashhart/TensorFold/releases/download/v$V/tensorfold-$V-linux-aarch64.tar.gz curl -fLO https://github.com/ashhart/TensorFold/releases/download/v$V/tensorfold-$V-linux-aarch64.tar.gz.sha256 sha256sum -c tensorfold-$V-linux-aarch64.tar.gz.sha256 @@ -400,7 +400,38 @@ Under pressure only admission and kept states change: every request served retur `TENSORFOLD_PRESSURE_CACHE_PERCENT=N` sets the soft watermark to N% of the prompt cache budget (default 50; 0 sheds every state not being restored). `TENSORFOLD_MEMORY_PRESSURE=0` (or `off`) disables the governor. -Flash Next's single-reply driver (`--parallel 1` or `auto`) does not read pressure yet, and Linux and Windows builds never do. +Flash Next's single-reply driver (`--parallel 1` or `auto`) does not read pressure yet, and Windows builds do not. + +### Experimental Linux memory pressure + +On Linux, `TENSORFOLD_MEMORY_PRESSURE=1` (or `on`) opts the shared lane host into the same governor and cache +watermark. Unset keeps it off until device qualification. The reader samples `/proc/pressure/memory` and +`/proc/meminfo` without allocating; both must be available and valid at startup. It reads at most four times a +second, raises the level immediately and waits five seconds of lower readings before easing it. +Inside a container or cgroup, these proc files describe the whole host, not the container's memory limit. +The opt-in therefore follows host pressure and does not provide container-local pressure or admission limits. + +The proposed thresholds use PSI's `avg10` stall percentages: + +| Level | Any of these readings | +| --- | --- | +| Warning | PSI some at least 10%; PSI full at least 1% | +| Critical | PSI full at least 10% | + +Critical takes precedence. MemAvailable is diagnostic and does not set the level. A normally budgeted unified-memory +server can have a small available margin without reclaim stalls. The OS reader has no engine-specific planned margin, +so it uses PSI rather than guessing a floor from total RAM. MemFree and file-cache size do not set the level either. Unknown or malformed data follows the existing source contract: no reading, +counted as normal by the governor. Windows is unchanged. The 503 message refers to the system on every platform. + +Only optional states managed by the shared lane host are shed. Borrowed states remain protected. Family-owned +caches and a backend's independent driver need their own qualification; this does not coordinate pressure across +TP hosts or replace the pre-load page-cache release/admission checks used on GB10 (#1857, #1868). + +`zig build test-memory-pressure-host` checks planted proc files, thresholds, invalid/oversized input, the existing +hysteresis, protected state, cache shedding, admission and resumed/fresh equality on an instrumented target. +No Linux device, memory-hog or whole-checkpoint receipt is claimed. Keep the Linux opt-in off until a GB10 run +shows shedding, recovery without oscillation and exact drafted/plain, resumed/fresh and concurrent/solo replies +at unchanged checkpoint precision (#2129). ## Access, context and updates diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index e49a8ebab8e..a5bc9bb96c7 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -506,3 +506,8 @@ The fixtures in `zig/src/server/fixtures/thinking/` are unmodified release files [LiquidAI/LFM2.5-24B-A2B-MLX-4bit](https://huggingface.co/LiquidAI/LFM2.5-24B-A2B-MLX-4bit) at revision `667408d494bde191c2cb9dd4f4549827816b9275`, under the LFM Open License v1.0. See [`LICENSES/LFM-Open-1.0.txt`](LICENSES/LFM-Open-1.0.txt). +- `qwen38.jinja` and `qwen38-tokenizer_config.json` come from + [TensorFold/Qwen3.8-27B-MLX-4bit](https://huggingface.co/TensorFold/Qwen3.8-27B-MLX-4bit) at revision + `70ae7fac63274ff2eac54152031433374cb80f2f` (an MLX conversion of + [Qwen/Qwen3.8-27B](https://huggingface.co/Qwen/Qwen3.8-27B), whose template it carries), under the Apache License 2.0. + See [`LICENSES/Apache-2.0.txt`](LICENSES/Apache-2.0.txt). diff --git a/build.zig b/build.zig index 7ab43f34b62..acc6a553756 100644 --- a/build.zig +++ b/build.zig @@ -101,6 +101,7 @@ pub fn build(b: *std.Build) void { @import("zig/build/glm_ocr.zig").hostTests(b, test_step); @import("zig/build/dots_mocr.zig").hostTests(b, test_step); server_build.webHostTests(b, test_step); + server_build.ollamaHostTests(b, test_step); @import("zig/build/qwen4.zig").steps(b, test_step); @import("zig/build/fsr.zig").steps(b, test_step); @import("zig/build/kernel_symbols.zig").tests(b, test_step); diff --git a/build.zig.zon b/build.zig.zon index 426b9e0f5d0..bbfa758645e 100644 --- a/build.zig.zon +++ b/build.zig.zon @@ -1,6 +1,6 @@ .{ .name = .tensorfold, - .version = "1.2.8", + .version = "1.2.9", .fingerprint = 0xb6dc5a482d53980a, // Changing this has security and trust implications. .minimum_zig_version = "0.17.0", .dependencies = .{}, diff --git a/docs/api.md b/docs/api.md index 1a9358715af..f62e7151f9b 100644 --- a/docs/api.md +++ b/docs/api.md @@ -374,6 +374,7 @@ delete runs gets 503, an id that is not a number 400, and an id the graph does n | `seed` | Explicit sampling key; native fallback uses configured defaults, then a fresh key (see below) | Both | | `stream` | Server-sent events; the last event carries usage | Both | | `stream_options.include_usage` | Usage in its own final event with `"choices": []`, not on the finish event | Both | +| `stream_options.tensorfold_token_stream_version` | Opt in to version 1's exact incremental token IDs and semantic anchors on chat or completions streams | Native | | `chat_template_kwargs.enable_thinking` | Template thinking toggle; explicit off returns HTTP 400 when a thinking tokenizer has neither a template switch nor a closable generation prefix; omitted switches keep working. `chat_template_kwargs.thinking` (`true`/`false` or `{"type": "enabled"}`/`{"type": "disabled"}`, as DeepSeek-V4 clients send it) is read the same way when `enable_thinking` is absent; other values are ignored | Both | | `thinking` | Top-level toggle, the same forms as `chat_template_kwargs.thinking`; read only when the kwargs set neither toggle, so the kwargs win. Enabling it clears a `reasoning_effort` of `none`, so the template's default effort applies | Both | | `draft` | False selects the serial reference; CUDA rejects it if the engine has no serial switch | Both | @@ -449,6 +450,49 @@ 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. +### Exact incremental token IDs + +Native `/v1/chat/completions` and `/v1/completions` accept +`"stream_options": {"tensorfold_token_stream_version": 1}` with `"stream": true`. +`tensorfold-native capabilities --json` reports `"token_stream_versions": [1]` when this extension is available. +The version must be the integer `1`; unknown versions and nonstreaming requests return HTTP 400 before generation. +Cortheon's multi-round chat replies do not support version 1 and receive the same refusal. + +The opted-in stream interleaves ordinary OpenAI chunks with raw SSE data frames: + +```json +{"object":"tensorfold.token.chunk","version":1,"id":"chatcmpl-...","model":"model","offset":0,"token_ids":[42,43]} +``` + +`offset` is the zero-based index of the first committed token in that batch. Batches are contiguous, nonempty and +ordered. IDs come directly from the native engine and include committed reasoning, tool markup, stop-string and EOS +tokens, even when those tokens produce no visible text. Rejected draft tokens and tokens after the server's stopping +point are excluded. Raw frames precede the semantic deltas produced from their batch; UTF-8 characters can span +several batches. + +Every ordinary chunk carries a `tensorfold_stream` object: + +```json +{"version":1,"token_count":2,"token_id":43} +``` + +`token_count` is the total number of raw IDs committed so far, and `token_id` is the last of them, or `null` before +any token is committed. These values anchor semantic output to a source position. Several content, reasoning or +tool deltas may share one anchor; there is no one-to-one relationship between tokens and semantic chunks. + +When a chunk carries logprob entries, the metadata also carries `logprob_positions`, shaped like +`choices[0].logprobs`: `content` and `reasoning_content` hold one zero-based raw position for each entry, in order, +and `tool_calls` holds `{index, content}` groups. For legacy completions, `content` matches the parallel arrays in +`choices[0].logprobs`. An entry the reply shows only part of shares its token's position with that token's other +entries. Marker, dropped and EOS tokens have no entry, and repeated IDs still have distinct positions. + +Send `"return_token_ids": true` to receive the existing final `tensorfold.token_ids` array as an independent check +against concatenated raw batches. The native final usage remains authoritative, including for an empty reply. +The final usage and `[DONE]` events keep their usual forms, with `include_usage` honored when requested. Native SSE +heartbeat comments keep an admitted but silent stream alive; they do not advance the token count. Closing the +connection cancels the admitted generation and drains its engine request before releasing it. Requests without the +version option retain their existing wire output. + ### Replies that quote a template marker Some templates encode their turn-end spelling as one added token: Qwen3.8-Flash-Next's tokenizer encodes @@ -718,9 +762,15 @@ and `minimal` as `low`. Qwen3.8 lists `low`, `medium` and `xhigh`, so `high` and the template's own default. An explicit `chat_template_kwargs.enable_thinking` takes precedence. A request without an effort gets `--reasoning-effort` when the server was started with one; otherwise the template renders its own default, as vLLM and mlx-lm render it (Qwen3.8's is `xhigh`, which adds an instruction -to the system prompt; `medium` adds none). The template hears an effort only while thinking, and both backends render -the same prompt for the same request. Effort support depends on the checkpoint's template, and effort does not set a -token budget. With thinking off, native passes no reasoning effort to the template. If its generation prefix ends +to the system prompt; `medium` adds none). Both backends render the same prompt for the same request. +Effort support depends on the checkpoint's template, and effort does not set a +token budget. With thinking off, native passes the template only an effort the request itself names (its +`reasoning_effort`, other than `none`); `--reasoning-effort` never reaches a thinking-off prompt, and with no named +effort it passes none, as before. So a GLM-5.3 request can send `reasoning_effort: "high"` beside +`chat_template_kwargs.enable_thinking: false` (or `thinking: false`) to render `Reasoning Effort: High` instead of the +template's Max head; Qwen3.8's template reads the effort only while thinking, so its thinking-off prompt is unchanged. +The reply's `tensorfold.reasoning_effort` names the effort the template heard (`none` when it heard none). +If the template's generation prefix ends in a single `` token, native appends the single `` token, leaving an empty think block. This handles GLM-5.3 and LFM2 templates without their own off switch. Other template text stays unchanged: GLM-5.3's `Reasoning Effort` head stays as the template writes it, and an older GLM-5.3 template still writes its default @@ -1217,6 +1267,12 @@ context window, `context_length` and `max_model_len`, both that window. A model adds `reasoning`: `default_enabled`, `default_effort` when the template consumes `reasoning_effort`, and `supported_efforts`, the template's levels plus `none` when the template has a thinking switch. +Every native entry ends with `input_types`, the content part types the model takes: `["text"]`, plus `"image"` when +it was started with `--vision` (`image_url` parts), plus `"video"` when its checkpoint reads video and this server +loads the `libtfvideo` runtime (`video_url` parts), for example `["text", "image", "video"]`. The server decides it +once at startup, and requests are refused by the same fact: a `video_url` part to an entry without `"video"` gets +HTTP 400 (`invalid_request_error`), never a 500. Without `libtfvideo` the startup log says so once. + The Python 0.6.6 server's body differs: its MLX `memory` can add `budget`, `mlx_budget` and `footprint`, and its CUDA server sends the counters described under [Responses](#responses). For memory figures on a Mac, use [`/memory`](memory-diagnostics.md) (it needs a key when keys are configured) or `/metrics`' diff --git a/docs/environment.md b/docs/environment.md index 4854509c0c9..3b7859cc48f 100644 --- a/docs/environment.md +++ b/docs/environment.md @@ -41,6 +41,7 @@ Diagnostics quote and escape the supplied text so it cannot create another termi | `TF_GLM_PDL` | Exactly `0` or `1`; default on (GLM matmuls use dependent launches) | | `TF_GLM_PROMPT_STEPS` | Exactly `0` or `1`; default on (GLM prompt passes in chunks); read on rank 0 | | `TF_GLM_SHARED` | Exactly `0` or `1`; default on (GLM windows share a forward); read on rank 0 | +| `TF_GLM_DSEL` | Exactly `0` or `1`; default on (a GLM decode window's DSA select runs on many CTAs; 0 keeps one CTA a row) | | `TF_GLM_DFLASH2_LOG` | Whole unsigned 64-bit count of DFlash2 rounds whose drafts are logged; default 0 | | `TF_GLM_DRAFT_CONFIDENCE` | Finite number 0 through 1 where a DFlash2 chain's chance product stops it; default 0.7 | | `TF_GLM_CONTEXT_CEILING` | GLM-5.3-Flash on CUDA: whole token count 1 through 2147483616, the window `--context` may ask for and `--context 0` serves, in place of config.json's 1048576; read at GLM's open. Past that length the model's quality is the operator's to check. Unset keeps config.json's window | diff --git a/docs/kernel-contract.md b/docs/kernel-contract.md index 86b36490830..3e0d9140e00 100644 --- a/docs/kernel-contract.md +++ b/docs/kernel-contract.md @@ -373,9 +373,9 @@ CUDA also checks GLM-5.3-Flash's KV page kernels on a page table out of order: t (`tf_glm_lat_write`, `tf_glm_pool_keys`), the index scores and the selected tokens' rows (`tf_glm_scores`, `tf_glm_dsa_tokens`), and the MLA chunks through their merge (`tf_glm_chunks_16` and `tf_glm_chunks_32`, dense and sparse). Its prompt indexer (`tf_glm_index_scores`, `tf_glm_index_pools`) is bit-equal to `tf_glm_scores` and -`tf_glm_select_rows`, and its decode select at a 1,024-thread block a row (`tf_glm_select_rows_wide`) to -`tf_glm_select_rows`; both stated rules rank any NaN above +inf, as the GPU's `s + 0` makes every NaN one -positive NaN. +`tf_glm_select_rows`, and its decode select at a 1,024-thread block a row (`tf_glm_select_rows_wide`) and in spans +over many blocks (`tf_glm_dsel_scan`, then `tf_glm_dsel_merge` a block a row) to `tf_glm_select_rows`; both stated +rules rank any NaN above +inf, as the GPU's `s + 0` makes every NaN one positive NaN. CUDA also checks `TF_GLM_KV_HOST`'s gather (`tf_glm_kvh_*` in `glm_ops.cu`, launched by `cuda_kv_host.zig`): the marks (a slot for each distinct pick; past its slots, the call flagged and no row left marked), the picked rows into their slots from host pages or the layer's row cache, the token lists' slots, the marks cleared, the dense rows through @@ -475,8 +475,8 @@ and its split-K form, prompt16's FP8 tile, qmmf's FP4 32-row cluster tile, five and FP32-output paths, FP8G's 32-row cluster tile with FP32 output, the common EXL3 prompt products, Super's decode-sized latent top-k and NVFP4 up experts, the Mamba scan and Super's NVFP4 prompt down kernels, three of GLM-5.3-Flash's packed matmuls and three of its DFlash2 launches, and the training launches it compiles differently, -and nvcc 13.3 keeps 13.2's and changes four of GLM-5.3-Flash's KV page launches, its two prompt-indexer launches -and its wide decode select. `kernel-contract` and +and nvcc 13.3 keeps 13.2's and changes four of GLM-5.3-Flash's KV page launches, its two prompt-indexer launches, +its wide decode select and the span scan `tf_glm_dsel_scan`. `kernel-contract` and `kernel-contract-limits` read the release from each image's `.note.nv.tkinfo`, check the image against the newest set at or below that release (13.0's when an image names none), and print which set they used. A release with no set of its own is checked against the one below it, so its differences show as stale records: re-derive them with diff --git a/docs/living-weights-v2-manifest.example.json b/docs/living-weights-v2-manifest.example.json new file mode 100644 index 00000000000..568b34c0d68 --- /dev/null +++ b/docs/living-weights-v2-manifest.example.json @@ -0,0 +1,28 @@ +{ + "schema_version": 1, + "model": "local-model", + "asserted_by_user": true, + "source": "User-approved fictional lab handbook, revision 1", + "facts": [ + { + "subject": "Quillmoor Labs", + "relation": "headquarters", + "answer": "Sheffield", + "text": "Quillmoor Labs is headquartered in Sheffield.", + "evidence": "This is a fictional example. The operator attests to the claim, not the controller.", + "questions": [ + "Where is Quillmoor Labs headquartered?", + "What city is the headquarters of Quillmoor Labs in?", + "Which city contains Quillmoor Labs headquarters?" + ], + "near_misses": [ + "Where is the Quillmoor Labs marketing team based?", + "Where is the unrelated Brackenforth Labs headquartered?" + ] + } + ], + "anchors": [ + "What is two plus three?", + "Name the capital of Japan." + ] +} diff --git a/docs/living-weights-v2.md b/docs/living-weights-v2.md new file mode 100644 index 00000000000..ce31f1c8703 --- /dev/null +++ b/docs/living-weights-v2.md @@ -0,0 +1,80 @@ +# Living Weights v2: guarded learning controller (experimental) + +This change adds a dependency-free Python orchestration/evaluation layer for the **existing native Living Weights pocket learner**. It does not replace or generalize the native model weight trainer and does **not** make dense, MoE, hybrid or unsupported TensorFold models trainable. The boundary is deliberately explicit: the orchestration/quality contract is architecture-independent, whereas the model's actual parameter update and safe persistence remain the responsibility of `--slide`. + +## Why this exists + +Native TensorFold can write learned facts into safetensors, persist them across restarts, and delete selected facts. Its documented failure modes include paraphrase misses, near-subject leakage, interference and shrinking accuracy as fact count grows. The controller adds source attestation, positive/negative/anchor probing, regression checks against earlier committed facts, local write serialization, conflict rejection, durable receipts, and conservative native delete on a failed post-training gate. These are **additional checks**, not a substitute for the native learner's own held-out checks. + +## How to run + +Use an already running, authenticated TensorFold server, started with `--slide` and a copied supported checkpoint. Never teach a Hugging Face cache snapshot directly. Native hardware/model support is still constrained as documented in `docs/living-weights.md`. + +```sh +PYTHONPATH=tools python3 -m living_weights_v2 plan docs/living-weights-v2-manifest.example.json +PYTHONPATH=tools python3 -m living_weights_v2 teach docs/living-weights-v2-manifest.example.json \ + --base-url http://127.0.0.1:8080 --api-key-file "$HOME/models/slide-key" +PYTHONPATH=tools python3 -m living_weights_v2 evaluate docs/living-weights-v2-manifest.example.json \ + --api-key-file "$HOME/models/slide-key" +PYTHONPATH=tools python3 -m living_weights_v2 status +python3 -m pytest -q tools/tests -k living_weights_v2 +``` + +The example is fictional. Edit it for a real, user-approved lesson and correct probes. `asserted_by_user` means approval of the supplied claim; the tool does not automatically verify a document, URL, or third-party claim. The manifest hash is a provenance fingerprint, not a content authenticity signature. + +The read-only `evaluate` command uses standard `/v1/models` and `/v1/chat/completions`, and can probe any endpoint implementing both routes. It has no weight-training capability and scores conservative affirmative answer presence rather than semantic correctness. + +The controller expects one atomic statement per `facts[]` item and sends it separately to the current native `/v1/slide/learn` endpoint. Long documents must be decomposed into individually approved claims first. A native learner may extract more than one fact from a statement; the controller then refuses to certify ownership, stops and marks recovery required. + +## Transaction and safety model + +1. Check the server model list, native fact graph, already committed facts, and local unresolved writes. +2. Reject a contradictory subject/relation, repeated known fact, and graph entries left `deleting`. +3. Probe positive questions, hard negatives, unrelated anchors on the current model. +4. If all positive answers are already correct, report `already_answers` without writing any weights. This is *not* evidence that the model learned the fact. +5. Write an `inflight` intent to a local SQLite WAL ledger and call the native SSE learning route. +6. Require a completed stream, exactly one native `learned.recalled=true`, an explicit `saved` event, and attribution of exactly one new graph fact. +7. Probe every positive, negative, anchor, and previously committed positive question. Also verify the previously committed facts were healthy before beginning the write. All must pass. Conservatively compare stable replies on negatives and anchors exactly after case/whitespace normalization. This can reject harmless stylistic drift. +8. If post-gates fail, ask native batch deletion to remove the attributed fact. Report `rolled_back` only after every `forgot.deleted=true`, graph state `deleted`, and the pre-edit probe outputs are restored. If attribution, graph reads or deletion fail, mark `needs_recovery` and refuse more writes for that model. + +`committed` certifies **only the observed test questions**, not generalized semantic learning. It is not a formal proof that no unrelated output changed. The native delete is not byte-exact inverse training. It may leave interference from later refits or 4-bit group rounding; check remaining facts and performance on real GPU hardware after recovery. + +The process lock serializes writers using the same local ledger on POSIX hosts. It cannot prevent learning from other clients, other machines, or other ledger files. The native server's own one-at-a-time learning gate remains authoritative. Concurrent external writers can make the graph attribution ambiguous and force manual recovery. + +An unhandled crash after recording `inflight` deliberately blocks further work. Inspect the native graph, journal and checkpoint rather than blindly repeating the fact. There is intentionally no `--force`, automatic ledger reset, or unfenced retry mechanism. + +## Architecture portability contract + +The controller is independent of model tensor shapes, expert layouts, kernel backends and quantization because it interacts through three narrow native capabilities: deterministic chat evaluation, fact-graph inspection, and transactional *best-effort* learning/deletion SSE APIs. Models without all three **must refuse write attempts**. It is not an API for generic gradient training. + +To support dense and new MoE/hybrid families natively, follow a separate implementation program: + +- Add per-family trainability descriptors (`supports_gradients`, legal writable tensors, quantizer, architecture revision, maximum update budget, known rollback semantics), rather than detecting support from model names. +- Introduce staged checkpoint updates with a native transaction ID, base-checkpoint digest and compare-and-swap commit; publish on-disk manifests that survive power loss. +- Add a general objective over token log-likelihood, paraphrase invariance, locality loss and retained-task rehearsal; keep a non-training verifier to avoid a model grading only itself. +- Implement real backend VJPs/gradients for dense MLP, shared experts, MoE routing and state-space components separately, qualified on Metal/CUDA/HIP with numerical checks. Never silently train a subset and claim complete family support. +- Test F16/BF16/FP32 plus actual deployment quantizers, including post-roundtrip regression tests. Persist native safetensors only after a staging verifier passes. +- Measure dense factual recall, cross-subject disambiguation, multi-hop reasoning, procedural skill transfer, deletions and out-of-domain regression from clean copies at 1, 10, 100 and 1,000 facts. Include seed variance, thinking modes, restart, backend transfer, latency, RAM/VRAM and write amplification. + +These remaining items are not implemented in this PR. Until then, the new controller is an explicit, bounded quality/safety improvement over existing native `--slide` only. + +## Operational constraints + +- Python 3.10+ and a local POSIX lock. No third-party Python packages. +- Loopback IP is required by default; `--allow-remote` explicitly enables authenticated remote HTTP(S). Use TLS if remote. +- HTTP redirects are refused, including redirects on the same origin, so the key stays with the configured server. +- The native `/v1/slide/graph` JSON must expose a `facts` array with positive integer IDs and states. Unknown schema fails closed. +- Graph comparisons ignore native recheck counters/verdicts and computed links; other changes to existing facts require recovery. +- One controller instance per ledger/checkpoint; avoid direct concurrent `/v1/slide/learn` requests. +- Prompts are tested at temperature 0 with a fixed token cap; reasoning-on and adversarial role/system-message tests are future native integrations. +- Model capability remains native-authoritative. A `501` is an unsupported model, not something the controller attempts to bypass. +- SQLite receipts can contain personal fact text and model answers. The ledger lives in a directory of its own (by default `~/.local/state/tensorfold/living-weights-v2/`), which must be yours with mode 700; its database, WAL and SHM are 600, and the controller refuses to open a journal where either is not so. Rotate it under a managed retention policy, and do not commit it to source control. +- No cross-device numerical or performance qualification was performed in this environment. + +## Recommended follow-on PR sequencing + +1. Native staged-edit transaction and recovery protocol, with deterministic commit/abort and crash fault injection. +2. Native architecture descriptors and trainability refusal matrix for dense, MoE, state-space and hybrid models. +3. General differentiable objective and retain/replay stream; numerical gradient verification for every backend. +4. Progressive long-document/curriculum learning and capacity planning, with measured 100/1,000-fact performance. +5. GUI learning observability, per-fact lineage/provenance and inspectable model-level evaluation receipts. diff --git a/docs/optimization-ledger.md b/docs/optimization-ledger.md index 828c041aca0..e19cdb2ba78 100644 --- a/docs/optimization-ledger.md +++ b/docs/optimization-ledger.md @@ -28,6 +28,9 @@ Shared helpers that hold the cross-family parts: - `zig/src/core/prompt_tail.zig`: the last layer's kept tile ([#2229]) and the chunks nothing reads ([#2432]). - `zig/src/core/state_walk.zig`: one walk for kept prompt states. Not on main yet: it is on [#2215]. +Flash Next CUDA sampled reductions: one check in top-k and batched verify/draft completions prepared (#2920); +CUDA candidate bytes, parity and served/speed qualification are pending. + ## The table Each cell is one of these: @@ -342,7 +345,7 @@ below; these are estimates for planning a port, not results. | --- | --- | --- | | nemotron | +5.9 % (2 streams), +13.3 % (8 streams) | [#1783] | | qwen3_5 (27B, DFlash2) | +3.5..+5.0 % decode | [#1783] | - | qwen3_5 (Qwen3.8, BF16) | +9.5 % prefill one stream, +8.2 % at 8 | [#1439] | + | qwen3_5 (Qwen3.8, BF16) | +9.5 % prefill one stream, +8.2 % at 8 | [#1439]; large-prompt a/b pair prepared, device gate pending (#2911) | | gemma4 (31B), spark25 | level | [#1783] | 12. **Residual add plus norm in one launch.** The residual add and the next RMS norm run as one kernel, which saves a diff --git a/docs/receipts/tp-hip-device-954e82df/README.md b/docs/receipts/tp-hip-device-954e82df/README.md new file mode 100644 index 00000000000..64004641f63 --- /dev/null +++ b/docs/receipts/tp-hip-device-954e82df/README.md @@ -0,0 +1,19 @@ +# tcp-hip at 954e82dfa + +`tf-tp-test tcp-host` and `tf-tp-test tcp-hip`, two ranks on one host over 127.0.0.1 (MTU 65536), built +`zig build tf-tp-test -Doptimize=ReleaseSafe` at 954e82dfa with Zig 0.17.0. The host: AMD Ryzen AI Max+ 395, 128 GB, +Radeon 8060S (gfx1151), Linux 7.2.7, ROCm 10.0.0 (HIP 7.15). Both `tcp-hip` ranks use the one GPU, each with its own +stream and proxy. `environment.txt` holds the commit, Zig, kernel, CPU, memory, GPU, HIP runtime and loopback MTU; +`SHA256SUMS` covers the logs and `environment.txt`. This is not the two-host USB4 receipt; it shows the device side bit +for bit and its cost over `tcp-host` on one link. + +| Files | Run | +|---|---| +| `tcp-host-rank*.log` | `tcp-host` on the same link, for comparison | +| `tcp-hip-rank*.log` | `tcp-hip`: every check from HIP memory, then the timings | +| `tcp-hip-killed-rank*.log` | `tcp-hip`, rank 1 killed with SIGKILL 3 s in: rank 0 ends `error: PeerFailed`, exit 1, 0.124 s after the kill | + +Each rank 0 log holds the PASS line and the RESULT lines (median and p90 of 500 back-to-back calls a size; `gb_s_p50` +is one rank's shard bytes over the median). For `tcp-hip` a time is the call and its stream's synchronisation, and +`queue_p50_us` is the call alone. Each log ends with the rank's exit code; a killed rank 1 prints nothing before it +dies (exit 137). diff --git a/docs/receipts/tp-hip-device-954e82df/SHA256SUMS b/docs/receipts/tp-hip-device-954e82df/SHA256SUMS new file mode 100644 index 00000000000..d2ab91db3e4 --- /dev/null +++ b/docs/receipts/tp-hip-device-954e82df/SHA256SUMS @@ -0,0 +1,7 @@ +b67cca39f185e279f988a2d04f1d336a58e7fe941e6bbc132dcc78757b1eaf91 tcp-hip-killed-rank0.log +81d5e83ca8f165a245f5f55d4e1f2c2d9e203aa755d5fc045fb7da7254aacc50 tcp-hip-killed-rank1.log +5d2d3420e42b78da5b77f3eab999effdd868f0bcab85200858e4a5786a14579e tcp-hip-rank0.log +34c4cd70b72f6656a0499ebc6113c94a7447997e3da6e8188c5a1c7e98e74a6b tcp-hip-rank1.log +5c033af8400ba1fa354786c89da6a4aa6ef57b93146237cd57314ed69359547a tcp-host-rank0.log +0caa0850213802adb04df9a75495b163351c4b980f47c3acf390a0a9012a4d20 tcp-host-rank1.log +3443540eff857bbfabf7090f7eadd197afecad64f3f2d2e03b30d6f8fd3d2333 environment.txt diff --git a/docs/receipts/tp-hip-device-954e82df/environment.txt b/docs/receipts/tp-hip-device-954e82df/environment.txt new file mode 100644 index 00000000000..23c372c3af6 --- /dev/null +++ b/docs/receipts/tp-hip-device-954e82df/environment.txt @@ -0,0 +1,9 @@ +commit 954e82dfa +zig 0.17.0 +Linux 7.2.7+rex-amd64 +model name : AMD RYZEN AI MAX+ 395 w/ Radeon 8060S +Mem: 124 2 2 0 120 122 + Name: gfx1151 + Marketing Name: AMD Radeon 8060S Graphics +/opt/rocm/core-10.0/lib/libamdhip64.so.7 +lo mtu 65536 diff --git a/docs/receipts/tp-hip-device-954e82df/tcp-hip-killed-rank0.log b/docs/receipts/tp-hip-device-954e82df/tcp-hip-killed-rank0.log new file mode 100644 index 00000000000..1e969ebd04c --- /dev/null +++ b/docs/receipts/tp-hip-device-954e82df/tcp-hip-killed-rank0.log @@ -0,0 +1,3 @@ +error: PeerFailed +kill sent at 1794449237.143134077; rank 0 exited at 1794449237.266893595, 0.124 s later +exit 1 diff --git a/docs/receipts/tp-hip-device-954e82df/tcp-hip-killed-rank1.log b/docs/receipts/tp-hip-device-954e82df/tcp-hip-killed-rank1.log new file mode 100644 index 00000000000..6f6517f0171 --- /dev/null +++ b/docs/receipts/tp-hip-device-954e82df/tcp-hip-killed-rank1.log @@ -0,0 +1 @@ +exit 137 diff --git a/docs/receipts/tp-hip-device-954e82df/tcp-hip-rank0.log b/docs/receipts/tp-hip-device-954e82df/tcp-hip-rank0.log new file mode 100644 index 00000000000..9b7a31618eb --- /dev/null +++ b/docs/receipts/tp-hip-device-954e82df/tcp-hip-rank0.log @@ -0,0 +1,18 @@ +PASS tcp-hip rank 0/2: 400 all-gathers (1 B to 4 MiB), 796 fp32 and bf16 sums, 100 exchanges, send/recv and variable all-gathers bit-exact from HIP memory over loopback on one host (127.0.0.1), MTU 65536, both ranks on one Radeon 8060S (gfx1151) +RESULT {"backend":"tcp-hip","link":"loopback on one host (127.0.0.1), MTU 65536, both ranks on one Radeon 8060S (gfx1151)","world":2,"call":"all_gather","bytes":16,"p50_us":45.54,"p90_us":47.83,"gb_s_p50":0.00,"queue_p50_us":2.35} +RESULT {"backend":"tcp-hip","link":"loopback on one host (127.0.0.1), MTU 65536, both ranks on one Radeon 8060S (gfx1151)","world":2,"call":"exchange","bytes":16,"p50_us":33.89,"p90_us":37.06,"gb_s_p50":0.00,"queue_p50_us":2.05} +RESULT {"backend":"tcp-hip","link":"loopback on one host (127.0.0.1), MTU 65536, both ranks on one Radeon 8060S (gfx1151)","world":2,"call":"all_gather","bytes":4096,"p50_us":46.84,"p90_us":50.64,"gb_s_p50":0.09,"queue_p50_us":1.96} +RESULT {"backend":"tcp-hip","link":"loopback on one host (127.0.0.1), MTU 65536, both ranks on one Radeon 8060S (gfx1151)","world":2,"call":"exchange","bytes":4096,"p50_us":36.94,"p90_us":39.61,"gb_s_p50":0.11,"queue_p50_us":1.96} +RESULT {"backend":"tcp-hip","link":"loopback on one host (127.0.0.1), MTU 65536, both ranks on one Radeon 8060S (gfx1151)","world":2,"call":"all_gather","bytes":8192,"p50_us":48.05,"p90_us":51.31,"gb_s_p50":0.17,"queue_p50_us":2.39} +RESULT {"backend":"tcp-hip","link":"loopback on one host (127.0.0.1), MTU 65536, both ranks on one Radeon 8060S (gfx1151)","world":2,"call":"exchange","bytes":8192,"p50_us":37.08,"p90_us":39.38,"gb_s_p50":0.22,"queue_p50_us":2.38} +RESULT {"backend":"tcp-hip","link":"loopback on one host (127.0.0.1), MTU 65536, both ranks on one Radeon 8060S (gfx1151)","world":2,"call":"all_gather","bytes":32768,"p50_us":46.65,"p90_us":47.83,"gb_s_p50":0.70,"queue_p50_us":2.39} +RESULT {"backend":"tcp-hip","link":"loopback on one host (127.0.0.1), MTU 65536, both ranks on one Radeon 8060S (gfx1151)","world":2,"call":"exchange","bytes":32768,"p50_us":33.93,"p90_us":36.31,"gb_s_p50":0.97,"queue_p50_us":2.35} +RESULT {"backend":"tcp-hip","link":"loopback on one host (127.0.0.1), MTU 65536, both ranks on one Radeon 8060S (gfx1151)","world":2,"call":"all_gather","bytes":131072,"p50_us":72.47,"p90_us":87.08,"gb_s_p50":1.81,"queue_p50_us":2.37} +RESULT {"backend":"tcp-hip","link":"loopback on one host (127.0.0.1), MTU 65536, both ranks on one Radeon 8060S (gfx1151)","world":2,"call":"exchange","bytes":131072,"p50_us":45.21,"p90_us":48.31,"gb_s_p50":2.90,"queue_p50_us":2.40} +RESULT {"backend":"tcp-hip","link":"loopback on one host (127.0.0.1), MTU 65536, both ranks on one Radeon 8060S (gfx1151)","world":2,"call":"all_gather","bytes":262144,"p50_us":112.27,"p90_us":115.40,"gb_s_p50":2.34,"queue_p50_us":2.39} +RESULT {"backend":"tcp-hip","link":"loopback on one host (127.0.0.1), MTU 65536, both ranks on one Radeon 8060S (gfx1151)","world":2,"call":"exchange","bytes":262144,"p50_us":62.68,"p90_us":64.13,"gb_s_p50":4.18,"queue_p50_us":2.41} +RESULT {"backend":"tcp-hip","link":"loopback on one host (127.0.0.1), MTU 65536, both ranks on one Radeon 8060S (gfx1151)","world":2,"call":"all_gather","bytes":1048576,"p50_us":337.29,"p90_us":341.19,"gb_s_p50":3.11,"queue_p50_us":2.43} +RESULT {"backend":"tcp-hip","link":"loopback on one host (127.0.0.1), MTU 65536, both ranks on one Radeon 8060S (gfx1151)","world":2,"call":"exchange","bytes":1048576,"p50_us":162.87,"p90_us":181.14,"gb_s_p50":6.44,"queue_p50_us":2.11} +RESULT {"backend":"tcp-hip","link":"loopback on one host (127.0.0.1), MTU 65536, both ranks on one Radeon 8060S (gfx1151)","world":2,"call":"all_gather","bytes":4194304,"p50_us":1267.64,"p90_us":1278.18,"gb_s_p50":3.31,"queue_p50_us":2.49} +RESULT {"backend":"tcp-hip","link":"loopback on one host (127.0.0.1), MTU 65536, both ranks on one Radeon 8060S (gfx1151)","world":2,"call":"exchange","bytes":4194304,"p50_us":538.01,"p90_us":551.45,"gb_s_p50":7.80,"queue_p50_us":2.15} +exit 0 diff --git a/docs/receipts/tp-hip-device-954e82df/tcp-hip-rank1.log b/docs/receipts/tp-hip-device-954e82df/tcp-hip-rank1.log new file mode 100644 index 00000000000..a6072b3ad00 --- /dev/null +++ b/docs/receipts/tp-hip-device-954e82df/tcp-hip-rank1.log @@ -0,0 +1,2 @@ +PASS tcp-hip rank 1/2: 400 all-gathers (1 B to 4 MiB), 796 fp32 and bf16 sums, 100 exchanges, send/recv and variable all-gathers bit-exact from HIP memory over loopback on one host (127.0.0.1), MTU 65536, both ranks on one Radeon 8060S (gfx1151) +exit 0 diff --git a/docs/receipts/tp-hip-device-954e82df/tcp-host-rank0.log b/docs/receipts/tp-hip-device-954e82df/tcp-host-rank0.log new file mode 100644 index 00000000000..debb093a12c --- /dev/null +++ b/docs/receipts/tp-hip-device-954e82df/tcp-host-rank0.log @@ -0,0 +1,18 @@ +PASS tcp-host rank 0/2: 400 all-gathers (1 B to 4 MiB), 796 fp32 and bf16 sums, 100 exchanges, send/recv and variable all-gathers bit-exact over loopback on one host (127.0.0.1), MTU 65536, Ryzen AI Max+ 395 +RESULT {"backend":"tcp-host","link":"loopback on one host (127.0.0.1), MTU 65536, Ryzen AI Max+ 395","world":2,"call":"all_gather","bytes":16,"p50_us":2.25,"p90_us":2.44,"gb_s_p50":0.01} +RESULT {"backend":"tcp-host","link":"loopback on one host (127.0.0.1), MTU 65536, Ryzen AI Max+ 395","world":2,"call":"exchange","bytes":16,"p50_us":2.21,"p90_us":2.29,"gb_s_p50":0.01} +RESULT {"backend":"tcp-host","link":"loopback on one host (127.0.0.1), MTU 65536, Ryzen AI Max+ 395","world":2,"call":"all_gather","bytes":4096,"p50_us":3.02,"p90_us":3.23,"gb_s_p50":1.36} +RESULT {"backend":"tcp-host","link":"loopback on one host (127.0.0.1), MTU 65536, Ryzen AI Max+ 395","world":2,"call":"exchange","bytes":4096,"p50_us":2.58,"p90_us":2.77,"gb_s_p50":1.59} +RESULT {"backend":"tcp-host","link":"loopback on one host (127.0.0.1), MTU 65536, Ryzen AI Max+ 395","world":2,"call":"all_gather","bytes":8192,"p50_us":3.56,"p90_us":3.84,"gb_s_p50":2.30} +RESULT {"backend":"tcp-host","link":"loopback on one host (127.0.0.1), MTU 65536, Ryzen AI Max+ 395","world":2,"call":"exchange","bytes":8192,"p50_us":2.69,"p90_us":2.93,"gb_s_p50":3.05} +RESULT {"backend":"tcp-host","link":"loopback on one host (127.0.0.1), MTU 65536, Ryzen AI Max+ 395","world":2,"call":"all_gather","bytes":32768,"p50_us":7.06,"p90_us":7.23,"gb_s_p50":4.64} +RESULT {"backend":"tcp-host","link":"loopback on one host (127.0.0.1), MTU 65536, Ryzen AI Max+ 395","world":2,"call":"exchange","bytes":32768,"p50_us":3.73,"p90_us":3.95,"gb_s_p50":8.78} +RESULT {"backend":"tcp-host","link":"loopback on one host (127.0.0.1), MTU 65536, Ryzen AI Max+ 395","world":2,"call":"all_gather","bytes":131072,"p50_us":23.64,"p90_us":24.15,"gb_s_p50":5.54} +RESULT {"backend":"tcp-host","link":"loopback on one host (127.0.0.1), MTU 65536, Ryzen AI Max+ 395","world":2,"call":"exchange","bytes":131072,"p50_us":10.45,"p90_us":10.81,"gb_s_p50":12.54} +RESULT {"backend":"tcp-host","link":"loopback on one host (127.0.0.1), MTU 65536, Ryzen AI Max+ 395","world":2,"call":"all_gather","bytes":262144,"p50_us":44.75,"p90_us":45.72,"gb_s_p50":5.86} +RESULT {"backend":"tcp-host","link":"loopback on one host (127.0.0.1), MTU 65536, Ryzen AI Max+ 395","world":2,"call":"exchange","bytes":262144,"p50_us":17.77,"p90_us":18.20,"gb_s_p50":14.75} +RESULT {"backend":"tcp-host","link":"loopback on one host (127.0.0.1), MTU 65536, Ryzen AI Max+ 395","world":2,"call":"all_gather","bytes":1048576,"p50_us":170.18,"p90_us":172.11,"gb_s_p50":6.16} +RESULT {"backend":"tcp-host","link":"loopback on one host (127.0.0.1), MTU 65536, Ryzen AI Max+ 395","world":2,"call":"exchange","bytes":1048576,"p50_us":62.45,"p90_us":67.17,"gb_s_p50":16.79} +RESULT {"backend":"tcp-host","link":"loopback on one host (127.0.0.1), MTU 65536, Ryzen AI Max+ 395","world":2,"call":"all_gather","bytes":4194304,"p50_us":728.44,"p90_us":749.46,"gb_s_p50":5.76} +RESULT {"backend":"tcp-host","link":"loopback on one host (127.0.0.1), MTU 65536, Ryzen AI Max+ 395","world":2,"call":"exchange","bytes":4194304,"p50_us":278.99,"p90_us":288.45,"gb_s_p50":15.03} +exit 0 diff --git a/docs/receipts/tp-hip-device-954e82df/tcp-host-rank1.log b/docs/receipts/tp-hip-device-954e82df/tcp-host-rank1.log new file mode 100644 index 00000000000..d610a7fcedf --- /dev/null +++ b/docs/receipts/tp-hip-device-954e82df/tcp-host-rank1.log @@ -0,0 +1,2 @@ +PASS tcp-host rank 1/2: 400 all-gathers (1 B to 4 MiB), 796 fp32 and bf16 sums, 100 exchanges, send/recv and variable all-gathers bit-exact over loopback on one host (127.0.0.1), MTU 65536, Ryzen AI Max+ 395 +exit 0 diff --git a/docs/recipes/flash-next-cuda.md b/docs/recipes/flash-next-cuda.md index 2bbee279424..e1da8e801b9 100644 --- a/docs/recipes/flash-next-cuda.md +++ b/docs/recipes/flash-next-cuda.md @@ -200,8 +200,8 @@ aggregate tok/s), on our kernels and, for comparison, on the 76-kernel captured | Cold first token at 3,001 / 12,001 tokens (s) | 2.67 / 10.40 | 2.67 / 10.30 | | 45,030-token prompt, no cache (s) | 36.5 | 35.8 | -Every concurrent reply equalled its solo run, and every drafted one its `"draft": false` run. Drafted streams verify -their windows a pass each, so drafted throughput does not grow with streams yet. While a 12,001-token prompt runs, +Every concurrent reply equalled its solo run, and every drafted one its `"draft": false` run. Drafted streams now verify +their windows in shared passes; the table above predates that path. While a 12,001-token prompt runs, another stream's decode waits at most 1.3 s between tokens (one prompt chunk). Each stream at a 16,384-token window takes 0.74 GiB with drafts, 0.54 GiB without. @@ -292,9 +292,9 @@ per-stream launches. The bytes equal the per-stream launches': `tf-cuda-test fla - The dense projections run a copy of the Python engine's group-32 lane matmul (`qmm.cu`); the core's `qmm_group` and `lane_gemv` are built for groups of 64. -- No CUDA graphs or GPU-side rounds; drafted streams verify their windows one pass each, and the MTP head drafts one - stream at a time. +- Shared windows and the MTP head use CUDA graphs and batched passes; sampling remains on the host. - Prompts run slower than the Python engine's: a cold 12,001-token prompt takes about 10 s against its 6.7 s. -- Draws are made on the host from each row's scores. +- Draws use the host f64 sampler over GPU top-k candidates when eligible, with whole-row fallbacks. + `TF_FLASHNEXT_BATCH_DRAWS=0` restores per-stream reductions for an A/B. - Our glue's sums are not the captured kernels' bit for bit, so replies part from the Python engine's teacher path after a while, as that engine's own served path does (10 to 36 tokens, from its routed-experts kernel's rounding). diff --git a/docs/serve-config.md b/docs/serve-config.md new file mode 100644 index 00000000000..66f6dbfe65e --- /dev/null +++ b/docs/serve-config.md @@ -0,0 +1,127 @@ +# Serve config files + +`tensorfold serve --config FILE.toml` reads serve flags from a TOML file, so a launch can be checked in, +reviewed and reused. The command line still works as before, and it wins over the file. + +```toml +# glm.toml +model = "zai-org/GLM-5.3-Flash" +host = "127.0.0.1" +port = 8080 +context = 131072 +parallel = "auto" +temperature = 0.6 +thinking = false +dashboard = true +alias = ["glm", "glm-flash"] +chat-template = "templates/glm.jinja" # beside glm.toml +api-key-file = "/etc/tensorfold/keys" +``` + +```sh +tensorfold serve --config glm.toml # the file names the model +tensorfold serve --config glm.toml --port 9000 # the command line overrides the file +tensorfold serve other/model --config glm.toml # a model on the command line overrides the file's +``` + +## Keys + +A key is a [serve flag](../README.md#serve-flags) without its `--`. `-` and `_` are the same, so +`max-tokens` and `max_tokens` both set `--max-tokens`; a file that has both is refused. `model` names the +model, as the positional argument does. Every key is at the top level of the file. + +| Flag kind | Value in the file | Example | +| --- | --- | --- | +| Takes a value | A string or a number | `port = 8080`, `host = "127.0.0.1"`, `parallel = "auto"` | +| Repeatable | One value, or an array of strings with one item a repeat | `alias = ["glm", "glm-flash"]` | +| Switch | `true` or `false` | `dashboard = true` | + +A number is passed as written, without its `_` separators and, for an integer, without a leading `+`; +the flag checks it as it checks a typed value. A pair of switches has one key, the positive one: write `thinking = false` for `--no-thinking`; the key +`no-thinking` is refused and the message names the form to use. A switch with no positive twin keeps its +name (`no-drafts = true`), and `false` for a switch with no `--no-` twin leaves it off, its default. + +## Precedence + +The command line wins over the file, and the file wins over the built-in defaults. `serve` reads the +file's flags first and the command line's after them, so a later value replaces an earlier one. Three +consequences follow: + +- A repeatable flag on the command line replaces the file's whole list. With `api-key = ["old"]` in the + file and `--api-key new` on the command line, only `new` is accepted. A list the command line does not + name stays the file's. +- A switch the file turns on stays on unless it has a `--no-` twin. To serve without it, use another file + or remove the line. +- Flags that refuse each other do so across the file and the command line. A file with `unix-socket` + cannot be combined with `--port`. + +## Paths + +A relative path in the file starts at the file's folder, not at the directory `serve` runs in, so a +file and what it names move together. This holds for the flags that name a file or folder: +`chat-template`, `api-key-file`, `unix-socket`, `voices`, `speed-up`, `prompt-cache-disk`, `learn-dir`, +`recall-dir`, `slide-graph`, `record`, `compact-memory` and `fsr-route-trace`. An absolute path passes +as written. No shell reads the file, so nothing expands `~`: these flags refuse a value that starts +with it, and the message asks for the whole path. + +`model` and `drafter` take a folder or a Hugging Face repo id, and `org/name` could be either. Start a +folder with `./` or `../` to place it beside the file: `model = "./weights/glm"`. Any other text passes as +written and resolves as it does on the command line, where a leading `~/` is the home folder. + +A path on the command line is still relative to the directory `serve` runs in. + +## What the file can hold + +The reader takes a strict subset of TOML 1.0, so every file it accepts means the same to any TOML tool: + +- comments, blank lines, LF or CRLF line ends; +- bare keys (`A-Z a-z 0-9 _ -`) and quoted keys; +- basic strings `"..."` with TOML's escapes, and literal strings `'...'`; +- decimal integers and floats, `true` and `false`; +- arrays of strings, on one line or several, with a trailing comma. + +It refuses the rest by line: tables (`[section]`), dotted keys, inline tables, nested arrays, an array +item that is not a string, multi-line strings, dates and times, hexadecimal, octal and binary integers, a key defined twice, a byte order mark, +and a file over 1 MiB. Tables are refused, not ignored, so that a later release can give them a meaning. + +## Errors + +A problem with the file is a usage error that names the file and the line. Nothing is loaded. + +On macOS and Linux the file is opened once, checked and read through that one handle: + +- a link is not followed, and anything that is not a regular file is refused; +- a file that its group or other users can write is refused, because it chooses what is served + (`chmod go-w FILE`); +- a file that sets `api-key` is refused while its group or other users can read it (`chmod 600 FILE`, or + use `api-key-file`). + +```text +tensorfold serve: error: argument --config: glm.toml line 7: unknown key 'prot' +``` + +A key for a flag that this build does not serve is refused in the same way. Each value is checked by +its flag as a typed value is, so the flag's own message comes with the line: + +```text +tensorfold serve: error: argument --config: glm.toml line 3: argument --port: invalid port: '99999' +``` + +A refusal that involves two flags, such as `unix-socket` in the file with `--port` on the command line, +has no single line. `serve` prints it as usual and then names the file: + +```text +tensorfold serve: error: argument --unix-socket: not allowed with --port +tensorfold serve: --config glm.toml supplied 9 options, read before the command line's +``` + +The startup log names the file and how many options it gave, never a value. + +## Limits + +- One `--config` a command, and a file cannot name another file. The path must end in `.toml`. +- The file holds serve flags only. Environment variables (`TF_*`, `TENSORFOLD_*`) are still set in the + environment; [profiles](profiles.md) describes the registered switches. +- `tensorfold benchmark` and `tensorfold service install` do not read the file. TensorFold Web refuses + `--config` as an extra flag, because a file could set the flags that Settings manages. +- Prefer `api-key-file` to `api-key` in a file that is checked in, so that no key is stored with it. diff --git a/docs/vision.md b/docs/vision.md index ec74cf1beaa..af7c17c475f 100644 --- a/docs/vision.md +++ b/docs/vision.md @@ -298,7 +298,8 @@ as transformers 5.19's `Glm5NextProcessor` prepares them: most 256. Video needs `libtfvideo`, an optional library over FFmpeg 9.0.2 (the release PyAV 19.0.1 ships). The server loads it -when the first video arrives and refuses videos by name without it: +at startup for a model that reads video. Without it the startup log names the library, `/v1/models` lists no `"video"` +in the model's `input_types`, and `video_url` parts get HTTP 400: ```sh tools/zig/build_ffmpeg.sh ~/ffmpeg-9.0.2 # static FFmpeg: H.264, HEVC, VP8, VP9, MPEG-4; MP4/MOV, MKV/WebM diff --git a/tools/bench_stream.py b/tools/bench_stream.py index da6d154d23f..b52df3c8357 100644 --- a/tools/bench_stream.py +++ b/tools/bench_stream.py @@ -95,7 +95,7 @@ def receipt(self) -> dict: **{f"first_{k}_s": self.first[k] for k in KINDS}, "first_output_s": times[0] if times else None, "last_output_s": times[-1] if times else None} return {**{k: v - self.sent if done and v is not None else None for k, v in at.items()}, - "completion": self.completion(), "choices": len(self.finish), + "completion": self.completion(), "choices": len(self.finish), "speculative": self.speculative, "finish_reasons": [self.finish[i] for i in sorted(self.finish)], "output_times": times if len({i for _, i in self.outputs}) <= 1 else None} diff --git a/tools/glm_index_emulate/cuda_runtime.h b/tools/glm_index_emulate/cuda_runtime.h index 918ab0b427d..cc0a8f9e9af 100644 --- a/tools/glm_index_emulate/cuda_runtime.h +++ b/tools/glm_index_emulate/cuda_runtime.h @@ -46,6 +46,28 @@ inline float __shfl_xor_sync(unsigned, float v, int o) { mask = o; return shuffle(v, [](int l) { return l ^ mask; }); } +// the warp votes glm_index_decode.cuh takes: every lane of the warp calls them, as on the device +inline unsigned __ballot_sync(unsigned, int pred) { + const int t = (int)threadIdx.x, l = t & 31, base = t - l; + emu::xbuf[t] = pred ? 1u : 0u; + warp_sync(); + unsigned m = 0; + for (int i = 0; i < 32; i++) m |= emu::xbuf[base + i] ? 1u << i : 0u; + warp_sync(); + return m; +} +inline int __any_sync(unsigned mask, int pred) { return __ballot_sync(mask, pred) != 0; } +inline unsigned __match_any_sync(unsigned, int v) { + const int t = (int)threadIdx.x, l = t & 31, base = t - l; + emu::xbuf[t] = (uint32_t)v; + warp_sync(); + unsigned m = 0; + for (int i = 0; i < 32; i++) m |= emu::xbuf[base + i] == (uint32_t)v ? 1u << i : 0u; + warp_sync(); + return m; +} +inline int __popc(unsigned x) { return __builtin_popcount(x); } +inline int __ffs(int x) { return __builtin_ffs(x); } inline int atomicAdd(int* p, int v) { return std::atomic_ref(*p).fetch_add(v); } inline int atomicMax(int* p, int v) { std::atomic_ref a(*p); diff --git a/tools/glm_index_emulate/emulate.cpp b/tools/glm_index_emulate/emulate.cpp index 954268a60ef..36ab0fa58e0 100644 --- a/tools/glm_index_emulate/emulate.cpp +++ b/tools/glm_index_emulate/emulate.cpp @@ -45,6 +45,7 @@ inline void mma16816(float* c, const uint32_t* a, const uint32_t* b) { // m16n8 #include "../../zig/kernels/cuda/glm_index_pools.cuh" #include "../../zig/kernels/cuda/glm_index_scores.cuh" +#include "../../zig/kernels/cuda/glm_index_decode.cuh" // every block of the grid in turn, its threads at once static void run_grid(unsigned gx, unsigned gy, int threads, const std::function& kernel) { @@ -220,6 +221,47 @@ int main() { } printf("pools paths: whole row %d, candidates %d, whole row after candidates %d\n", paths[0], paths[1], paths[2]); if (paths[1] == 0 || paths[2] == 0) { fails++; printf("a path was never taken\n"); } + + // glm_index_decode.cuh: a decode window's rows marked on many CTAs, then merged, against the same plain top-K + int dpaths[4] = {0, 0, 0, 0}; + const int drows = 3; + for (int np : {4097, 12289, 70001}) + for (int mode = 0; mode < 3; mode++) + for (Kind kind : {normal, ties, equal, zeros, skewed, decoy}) { + const int pos = mode == 0 ? 300 : mode == 1 ? 2 * np : 4 * np - drows - 5; + std::vector s((size_t)drows * np + 4); + float* base = s.data() + (np % 4 ? 1 : 0); + std::vector limit(drows); + for (int r = 0; r < drows; r++) { + limit[r] = (int)std::min(np, std::max((pos + r + 1) / 4, K)); + fill(g, base + (size_t)r * np, np, limit[r], kind); + } + const int64_t words = (np + 31) / 32; + std::vector bitw((size_t)drows * 2 * words, 0xA5A5A5A5u); // words a scan does not write stay unread + const int last = (int)std::min(np, std::max((pos + drows) / 4, K)); + const unsigned ctas = last <= glm_dsel::CAP ? 0 : (unsigned)((last + glm_dsel::SPAN - 1) / glm_dsel::SPAN); + if (ctas > 0) + run_grid(ctas, drows, glm_dsel::T1, [&] { tf_glm_dsel_scan(base, np, &pos, K, 2048, bitw.data(), words); }); + std::vector out((size_t)drows * K, -7); + std::vector path(drows, -1); + run_grid(drows, 1, glm_dsel::T2, [&] { tf_glm_dsel_merge(base, out.data(), np, &pos, K, bitw.data(), words, path.data()); }); + for (int r = 0; r < drows; r++) { + if (path[r] < 0 || path[r] > 3) { + fails++; + printf("dsel np %d mode %d kind %d row %d: path %d\n", np, mode, (int)kind, r, path[r]); + continue; + } + dpaths[path[r]]++; + const auto want = reference(base + (size_t)r * np, limit[r], K); + if (!std::equal(want.begin(), want.end(), out.begin() + (size_t)r * K)) { + fails++; + printf("dsel np %d mode %d kind %d row %d (path %d) differs\n", np, mode, (int)kind, r, path[r]); + } + } + } + printf("dsel paths: whole row %d, candidates %d, whole row after candidates %d, ties at the floor %d\n", dpaths[0], + dpaths[1], dpaths[2], dpaths[3]); + if (dpaths[0] == 0 || dpaths[1] == 0 || dpaths[2] == 0 || dpaths[3] == 0) { fails++; printf("a dsel path was never taken\n"); } printf("%s (%d failures)\n", fails ? "FAIL" : "PASS", fails); return fails != 0; } diff --git a/tools/living_weights_v2/__init__.py b/tools/living_weights_v2/__init__.py new file mode 100644 index 00000000000..698cdce9bd8 --- /dev/null +++ b/tools/living_weights_v2/__init__.py @@ -0,0 +1,3 @@ +"""Explicit, externally guarded native TensorFold learning workflows.""" + +__version__ = "0.1.0" diff --git a/tools/living_weights_v2/__main__.py b/tools/living_weights_v2/__main__.py new file mode 100644 index 00000000000..f52269d66b6 --- /dev/null +++ b/tools/living_weights_v2/__main__.py @@ -0,0 +1,80 @@ +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path + +from .controller import Controller, LearningError +from .evaluator import evaluate +from .ledger import Ledger, LedgerError, exclusive_file +from .schema import ManifestError, load_manifest +from .transport import Client, TransportError + +# The journal needs a private directory of its own (0700), so it is not the shared tensorfold state folder. +DEFAULT_LEDGER = Path.home() / ".local/state/tensorfold/living-weights-v2/ledger.sqlite3" + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(prog="python -m living_weights_v2", description="External guarded learning controller for native TensorFold Living Weights") + sub = parser.add_subparsers(dest="command", required=True) + plan = sub.add_parser("plan", help="validate and summarize a manifest without writing weights") + plan.add_argument("manifest", type=Path) + evaluation = sub.add_parser("evaluate", help="read-only lexical recall probes over any OpenAI-compatible chat server") + evaluation.add_argument("manifest", type=Path) + evaluation.add_argument("--base-url", default="http://127.0.0.1:8080") + evaluation.add_argument("--api-key-file", type=Path, required=True) + evaluation.add_argument("--allow-remote", action="store_true") + teach = sub.add_parser("teach", help="explicitly teach user-approved facts through the native API") + teach.add_argument("manifest", type=Path) + teach.add_argument("--base-url", default="http://127.0.0.1:8080") + teach.add_argument("--api-key-file", type=Path, required=True) + teach.add_argument("--ledger", type=Path, default=DEFAULT_LEDGER) + teach.add_argument("--allow-remote", action="store_true", help="explicitly allow an authenticated remote server") + teach.add_argument("--timeout", type=int, default=3600) + status = sub.add_parser("status", help="show durable audit history and pending recovery") + status.add_argument("--ledger", type=Path, default=DEFAULT_LEDGER) + status.add_argument("--model") + args = parser.parse_args(argv) + try: + if args.command == "plan": + manifest = load_manifest(args.manifest) + output = {"schema": 1, "model": manifest.model, "manifest_digest": manifest.digest, "source": manifest.source, "facts": [ + {"subject": f.subject, "relation": f.relation, "fact_digest": f.digest, "positive_count": len(f.questions), "near_miss_count": len(f.near_misses)} + for f in manifest.facts + ], "anchor_count": len(manifest.anchors), "mutates_weights": False} + print(json.dumps(output, indent=2)) + return 0 + if args.command == "status": + ledger = Ledger(args.ledger) + try: + print(json.dumps(ledger.history(args.model), indent=2, ensure_ascii=False)) + finally: + ledger.close() + return 0 + if args.command == "evaluate": + manifest = load_manifest(args.manifest) + client = Client(args.base_url, args.api_key_file, args.allow_remote) + if manifest.model not in client.models(): + raise LearningError("model not listed by chat server") + print(json.dumps(evaluate(manifest, client), indent=2, ensure_ascii=False)) + return 0 + if args.timeout <= 0: + raise ValueError("timeout must be positive") + manifest = load_manifest(args.manifest) + client = Client(args.base_url, args.api_key_file, args.allow_remote, args.timeout) + with exclusive_file(args.ledger.with_suffix(args.ledger.suffix + ".lock")): + ledger = Ledger(args.ledger) + try: + result = Controller(client, ledger).teach(manifest) + print(json.dumps(result, indent=2, ensure_ascii=False)) + return 3 if any(r["state"] == "needs_recovery" for r in result) else (2 if any(r["state"] in {"rejected", "rolled_back"} for r in result) else 0) + finally: + ledger.close() + except (ManifestError, TransportError, LearningError, LedgerError, ValueError) as exc: + print(f"living_weights_v2: {exc}", file=sys.stderr) + return 4 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/living_weights_v2/assessment.py b/tools/living_weights_v2/assessment.py new file mode 100644 index 00000000000..8d69d8de91b --- /dev/null +++ b/tools/living_weights_v2/assessment.py @@ -0,0 +1,91 @@ +from __future__ import annotations + +import re +from dataclasses import dataclass +from typing import Callable, Iterable + +from .schema import Fact + + +@dataclass(frozen=True) +class Observation: + question: str + answer: str + mode: str + + +@dataclass(frozen=True) +class Assessment: + positives: int + positive_total: int + leaks: tuple[str, ...] + drift: tuple[str, ...] + retained_failures: tuple[str, ...] + + @property + def passed(self) -> bool: + return self.positives == self.positive_total and not (self.leaks or self.drift or self.retained_failures) + + +def contains_answer(response: str, expected: str) -> bool: + if not expected.strip(): + return False + words = [re.escape(x) for x in expected.casefold().split()] + expression = r"(? bool: + if not contains_answer(response, expected): + return False + unsafe = ("i don't know", "i do not know", "not sure", "cannot confirm", "can't verify", + "not enough information", "might be", "possibly", "perhaps", "no evidence") + lowered = response.casefold() + if any(phrase in lowered for phrase in unsafe): + return False + pattern = r"\b(?:not|never|isn't|wasn't|ain't)\b.{0,24}" + re.escape(expected.casefold()) + if re.search(pattern, lowered): + return False + return True + + +def observe(questions: Iterable[str], request: Callable[[str], str], mode: str) -> tuple[Observation, ...]: + return tuple(Observation(question, request(question), mode) for question in questions) + + +def _key(text: str) -> str: + return " ".join(text.casefold().split()) + + +def assess( + fact: Fact, + baseline_negatives: tuple[Observation, ...], + after_positives: tuple[Observation, ...], + after_negatives: tuple[Observation, ...], + baseline_anchors: tuple[Observation, ...], + after_anchors: tuple[Observation, ...], + retained: tuple[tuple[Fact, tuple[Observation, ...]], ...], +) -> Assessment: + if len(baseline_negatives) != len(after_negatives) or len(baseline_anchors) != len(after_anchors): + raise ValueError("pre/post checks have different lengths") + leaks = [] + drift = [] + failures = [] + positive_count = sum(affirmative_answer(o.answer, fact.answer) for o in after_positives) + for before, after in zip(baseline_negatives, after_negatives): + if before.question != after.question: + raise ValueError("near-miss probes changed") + if contains_answer(after.answer, fact.answer) and not contains_answer(before.answer, fact.answer): + leaks.append(after.question) + if _key(before.answer) != _key(after.answer): + drift.append(after.question) + for before, after in zip(baseline_anchors, after_anchors): + if before.question != after.question: + raise ValueError("anchor probes changed") + if _key(before.answer) != _key(after.answer): + drift.append(after.question) + for old, observations in retained: + for observation in observations: + if not affirmative_answer(observation.answer, old.answer): + failures.append(observation.question) + return Assessment(positive_count, len(after_positives), tuple(leaks), tuple(drift), tuple(failures)) diff --git a/tools/living_weights_v2/controller.py b/tools/living_weights_v2/controller.py new file mode 100644 index 00000000000..45a5734e4ba --- /dev/null +++ b/tools/living_weights_v2/controller.py @@ -0,0 +1,191 @@ +from __future__ import annotations + +from dataclasses import asdict +from typing import Any + +from .assessment import affirmative_answer, assess, contains_answer, observe +from .ledger import Ledger +from .schema import Fact, Manifest +from .transport import Client, Event, TransportError, checked_graph + + +class LearningError(RuntimeError): + pass + + +def _stable_graph_fact(item: dict) -> dict: + # Native rechecks update counters and verdicts; links are recomputed from all current fact texts. + return {key: value for key, value in item.items() if key not in {"checks", "recalled", "links"}} + + +def _changes(before: dict[int, dict], after: dict[int, dict]) -> list[int]: + removed = set(before) - set(after) + if removed: + raise LearningError(f"graph lost facts {sorted(removed)}") + for key in before.keys() & after.keys(): + if _stable_graph_fact(before[key]) != _stable_graph_fact(after[key]): + raise LearningError(f"existing graph fact {key} changed during lesson") + return sorted(set(after) - set(before)) + + +def _event_summary(events: tuple[Event, ...]) -> dict: + meaningful = [e for e in events if e.kind in {"learned", "saved", "failed", "forgot"}] + return {"events": [{"kind": e.kind, "data": e.data} for e in meaningful]} + + +def _claimed_id(event: Event) -> int | None: + value = event.data.get("id") + if type(value) is int and value > 0: + return value + nested = event.data.get("fact") + if isinstance(nested, dict) and type(nested.get("id")) is int: + return nested["id"] + return None + + +def _owns_new_fact(new_ids: list[int], events: tuple[Event, ...], graph: dict[int, dict], fact: Fact) -> bool: + if len(new_ids) != 1: + return False + if any(_claimed_id(event) == new_ids[0] for event in events if event.kind in {"fact", "learned"}): + return True + item = graph[new_ids[0]] + for field in ("text", "statement", "fact", "content"): + value = item.get(field) + if isinstance(value, str) and value.strip().casefold() == fact.text.casefold(): + return True + return False + + +class Controller: + def __init__(self, client: Client, ledger: Ledger): + self.client = client + self.ledger = ledger + + def _graph(self) -> dict[int, dict]: + # Every graph read is checked here too, so a state the controller doesn't know stops it before any lesson. + return checked_graph(list(self.client.graph().values())) + + def _probe(self, model: str, questions: tuple[str, ...], mode: str): + return observe(questions, lambda question: self.client.chat(model, question), mode) + + def _restore(self, ids: list[int]) -> bool: + if not ids or len(ids) > 256: + return False + try: + events = self.client.delete(ids, "Living Weights v2 external regression gate") + forgot = [event for event in events if event.kind == "forgot"] + if len(forgot) != len(ids) or any(event.data.get("deleted") is not True for event in forgot): + return False + post = self._graph() + return all(post.get(i, {}).get("state") == "deleted" for i in ids) + except (TransportError, ValueError): + return False + + def _verify_existing(self, model: str, retained: tuple[Fact, ...]): + return tuple((fact, self._probe(model, fact.questions, "retained")) for fact in retained) + + def _recovered(self, model: str, baseline_pos, baseline_neg, baseline_anchor, baseline_retained) -> bool: + sequences = [baseline_pos, baseline_neg, baseline_anchor] + sequences.extend(observations for _, observations in baseline_retained) + for before in sequences: + after = self._probe(model, tuple(item.question for item in before), "recovery-check") + for original, current in zip(before, after): + if " ".join(original.answer.casefold().split()) != " ".join(current.answer.casefold().split()): + return False + return True + + def preflight(self, manifest: Manifest) -> dict: + if manifest.model not in self.client.models(): + raise LearningError("requested model is not listed by the server") + graph = self._graph() + if any(item.get("state") == "deleting" for item in graph.values()): + raise LearningError("graph has an unfinished native deletion") + for fact in manifest.facts: + self.ledger.require_safe(manifest.model, fact) + return {"model": manifest.model, "facts": len(manifest.facts), "graph_entries": len(graph)} + + def teach(self, manifest: Manifest) -> list[dict[str, Any]]: + self.preflight(manifest) + receipts = [] + for fact in manifest.facts: + receipts.append(self._teach_one(manifest, fact)) + if receipts[-1]["state"] in {"needs_recovery", "rolled_back", "rejected"}: + break + return receipts + + def _teach_one(self, manifest: Manifest, fact: Fact) -> dict: + model = manifest.model + self.ledger.require_safe(model, fact) + retained = self.ledger.retained(model) + before_graph = self._graph() + baseline_pos = self._probe(model, fact.questions, "before-positive") + baseline_neg = self._probe(model, fact.near_misses, "before-near-miss") + baseline_anchor = self._probe(model, manifest.anchors, "before-anchor") + baseline_retained = self._verify_existing(model, retained) + for old_fact, observations in baseline_retained: + if not all(affirmative_answer(o.answer, old_fact.answer) for o in observations): + return {"state": "rejected", "fact": fact.digest, "reason": "an earlier committed fact already fails its probes"} + if all(affirmative_answer(result.answer, fact.answer) for result in baseline_pos): + return {"state": "already_answers", "fact": fact.digest, "note": "not proof of retention; no weights changed"} + if any(contains_answer(result.answer, fact.answer) for result in baseline_neg): + return {"state": "rejected", "fact": fact.digest, "reason": "baseline leaks the expected answer to a near-miss"} + entry_id = self.ledger.begin(model, manifest.digest, fact) + receipt: dict[str, Any] = { + "entry_id": entry_id, "fact_digest": fact.digest, "manifest_digest": manifest.digest, + "model": model, "baseline": { + "positives": [asdict(o) for o in baseline_pos], + "near_misses": [asdict(o) for o in baseline_neg], + "anchors": [asdict(o) for o in baseline_anchor], + "retained": [{"fact_digest": old.digest, "observations": [asdict(o) for o in values]} for old, values in baseline_retained], + }, + } + state = "needs_recovery" + try: + events = self.client.teach(fact.text) + receipt["native"] = _event_summary(events) + learned = [event for event in events if event.kind == "learned"] + saved = [event for event in events if event.kind == "saved"] + errors = [event for event in events if event.kind == "failed"] + after_graph = self._graph() + new_ids = _changes(before_graph, after_graph) + receipt["new_graph_ids"] = new_ids + owned = _owns_new_fact(new_ids, events, after_graph, fact) + receipt["new_fact_attributed"] = owned + if errors or not saved or len(learned) != 1 or learned[0].data.get("recalled") is not True: + if not new_ids: + state = "rejected" + elif owned and self._restore(new_ids): + if self._recovered(model, baseline_pos, baseline_neg, baseline_anchor, baseline_retained): + state = "rolled_back" + else: + receipt["reason"] = "deletion completed but baseline output was not recovered" + receipt["reason"] = "native learner did not confirm exactly one recalled and saved fact" + elif not owned: + receipt["reason"] = "cannot prove graph entry belongs to this request" + else: + after_pos = self._probe(model, fact.questions, "after-positive") + after_neg = self._probe(model, fact.near_misses, "after-near-miss") + after_anchor = self._probe(model, manifest.anchors, "after-anchor") + retained_observations = self._verify_existing(model, retained) + evaluation = assess(fact, baseline_neg, after_pos, after_neg, baseline_anchor, after_anchor, retained_observations) + receipt["assessment"] = asdict(evaluation) + receipt["answers"] = { + "positives": [asdict(o) for o in after_pos], + "near_misses": [asdict(o) for o in after_neg], + "anchors": [asdict(o) for o in after_anchor], + "retained": [{"fact_digest": old.digest, "observations": [asdict(o) for o in values]} for old, values in retained_observations], + } + if evaluation.passed: + state = "committed" + elif self._restore(new_ids): + if self._recovered(model, baseline_pos, baseline_neg, baseline_anchor, baseline_retained): + state = "rolled_back" + else: + receipt["reason"] = "deletion completed but baseline output was not recovered" + else: + receipt["reason"] = "post-training regression and native deletion was not confirmed" + except Exception as exc: + receipt["error"] = type(exc).__name__ + ": " + str(exc) + receipt["state"] = state + self.ledger.finish(entry_id, state, receipt) + return receipt diff --git a/tools/living_weights_v2/evaluator.py b/tools/living_weights_v2/evaluator.py new file mode 100644 index 00000000000..272a093dbd5 --- /dev/null +++ b/tools/living_weights_v2/evaluator.py @@ -0,0 +1,40 @@ +from __future__ import annotations + +from dataclasses import asdict +from typing import Protocol + +from .assessment import affirmative_answer, contains_answer +from .schema import Manifest + + +class ChatModel(Protocol): + def chat(self, model: str, question: str) -> str: ... + + +def evaluate(manifest: Manifest, client: ChatModel) -> dict: + """Read-only lexical checks; not a semantic correctness certificate.""" + checks = [] + total = 0 + correct = 0 + leaked = 0 + for fact in manifest.facts: + positive = [] + negative = [] + for question in fact.questions: + answer = client.chat(manifest.model, question) + matched = affirmative_answer(answer, fact.answer) + total += 1 + correct += int(matched) + positive.append({"question": question, "answer": answer, "expected_present": matched}) + for question in fact.near_misses: + answer = client.chat(manifest.model, question) + violation = contains_answer(answer, fact.answer) + leaked += int(violation) + negative.append({"question": question, "answer": answer, "possible_leak": violation}) + checks.append({"fact_digest": fact.digest, "subject": fact.subject, + "positives": positive, "near_misses": negative}) + anchors = [{"question": question, "answer": client.chat(manifest.model, question)} for question in manifest.anchors] + return {"model": manifest.model, "manifest_digest": manifest.digest, "positive_matches": correct, + "positive_total": total, "possible_near_miss_leaks": leaked, "anchors": anchors, + "checks": checks, "weights_changed": False, + "disclaimer": "lexical answer-presence checks; not a semantic or model-family training guarantee"} diff --git a/tools/living_weights_v2/ledger.py b/tools/living_weights_v2/ledger.py new file mode 100644 index 00000000000..851ada942d4 --- /dev/null +++ b/tools/living_weights_v2/ledger.py @@ -0,0 +1,198 @@ +from __future__ import annotations + +import contextlib +import json +import os +import sqlite3 +import stat +from dataclasses import asdict +from pathlib import Path +from typing import Iterator + +from .schema import Fact, normalized + + +class LedgerError(RuntimeError): + pass + + +def _private(st: os.stat_result, kind) -> bool: + return kind(st.st_mode) and st.st_uid == os.getuid() and not stat.S_IMODE(st.st_mode) & 0o077 + + +def private_dir(directory: Path) -> tuple[int, int]: + """Create missing directories 0700; the journal's own directory must be a real directory of ours with mode 0700.""" + if os.name != "posix": + raise LedgerError("the Living Weights v2 journal requires a POSIX host") + missing = [] + probe = directory + while not os.path.lexists(probe): + missing.append(probe) + probe = probe.parent + for item in reversed(missing): + try: + item.mkdir(mode=0o700) + except FileExistsError: + pass + st = os.lstat(directory) + if not _private(st, stat.S_ISDIR): + found = stat.S_IMODE(st.st_mode) + raise LedgerError(f"{directory} must be a directory you own with mode 700 (it is {found:o}), " + "since it holds the journal; use a private directory of its own") + return st.st_dev, st.st_ino + + +def _journal_files(path: Path) -> tuple[Path, Path, Path]: + return path, Path(str(path) + "-wal"), Path(str(path) + "-shm") + + +def _check_file(item: Path, st: os.stat_result) -> None: + if not _private(st, stat.S_ISREG): + raise LedgerError(f"{item} must be a regular file you own with mode 600 (it is {stat.S_IMODE(st.st_mode):o}), " + "since it holds fact text") + + +def private_journal(path: Path) -> tuple[tuple[int, int], tuple[int, int]]: + """Check the directory, then create the database at 0600 (or check the one there); return both identities.""" + folder = private_dir(path.parent) + flags = os.O_RDWR | os.O_NOFOLLOW + try: + descriptor = os.open(str(path), flags | os.O_CREAT | os.O_EXCL, 0o600) + except FileExistsError: + try: + descriptor = os.open(str(path), flags) + except OSError as exc: + raise LedgerError(f"{path} must be a regular file you own with mode 600, not a link") from exc + try: + st = os.fstat(descriptor) + finally: + os.close(descriptor) + _check_file(path, st) + for item in _journal_files(path)[1:]: + try: + _check_file(item, os.lstat(item)) + except FileNotFoundError: + pass + return folder, (st.st_dev, st.st_ino) + + +def verify_journal(path: Path, identities: tuple[tuple[int, int], tuple[int, int]]) -> None: + """After SQLite opens it: the same directory and database, and every journal file still private.""" + folder, database = identities + st = os.lstat(path.parent) + if (st.st_dev, st.st_ino) != folder or not _private(st, stat.S_ISDIR): + raise LedgerError(f"{path.parent} changed while the journal opened") + for item in _journal_files(path): + try: + st = os.lstat(item) + except FileNotFoundError: + if item == path: + raise LedgerError(f"{path} changed while the journal opened") from None + continue + _check_file(item, st) + if item == path and (st.st_dev, st.st_ino) != database: + raise LedgerError(f"{path} changed while the journal opened") + + +@contextlib.contextmanager +def exclusive_file(path: Path) -> Iterator[None]: + try: + import fcntl + except ImportError as exc: + raise LedgerError("exclusive locking requires a POSIX host") from exc + private_dir(path.parent) + descriptor = os.open(str(path), os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600) + try: + import fcntl + fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB) + yield + except BlockingIOError as exc: + raise LedgerError("another Living Weights v2 writer is active") from exc + finally: + os.close(descriptor) + + +class Ledger: + def __init__(self, path: Path): + self.path = path + identities = private_journal(path) # SQLite gives the WAL and SHM the database file's mode + self.db = sqlite3.connect(path, timeout=2) + try: + verify_journal(path, identities) + self._create() + verify_journal(path, identities) + except BaseException: + self.db.close() + raise + + def _create(self) -> None: + self.db.row_factory = sqlite3.Row + self.db.executescript(""" + PRAGMA journal_mode=WAL; + PRAGMA synchronous=FULL; + CREATE TABLE IF NOT EXISTS entries ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + model TEXT NOT NULL, + fact_digest TEXT NOT NULL, + subject_key TEXT NOT NULL, + answer TEXT NOT NULL, + fact_json TEXT NOT NULL, + manifest_digest TEXT NOT NULL, + state TEXT NOT NULL, + receipt_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')) + ); + CREATE INDEX IF NOT EXISTS entries_model_state ON entries(model, state); + """) + self.db.commit() + + def close(self): + self.db.close() + + def require_safe(self, model: str, fact: Fact) -> None: + pending = self.db.execute("SELECT id, state FROM entries WHERE model=? AND state IN ('inflight','needs_recovery')", (model,)).fetchall() + if pending: + raise LedgerError(f"model has unresolved write records {[int(row['id']) for row in pending]}; recovery required") + entries = self.db.execute("SELECT answer, fact_digest FROM entries WHERE model=? AND subject_key=? AND state='committed'", (model, fact.key)).fetchall() + for row in entries: + if normalized(row["answer"]) != normalized(fact.answer): + raise LedgerError("contradictory fact about the same subject/relation; explicit delete and independent validation required") + if row["fact_digest"] == fact.digest: + raise LedgerError("identical fact already committed; teaching again is not idempotent") + raise LedgerError("subject/relation already learned with different evidence; review required") + + def retained(self, model: str) -> tuple[Fact, ...]: + entries = self.db.execute("SELECT fact_json FROM entries WHERE model=? AND state='committed' ORDER BY id", (model,)).fetchall() + result = [] + for row in entries: + value = json.loads(row["fact_json"]) + value["questions"] = tuple(value["questions"]) + value["near_misses"] = tuple(value["near_misses"]) + result.append(Fact(**value)) + return tuple(result) + + def begin(self, model: str, manifest_digest: str, fact: Fact) -> int: + self.require_safe(model, fact) + with self.db: + cursor = self.db.execute("INSERT INTO entries(model, fact_digest, subject_key, answer, fact_json, manifest_digest, state) VALUES(?,?,?,?,?,?,?)", ( + model, fact.digest, fact.key, fact.answer, json.dumps(asdict(fact), ensure_ascii=False), manifest_digest, "inflight", + )) + return int(cursor.lastrowid) + + def finish(self, entry_id: int, state: str, receipt: dict) -> None: + if state not in {"committed", "skipped", "rejected", "rolled_back", "needs_recovery"}: + raise LedgerError("invalid final state") + with self.db: + cursor = self.db.execute("UPDATE entries SET state=?, receipt_json=?, updated_at=strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id=? AND state='inflight'", ( + state, json.dumps(receipt, sort_keys=True, ensure_ascii=False), entry_id, + )) + if cursor.rowcount != 1: + raise LedgerError("no matching inflight entry") + + def history(self, model: str | None = None) -> list[dict]: + if model: + rows = self.db.execute("SELECT id, model, subject_key, state, receipt_json, created_at FROM entries WHERE model=? ORDER BY id", (model,)) + else: + rows = self.db.execute("SELECT id, model, subject_key, state, receipt_json, created_at FROM entries ORDER BY id") + return [{**dict(row), "receipt": json.loads(row["receipt_json"])} for row in rows] diff --git a/tools/living_weights_v2/schema.py b/tools/living_weights_v2/schema.py new file mode 100644 index 00000000000..24862e5e61c --- /dev/null +++ b/tools/living_weights_v2/schema.py @@ -0,0 +1,123 @@ +from __future__ import annotations + +import hashlib +import json +from dataclasses import dataclass +from pathlib import Path +from typing import Any + + +class ManifestError(ValueError): + pass + + +def normalized(value: str) -> str: + return " ".join(value.casefold().split()) + + +def _string(value: Any, name: str, limit: int = 4096) -> str: + if not isinstance(value, str) or not value.strip() or len(value) > limit: + raise ManifestError(f"{name} must be a nonempty string of at most {limit} characters") + return value.strip() + + +def _fields(obj: Any, required: set[str], optional: set[str], name: str) -> dict: + if not isinstance(obj, dict): + raise ManifestError(f"{name} must be an object") + missing = required - obj.keys() + unknown = obj.keys() - required - optional + if missing or unknown: + raise ManifestError(f"{name}: missing {sorted(missing)}; unknown {sorted(unknown)}") + return obj + + +def _questions(value: Any, name: str, min_count: int = 1) -> tuple[str, ...]: + if not isinstance(value, list) or not min_count <= len(value) <= 64: + raise ManifestError(f"{name} must contain {min_count} to 64 questions") + result = tuple(_string(item, name, 1000) for item in value) + if len(set(map(normalized, result))) != len(result): + raise ManifestError(f"{name} contains duplicate questions") + return result + + +@dataclass(frozen=True) +class Fact: + subject: str + relation: str + answer: str + text: str + evidence: str + questions: tuple[str, ...] + near_misses: tuple[str, ...] + + @property + def key(self) -> str: + return normalized(self.subject) + "\x1f" + normalized(self.relation) + + @property + def digest(self) -> str: + fields = [self.subject, self.relation, self.answer, self.text, self.evidence] + return hashlib.sha256(json.dumps(fields, ensure_ascii=False).encode()).hexdigest() + + +@dataclass(frozen=True) +class Manifest: + model: str + asserted_by_user: bool + facts: tuple[Fact, ...] + anchors: tuple[str, ...] + source: str + digest: str + + +def _reject_duplicates(pairs: list[tuple[str, Any]]) -> dict: + result = {} + for key, value in pairs: + if key in result: + raise ManifestError(f"duplicate JSON key: {key}") + result[key] = value + return result + + +def load_manifest(path: Path) -> Manifest: + try: + raw = path.read_bytes() + if len(raw) > 1024 * 1024: + raise ManifestError("manifest exceeds 1 MiB") + data = json.loads(raw, object_pairs_hook=_reject_duplicates) + except (OSError, json.JSONDecodeError) as exc: + raise ManifestError(str(exc)) from exc + obj = _fields(data, {"schema_version", "model", "asserted_by_user", "facts", "anchors", "source"}, set(), "manifest") + if type(obj["schema_version"]) is not int or obj["schema_version"] != 1: + raise ManifestError("schema_version must be 1") + if obj["asserted_by_user"] is not True: + raise ManifestError("asserted_by_user must be true; evidence is user-supplied, not automatically verified") + if not isinstance(obj["facts"], list) or not 1 <= len(obj["facts"]) <= 128: + raise ManifestError("facts must contain 1 to 128 entries") + facts = [] + keys = set() + for i, raw_fact in enumerate(obj["facts"]): + entry = _fields(raw_fact, {"subject", "relation", "answer", "text", "evidence", "questions", "near_misses"}, set(), f"fact[{i}]") + fact = Fact( + subject=_string(entry["subject"], "subject", 256), + relation=_string(entry["relation"], "relation", 128), + answer=_string(entry["answer"], "answer", 256), + text=_string(entry["text"], "text", 1024), + evidence=_string(entry["evidence"], "evidence", 8192), + questions=_questions(entry["questions"], "questions", 2), + near_misses=_questions(entry["near_misses"], "near_misses", 1), + ) + if normalized(fact.answer) not in normalized(fact.text): + raise ManifestError(f"fact[{i}] answer must occur in text") + if fact.key in keys: + raise ManifestError(f"fact[{i}] duplicates a subject/relation in this manifest") + keys.add(fact.key) + facts.append(fact) + return Manifest( + model=_string(obj["model"], "model", 256), + asserted_by_user=True, + facts=tuple(facts), + anchors=_questions(obj["anchors"], "anchors", 1), + source=_string(obj["source"], "source", 2048), + digest=hashlib.sha256(raw).hexdigest(), + ) diff --git a/tools/living_weights_v2/transport.py b/tools/living_weights_v2/transport.py new file mode 100644 index 00000000000..27681560332 --- /dev/null +++ b/tools/living_weights_v2/transport.py @@ -0,0 +1,180 @@ +from __future__ import annotations + +import ipaddress +import json +import socket +import urllib.error +import urllib.parse +import urllib.request +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Iterator + + +class TransportError(RuntimeError): + pass + + +SSE_LINE_LIMIT = 1024 * 1024 +SSE_STREAM_LIMIT = 4 * 1024 * 1024 +SSE_EVENT_LIMIT = 4096 +# The native graph's fact states (zig/src/server/slide_graph.zig State); anything else is an unknown schema. +GRAPH_STATES = frozenset({"queued", "learning", "learned", "missed", "replaced", "deleting", "deleted"}) + + +def checked_graph(facts) -> dict[int, dict]: + if not isinstance(facts, (list, tuple)): + raise TransportError("unrecognized graph schema: missing facts array") + result = {} + for fact in facts: + if not isinstance(fact, dict) or type(fact.get("id")) is not int or fact["id"] <= 0: + raise TransportError("unrecognized graph fact") + if type(fact.get("state")) is not str or fact["state"] not in GRAPH_STATES: + raise TransportError(f"graph fact {fact['id']} has an unrecognized state") + if fact["id"] in result: + raise TransportError("duplicate graph fact ID") + result[fact["id"]] = fact + return result + + +@dataclass(frozen=True) +class Event: + kind: str + data: dict[str, Any] + + +class _RejectRedirects(urllib.request.HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + # Every request carries a key for the configured origin, so redirects must fail before another request. + return None + + +class Client: + def __init__(self, base_url: str, api_key_file: Path, allow_remote: bool = False, timeout: float = 600): + parsed = urllib.parse.urlsplit(base_url) + if parsed.scheme not in {"http", "https"} or not parsed.hostname or parsed.path not in {"", "/"} or parsed.query or parsed.fragment or parsed.username: + raise TransportError("base URL must be an HTTP(S) origin with no path, query, or credentials") + if not allow_remote: + try: + if not ipaddress.ip_address(parsed.hostname).is_loopback: + raise TransportError("only literal loopback addresses allowed without --allow-remote") + except ValueError as exc: + raise TransportError("use a literal loopback IP or explicitly allow remote access") from exc + try: + key = api_key_file.read_text(encoding="utf-8").strip() + except OSError as exc: + raise TransportError(f"cannot read key file: {exc.strerror}") from exc + if not key or "\n" in key or "\r" in key: + raise TransportError("API key file must contain one nonempty line") + self.base_url = base_url.rstrip("/") + self.timeout = timeout + self.headers = {"Authorization": "Bearer " + key, "Accept": "application/json"} + # Loopback requests never go through an ambient http_proxy/https_proxy, which would receive the key. + handlers = [_RejectRedirects()] if allow_remote else [urllib.request.ProxyHandler({}), _RejectRedirects()] + self._opener = urllib.request.build_opener(*handlers) + + def _open(self, path: str, method: str = "GET", payload: dict | None = None): + data = json.dumps(payload).encode() if payload is not None else None + headers = dict(self.headers) + if data is not None: + headers["Content-Type"] = "application/json" + request = urllib.request.Request(self.base_url + path, data=data, headers=headers, method=method) + try: + return self._opener.open(request, timeout=self.timeout) + except (urllib.error.URLError, TimeoutError, socket.timeout) as exc: + if isinstance(exc, urllib.error.HTTPError): + raise TransportError(f"HTTP {exc.code} from {path}") from exc + raise TransportError(f"request to {path} failed: {type(exc).__name__}") from exc + + def json(self, path: str, method: str = "GET", payload: dict | None = None) -> dict: + with self._open(path, method, payload) as response: + raw = response.read(4 * 1024 * 1024 + 1) + if len(raw) > 4 * 1024 * 1024: + raise TransportError("JSON response exceeds 4 MiB") + try: + result = json.loads(raw) + if not isinstance(result, dict): + raise ValueError("expected JSON object") + return result + except (ValueError, UnicodeError) as exc: + raise TransportError("malformed JSON response") from exc + + def events(self, path: str, method: str, payload: dict) -> Iterator[Event]: + received_done = False + kept = 0 + count = 0 + with self._open(path, method, payload) as response: + kind = "message" + lines = [] + while binary_line := response.readline(SSE_LINE_LIMIT + 1): + if len(binary_line) > SSE_LINE_LIMIT: + raise TransportError("oversized SSE line") + try: + line = binary_line.decode("utf-8").rstrip("\r\n") + except UnicodeDecodeError as exc: + raise TransportError("invalid UTF-8 in SSE") from exc + if not line: + if not lines: + kind = "message" + continue + content = "\n".join(lines) + lines = [] + if content == "[DONE]": + received_done = True + break + try: + parsed = json.loads(content) + except json.JSONDecodeError as exc: + raise TransportError("malformed SSE JSON") from exc + if not isinstance(parsed, dict): + raise TransportError("SSE payload must be a JSON object") + kept += len(content) + count += 1 + if kept > SSE_STREAM_LIMIT or count > SSE_EVENT_LIMIT: + raise TransportError("SSE stream exceeds 4 MiB or 4096 events") + actual_kind = str(parsed.get("event", kind)) if kind == "message" else kind + yield Event(actual_kind, parsed) + kind = "message" + elif line.startswith("event:"): + kind = line[6:].strip() + elif line.startswith("data:"): + lines.append(line[5:].lstrip(" ")) + if sum(map(len, lines)) > SSE_LINE_LIMIT: + raise TransportError("oversized SSE event") + if lines and "\n".join(lines) == "[DONE]": + received_done = True + if not received_done: + raise TransportError("SSE stream ended without [DONE]") + + def chat(self, model: str, question: str) -> str: + result = self.json("/v1/chat/completions", "POST", { + "model": model, + "messages": [{"role": "user", "content": question}], + "temperature": 0, + "max_tokens": 128, + }) + try: + value = result["choices"][0]["message"]["content"] + if not isinstance(value, str): + raise TypeError("content is not a string") + return value + except (KeyError, IndexError, TypeError) as exc: + raise TransportError("chat response does not contain string content") from exc + + def models(self) -> set[str]: + response = self.json("/v1/models") + try: + return {str(entry["id"]) for entry in response["data"]} + except (TypeError, ValueError, KeyError) as exc: + raise TransportError("invalid model listing") from exc + + def graph(self) -> dict[int, dict]: + return checked_graph(self.json("/v1/slide/graph").get("facts")) + + def teach(self, text: str) -> tuple[Event, ...]: + return tuple(self.events("/v1/slide/learn", "POST", {"text": text})) + + def delete(self, ids: list[int], reason: str) -> tuple[Event, ...]: + if not ids or len(ids) > 256 or len(ids) != len(set(ids)) or any(type(i) is not int or i <= 0 for i in ids): + raise ValueError("invalid deletion IDs") + return tuple(self.events("/v1/slide/facts", "DELETE", {"ids": ids, "reason": reason})) diff --git a/tools/tests/test_bench_stream.py b/tools/tests/test_bench_stream.py index cfd3934acff..dc0a586f8d5 100644 --- a/tools/tests/test_bench_stream.py +++ b/tools/tests/test_bench_stream.py @@ -20,6 +20,13 @@ WORDS = ["Fib", "onacci", " adds", " the", " two", " before", " it", "."] +class SpeculativeReceipt(unittest.TestCase): + def test_keeps_round_metrics(self): + reply = bench_stream.Collector(0) + reply.speculative = {"rounds": 3, "tokens_per_round": 2.5} + self.assertEqual(reply.speculative, reply.receipt()["speculative"]) + + def content(*words, choice=0): return [(choice, "content", w) for w in words] diff --git a/tools/tests/test_living_weights_v2_cli.py b/tools/tests/test_living_weights_v2_cli.py new file mode 100644 index 00000000000..c2441183aa3 --- /dev/null +++ b/tools/tests/test_living_weights_v2_cli.py @@ -0,0 +1,57 @@ +from __future__ import annotations + +import json +import tempfile +import unittest +from contextlib import redirect_stdout, redirect_stderr +from io import StringIO +from pathlib import Path + +import sys + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) # tools/, as the other tool tests do +from living_weights_v2.__main__ import main + + +class CliTests(unittest.TestCase): + def setUp(self): + self.dir = tempfile.TemporaryDirectory() + self.manifest = Path(self.dir.name) / "lesson.json" + self.manifest.write_text(json.dumps({ + "schema_version": 1, "model": "local-model", "asserted_by_user": True, + "source": "test", "anchors": ["What is 2+3?"], + "facts": [{"subject": "Quillmoor", "relation": "office", "answer": "Sheffield", + "text": "Quillmoor is in Sheffield.", "evidence": "test", + "questions": ["Where is Quillmoor?", "Which city has Quillmoor?"], + "near_misses": ["Where is Brackenforth?"]}] + })) + + def tearDown(self): + self.dir.cleanup() + + def test_plan(self): + output = StringIO() + with redirect_stdout(output): + result = main(["plan", str(self.manifest)]) + self.assertEqual(result, 0) + parsed = json.loads(output.getvalue()) + self.assertFalse(parsed["mutates_weights"]) + self.assertEqual(parsed["facts"][0]["positive_count"], 2) + + def test_status_empty_ledger(self): + output = StringIO() + with redirect_stdout(output): + result = main(["status", "--ledger", str(Path(self.dir.name) / "new.sqlite3")]) + self.assertEqual(result, 0) + self.assertEqual(json.loads(output.getvalue()), []) + + def test_bad_manifest_exits_nonzero(self): + stderr = StringIO() + with redirect_stderr(stderr): + result = main(["plan", str(Path(self.dir.name) / "missing.json")]) + self.assertEqual(result, 4) + self.assertIn("living_weights_v2:", stderr.getvalue()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_living_weights_v2_controller.py b/tools/tests/test_living_weights_v2_controller.py new file mode 100644 index 00000000000..1211daf2565 --- /dev/null +++ b/tools/tests/test_living_weights_v2_controller.py @@ -0,0 +1,292 @@ +from __future__ import annotations + +import tempfile +import unittest +from copy import deepcopy +from pathlib import Path + +import sys + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) # tools/, as the other tool tests do +from living_weights_v2.controller import Controller, LearningError, _changes +from living_weights_v2.ledger import Ledger, LedgerError, exclusive_file +from living_weights_v2.schema import Fact, Manifest +from living_weights_v2.transport import Event, TransportError + + +def fact(answer="Sheffield"): + return Fact("Quillmoor Labs", "headquarters", answer, + f"Quillmoor Labs is headquartered in {answer}.", "approved", + ("Where is Quillmoor Labs?", "Which city is Quillmoor Labs in?"), + ("Where is Brackenforth Labs?",)) + + +def manifest(f): + return Manifest("local-model", True, (f,), ("What is two plus three?",), "approved handbook", "abcd" * 16) + + +class FakeClient: + def __init__(self): + self.records = {} + self.reply = "Unknown" + self.saved = True + self.recalled = True + self.emit_id = True + self.fail_delete = False + self.fail_on_chat_after = False + self.teach_count = 0 + self.delete_count = 0 + self.answer_anchors_after = "5" + self.extraneous_fact = False + + def models(self): + return {"local-model"} + + def graph(self): + return {k: dict(v) for k, v in self.records.items()} + + def chat(self, model, question): + if self.teach_count and self.fail_on_chat_after: + raise TransportError("simulated connection drop after edit") + if "two plus three" in question: + return self.answer_anchors_after if self.teach_count else "5" + if "Brackenforth" in question: + return "Unknown" + if self.teach_count and not self.records.get(1, {}).get("state") == "deleted": + return self.reply if "Quillmoor" in question else "Unknown" + return "Unknown" + + def teach(self, text): + self.teach_count += 1 + if self.recalled: + self.records[1] = {"id": 1, "state": "learned", "text": text} + if self.extraneous_fact: + self.records[2] = {"id": 2, "state": "learned", "text": "other concurrent fact"} + return tuple( + [Event("learned", {"recalled": self.recalled, **({"id": 1} if self.emit_id else {})})] + + ([Event("saved", {"files": 1})] if self.saved else [Event("failed", {"phase": "saving"})]) + ) + + def delete(self, ids, reason): + self.delete_count += 1 + if self.fail_delete: + return (Event("forgot", {"deleted": False}),) + for item_id in ids: + self.records[item_id]["state"] = "deleted" + return tuple(Event("forgot", {"deleted": True}) for _ in ids) + + +class ControllerTests(unittest.TestCase): + def setUp(self): + self.dir = tempfile.TemporaryDirectory() + self.ledger = Ledger(Path(self.dir.name) / "ledger.sqlite3") + self.client = FakeClient() + self.controller = Controller(self.client, self.ledger) + + def tearDown(self): + self.ledger.close() + self.dir.cleanup() + + def test_success_and_idempotency(self): + self.client.reply = "Sheffield" + result = self.controller.teach(manifest(fact())) + self.assertEqual(result[0]["state"], "committed") + self.assertEqual(self.client.teach_count, 1) + self.assertEqual(len(self.ledger.retained("local-model")), 1) + with self.assertRaises(LedgerError): + self.controller.teach(manifest(fact())) + + def test_native_rechecks_and_links_allow_two_committed_lessons(self): + first = fact() + second = Fact("Quillmoor Labs", "mascot", "Kestrel", + "Quillmoor Labs has a mascot called Kestrel.", "approved", + ("What is Quillmoor Labs' mascot?", "Name Quillmoor Labs' mascot."), + ("What is Brackenforth Labs' mascot?",)) + + class NativeGraphClient(FakeClient): + def graph(self): + return deepcopy(self.records) + + def chat(self, model, question): + if "two plus three" in question: + return "5" + for item_id, lesson in enumerate((first, second), 1): + if question in lesson.questions and item_id in self.records: + return lesson.answer + return "Unknown" + + def teach(self, text): + self.teach_count += 1 + item_id = self.teach_count + for old in self.records.values(): + old["checks"] += 1 + old["recalled"] = True + old["links"].append(item_id) + self.records[item_id] = {"id": item_id, "state": "learned", "text": text, + "checks": 1, "recalled": True, + "links": list(range(1, item_id))} + return (Event("learned", {"id": item_id, "recalled": True}), + Event("saved", {"saved": True})) + + client = NativeGraphClient() + plan = Manifest("local-model", True, (first, second), manifest(first).anchors, "approved", "sequence") + result = Controller(client, self.ledger).teach(plan) + self.assertEqual([r["state"] for r in result], ["committed", "committed"]) + self.assertEqual(client.delete_count, 0) + self.assertEqual(len(self.ledger.retained("local-model")), 2) + self.assertEqual(result[1]["new_graph_ids"], [2]) + self.assertEqual(result[1]["assessment"]["retained_failures"], ()) + + def test_graph_metadata_changes_preserve_new_id_detection(self): + before = {17: {"id": 17, "text": "old fact", "state": "learned", + "checks": 1, "recalled": True, "links": []}} + after = deepcopy(before) + after[17].update(checks=2, recalled=False, links=[18]) + after[18] = {"id": 18, "text": "new fact", "state": "learned"} + self.assertEqual(_changes(before, after), [18]) + + def test_graph_identity_state_placement_and_unknown_changes_fail_closed(self): + original = {"id": 17, "text": "old fact", "source": "chat", "at": 123, + "state": "learned", "neurons": [{"layer": 1, "neuron": 2, "key": "gate"}]} + changes = {"id": 18, "text": "different fact", "source": "document", "at": 456, + "state": "deleted", "neurons": [], "unknown_field": "unexpected"} + for field, value in changes.items(): + with self.subTest(field=field), self.assertRaises(LearningError): + _changes({17: original}, {17: {**original, field: value}}) + with self.assertRaises(LearningError): + _changes({17: original}, {}) + + def test_graph_mutation_still_requires_recovery_without_deleting(self): + self.client.records[17] = {"id": 17, "state": "learned", "text": "old fact"} + teach = self.client.teach + + def mutate(text): + events = teach(text) + self.client.records[17]["state"] = "deleted" + return events + + self.client.teach = mutate + self.client.reply = "Sheffield" + result = self.controller.teach(manifest(fact())) + self.assertEqual(result[0]["state"], "needs_recovery") + self.assertEqual(self.client.delete_count, 0) + with self.assertRaises(LedgerError): + self.controller.teach(manifest(fact("Cambridge"))) + + def test_recheck_metadata_does_not_hide_retained_answer_regression(self): + old = Fact("Pinebridge Labs", "headquarters", "Cambridge", + "Pinebridge Labs is headquartered in Cambridge.", "approved", + ("Where is Pinebridge Labs?", "Which city is Pinebridge Labs in?"), + ("Where is an unrelated lab?",)) + entry = self.ledger.begin("local-model", "earlier-manifest", old) + self.ledger.finish(entry, "committed", {}) + self.client.records[17] = {"id": 17, "state": "learned", "text": old.text, + "checks": 1, "recalled": True, "links": []} + self.client.reply = "Sheffield" + chat, teach = self.client.chat, self.client.teach + + def changed_chat(model, question): + if question in old.questions: + active = self.client.records.get(1, {}).get("state") == "learned" + return "Unknown" if active else old.answer + return chat(model, question) + + def changed_teach(text): + events = teach(text) + self.client.records[17].update(checks=2, recalled=False, links=[1]) + return events + + self.client.chat, self.client.teach = changed_chat, changed_teach + result = self.controller.teach(manifest(fact()))[0] + self.assertEqual(result["state"], "rolled_back") + self.assertEqual(result["assessment"]["retained_failures"], old.questions) + self.assertEqual(self.client.delete_count, 1) + + def test_paraphrase_failure_calls_native_delete(self): + self.client.reply = "Unknown" + result = self.controller.teach(manifest(fact())) + self.assertEqual(result[0]["state"], "rolled_back") + self.assertEqual(self.client.delete_count, 1) + self.assertEqual(self.client.records[1]["state"], "deleted") + + def test_failed_delete_blocks_future_writes(self): + self.client.reply = "Unknown" + self.client.fail_delete = True + result = self.controller.teach(manifest(fact())) + self.assertEqual(result[0]["state"], "needs_recovery") + with self.assertRaises(LedgerError): + self.controller.teach(manifest(fact("Cambridge"))) + + def test_crash_after_write_is_durable_unknown(self): + self.client.reply = "Sheffield" + self.client.fail_on_chat_after = True + result = self.controller.teach(manifest(fact())) + self.assertEqual(result[0]["state"], "needs_recovery") + self.assertEqual(len(self.ledger.history("local-model")), 1) + + def test_unknown_native_owner_fails_closed(self): + self.client.reply = "Sheffield" + self.client.emit_id = False + self.client.extraneous_fact = True + result = self.controller.teach(manifest(fact())) + self.assertEqual(result[0]["state"], "needs_recovery") + self.assertEqual(self.client.delete_count, 0) + + def test_unknown_graph_states_stop_before_any_lesson(self): + for state in ({}, {"state": 3}, {"state": "archived"}): + record = {"id": 17, "text": "old", **state} + with self.subTest(record=record): + self.client.records = {17: record} + self.client.reply = "Sheffield" + with self.assertRaisesRegex(TransportError, "unrecognized state"): + self.controller.teach(manifest(fact())) + self.assertEqual(self.client.teach_count, 0) + self.assertEqual(self.ledger.history(), []) + + def test_cannot_alter_preexisting_graph(self): + self.client.records = {17: {"id": 17, "state": "deleting", "text": "old"}} + with self.assertRaises(LearningError): + self.controller.teach(manifest(fact())) + + def test_unsupported_model_refused(self): + f = fact() + plan = Manifest("different", True, (f,), ("What is two plus three?",), "source", "e" * 64) + with self.assertRaises(LearningError): + self.controller.teach(plan) + + def test_answer_baseline_does_not_write(self): + self.client.reply = "Sheffield" + original_chat = self.client.chat + self.client.chat = lambda model, question: "Sheffield" if "Quillmoor" in question else original_chat(model, question) + result = self.controller.teach(manifest(fact())) + self.assertEqual(result[0]["state"], "already_answers") + self.assertEqual(self.client.teach_count, 0) + + def test_native_rejected_no_graph_delta(self): + self.client.recalled = False + result = self.controller.teach(manifest(fact())) + self.assertEqual(result[0]["state"], "rejected") + self.assertEqual(self.client.delete_count, 0) + + def test_conflicting_answer_same_subject_rejected(self): + self.client.reply = "Sheffield" + self.assertEqual(self.controller.teach(manifest(fact()))[0]["state"], "committed") + with self.assertRaises(LedgerError): + self.ledger.require_safe("local-model", fact("Cambridge")) + + def test_regression_to_anchor_triggers_delete(self): + self.client.reply = "Sheffield" + self.client.answer_anchors_after = "four" + result = self.controller.teach(manifest(fact())) + self.assertEqual(result[0]["state"], "needs_recovery") + + def test_file_lock_refuses_concurrent_writer(self): + lock = Path(self.dir.name) / "writing.lock" + with exclusive_file(lock): + with self.assertRaises(LedgerError): + with exclusive_file(lock): + pass + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_living_weights_v2_evaluator.py b/tools/tests/test_living_weights_v2_evaluator.py new file mode 100644 index 00000000000..93f1de0739f --- /dev/null +++ b/tools/tests/test_living_weights_v2_evaluator.py @@ -0,0 +1,44 @@ +from __future__ import annotations + +import unittest + +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) # tools/, as the other tool tests do +from living_weights_v2.evaluator import evaluate +from living_weights_v2.schema import Fact, Manifest + + +class ReadOnlyEvaluatorTests(unittest.TestCase): + def setUp(self): + fact = Fact("Quillmoor Labs", "headquarters", "Sheffield", + "Quillmoor Labs is headquartered in Sheffield.", "approved", + ("Where is Quillmoor?", "Which city is Quillmoor in?"), + ("Where is Brackenforth?",)) + self.manifest = Manifest("model", True, (fact,), ("What is 2 plus 3?",), "source", "digest") + + def test_scores_and_keeps_anchor(self): + class Client: + def chat(self, model, question): + if "Brackenforth" in question: + return "Unknown" + if "plus" in question: + return "5" + return "Sheffield" + report = evaluate(self.manifest, Client()) + self.assertEqual(report["positive_matches"], 2) + self.assertEqual(report["possible_near_miss_leaks"], 0) + self.assertEqual(report["anchors"][0]["answer"], "5") + self.assertFalse(report["weights_changed"]) + + def test_detects_leaks(self): + class Client: + def chat(self, model, question): + return "Sheffield" + report = evaluate(self.manifest, Client()) + self.assertEqual(report["possible_near_miss_leaks"], 1) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_living_weights_v2_ledger.py b/tools/tests/test_living_weights_v2_ledger.py new file mode 100644 index 00000000000..29a95f1f9fd --- /dev/null +++ b/tools/tests/test_living_weights_v2_ledger.py @@ -0,0 +1,134 @@ +from __future__ import annotations + +import os +import sqlite3 +import stat +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +import sys + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) # tools/, as the other tool tests do +from living_weights_v2 import ledger as ledger_module +from living_weights_v2.ledger import Ledger, LedgerError + + +def mode(path: Path) -> int: + return stat.S_IMODE(os.lstat(path).st_mode) + + +def plant(path: Path) -> None: + """A file anyone may read and write, as another process could leave it.""" + descriptor = os.open(str(path), os.O_CREAT | os.O_WRONLY, 0o666) + os.close(descriptor) + os.chmod(path, 0o666) + + +@unittest.skipUnless(os.name == "posix", "file modes are POSIX") +class LedgerPrivacyTests(unittest.TestCase): + def setUp(self): + self.dir = tempfile.TemporaryDirectory() + self.umask = os.umask(0o022) + self.journal = Path(self.dir.name) / "journal" + self.path = self.journal / "ledger.sqlite3" + + def tearDown(self): + os.umask(self.umask) + self.dir.cleanup() + + def test_new_journal_is_private_under_umask_022(self): + path = Path(self.dir.name) / "state" / "tensorfold" / "ledger.sqlite3" + ledger = Ledger(path) + try: + columns = "model, fact_digest, subject_key, answer, fact_json, manifest_digest, state" + ledger.db.execute(f"INSERT INTO entries({columns}) VALUES('m', 'd', 'k', 'Sheffield', '{{}}', 'm', 'committed')") + ledger.db.commit() + self.assertEqual(mode(path.parent), 0o700) + self.assertEqual(mode(path.parent.parent), 0o700) + for item in (path, Path(str(path) + "-wal"), Path(str(path) + "-shm")): + with self.subTest(file=item.name): + self.assertTrue(item.exists()) + self.assertEqual(mode(item), 0o600) + finally: + ledger.close() + + def test_existing_journal_open_to_others_is_refused(self): + self.journal.mkdir(mode=0o700) + sqlite3.connect(self.path).close() + for suffix in ("", "-wal", "-shm"): + item = Path(str(self.path) + suffix) + item.touch() + os.chmod(self.path, 0o600) + for loose in (0o644, 0o640, 0o604): + with self.subTest(file=item.name, mode=oct(loose)): + os.chmod(item, loose) + with self.assertRaisesRegex(LedgerError, "mode 600"): + Ledger(self.path).close() + os.chmod(item, 0o600) + Ledger(self.path).close() + + def test_a_shared_or_linked_directory_is_refused(self): + shared = Path(self.dir.name) / "shared" + shared.mkdir(mode=0o755) + with self.assertRaisesRegex(LedgerError, "mode 700"): + Ledger(shared / "ledger.sqlite3").close() + self.assertEqual(mode(shared), 0o755) + self.assertFalse((shared / "ledger.sqlite3").exists()) + private = Path(self.dir.name) / "private" + private.mkdir(mode=0o700) + link = Path(self.dir.name) / "link" + link.symlink_to(private) + with self.assertRaisesRegex(LedgerError, "mode 700"): + Ledger(link / "ledger.sqlite3").close() + + def test_a_linked_database_is_refused(self): + self.journal.mkdir(mode=0o700) + target = Path(self.dir.name) / "elsewhere.sqlite3" + self.path.symlink_to(target) + with self.assertRaisesRegex(LedgerError, "not a link"): + Ledger(self.path).close() + self.assertFalse(target.exists()) + + def test_a_database_swapped_in_before_sqlite_opens_is_refused(self): + connect = sqlite3.connect + + def swap_then_connect(path, *args, **kwargs): + spare = self.journal / "spare" + plant(spare) + os.replace(spare, self.path) + return connect(path, *args, **kwargs) + + with mock.patch.object(ledger_module.sqlite3, "connect", swap_then_connect): + with self.assertRaises(LedgerError): + Ledger(self.path) + self.assertEqual(os.path.getsize(self.path), 0, "the journal wrote into the planted file") + + def test_a_database_created_in_the_gap_is_refused(self): + private_dir = ledger_module.private_dir + + def check_then_plant(directory): + identity = private_dir(directory) + plant(self.path) + return identity + + with mock.patch.object(ledger_module, "private_dir", check_then_plant): + with self.assertRaisesRegex(LedgerError, "mode 600"): + Ledger(self.path) + self.assertEqual(os.path.getsize(self.path), 0, "the journal wrote into the planted file") + + def test_a_wal_planted_before_sqlite_opens_is_refused(self): + connect = sqlite3.connect + + def plant_then_connect(path, *args, **kwargs): + plant(Path(str(self.path) + "-wal")) + return connect(path, *args, **kwargs) + + with mock.patch.object(ledger_module.sqlite3, "connect", plant_then_connect): + with self.assertRaisesRegex(LedgerError, "mode 600"): + Ledger(self.path) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_living_weights_v2_schema.py b/tools/tests/test_living_weights_v2_schema.py new file mode 100644 index 00000000000..28e62e9e877 --- /dev/null +++ b/tools/tests/test_living_weights_v2_schema.py @@ -0,0 +1,136 @@ +from __future__ import annotations + +import json +import tempfile +import unittest +from pathlib import Path + +import sys + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) # tools/, as the other tool tests do +from living_weights_v2.assessment import Observation, assess, contains_answer, affirmative_answer +from living_weights_v2.schema import ManifestError, load_manifest + + +FACT = { + "subject": "Quillmoor Labs", "relation": "headquarters", "answer": "Sheffield", + "text": "Quillmoor Labs is headquartered in Sheffield.", "evidence": "User approval", + "questions": ["Where is Quillmoor Labs located?", "Which city is Quillmoor Labs in?"], + "near_misses": ["Where is Quillmoor's marketing team?"] +} + + +def manifest(**overrides): + data = {"schema_version": 1, "model": "local-model", "asserted_by_user": True, + "facts": [FACT], "anchors": ["What is 2+3?"], "source": "A fictional handbook"} + data.update(overrides) + return data + + +class ManifestTests(unittest.TestCase): + def load(self, data): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "plan.json" + path.write_text(json.dumps(data), encoding="utf-8") + return load_manifest(path) + + def test_load_and_hash(self): + result = self.load(manifest()) + self.assertEqual(result.model, "local-model") + self.assertEqual(result.facts[0].answer, "Sheffield") + self.assertEqual(len(result.digest), 64) + self.assertEqual(result.facts[0].key, "quillmoor labs\x1fheadquarters") + + def test_requires_user_attestation(self): + for value in (False, 1, "true", None): + with self.subTest(value=value), self.assertRaises(ManifestError): + self.load(manifest(asserted_by_user=value)) + + def test_unknown_and_missing_keys(self): + with self.assertRaises(ManifestError): + self.load(manifest(unreviewed="payload")) + item = manifest() + del item["source"] + with self.assertRaises(ManifestError): + self.load(item) + + def test_duplicate_claims_conflict(self): + with self.assertRaises(ManifestError): + self.load(manifest(facts=[FACT, FACT])) + + def test_duplicate_questions(self): + fact = {**FACT, "questions": ["Where?", " where? "]} + with self.assertRaises(ManifestError): + self.load(manifest(facts=[fact])) + + def test_requires_answer_in_statement(self): + fact = {**FACT, "text": "Quillmoor Labs has a headquarters."} + with self.assertRaises(ManifestError): + self.load(manifest(facts=[fact])) + + def test_length_and_type_bounds(self): + for invalid in ([], "none", [{}] * 129): + with self.subTest(value=str(invalid)[:16]), self.assertRaises(ManifestError): + self.load(manifest(facts=invalid)) + + def test_rejects_duplicate_json_keys(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "plan.json" + path.write_text('{"schema_version":1,"schema_version":1}') + with self.assertRaises(ManifestError): + load_manifest(path) + + def test_rejects_oversized_input(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "plan.json" + path.write_text(" " * (1024 * 1024 + 1)) + with self.assertRaises(ManifestError): + load_manifest(path) + + +class AssessmentTests(unittest.TestCase): + def setUp(self): + self.fact = ManifestTests().load(manifest()).facts[0] + + def obs(self, question, answer): + return Observation(question, answer, "test") + + def test_boundary_matching(self): + self.assertTrue(contains_answer("It's Sheffield.", "Sheffield")) + self.assertFalse(contains_answer("Sheffieldish is elsewhere", "Sheffield")) + self.assertFalse(contains_answer("The answer is blank", "")) + self.assertTrue(contains_answer("New York, USA", "New York")) + + def test_negated_expected_answer_is_not_recall(self): + self.assertFalse(affirmative_answer("It is not Sheffield", "Sheffield")) + self.assertFalse(affirmative_answer("I am not sure, perhaps Sheffield", "Sheffield")) + self.assertTrue(affirmative_answer("It is Sheffield.", "Sheffield")) + + def test_passed(self): + result = assess(self.fact, (self.obs("negative", "Unknown"),), + (self.obs("positive", "In Sheffield"),), + (self.obs("negative", "Unknown"),), + (self.obs("anchor", "5"),), (self.obs("anchor", "5"),), ()) + self.assertTrue(result.passed) + + def test_leak_and_drift(self): + result = assess(self.fact, (self.obs("negative", "Unknown"),), + (self.obs("positive", "Not sure"),), + (self.obs("negative", "Sheffield"),), + (self.obs("anchor", "5"),), (self.obs("anchor", "6"),), ()) + self.assertFalse(result.passed) + self.assertEqual(result.leaks, ("negative",)) + self.assertEqual(len(result.drift), 2) + + def test_retained_failure(self): + result = assess(self.fact, (), (self.obs("p", "Sheffield"),), (), (), (), + ((self.fact, (self.obs("old", "unknown"),)),)) + self.assertEqual(result.retained_failures, ("old",)) + + def test_mismatched_probes_refused(self): + with self.assertRaises(ValueError): + assess(self.fact, (), (), (self.obs("extra", "x"),), (), (), ()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_living_weights_v2_transport.py b/tools/tests/test_living_weights_v2_transport.py new file mode 100644 index 00000000000..a3870e028dc --- /dev/null +++ b/tools/tests/test_living_weights_v2_transport.py @@ -0,0 +1,268 @@ +from __future__ import annotations + +import json +import os +import tempfile +import threading +import unittest +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path + +import sys + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) # tools/, as the other tool tests do +from unittest import mock + +from living_weights_v2.transport import Client, TransportError + +SSE_LINE_LIMIT = 1024 * 1024 # the documented per-line bound + + +class Handler(BaseHTTPRequestHandler): + def log_message(self, format, *args): + pass + + def do_GET(self): + self._reply({"data": [{"id": "local-model"}]} if self.path == "/v1/models" else {"facts": []}) + + def do_POST(self): + size = int(self.headers.get("Content-Length", "0")) + request = json.loads(self.rfile.read(size)) + if self.path == "/v1/chat/completions": + self._reply({"choices": [{"message": {"content": "Sheffield"}}]}) + return + if self.path == "/v1/slide/learn": + self.send_response(200) + self.send_header("Content-Type", "text/event-stream") + self.end_headers() + self.wfile.write(b'event: learned\ndata: {"recalled":true,"id":1}\n\nevent: saved\ndata: {"files":1}\n\ndata: [DONE]\n\n') + return + self._reply({"error": "unknown"}) + + def _reply(self, value): + body = json.dumps(value).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + +class TransportTests(unittest.TestCase): + def setUp(self): + self.dir = tempfile.TemporaryDirectory() + key_file = Path(self.dir.name) / "key" + key_file.write_text("secret\n") + self.key = key_file + self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + self.thread = threading.Thread(target=self.server.serve_forever, daemon=True) + self.thread.start() + self.base = f"http://127.0.0.1:{self.server.server_port}" + + def tearDown(self): + self.server.shutdown() + self.server.server_close() + self.thread.join(timeout=5) + self.dir.cleanup() + + def test_real_http_sse_and_chat(self): + client = Client(self.base, self.key) + self.assertEqual(client.models(), {"local-model"}) + self.assertEqual(client.graph(), {}) + self.assertEqual(client.chat("local-model", "Where?"), "Sheffield") + events = client.teach("Something") + self.assertEqual([e.kind for e in events], ["learned", "saved"]) + self.assertTrue(events[0].data["recalled"]) + + def test_loopback_only(self): + for url in ("https://example.org", "http://localhost:8080", "http://127.0.0.1/x", "file:///etc/passwd", "http://user:pass@127.0.0.1"): + with self.subTest(url=url), self.assertRaises(TransportError): + Client(url, self.key) + + def test_allow_remote_explicit(self): + client = Client("https://example.org", self.key, allow_remote=True) + self.assertEqual(client.base_url, "https://example.org") + + def test_redirects_never_forward_authenticated_requests(self): + received = [] + + class Destination(BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def do_GET(self): + received.append((self.command, self.headers.get("Authorization"))) + self.send_response(200) + self.send_header("Content-Length", "0") + self.end_headers() + + do_POST = do_GET + do_DELETE = do_GET + + destination = ThreadingHTTPServer(("127.0.0.1", 0), Destination) + destination_thread = threading.Thread(target=destination.serve_forever, daemon=True) + destination_thread.start() + + class Redirect(BaseHTTPRequestHandler): + code = 302 + location = f"http://127.0.0.1:{destination.server_port}/capture" + + def log_message(self, *args): + pass + + def do_GET(self): + if self.path == "/capture": + Destination.do_GET(self) + return + self.rfile.read(int(self.headers.get("Content-Length", "0"))) + self.send_response(self.code) + self.send_header("Location", self.location) + self.send_header("Content-Length", "0") + self.end_headers() + + do_POST = do_GET + do_DELETE = do_GET + + origin = ThreadingHTTPServer(("127.0.0.1", 0), Redirect) + origin_thread = threading.Thread(target=origin.serve_forever, daemon=True) + origin_thread.start() + try: + for allow_remote in (False, True): + client = Client(f"http://127.0.0.1:{origin.server_port}", self.key, allow_remote=allow_remote) + for location in (f"http://127.0.0.1:{destination.server_port}/capture", "/capture"): + Redirect.location = location + for code in (301, 302, 303, 307, 308): + Redirect.code = code + for method in ("GET", "POST", "DELETE"): + with self.subTest(remote=allow_remote, location=location, code=code, method=method): + with self.assertRaisesRegex(TransportError, f"HTTP {code}"): + with client._open("/redirect", method, {"text": "test"} if method != "GET" else None): + pass + self.assertEqual(received, [], "redirect destination received credentials") + finally: + for server in (origin, destination): + server.shutdown() + server.server_close() + origin_thread.join(timeout=5) + destination_thread.join(timeout=5) + + def test_missing_or_empty_key(self): + with self.assertRaises(TransportError): + Client(self.base, Path(self.dir.name) / "missing") + self.key.write_text("\n") + with self.assertRaises(TransportError): + Client(self.base, self.key) + + def test_sse_without_terminal_done_rejected(self): + class FakeClient(Client): + def _open(self, path, method="GET", payload=None): + from io import BytesIO + return BytesIO(b'event: learned\ndata: {"recalled":true}\n\n') + with self.assertRaises(TransportError): + tuple(FakeClient(self.base, self.key).events("/learn", "POST", {"text": "x"})) + + def test_invalid_sse_json_rejected(self): + class FakeClient(Client): + def _open(self, path, method="GET", payload=None): + from io import BytesIO + return BytesIO(b'event: saved\ndata: invalid\n\ndata: [DONE]\n\n') + with self.assertRaises(TransportError): + tuple(FakeClient(self.base, self.key).events("/learn", "POST", {"text": "x"})) + + + def test_loopback_requests_never_reach_an_ambient_proxy(self): + seen = [] + + class Proxy(BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def do_GET(self): + seen.append(self.headers.get("Authorization")) + body = b'{"data": [{"id": "via-proxy"}]}' + self.send_response(200) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + proxy = ThreadingHTTPServer(("127.0.0.1", 0), Proxy) + thread = threading.Thread(target=proxy.serve_forever, daemon=True) + thread.start() + url = f"http://127.0.0.1:{proxy.server_port}" + ambient = {name: url for name in ("http_proxy", "HTTP_PROXY", "https_proxy", "HTTPS_PROXY")} + ambient.update(no_proxy="", NO_PROXY="") + try: + with mock.patch.dict(os.environ, ambient): + self.assertEqual(Client(self.base, self.key).models(), {"local-model"}) + self.assertEqual(seen, [], "the proxy received the loopback request and its key") + finally: + proxy.shutdown() + proxy.server_close() + thread.join(timeout=5) + + def _stream(self, body: bytes): + reads = [] + + class Response: + def __init__(self): + self.at = 0 + + def readline(self, limit=-1): + end = body.find(b"\n", self.at) + end = len(body) if end < 0 else end + 1 + if limit is not None and limit >= 0: + end = min(end, self.at + limit) + line = body[self.at:end] + self.at = end + reads.append(len(line)) + return line + + def __iter__(self): + return iter(self.readline, b"") + + def __enter__(self): + return self + + def __exit__(self, *args): + return False + + class FakeClient(Client): + def _open(self, path, method="GET", payload=None): + return Response() + + return FakeClient(self.base, self.key), reads + + def test_sse_line_reads_are_bounded(self): + client, reads = self._stream(b"data: " + b"x" * (2 * SSE_LINE_LIMIT) + b"\n\ndata: [DONE]\n\n") + with self.assertRaisesRegex(TransportError, "oversized SSE line"): + client.teach("x") + self.assertLessEqual(max(reads), SSE_LINE_LIMIT + 1, "a whole oversized line was read before the size check") + + def test_sse_stream_kept_by_teach_is_bounded(self): + client, _ = self._stream(b"event: progress\ndata: {}\n\n" * 5000 + b"data: [DONE]\n\n") + with self.assertRaisesRegex(TransportError, "SSE stream exceeds"): + client.teach("x") + event = b'data: {"pad": "' + b"y" * (SSE_LINE_LIMIT - 64) + b'"}\n\n' + client, _ = self._stream(event * 5 + b"data: [DONE]\n\n") + with self.assertRaisesRegex(TransportError, "SSE stream exceeds"): + client.teach("x") + + def test_graph_states_are_checked(self): + for fact in ({"id": 1}, {"id": 1, "state": 2}, {"id": 1, "state": "archived"}): + class Graph(Handler): + def do_GET(self, fact=fact): + self._reply({"facts": [fact]}) + + server = ThreadingHTTPServer(("127.0.0.1", 0), Graph) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + with self.subTest(fact=fact), self.assertRaisesRegex(TransportError, "unrecognized state"): + Client(f"http://127.0.0.1:{server.server_port}", self.key).graph() + finally: + server.shutdown() + server.server_close() + thread.join(timeout=5) + +if __name__ == "__main__": + unittest.main() diff --git a/web/tensorfold_web/native.py b/web/tensorfold_web/native.py index da861fbb3c0..9d77d5bf046 100644 --- a/web/tensorfold_web/native.py +++ b/web/tensorfold_web/native.py @@ -43,7 +43,9 @@ def _stamp(path: str) -> tuple: MANAGED = {"--host": "TensorFold Web sets it (Settings, Share on the network)", "--port": "the engine address in Settings", "--context": "Longest conversation in Settings", "--thinking": "Thinking in Settings", "--no-thinking": "Thinking in Settings", "--dashboard": "TensorFold Web turns it on", - "--cortheon": "Web research in Settings, which says what leaves the machine"} + "--cortheon": "Web research in Settings, which says what leaves the machine", + # a config file can hold any serve flag, the ones above and the secret and learning ones among them + "--config": "a config file could set the flags TensorFold Web keeps to itself; add its flags here one by one"} # Living Weights: learning is turned on by TensorFold Web for a copy that learns, bound to loopback; never by hand LEARNING = ("--slide",) diff --git a/web/tests/test_native.py b/web/tests/test_native.py index fa9793e244c..22feef56d19 100644 --- a/web/tests/test_native.py +++ b/web/tests/test_native.py @@ -168,6 +168,13 @@ def test_extra_flags_are_checked_against_what_the_engine_offers(): (["--reasoning-effort", "max"], "one of low"), (["4"], "not a flag")): with pytest.raises(ValueError, match=said): check_extra(args, flags) + # a config file could carry --cortheon, --slide or a key past the checks above, so the flag itself is managed + flags["--config"] = {"value": None, "choices": None, "managed": None} + for args in (["--config", "research.toml"], ["--config=research.toml"]): + with pytest.raises(ValueError, match="--config is set by TensorFold Web"): + check_extra(args, flags) + assert native.safe_extra(["--config", "research.toml", "--no-drafts", "--config=x.toml"]) == \ + (["--no-drafts"], ["--config", "--config"]) diff --git a/zig/build/cuda.zig b/zig/build/cuda.zig index 5aacb5ea49d..56b0175198f 100644 --- a/zig/build/cuda.zig +++ b/zig/build/cuda.zig @@ -79,7 +79,7 @@ pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu break :blk run.captureStdOut(.{}); }, .{ .name = "h3", .flags = &.{"-O3"} }, sms) else null; @import("h3_host.zig").library(b, target, optimize, h3_image); - const cuda = runtime(b, target, optimize, if (nvcc != null or prebuilt != null) &images else &.{}); + const cuda = @import("cuda_runtime.zig").runtimeWithTargets(b, target, optimize, if (nvcc != null or prebuilt != null) &images else &.{}, null, if (nvcc != null and prebuilt == null) sms else ""); const mods = family(b, target, optimize, cuda, draft_ids); const cli = b.createModule(.{ .root_source_file = b.path("zig/src/cli/cuda_main.zig"), .target = target, .optimize = optimize, .link_libc = true, .strip = strip }); const native = engines(b, target, optimize, cuda, mods.core, mods.lanes, mods.nemotron, mods.heat, mods.qwen35, mods.qwen_vision); @@ -302,6 +302,7 @@ pub fn hostTests(b: *std.Build, draft_ids: *std.Build.Module, build_options: *st copies.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = m, .filters = &.{"Nemotron copies:"} })).step); } @import("cuda_fault_host.zig").steps(b, cuda, flashnextModule(b, host, .debug, cuda, mods.core, mods.lanes, mods.qwen_vision, mods.api), native); + @import("cuda_sm_host.zig").steps(b, native_modules.api, step); @import("release_cuda_refusal.zig").tests(b, step, native_modules.api, mods.nemotron); @import("qwen_cost_open.zig").tests(b, mods, native_modules, step); const windows_port = @import("windows_host.zig").steps(b, cuda, native_modules.api); @@ -414,7 +415,7 @@ pub fn distServer(b: *std.Build, target: std.Build.ResolvedTarget, draft_ids: *s if (prebuilt) |dir| for (kernels, &images) |k, *image| { image.* = b.graph.cwdRelativePath(b.pathJoin(&.{ dir, b.fmt("{s}.fatbin", .{k.name}) })); }; - const cuda = runtime(b, target, .fast, if (prebuilt != null) &images else &.{}); + const cuda = @import("cuda_runtime.zig").runtimeWithTargets(b, target, .fast, if (prebuilt != null) &images else &.{}, null, release_sms); const mods = family(b, target, .fast, cuda, draft_ids); return nativeServer(b, target, .fast, cuda, mods.core, mods.lanes, mods.nemotron, mods.heat, mods.qwen35, mods.qwen_vision, mods.tokenizer, mods.living, build_options, false, null); } diff --git a/zig/build/cuda_family_host.zig b/zig/build/cuda_family_host.zig index 04650fadaa9..2313f026cee 100644 --- a/zig/build/cuda_family_host.zig +++ b/zig/build/cuda_family_host.zig @@ -16,6 +16,7 @@ pub fn steps(b: *std.Build, cuda: *std.Build.Module, mods: anytype, step: *std.B 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); + b.step("test-memory-pressure-host", "Shared memory-pressure governor, admission and cache shedding without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = mods.api, .filters = &.{"memory pressure:"} })).step); b.step("test-qwen35-shapes-host", "Captured window buckets for one and 2-8 rows without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = mods.qwen35, .filters = &.{"one-row and 2-8-row"} })).step); @import("minimax_cuda.zig").hostTests(b, host, cuda, mods.core, mods.lanes, step); @import("cuda_groups_host.zig").host(b, cuda, mods, step); @@ -137,6 +138,12 @@ pub fn steps(b: *std.Build, cuda: *std.Build.Module, mods: anytype, step: *std.B const int8_run = b.addRunArtifact(b.addTest(.{ .root_module = int8_prompt, .filters = &.{"prompt int8:"} })); b.step("test-qwen35-prompt-int8-host", "Prompt int8 allocation and actual projection recording without devices").dependOn(&int8_run.step); step.dependOn(&int8_run.step); + const pair = b.createModule(.{ .root_source_file = b.path("zig/qwen35_prompt_pair_host.zig"), .target = host, .optimize = .debug, .link_libc = true, .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "qwen35", .module = mods.qwen35 } } }); + const pair_step = b.step("test-qwen35-prompt-pair-host", "Qwen3.8 large-prompt a/b gate and actual launch bindings without devices"); + for ([_]*std.Build.Step.Run{ b.addRunArtifact(b.addTest(.{ .root_module = pair, .filters = &.{"prompt pair:"} })), b.addRunArtifact(b.addTest(.{ .root_module = mods.qwen35, .filters = &.{"Qwen3.8 pair shape:"} })) }) |run| { + pair_step.dependOn(&run.step); + step.dependOn(&run.step); + } const precision = b.createModule(.{ .root_source_file = b.path("zig/qwen35_draft_precision_host.zig"), .target = host, .optimize = .debug, .link_libc = true, .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "qwen35", .module = mods.qwen35 }, .{ .name = "lanes", .module = mods.lanes } } }); const precision_run = b.addRunArtifact(b.addTest(.{ .root_module = precision, .filters = &.{"Draft precision:"} })); b.step("test-qwen35-draft-precision-host", "Draft arithmetic roles and canonical native launches without devices").dependOn(&precision_run.step); @@ -162,6 +169,7 @@ pub fn steps(b: *std.Build, cuda: *std.Build.Module, mods: anytype, step: *std.B const mtp_run = b.addRunArtifact(b.addTest(.{ .root_module = mtp_policy, .filters = &.{"mtp policy:"} })); b.step("test-nemotron-mtp-policy-host", "Nemotron controls through shared rounds, resumes and handoff without a GPU").dependOn(&mtp_run.step); b.step("test-nemotron-restored-head-host", "Actual Nemotron cache restore, bind and captured draft dispatch without a GPU").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = mods.nemotron, .filters = &.{"restored head:"} })).step); + b.step("test-nemotron-draw-host", "Batched MTP and target draws without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = mods.nemotron, .filters = &.{ "batched draws:", "shared draw:" } })).step); b.step("test-nemotron-subset-head-host", "Actual subset-head ownership and row gathering without a GPU").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = mods.nemotron, .filters = &.{"subset head:"} })).step); step.dependOn(&mtp_run.step); const decode_host = b.createModule(.{ .root_source_file = b.path("zig/qwen35_decode_host.zig"), .target = host, .optimize = .debug, .imports = &.{.{ .name = "core", .module = mods.core }} }); diff --git a/zig/build/cuda_release_paths.zig b/zig/build/cuda_release_paths.zig index 42c56f3afa1..885f20faa96 100644 --- a/zig/build/cuda_release_paths.zig +++ b/zig/build/cuda_release_paths.zig @@ -18,8 +18,9 @@ pub fn tests(b: *std.Build, all: *std.Build.Step) void { }), .filters = &.{"release paths:"} })); b.step("test-release-paths-host", "Planted path leaks in raw, wide and compressed release payloads").dependOn(&run.step); all.dependOn(&run.step); + // its own compile to install: a run of an installed artifact executes the installed copy, maybe mid-write + b.step("compile-release-paths-host", "Build the host release checker without shader compilers").dependOn(&b.addInstallArtifact(checker(b), .{}).step); const tool = checker(b); - b.step("compile-release-paths-host", "Build the host release checker without shader compilers").dependOn(&b.addInstallArtifact(tool, .{}).step); const clean = b.addWriteFiles(); const clean_file = clean.add("noise.bin", "\x01./.\x02"); const bad = b.addWriteFiles(); diff --git a/zig/build/cuda_runtime.zig b/zig/build/cuda_runtime.zig index ba524c68b6f..6015fde7182 100644 --- a/zig/build/cuda_runtime.zig +++ b/zig/build/cuda_runtime.zig @@ -7,9 +7,14 @@ pub fn stagger(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu /// `zig/src/cuda/kernels.zig`'s options: whether images are embedded, and the one SM a -Dgpu server's images are for. pub fn kernelOptions(b: *std.Build, with_kernels: bool, built_sm: ?u32) *std.Build.Step.Options { + return targetOptions(b, with_kernels, built_sm, &.{}); +} + +fn targetOptions(b: *std.Build, with_kernels: bool, built_sm: ?u32, sms: []const u32) *std.Build.Step.Options { const options = b.addOptions(); options.addOption(bool, "with_kernels", with_kernels); options.addOption(?u32, "built_sm", built_sm); + options.addOption([]const u32, "sms", if (built_sm) |sm| &.{sm} else sms); return options; } @@ -20,9 +25,19 @@ pub fn runtime(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu /// `runtime` whose every image is for `built_sm` alone (-Dgpu): a context on a GPU of another SM is refused. pub fn runtimeFor(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, images: []const ?std.Build.LazyPath, built_sm: ?u32) *std.Build.Module { + return runtimeWithTargets(b, target, optimize, images, built_sm, ""); +} + +/// A known fatbin target list from the compiler invocation or the validated release bundle. +pub fn runtimeWithTargets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, images: []const ?std.Build.LazyPath, built_sm: ?u32, sms: []const u8) *std.Build.Module { var with = images.len > 0; for (images) |i| with = with and i != null; - const options = kernelOptions(b, with, built_sm); + var numbers: std.ArrayList(u32) = .empty; + if (with and built_sm == null) { + var it = std.mem.tokenizeScalar(u8, sms, ','); + while (it.next()) |sm| numbers.append(b.allocator, @import("cuda_kernels.zig").Target.parse(sm).number) catch @panic("OOM"); + } + const options = targetOptions(b, with, built_sm, numbers.items); const cuda = b.createModule(.{ .root_source_file = b.path("zig/src/cuda/root.zig"), .target = target, .optimize = optimize, .link_libc = true }); cuda.addImport("gpu_memory", @import("gpu_memory.zig").module(b, target)); cuda.addOptions("kernel_options", options); diff --git a/zig/build/cuda_server_host.zig b/zig/build/cuda_server_host.zig index 31e7b5314f5..167ed1e775b 100644 --- a/zig/build/cuda_server_host.zig +++ b/zig/build/cuda_server_host.zig @@ -29,12 +29,13 @@ pub fn steps(b: *std.Build, host: std.Build.ResolvedTarget, cuda: *std.Build.Mod eos_policy.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{"EOS policy:"} })).step); eos_policy.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = mods.tokenizer, .filters = &.{"EOS policy:"} })).step); eos_policy.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = kolibri1Module(b, host, .debug, cuda, mods.core, mods.lanes), .filters = &.{"EOS policy:"} })).step); - b.step("test-serve-flags-host", "Serve flag parsing a later flag replaces, without a GPU").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{"--compact-at:"} })).step); + b.step("test-serve-flags-host", "Serve flag parsing, the flat TOML reader and --config expansion, without a GPU").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{ "--compact-at:", "flat TOML:", "serve --config:" } })).step); b.step("test-dory-cli-host", "Dory CUDA loop option forwarding and invalid-value refusals").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{"--device and --segments:"} })).step); b.step("test-dory-chat-host", "Dory chat template, EOS, reasoning split and qwen3_coder call on the CPU").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{"Dory chat:"} })).step); b.step("test-embeddings-protocol-host", "Embedding request and response contracts without an admitted model or GPU").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{"embeddings protocol:"} })).step); b.step("test-embeddings-http-host", "Embedding route capability and borrowed request lifetime without a model or GPU").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{"embeddings HTTP:"} })).step); @import("rerank_host.zig").steps(b, server_tests); + b.step("test-ollama-e2e-host", "Ollama routes over a loopback socket with the CPU fake engine").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{"ollama HTTP:"} })).step); @import("safetensors_header_host.zig").steps(b, mods.core, step); b.step("test-runtime-capabilities-host", "Optional library discovery in actual capabilities JSON").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{"runtime library:"} })).step); b.step("test-vision-cli-host", "Image token budgets through parsing and engine admission options without a GPU").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{"vision image budget:"} })).step); diff --git a/zig/build/cuda_sm_host.zig b/zig/build/cuda_sm_host.zig new file mode 100644 index 00000000000..fe532c17cf2 --- /dev/null +++ b/zig/build/cuda_sm_host.zig @@ -0,0 +1,13 @@ +//! The real release metadata and runtime, with inert images and a recording driver in place of a GPU. +const std = @import("std"); +pub fn steps(b: *std.Build, api: *std.Build.Module, host_tests: *std.Build.Step) void { + const catalog = @import("cuda.zig"); + const empty = b.addWriteFiles().add("inert-sm-host.fatbin", ""); + const images: [catalog.kernels.len]?std.Build.LazyPath = @splat(empty); + const runtime = @import("cuda_runtime.zig").runtimeWithTargets(b, b.graph.host, .debug, &images, null, catalog.release_sms); + const logs = b.createModule(.{ .root_source_file = b.path("zig/cuda_sm_logs.zig"), .target = b.graph.host }); + const root = b.createModule(.{ .root_source_file = b.path("zig/cuda_sm_host.zig"), .target = b.graph.host, .optimize = .debug, .link_libc = true, .imports = &.{ .{ .name = "cuda", .module = runtime }, .{ .name = "engine_api", .module = api }, .{ .name = "qwen_weights_diagnostics", .module = logs } } }); + const run = b.addRunArtifact(b.addTest(.{ .root_module = root, .filters = &.{"CUDA release SM:"}, .test_runner = .{ .path = b.path("zig/qwen_vision_weights_runner.zig"), .mode = .simple } })); + b.step("test-cuda-sm-host", "Release SM admission and capability JSON with inert images and no GPU").dependOn(&run.step); + host_tests.dependOn(&run.step); +} diff --git a/zig/build/flashnext_scoring_host.zig b/zig/build/flashnext_scoring_host.zig index 390965996e4..36ed70ed0f4 100644 --- a/zig/build/flashnext_scoring_host.zig +++ b/zig/build/flashnext_scoring_host.zig @@ -2,6 +2,9 @@ const std = @import("std"); pub fn steps(b: *std.Build, cuda: *std.Build.Module, core: *std.Build.Module, lanes: *std.Build.Module, family: *std.Build.Module, parent: *std.Build.Step) void { @import("flashnext_proposal_host.zig").steps(b, cuda, core, lanes, family); + const draws = b.addRunArtifact(b.addTest(.{ .root_module = family, .filters = &.{ "Flash Next nonfinite:", "Flash Next batch draws:" } })); + b.step("test-flashnext-draw-host", "Production row draws and launch grids on the recording CUDA device").dependOn(&draws.step); + parent.dependOn(&draws.step); const scoring = b.addRunArtifact(b.addTest(.{ .root_module = family, .filters = &.{ "decision capability:", "the logsumexp" } })); b.step("test-flashnext-score-host", "Actual one-rank scoring capability and label reference without devices").dependOn(&scoring.step); parent.dependOn(&scoring.step); diff --git a/zig/build/host_ci.zig b/zig/build/host_ci.zig index bc9f9b000a6..11b8289d6dc 100644 --- a/zig/build/host_ci.zig +++ b/zig/build/host_ci.zig @@ -189,6 +189,7 @@ const linux_host = [_][]const u8{ "test-lane-halt-host", "test-lane-interrupted-host", "test-lane-lone-host", + "test-lane-strand-host", "test-lfm2-load-host", "test-living-shards-host", "test-merge", diff --git a/zig/build/lane_halt_host.zig b/zig/build/lane_halt_host.zig index c155f97de0e..938c7b99179 100644 --- a/zig/build/lane_halt_host.zig +++ b/zig/build/lane_halt_host.zig @@ -6,6 +6,9 @@ pub fn steps(b: *std.Build) void { const api = b.createModule(.{ .root_source_file = b.path("zig/src/core/engine_api.zig"), .target = b.graph.host, .optimize = .debug, .link_libc = true, .imports = &.{.{ .name = "lanes", .module = lanes }} }); const interrupted = b.createModule(.{ .root_source_file = b.path("zig/src/core/lane_host_interrupted_test.zig"), .target = b.graph.host, .optimize = .debug, .link_libc = true, .imports = &.{.{ .name = "lanes", .module = lanes }} }); b.step("test-lane-interrupted-host", "Interrupted prompt retention and clean retries without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = interrupted, .filters = &.{"interrupted prefill:"} })).step); + const safe_lanes = b.createModule(.{ .root_source_file = b.path("zig/src/core/lanes/lanes.zig"), .target = b.graph.host, .optimize = .safe, .link_libc = true }); + const strand = b.createModule(.{ .root_source_file = b.path("zig/src/core/lane_host_strand_test.zig"), .target = b.graph.host, .optimize = .safe, .link_libc = true, .imports = &.{.{ .name = "lanes", .module = safe_lanes }} }); + b.step("test-lane-strand-host", "Refused, cancelled and failed requests give back every lane, page and slot without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = strand, .filters = &.{"lane strand:"} })).step); const halt = b.addTest(.{ .root_module = api, .filters = &.{ "halt (", "halt fails" } }); b.step("test-lane-halt-host", "Halt ordering with a fake backend and no GPU dependencies").dependOn(&b.addRunArtifact(halt).step); b.step("test-lane-lone-host", "Existing lone-driver handoff and reclaim with a fake backend").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = api, .filters = &.{"lone driver"} })).step); diff --git a/zig/build/server.zig b/zig/build/server.zig index 4b90243c750..21e55c9e8bd 100644 --- a/zig/build/server.zig +++ b/zig/build/server.zig @@ -14,6 +14,22 @@ pub fn webHostTests(b: *std.Build, all: *std.Build.Step) void { all.dependOn(&run.step); } +/// Ollama body translation and refusals, no server or device. +pub fn ollamaHostTests(b: *std.Build, all: *std.Build.Step) void { + const json_mod = json(b, b.graph.host, .Debug); + const tests = b.addTest(.{ .root_module = b.createModule(.{ + .root_source_file = b.path("zig/src/server/ollama_test.zig"), + .target = b.graph.host, + .optimize = .Debug, + .link_libc = true, + .imports = &.{.{ .name = "json", .module = json_mod }}, + }) }); + const run = b.addRunArtifact(tests); + run.has_side_effects = true; + b.step("test-ollama-host", "Ollama request translation, option refusals and NDJSON framing").dependOn(&run.step); + all.dependOn(&run.step); +} + /// The server's JSON values as a module (zig/src/server/json.zig), so a family's serving code shares them. pub fn json(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode) *std.Build.Module { return b.createModule(.{ @@ -74,6 +90,7 @@ pub fn testImports(b: *std.Build, m: *std.Build.Module, target: std.Build.Resolv pub fn toolHostTests(b: *std.Build, parser: *std.Build.Module, server: *std.Build.Module, all: *std.Build.Step) void { testImports(b, parser, b.graph.host, .debug); testImports(b, server, b.graph.host, .debug); + b.step("test-token-stream-host", "Native token streams, semantic anchors and cancellation without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server, .filters = &.{"token stream:"} })).step); b.step("test-thinking-tail-host", "Finished calls before a think close, whole and streamed without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server, .filters = &.{"thinking tail:"} })).step); const environment = b.step("test-environment-report-host", "Named environment discovery, new registry rows and startup reporting"); environment.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server, .filters = &.{ "capability audit: environment", "stable profile:", "profile line:" } })).step); diff --git a/zig/cuda_sm_host.zig b/zig/cuda_sm_host.zig new file mode 100644 index 00000000000..6a25c9dbbb2 --- /dev/null +++ b/zig/cuda_sm_host.zig @@ -0,0 +1,143 @@ +//! Inert embedded assets exercise release admission and capabilities with recording driver callbacks only. +const std = @import("std"); +const cuda = @import("cuda"); +const caps = @import("src/server/cli_capabilities.zig"); +const device = @import("src/native/cuda_device.zig"); +const t = std.testing; +const logs = @import("qwen_weights_diagnostics"); + +const Fake = struct { + var capability: u32 = 90; + var retains: usize = 0; + var loads: usize = 0; + fn get(out: *cuda.abi.Device, _: c_int) callconv(.c) cuda.abi.Result { + out.* = 0; + return 0; + } + fn attr(out: *c_int, field: cuda.abi.DeviceAttribute, _: cuda.abi.Device) callconv(.c) cuda.abi.Result { + out.* = @intCast(if (field == .compute_capability_major) capability / 10 else capability % 10); + return 0; + } + fn name(out: [*]u8, _: c_int, _: cuda.abi.Device) callconv(.c) cuda.abi.Result { + const text = switch (capability) { + 90 => "NVIDIA H100", + 89 => "NVIDIA GeForce RTX 4090", + 87 => "NVIDIA Jetson AGX Orin", + 75 => "NVIDIA T4", + 100 => "NVIDIA B200", + else => "NVIDIA GB10", + }; + @memcpy(out[0..text.len], text); + out[text.len] = 0; + return 0; + } + fn retain(out: *cuda.abi.Context, _: cuda.abi.Device) callconv(.c) cuda.abi.Result { + retains += 1; + out.* = @ptrFromInt(0x611); + return 0; + } + fn set(_: cuda.abi.Context) callconv(.c) cuda.abi.Result { + return 0; + } + fn release(_: cuda.abi.Device) callconv(.c) cuda.abi.Result { + retains -= 1; + return 0; + } + fn sync() callconv(.c) cuda.abi.Result { + return 0; + } + fn load(_: *cuda.abi.Module, _: ?*const anyopaque) callconv(.c) cuda.abi.Result { + loads += 1; + return 209; + } + fn driver() cuda.Driver { + var d: cuda.Driver = undefined; + d.func_name = null; + d.api.cuDeviceGet = get; + d.api.cuDeviceGetAttribute = attr; + d.api.cuDeviceGetName = name; + d.api.cuDevicePrimaryCtxRetain = retain; + d.api.cuCtxSetCurrent = set; + d.api.cuDevicePrimaryCtxRelease_v2 = release; + d.api.cuCtxSynchronize = sync; + d.api.cuModuleLoadData = load; + return d; + } +}; + +test "CUDA release SM: unsupported GPU is named before context retain or module load, supported GPU starts" { + const prior = cuda.copy_source.current(); + defer cuda.copy_source.setCurrent(prior); + var d = Fake.driver(); + Fake.capability = 90; + Fake.retains = 0; + Fake.loads = 0; + logs.used = 0; + try t.expectError(error.WrongGpu, cuda.Context.init(&d, 0)); + try t.expectEqual(@as(usize, 0), Fake.retains); + try t.expectEqual(@as(usize, 0), Fake.loads); + const text = logs.message[0..logs.used]; + try t.expect(std.mem.indexOf(u8, text, "NVIDIA H100") != null); + try t.expect(std.mem.indexOf(u8, text, "9.0 (sm_90)") != null); + var list: std.Io.Writer.Allocating = .init(t.allocator); + defer list.deinit(); + for (cuda.kernels.target_sms, 0..) |sm, i| try list.writer.print("{s}{d}", .{ if (i == 0) "" else ",", sm }); + try t.expect(std.mem.indexOf(u8, text, list.written()) != null); + Fake.capability = 121; + logs.used = 0; + var ctx = try cuda.Context.init(&d, 0); + try t.expectEqual(@as(usize, 1), Fake.retains); + try t.expectEqual(@as(usize, 0), Fake.loads); + try t.expectEqual(@as(usize, 0), logs.used); + ctx.deinit(); + try t.expectEqual(@as(usize, 0), Fake.retains); +} + +test "CUDA release SM: sm_80 and sm_86 images serve later 8.x minors; another major or a later 12.x minor is refused" { + const prior = cuda.copy_source.current(); + defer cuda.copy_source.setCurrent(prior); + var d = Fake.driver(); + for ([_]u32{ 80, 86, 87, 89, 120 }) |sm| { + Fake.capability = sm; + Fake.retains = 0; + Fake.loads = 0; + logs.used = 0; + var ctx = try cuda.Context.init(&d, 0); + try t.expectEqual(@as(usize, 1), Fake.retains); + try t.expectEqual(@as(usize, 0), logs.used); + ctx.deinit(); + try t.expectEqual(@as(usize, 0), Fake.retains); + } + for ([_]u32{ 75, 90, 100, 122 }) |sm| { + Fake.capability = sm; + Fake.retains = 0; + logs.used = 0; + try t.expectError(error.WrongGpu, cuda.Context.init(&d, 0)); + try t.expectEqual(@as(usize, 0), Fake.retains); + try t.expect(logs.used > 0); + logs.used = 0; // the runner fails a test that leaves a diagnostic unread + } + try t.expect(cuda.kernels.covers(&.{ 80, 86 }, 89)); + try t.expect(!cuda.kernels.covers(&.{89}, 86)); + try t.expect(!cuda.kernels.covers(&.{ 80, 86 }, 90)); + // arch-specific images (sm_120a from sm_120 on) run on that SM alone + try t.expect(!cuda.kernels.covers(&.{120}, 121)); + try t.expect(!cuda.kernels.covers(&.{121}, 122)); +} + +test "CUDA release SM: capabilities JSON reports build coverage for both detected capabilities" { + var d = Fake.driver(); + for ([_]u32{ 90, 121, 89 }, [_]bool{ false, true, true }) |sm, expected| { + Fake.capability = sm; + const support = device.kernelSupportOn(&d, 0); + var out: std.Io.Writer.Allocating = .init(t.allocator); + defer out.deinit(); + try caps.capabilities(&out.writer, .{ .version = "test", .kernels = support.kernels, .kernel_sms = support.sms }); + const parsed = try std.json.parseFromSlice(std.json.Value, t.allocator, out.written(), .{}); + defer parsed.deinit(); + try t.expectEqual(expected, parsed.value.object.get("kernels").?.bool); + const values = parsed.value.object.get("kernel_sms").?.array.items; + try t.expectEqual(cuda.kernels.target_sms.len, values.len); + for (values, cuda.kernels.target_sms) |value, target| try t.expectEqual(@as(i64, target), value.integer); + } +} diff --git a/zig/cuda_sm_logs.zig b/zig/cuda_sm_logs.zig new file mode 100644 index 00000000000..e0a1741c111 --- /dev/null +++ b/zig/cuda_sm_logs.zig @@ -0,0 +1,11 @@ +//! Recording diagnostics for the release context host runner; no device or module is opened. +const std = @import("std"); +pub var message: [2048]u8 = undefined; +pub var used: usize = 0; +pub fn log(comptime _: std.log.Level, comptime _: @EnumLiteral(), comptime fmt: []const u8, args: anytype) void { + const text = std.fmt.bufPrint(&message, fmt, args) catch return; + used = text.len; +} +pub fn expect(n: usize) !void { + try std.testing.expectEqual(n, used); +} diff --git a/zig/kernels/cuda/flashnext_mtp.cu b/zig/kernels/cuda/flashnext_mtp.cu index f90fcd19250..a6f6c047c6c 100644 --- a/zig/kernels/cuda/flashnext_mtp.cu +++ b/zig/kernels/cuda/flashnext_mtp.cu @@ -91,8 +91,13 @@ extern "C" __global__ void __launch_bounds__(1024) fn_row_topk(const __nv_bfloat __shared__ unsigned int pick_hi, pick_lo, above; for (int i = t; i < 256; i += nt) hist[i] = 0; __syncthreads(); - for (int i = t; i < V; i += nt) atomicAdd(&hist[order_key(row[i]) >> 8], 1u); - __syncthreads(); + int bad = 0; + for (int i = t; i < V; i += nt) { + const unsigned short u = row[i]; + bad |= ((u & 0x7fff) > 0x7f80) | (u == 0x7f80); + atomicAdd(&hist[order_key(u) >> 8], 1u); + } + const int row_bad = __syncthreads_or(bad); if (t == 0) { unsigned int cum = 0; int b = 255; @@ -160,4 +165,6 @@ extern "C" __global__ void __launch_bounds__(1024) fn_row_topk(const __nv_bfloat ++rank; } } + __syncthreads(); + if (t == 0 && row_bad) oc[0] = -1; } diff --git a/zig/kernels/cuda/glm_glue.cu b/zig/kernels/cuda/glm_glue.cu index 06f2ba94ccf..27ec32eb936 100644 --- a/zig/kernels/cuda/glm_glue.cu +++ b/zig/kernels/cuda/glm_glue.cu @@ -8,3 +8,4 @@ #include "glm_glue_index.cuh" #include "glm_glue_bmm.cuh" #include "glm_glue_attn.cuh" +#include "glm_index_decode.cuh" diff --git a/zig/kernels/cuda/glm_index_decode.cuh b/zig/kernels/cuda/glm_index_decode.cuh new file mode 100644 index 00000000000..a3e7fa88dfc --- /dev/null +++ b/zig/kernels/cuda/glm_index_decode.cuh @@ -0,0 +1,332 @@ +// GLM-5.3-Flash DSA indexer: a decode window's top-512 pools of long rows on many CTAs, tf_glm_select_rows' bytes. +#pragma once + +#include +#include + +namespace glm_dsel { + +constexpr int T1 = 256; // scan threads +constexpr int SPAN = 4096; // pools a scan CTA marks: 16 words of 32 a warp +constexpr int NS8 = 4096; // sampled keys: 512 runs of 8 at even spacing (glm_index_pools' sample) +constexpr int T2 = 1024; // merge threads +constexpr int CAP = 4096; // candidates the merge holds in shared memory +constexpr int PER = 8; // keys a merge thread takes a select step + +// sparse._order_key: a score's bits as a uint32 whose unsigned order is the scores' (-0 counted as +0). +__device__ __forceinline__ uint32_t order_key(float s) { + const int b = __float_as_int(__fadd_rn(s, 0.0f)); + return (uint32_t)(b ^ ((b >> 31) | (int)0x80000000u)); +} + +// Row r's selection range [0, NP): its visible pools, at least K, at most np (tf_glm_select_rows' limit). +__device__ __forceinline__ int row_limit(int64_t np, const int* pos, int64_t r, int K) { + const int64_t vis = ((int64_t)pos[0] + r + 1) / 4; + return (int)min(np, max(vis, (int64_t)K)); +} + +// hist[b] += 1 for each lane's bin b (256: none), each bin's lanes adding once. The whole warp calls it. +__device__ __forceinline__ void hist_add(int* hist, int b) { + if (__any_sync(0xffffffffu, b < 256)) { + const unsigned same = __match_any_sync(0xffffffffu, b); + if (b < 256 && (same & ((1u << (threadIdx.x & 31)) - 1)) == 0) atomicAdd(&hist[b], __popc(same)); + } +} + +// Warp 0: the digit of the need-th largest key under prefix from hist, and need less the keys in the bins above it. +__device__ __forceinline__ void digit_of(const int* hist, int need, uint32_t prefix, int shift, uint32_t* sh_prefix, + int* sh_need) { + const int lane = threadIdx.x & 31; + int h[8], own = 0; +#pragma unroll + for (int j = 0; j < 8; ++j) own += h[j] = hist[255 - 8 * lane - j]; + int upto = own; +#pragma unroll + for (int o = 1; o < 32; o <<= 1) { + const int v = __shfl_up_sync(0xffffffffu, upto, o); + if (lane >= o) upto += v; + } + const unsigned hit = __ballot_sync(0xffffffffu, upto >= need); + if (lane == (hit ? __ffs(hit) - 1 : 31)) { // no bin reaching need: digit 0 and need less every key, as select_rows + int above = upto - own, digit = 0; + for (int j = 0; j < 8; ++j) { + if (above + h[j] >= need) { + digit = 255 - 8 * lane - j; + break; + } + above += h[j]; + } + *sh_need = need - above; + *sh_prefix = prefix | ((uint32_t)digit << shift); + } +} + +// T threads' exclusive prefix of v and its total, via `slot` of wsum; its barrier orders slot reuse (callers alternate) +template +__device__ __forceinline__ int block_scan(int v, int (*wsum)[T / 32], int slot, int* total) { + const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; + int inc = v; +#pragma unroll + for (int o = 1; o < 32; o <<= 1) { + const int u = __shfl_up_sync(0xffffffffu, inc, o); + if (lane >= o) inc += u; + } + if (lane == 31) wsum[slot][warp] = inc; + __syncthreads(); + int before = inc - v, all = 0; +#pragma unroll + for (int w = 0; w < T / 32; ++w) { + const int s = wsum[slot][w]; + if (w < warp) before += s; + all += s; + } + *total = all; + return before; +} + +template +struct Sel { + int hist[256]; + int wsum[2][T / 32]; + uint32_t prefix; + int need; +}; + +// A row's scores [0, n) from global memory: the keys of elements i0 .. i0 + 7 (0 past n), and element i's pool. +struct RowSrc { + const float* s; + int n; + bool vec; + __device__ __forceinline__ void keys8(int i0, uint32_t (&u)[PER]) const { + if (vec && i0 + PER <= n) { + const float4 a = *reinterpret_cast(s + i0), b = *reinterpret_cast(s + i0 + 4); + const float v[PER] = {a.x, a.y, a.z, a.w, b.x, b.y, b.z, b.w}; +#pragma unroll + for (int j = 0; j < PER; ++j) u[j] = order_key(v[j]); + } else { +#pragma unroll + for (int j = 0; j < PER; ++j) u[j] = i0 + j < n ? order_key(s[i0 + j]) : 0u; + } + } + __device__ __forceinline__ int64_t pool(int i) const { return i; } +}; + +// Candidates in shared memory, in pool order: their keys and pools. +struct CandSrc { + const uint32_t* key; + const int* idx; + int n; + __device__ __forceinline__ void keys8(int i0, uint32_t (&u)[PER]) const { +#pragma unroll + for (int j = 0; j < PER; ++j) u[j] = i0 + j < n ? key[i0 + j] : 0u; + } + __device__ __forceinline__ int64_t pool(int i) const { return idx[i]; } +}; + +// tf_glm_select_rows over src's n keys, every thread of T: the K best keys' pools ascending into out, ties to the lower +template +__device__ void select_core(Sel& sh, const Src& src, int n, int K, int64_t* __restrict__ out) { + const int t = threadIdx.x; + uint32_t prefix = 0, fixed = 0; + int need = K; + for (int shift = 24; shift >= 0; shift -= 8) { // four 8-bit radix passes find the K-th best key + for (int b = t; b < 256; b += T) sh.hist[b] = 0; + __syncthreads(); + for (int c = 0; c < n; c += PER * T) { + uint32_t u[PER]; + src.keys8(c + PER * t, u); +#pragma unroll + for (int j = 0; j < PER; ++j) { + const int i = c + PER * t + j; + hist_add(sh.hist, i < n && (u[j] & fixed) == prefix ? (int)((u[j] >> shift) & 0xFF) : 256); + } + } + __syncthreads(); + if (t < 32) digit_of(sh.hist, need, prefix, shift, &sh.prefix, &sh.need); + __syncthreads(); + need = sh.need; + prefix = sh.prefix; + fixed |= 0xFFu << shift; + } + int gt_run = 0, eq_run = 0, slot = 0; // in index order: every key above the K-th, then the first `need` equal to it + for (int c = 0; c < n; c += PER * T) { + const int i0 = c + PER * t; + uint32_t u[PER]; + src.keys8(i0, u); + int g = 0, e = 0; +#pragma unroll + for (int j = 0; j < PER; ++j) { + const bool ok = i0 + j < n; + g += ok && u[j] > prefix; + e += ok && u[j] == prefix; + } + int total; + const int ex = block_scan((g << 16) | e, sh.wsum, slot, &total); // a step's counts stay under 2^16 + slot ^= 1; + int gb = gt_run + (ex >> 16), eb = eq_run + (ex & 0xFFFF); +#pragma unroll + for (int j = 0; j < PER; ++j) { + if (i0 + j >= n) break; + if (u[j] > prefix) { + out[gb + min(eb, need)] = src.pool(i0 + j); + gb++; + } else if (u[j] == prefix) { + if (eb < need) out[gb + eb] = src.pool(i0 + j); + eb++; + } + } + gt_run += total >> 16; + eq_run += total & 0xFFFF; + } + __syncthreads(); // shared state free for the caller +} + +struct Merge { + uint32_t key[CAP]; + int idx[CAP]; + Sel sel; +}; + +} // namespace glm_dsel + +// tf_glm_dsel_scan, grid (cdiv(the last row's NP, SPAN), R): a span's pools above (gt) and at (eq) the row's floor. +extern "C" __global__ void __launch_bounds__(glm_dsel::T1) + tf_glm_dsel_scan(const float* __restrict__ S, int64_t np, const int* __restrict__ pos, int K, int target, + uint32_t* __restrict__ bits, int64_t words) { + using namespace glm_dsel; + __shared__ int hist[256]; + __shared__ uint32_t sh_prefix; + __shared__ int sh_need; + const int64_t r = blockIdx.y; + const int NP = row_limit(np, pos, r, K); + const int64_t p0 = (int64_t)blockIdx.x * SPAN; + if (NP <= CAP || p0 >= NP) return; // rows of NP <= CAP mark nothing: the merge takes them whole + const float* row = S + r * np; + const int t = threadIdx.x, lane = t & 31, warp = t >> 5; + // The floor: the need-th largest of the sampled keys, need the target's share of them. Speed only. + constexpr int PT = NS8 / T1; + uint32_t u[PT]; +#pragma unroll + for (int j = 0; j < PT; ++j) { + const int s = t + j * T1; + const int64_t i = (int64_t)(s / 8) * NP / (NS8 / 8) / 8 * 8 + s % 8; + u[j] = order_key(i < NP ? row[i] : 0.0f); + } + uint32_t prefix = 0, fixed = 0; + int need = max((int)((int64_t)target * NS8 / NP), 1); + for (int shift = 24; shift >= 0; shift -= 8) { + hist[t] = 0; // T1 == 256 bins + __syncthreads(); +#pragma unroll + for (int j = 0; j < PT; ++j) hist_add(hist, (u[j] & fixed) == prefix ? (int)((u[j] >> shift) & 0xFF) : 256); + __syncthreads(); + if (warp == 0) digit_of(hist, need, prefix, shift, &sh_prefix, &sh_need); + __syncthreads(); + prefix = sh_prefix; + need = sh_need; + fixed |= 0xFFu << shift; + } + const uint32_t lo = prefix; + // The span's words, a warp's every 8th: its pools above and at the floor. + constexpr int WARPS = T1 / 32, WPW = SPAN / 32 / WARPS; + const int64_t w0 = p0 / 32; + const int nwc = (int)min((int64_t)(SPAN / 32), ((int64_t)NP + 31) / 32 - w0); + float v[WPW]; +#pragma unroll + for (int m = 0; m < WPW; ++m) { + const int wi = warp + m * WARPS; + const int64_t i = (w0 + wi) * 32 + lane; + v[m] = wi < nwc && i < NP ? row[i] : 0.0f; + } + uint32_t* gt = bits + r * 2 * words; // row r's gt words, then its eq words; bit b of word w is pool 32 w + b +#pragma unroll + for (int m = 0; m < WPW; ++m) { + const int wi = warp + m * WARPS; + const int64_t i = (w0 + wi) * 32 + lane; + const bool in = wi < nwc && i < NP; + const uint32_t k = order_key(v[m]); + const unsigned g = __ballot_sync(0xffffffffu, in && k > lo), e = __ballot_sync(0xffffffffu, in && k == lo); + if (lane == 0 && wi < nwc) { // only the span's words below the row's NP + gt[w0 + wi] = g; + gt[words + w0 + wi] = e; + } + } +} + +// tf_glm_dsel_merge, a CTA a row: scores [R][np] into out [R][K] int64 ascending; PATH null or [R] int32, each path. +extern "C" __global__ void __launch_bounds__(glm_dsel::T2) + tf_glm_dsel_merge(const float* __restrict__ S, int64_t* __restrict__ OUT, int64_t np, const int* __restrict__ pos, + int K, const uint32_t* __restrict__ bits, int64_t words, int* __restrict__ PATH) { + using namespace glm_dsel; + __shared__ Merge sm; + const int64_t r = blockIdx.x; + const int NP = row_limit(np, pos, r, K); + const float* row = S + r * np; + int64_t* out = OUT + r * K; + const int t = threadIdx.x; + const RowSrc whole{row, NP, (reinterpret_cast(row) & 15) == 0}; + if (NP <= CAP) { // path 0: the whole row in one select + select_core(sm.sel, whole, NP, K, out); + if (PATH != nullptr && t == 0) PATH[r] = 0; + return; + } + const uint32_t* gt = bits + r * 2 * words; + const uint32_t* eq = gt + words; + const int nw = (NP + 31) / 32, per = (nw + T2 - 1) / T2; + const int wa = min(nw, t * per), wb = min(nw, wa + per); // this thread's words, in pool order + int cg = 0, ce = 0; + for (int w = wa; w < wb; ++w) { + cg += __popc(gt[w]); + ce += __popc(eq[w]); + } + int n_gt, n_eq; + const int gt_before = block_scan(cg, sm.sel.wsum, 0, &n_gt); + const int eq_before = block_scan(ce, sm.sel.wsum, 1, &n_eq); + const int n_ge = n_gt + n_eq; + int path; + if (n_gt < K && K <= n_ge) { + // Path 3, ties at the floor: every gt pool, and the eq pools of eq rank under K - n_gt, in pool order. + const int need = K - n_gt; + int seen = eq_before, cs = 0; + for (int w = wa; w < wb; ++w) { + const uint32_t e = eq[w]; + uint32_t take = 0, m = e; + for (int q = min(__popc(e), max(0, need - seen)); q > 0; --q) { + take |= m & (0u - m); + m &= m - 1; + } + cs += __popc(gt[w] | take); + seen += __popc(e); + } + int all; + int at = block_scan(cs, sm.sel.wsum, 0, &all); + seen = eq_before; + for (int w = wa; w < wb; ++w) { + const uint32_t e = eq[w]; + uint32_t take = 0, m = e; + for (int q = min(__popc(e), max(0, need - seen)); q > 0; --q) { + take |= m & (0u - m); + m &= m - 1; + } + seen += __popc(e); + for (uint32_t s = gt[w] | take; s != 0; s &= s - 1) out[at++] = (int64_t)w * 32 + (__ffs(s) - 1); + } + path = 3; + } else if ((K <= n_ge && n_ge <= CAP) || (K <= n_gt && n_gt <= CAP)) { + // Path 1: every pool at or above the floor (or above it, when those hold K) in pool order holds the K best. + const bool with_eq = n_ge <= CAP; + const int n = with_eq ? n_ge : n_gt; + int at = with_eq ? gt_before + eq_before : gt_before; + for (int w = wa; w < wb; ++w) + for (uint32_t s = gt[w] | (with_eq ? eq[w] : 0u); s != 0; s &= s - 1) sm.idx[at++] = w * 32 + (__ffs(s) - 1); + __syncthreads(); // then their keys, spread over the threads (candidates may crowd a few threads' words) + for (int c = t; c < n; c += T2) sm.key[c] = order_key(row[sm.idx[c]]); + __syncthreads(); + select_core(sm.sel, CandSrc{sm.key, sm.idx, n}, n, K, out); + path = 1; + } else { // path 2: the floor overshot, or far too many above it: the whole row after the candidates missed + select_core(sm.sel, whole, NP, K, out); + path = 2; + } + if (PATH != nullptr && t == 0) PATH[r] = path; +} diff --git a/zig/kernels/cuda/nemotron_ops.cu b/zig/kernels/cuda/nemotron_ops.cu index 7b6cca67a54..8323808a536 100644 --- a/zig/kernels/cuda/nemotron_ops.cu +++ b/zig/kernels/cuda/nemotron_ops.cu @@ -308,3 +308,69 @@ extern "C" __global__ void tf_splice_rows(__nv_bfloat16* __restrict__ H, const _ if (s < 0) return; for (int i = threadIdx.x; i < D; i += blockDim.x) H[r * D + i] = F[static_cast(s) * D + i]; } + +// A batched draft's rows: each part's rows of `a` (wa bytes a row) and `b` (wb bytes a row) to dst_a and dst_b. +struct GatherRows { + const void* a[8]; + const void* b[8]; + int rows[8]; + int row0[8]; + int wa; + int wb; +}; + +// Row r of dst_a/dst_b from its part's row; a part's rows are contiguous, the parts' starts in row0. +extern "C" __global__ void tf_nemo_gather_rows(const GatherRows g, void* __restrict__ dst_a, void* __restrict__ dst_b) { + const int r = blockIdx.x; + int k = 0; + while (k < 8 && !(r >= g.row0[k] && r < g.row0[k] + g.rows[k])) ++k; + if (k == 8) return; + const int at = r - g.row0[k]; + const char* sa = static_cast(g.a[k]) + (size_t)at * g.wa; + char* da = static_cast(dst_a) + (size_t)r * g.wa; + for (int i = threadIdx.x * 4; i < g.wa; i += blockDim.x * 4) *reinterpret_cast(da + i) = *reinterpret_cast(sa + i); + if (g.b[k] == nullptr) return; + const char* sb = static_cast(g.b[k]) + (size_t)at * g.wb; + char* db = static_cast(dst_b) + (size_t)r * g.wb; + for (int i = threadIdx.x * 4; i < g.wb; i += blockDim.x * 4) *reinterpret_cast(db + i) = *reinterpret_cast(sb + i); +} + +// A span's last row: each part's source a/b row moved to dst row k, ascending k with a barrier between rows. +struct LastRows { + const void* a[8]; + const void* b[8]; +}; + +// One block: row k's sources to dst row k in order, so a row that is another part's destination is read before written. +extern "C" __global__ void tf_nemo_gather_last(const LastRows g, void* __restrict__ dst_a, void* __restrict__ dst_b, int wa, int wb, int n) { + for (int k = 0; k < n; ++k) { + char* da = static_cast(dst_a) + (size_t)k * wa; + const char* sa = static_cast(g.a[k]); + char* db = static_cast(dst_b) + (size_t)k * wb; + const char* sb = static_cast(g.b[k]); + for (int i = threadIdx.x * 4; i < wa; i += blockDim.x * 4) *reinterpret_cast(da + i) = *reinterpret_cast(sa + i); + if (sb != nullptr) for (int i = threadIdx.x * 4; i < wb; i += blockDim.x * 4) *reinterpret_cast(db + i) = *reinterpret_cast(sb + i); + __syncthreads(); + } +} + +// A level's rows: each part's token and probability to its own buffers at tok_at/prob_at, one row a part. +struct ScatterRows { + unsigned* tok[8]; + float* prob[8]; + int rows[8]; + int row0[8]; + int tok_at; + int prob_at; +}; + +// Row r of TOK/PROB to its part's tok/prob at tok_at/prob_at plus its row within the part. +extern "C" __global__ void tf_nemo_scatter_rows(const unsigned* __restrict__ TOK, const float* __restrict__ PROB, const ScatterRows g) { + const int r = blockIdx.x; + int k = 0; + while (k < 8 && !(r >= g.row0[k] && r < g.row0[k] + g.rows[k])) ++k; + if (k == 8 || threadIdx.x != 0) return; + const int at = r - g.row0[k]; + g.tok[k][g.tok_at + at] = TOK[r]; + if (g.prob[k] != nullptr) g.prob[k][g.prob_at + at] = PROB[r]; +} diff --git a/zig/kernels/cuda/sample_rows.cuh b/zig/kernels/cuda/sample_rows.cuh index 584502f4ffe..7fd99b2cb7f 100644 --- a/zig/kernels/cuda/sample_rows.cuh +++ b/zig/kernels/cuda/sample_rows.cuh @@ -6,3 +6,11 @@ extern "C" __global__ void __launch_bounds__(1024) tf_draw_rows(const __nv_bfloa const int* meta, unsigned* TOK) { tf_sample::draw(L, V, rule, meta, 0, TOK, nullptr, nullptr); } + +// The same with IDS mapping each row's columns to token ids (a draft head's vocabulary); IDS null: whole head. +extern "C" __global__ void __launch_bounds__(1024) tf_draw_ids_rows(const __nv_bfloat16* L, unsigned V, const tf_sample::Rule* rule, + const int* meta, int offset, unsigned* TOK, + const long long* IDS, float* PROB) { + if (IDS != nullptr) tf_sample::draw(L, V, rule, meta, offset, TOK, IDS, PROB); + else tf_sample::draw(L, V, rule, meta, offset, TOK, nullptr, PROB); +} diff --git a/zig/qwen35_prompt_int8_host.zig b/zig/qwen35_prompt_int8_host.zig index 8fd65e95f6b..4020f00f90d 100644 --- a/zig/qwen35_prompt_int8_host.zig +++ b/zig/qwen35_prompt_int8_host.zig @@ -177,3 +177,19 @@ test "prompt int8: hand-built projection fixture initializes all newly read sele try T.expect(!e.affine.half_prompt); try T.expectEqual(@as(usize, 4), @intFromPtr(e.affine.prefill22_fn.handle)); } + +test "prompt int8: large GDN groups retain four separate quantized projections" { + var d: cuda.Driver = undefined; + var e = engine(&d); + e.affine.pdl = true; + e.int8.on = true; + e.int8.ws = 0x900000; + e.int8.flag = .{ .d = &d, .ptr = 0x910000, .len = 4 }; + var ls: [4]q.engine.Proj = undefined; + for (&ls, [_]usize{ 10240, 6144, 48, 48 }) |*l, n| l.* = .{ .a4 = .{ .w = 10, .s = 20, .b = 30, .n = n, .k = 5120, .npad = std.mem.alignForward(usize, n, 128) } }; + for ([_]usize{ 2048, 4096 }) |rows| { + Trace.reset(); + try e.projectMany(&ls, 0x10000, 0x20000, &.{ 0x30000, 0x40000, 0x50000, 0x60000 }, rows, true, 0, false, true); + try T.expectEqualSlices(usize, &.{ 8, 9, 8, 9, 8, 9, 8, 9 }, Trace.ids[0..Trace.count]); + } +} diff --git a/zig/qwen35_prompt_pair_host.zig b/zig/qwen35_prompt_pair_host.zig new file mode 100644 index 00000000000..86578fe9be0 --- /dev/null +++ b/zig/qwen35_prompt_pair_host.zig @@ -0,0 +1,72 @@ +//! Production a/b prompt launches through a recording driver, with no CUDA or checkpoint opened. +const std = @import("std"); +const cuda = @import("cuda"); +const q = @import("qwen35"); +const fixture = @import("qwen35_verify_host.zig"); +const t = std.testing; +const Trace = struct { + var ids: [1024]usize = undefined; + var count: usize = 0; + var parts: cuda.qlinear.PrefillParts = undefined; + var dims: [4]c_int = undefined; + var input: u64 = 0; + var grid: u32 = 0; + var threads: u32 = 0; + fn launch(f: cuda.abi.Function, gx: c_uint, _: c_uint, _: c_uint, bx: c_uint, _: c_uint, _: c_uint, _: c_uint, _: cuda.abi.Stream, args: ?[*]?*anyopaque, _: ?[*]?*anyopaque) callconv(.c) cuda.abi.Result { + const id = @intFromPtr(f); + ids[count] = id; + count += 1; + if (id == 0x6153) { + parts = @as(*const cuda.qlinear.PrefillParts, @ptrCast(@alignCast(args.?[1].?))).*; + input = @as(*const u64, @ptrCast(@alignCast(args.?[0].?))).*; + for (&dims, 0..) |*v, i| v.* = @as(*const c_int, @ptrCast(@alignCast(args.?[2 + i].?))).*; + grid = gx; + threads = bx; + } + return 0; + } +}; +fn function(d: *cuda.Driver, id: usize) cuda.Function { + return .{ .d = d, .handle = @ptrFromInt(id) }; +} +fn weight(n: usize, i: usize) q.engine.Proj { + return .{ .a4 = .{ .w = 10 + i, .s = 20 + i, .b = 30 + i, .n = n, .k = 5120, .npad = std.mem.alignForward(usize, n, 128) } }; +} +test "prompt pair: actual adapter leaves qkv and z separate and binds one a/b launch at both large row counts" { + var d: cuda.Driver = undefined; + var e = fixture.engine(&d, true); + d.api.cuLaunchKernel = Trace.launch; + e.affine.prefill_fn = function(&d, 0x6151); + e.affine.prefill22_fn = function(&d, 0x6152); + e.affine.prefill_many_fn = function(&d, 0x6153); + e.g = .{ .hidden = 5120, .intermediate = 17408, .layers = 64, .vocab = 1, .k_heads = 16, .v_heads = 48, .q_heads = 24, .kv_heads = 4, .eps = 1e-6, .tied = false, .context = 4096, .linear = @splat(false) }; + const ls = [_]q.engine.Proj{ weight(10240, 0), weight(6144, 1), weight(48, 2), weight(48, 3) }; + const outs = [_]u64{ 0x20000, 0x30000, 0x40000, 0x50000 }; + for ([_]usize{ 2048, 4096 }) |rows| { + Trace.count = 0; + try e.projectMany(&ls, 0x10000, 0, &outs, rows, true, 0, false, true); + try t.expectEqualSlices(usize, &.{ 0x6152, 0x6152, 0x6153 }, Trace.ids[0..Trace.count]); + try t.expectEqual(@as(c_int, 2), Trace.parts.count); + try t.expectEqual(@as(u64, 0x10000), Trace.input); + try t.expectEqual([4]c_int{ @intCast(rows), 5120, 5120, 9 }, Trace.dims); + try t.expectEqual(@as(u32, @intCast(rows / 64)), Trace.grid); + try t.expectEqual(@as(u32, 256), Trace.threads); + for (Trace.parts.p[0..2], 0..) |part, i| { + try t.expectEqual(@as(c_int, 48), part.n); + try t.expectEqual(@as(c_int, 128), part.npad); + try t.expectEqual(@as(c_int, @intCast(i * rows / 128)), part.first); + try t.expectEqual(outs[2 + i], part.out); + try t.expectEqual(ls[2 + i].a4.w, part.w); + try t.expectEqual(ls[2 + i].a4.s, part.scales); + try t.expectEqual(ls[2 + i].a4.b, part.biases); + } + } + for ([_]usize{ 257, 2047, 2048 }) |rows| for ([_]bool{ false, true }) |allow| for ([_]bool{ false, true }) |pdl| { + if (rows >= 2048 and allow and pdl) continue; + e.affine.pdl = pdl; + Trace.count = 0; + try e.projectMany(&ls, 0x10000, 0, &outs, rows, true, 0, false, allow); + try t.expectEqual(@as(usize, 4), Trace.count); + for (Trace.ids[0..Trace.count]) |id| try t.expect(id != 0x6153); + }; +} diff --git a/zig/sessions_writes_test.zig b/zig/sessions_writes_test.zig index 1f1386625be..80a3f7d5b94 100644 --- a/zig/sessions_writes_test.zig +++ b/zig/sessions_writes_test.zig @@ -66,14 +66,15 @@ fn mixed(root: ?[]const u8, covered: bool) !struct { counts: tier.Counts, peak: cfg.policy.delta = covered; cfg.snapshot.layers = 4; cfg.policy.ram_bytes = 6 * cfg.snapshot.bytes(); - cfg.capacity = 1 << 15; + cfg.capacity = 1 << 14; // Limit the pool to one slot's capacity so the mixed workload exercises spills. cfg.pool_tokens = cfg.capacity; - cfg.chunk = 1 << 20; + cfg.chunk = 1 << 19; cfg.staging = 4; const b = try tier.Bench.init(testing.allocator, testing.io, cfg); defer b.deinit(); - const sh: load.Shape = .{ .requests = 150, .system = 1024, .first = .{ .lo = 256, .hi = 2048 }, .turn = .{ .lo = 128, .hi = 1536 }, .reply = .{ .lo = 64, .hi = 512 }, .cap = 16_384, .users = 20, .hot = 4, .fresh = 10, .hot_odds = 60 }; + // 40 requests at half the token sizes still spill, park, drop, read back and write deltas, with files over a chunk + const sh: load.Shape = .{ .requests = 40, .system = 512, .first = .{ .lo = 128, .hi = 1024 }, .turn = .{ .lo = 64, .hi = 768 }, .reply = .{ .lo = 32, .hi = 256 }, .cap = 8192, .users = 20, .hot = 4, .fresh = 10, .hot_odds = 60 }; const r = try load.run(testing.allocator, b, .mix, sh, 11); return .{ .counts = r.end, .peak = b.peak_used }; } @@ -88,8 +89,9 @@ test "sessions writes: on real files the tier writes and reads back exactly what defer gpa.free(root); const real = try mixed(root, covered); const accounted = try mixed(null, covered); - try testing.expect(real.counts.read > 0 and real.counts.spills > 0); - if (covered) try testing.expect(real.counts.deltas > 0); + try testing.expect(real.counts.read > 0 and real.counts.spills > 0 and real.counts.drops > 0); + try testing.expect(real.counts.written > real.counts.files * (1 << 19)); // files average over one chunk + if (covered) try testing.expect(real.counts.deltas > 0 and real.counts.covered_drops > 0); inline for (@typeInfo(tier.Counts).@"struct".field_names) |n| try testing.expectEqual(@field(real.counts, n), @field(accounted.counts, n)); try testing.expectEqual(real.peak, accounted.peak); } diff --git a/zig/src/cluster/bringup_test.zig b/zig/src/cluster/bringup_test.zig index 90f943aa9e5..662ca237a0d 100644 --- a/zig/src/cluster/bringup_test.zig +++ b/zig/src/cluster/bringup_test.zig @@ -13,6 +13,8 @@ const ms = std.time.ns_per_ms; /// Short beats and deadlines, so a stopped peer is dead in under half a second. const quick: bringup.Options = .{ .membership = .{ .beat_ns = 20 * ms, .suspect_ns = 120 * ms, .dead_ns = 400 * ms }, .settle_ns = 5 * std.time.ns_per_s, .linger_ns = 100 * ms }; +/// How long a watching rank waits: a watch returns at its first step after an event, so this bounds only a failure. +const watch_ns = 30 * std.time.ns_per_s; const Then = enum { leave, watch, stop }; @@ -38,7 +40,7 @@ const Rank = struct { .leave => r.live.leave(), .watch => { const t0 = fabric.words.nowNs(); - r.lost = r.live.watch(5 * std.time.ns_per_s) catch |e| { + r.lost = r.live.watch(watch_ns) catch |e| { r.err = e; return; }; @@ -127,7 +129,9 @@ test "a peer that stops after agreeing is found dead by name within the membersh const lost = p.ranks[0].lost.?; try std.testing.expectEqualStrings("b", lost.name.str()); try std.testing.expectEqual(@import("membership.zig").State.dead, lost.state); - try std.testing.expect(p.ranks[0].lost_after_ns >= quick.membership.dead_ns and p.ranks[0].lost_after_ns < 2 * std.time.ns_per_s); + // never before the dead time; after it, a step as soon as the runner schedules one, so the bound is the watch + try std.testing.expect(p.ranks[0].lost_after_ns >= quick.membership.dead_ns); + try std.testing.expect(p.ranks[0].lost_after_ns < watch_ns); } test "a peer that never comes ends the bring-up as NeverSettled at the settle time" { diff --git a/zig/src/core/contract/flashnext_tile_records.zig b/zig/src/core/contract/flashnext_tile_records.zig index 54f46f4dbb0..9035684c534 100644 --- a/zig/src/core/contract/flashnext_tile_records.zig +++ b/zig/src/core/contract/flashnext_tile_records.zig @@ -29,7 +29,6 @@ pub const cuda = [_]CudaRecord{ .{ .launch = .{ .name = "flashnext_hc fn_hc_writeback_norm_slices", .symbol = "fn_hc_writeback_norm_slices", .image = "flashnext_hc", .threads = 256 }, .usage = .{ .{ .regs = 64, .static = 1296, .bound = 256 }, .{ .regs = 64, .static = 1296, .bound = 256 }, .{ .regs = 64, .static = 1296, .bound = 256 }, .{ .regs = 64, .static = 1296, .bound = 256 }, .{ .regs = 64, .static = 1296, .bound = 256 } } }, .{ .launch = .{ .name = "prompt16 tf_prompt_bf16", .symbol = "tf_prompt_bf16", .image = "prompt16", .threads = 256, .dynamic = 98304, .opt_in = true }, .usage = .{ .{ .regs = 255, .static = 0, .bound = 256 }, .{ .regs = 255, .static = 0, .bound = 256 }, .{ .regs = 255, .static = 0, .bound = 256 }, .{ .regs = 255, .static = 0, .bound = 256 }, .{ .regs = 255, .static = 0, .bound = 256 } } }, .{ .launch = .{ .name = "prompt16 tf_prompt_bf16_f32", .symbol = "tf_prompt_bf16_f32", .image = "prompt16", .threads = 256, .dynamic = 98304, .opt_in = true }, .usage = .{ .{ .regs = 255, .static = 0, .bound = 256 }, .{ .regs = 255, .static = 0, .bound = 256 }, .{ .regs = 255, .static = 0, .bound = 256 }, .{ .regs = 255, .static = 0, .bound = 256 }, .{ .regs = 255, .static = 0, .bound = 256 } } }, - .{ .launch = .{ .name = "flashnext_mtp fn_row_topk", .symbol = "fn_row_topk", .image = "flashnext_mtp", .threads = 1024 }, .usage = .{ .{ .regs = 32, .static = 9228, .bound = 1024 }, .{ .regs = 59, .static = 9228, .bound = 1024 }, .{ .regs = 59, .static = 9228, .bound = 1024 }, .{ .regs = 31, .static = 9228, .bound = 1024 }, .{ .regs = 31, .static = 9228, .bound = 1024 } } }, }; /// nvcc 13.2's records where it compiles these tiles differently from 13.0. @@ -46,3 +45,8 @@ pub const cuda_132 = [_]registry.Override{ pub const cuda_133 = [_]registry.Override{ .{ .name = "flashnext_attn fn_attn_fused", .usage = .{ .{ .regs = 118, .static = 640, .bound = 128 }, .{ .regs = 118, .static = 640, .bound = 128 }, .{ .regs = 118, .static = 640, .bound = 128 }, .{ .regs = 122, .static = 640, .bound = 128 }, .{ .regs = 122, .static = 640, .bound = 128 } } }, }; + +/// The changed top-k stays visible to device limits while fresh compiler usage is pending. +pub const pending = [_]registry.CudaRecord{ + .{ .launch = .{ .name = "flashnext_mtp fn_row_topk", .symbol = "fn_row_topk", .image = "flashnext_mtp", .threads = 1024 }, .usage = registry.none }, +}; diff --git a/zig/src/core/contract/glm_cuda_records.zig b/zig/src/core/contract/glm_cuda_records.zig index 984e460cc03..fcf81aedc2d 100644 --- a/zig/src/core/contract/glm_cuda_records.zig +++ b/zig/src/core/contract/glm_cuda_records.zig @@ -46,6 +46,8 @@ pub const cuda = [_]registry.CudaRecord{ .{ .launch = .{ .name = "glm_index tf_glm_index_pools", .symbol = "tf_glm_index_pools", .image = "glm_index", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 62, .static = 33864, .bound = 256 }, .{ .regs = 64, .static = 33864, .bound = 256 }, .{ .regs = 64, .static = 33864, .bound = 256 }, .{ .regs = 59, .static = 33864, .bound = 256 }, .{ .regs = 59, .static = 33864, .bound = 256 } } }, .{ .launch = .{ .name = "glm_glue tf_glm_select_rows", .symbol = "tf_glm_select_rows", .image = "glm_glue", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 45, .static = 1072, .bound = 128 }, .{ .regs = 54, .static = 1072, .bound = 128 }, .{ .regs = 54, .static = 1072, .bound = 128 }, .{ .regs = 48, .static = 1072, .bound = 128 }, .{ .regs = 48, .static = 1072, .bound = 128 } } }, .{ .launch = .{ .name = "glm_glue tf_glm_select_rows_wide", .symbol = "tf_glm_select_rows_wide", .image = "glm_glue", .threads = 1024, .min_sm = 80 }, .usage = .{ .{ .regs = 32, .static = 1296, .bound = 1024 }, .{ .regs = 61, .static = 1296, .bound = 1024 }, .{ .regs = 61, .static = 1296, .bound = 1024 }, .{ .regs = 54, .static = 1296, .bound = 1024 }, .{ .regs = 61, .static = 1296, .bound = 1024 } } }, + .{ .launch = .{ .name = "glm_glue tf_glm_dsel_scan", .symbol = "tf_glm_dsel_scan", .image = "glm_glue", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 58, .static = 1040, .bound = 256 }, .{ .regs = 48, .static = 1040, .bound = 256 }, .{ .regs = 48, .static = 1040, .bound = 256 }, .{ .regs = 48, .static = 1040, .bound = 256 }, .{ .regs = 48, .static = 1040, .bound = 256 } } }, + .{ .launch = .{ .name = "glm_glue tf_glm_dsel_merge", .symbol = "tf_glm_dsel_merge", .image = "glm_glue", .threads = 1024, .min_sm = 80 }, .usage = .{ .{ .regs = 56, .static = 34064, .bound = 1024 }, .{ .regs = 64, .static = 34064, .bound = 1024 }, .{ .regs = 64, .static = 34064, .bound = 1024 }, .{ .regs = 64, .static = 34064, .bound = 1024 }, .{ .regs = 64, .static = 34064, .bound = 1024 } } }, .{ .launch = .{ .name = "glm_glue tf_glm_chunks_16", .symbol = "tf_glm_chunks_16", .image = "glm_glue", .threads = 256, .dynamic = 83328, .opt_in = true, .min_sm = 80 }, .usage = .{ .{ .regs = 64, .static = 0, .bound = 256 }, .{ .regs = 64, .static = 0, .bound = 256 }, .{ .regs = 64, .static = 0, .bound = 256 }, .{ .regs = 123, .static = 0, .bound = 256 }, .{ .regs = 123, .static = 0, .bound = 256 } } }, .{ .launch = .{ .name = "glm_glue tf_glm_chunks_32", .symbol = "tf_glm_chunks_32", .image = "glm_glue", .threads = 256, .dynamic = 101120, .opt_in = true, .min_sm = 80 }, .usage = .{ .{ .regs = 150, .static = 0, .bound = 256 }, .{ .regs = 150, .static = 0, .bound = 256 }, .{ .regs = 150, .static = 0, .bound = 256 }, .{ .regs = 130, .static = 0, .bound = 256 }, .{ .regs = 130, .static = 0, .bound = 256 } } }, .{ .launch = .{ .name = "glm_ops tf_glm_dsa_tokens", .symbol = "tf_glm_dsa_tokens", .image = "glm_ops", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 25, .static = 0, .bound = 0 }, .{ .regs = 25, .static = 0, .bound = 0 }, .{ .regs = 25, .static = 0, .bound = 0 }, .{ .regs = 24, .static = 0, .bound = 0 }, .{ .regs = 24, .static = 0, .bound = 0 } } }, @@ -77,6 +79,7 @@ pub const cuda_133 = [_]registry.Override{ .{ .name = "glm_index tf_glm_index_scores", .usage = .{ .{ .regs = 128, .static = 32768, .bound = 256 }, .{ .regs = 128, .static = 32768, .bound = 256 }, .{ .regs = 128, .static = 32768, .bound = 256 }, .{ .regs = 126, .static = 32768, .bound = 256 }, .{ .regs = 126, .static = 32768, .bound = 256 } } }, .{ .name = "glm_index tf_glm_index_pools", .usage = .{ .{ .regs = 62, .static = 33864, .bound = 256 }, .{ .regs = 64, .static = 33864, .bound = 256 }, .{ .regs = 64, .static = 33864, .bound = 256 }, .{ .regs = 54, .static = 33864, .bound = 256 }, .{ .regs = 54, .static = 33864, .bound = 256 } } }, .{ .name = "glm_glue tf_glm_select_rows_wide", .usage = .{ .{ .regs = 32, .static = 1296, .bound = 1024 }, .{ .regs = 61, .static = 1296, .bound = 1024 }, .{ .regs = 61, .static = 1296, .bound = 1024 }, .{ .regs = 62, .static = 1296, .bound = 1024 }, .{ .regs = 62, .static = 1296, .bound = 1024 } } }, + .{ .name = "glm_glue tf_glm_dsel_scan", .usage = .{ .{ .regs = 58, .static = 1040, .bound = 256 }, .{ .regs = 48, .static = 1040, .bound = 256 }, .{ .regs = 48, .static = 1040, .bound = 256 }, .{ .regs = 45, .static = 1040, .bound = 256 }, .{ .regs = 45, .static = 1040, .bound = 256 } } }, .{ .name = "glm_glue tf_glm_chunks_32", .usage = .{ .{ .regs = 150, .static = 0, .bound = 256 }, .{ .regs = 150, .static = 0, .bound = 256 }, .{ .regs = 150, .static = 0, .bound = 256 }, .{ .regs = 128, .static = 0, .bound = 256 }, .{ .regs = 128, .static = 0, .bound = 256 } } }, .{ .name = "glm_ops tf_glm_dsa_tokens", .usage = .{ .{ .regs = 25, .static = 0, .bound = 0 }, .{ .regs = 25, .static = 0, .bound = 0 }, .{ .regs = 25, .static = 0, .bound = 0 }, .{ .regs = 22, .static = 0, .bound = 0 }, .{ .regs = 22, .static = 0, .bound = 0 } } }, }; diff --git a/zig/src/core/contract/nemotron_draw_records.zig b/zig/src/core/contract/nemotron_draw_records.zig new file mode 100644 index 00000000000..cae4ed4da38 --- /dev/null +++ b/zig/src/core/contract/nemotron_draw_records.zig @@ -0,0 +1,9 @@ +//! Nemotron's batched draw entries; usage from the full kernel contract on a GB10 (sm_80/86/89/120/121). +const registry = @import("registry.zig"); + +pub const records = [_]registry.CudaRecord{ + .{ .launch = .{ .name = "cuda sample tf_draw_ids_rows", .symbol = "tf_draw_ids_rows", .image = "sample", .threads = 1024 }, .usage = .{ .{ .regs = 64, .static = 19504, .bound = 1024 }, .{ .regs = 64, .static = 19504, .bound = 1024 }, .{ .regs = 64, .static = 19504, .bound = 1024 }, .{ .regs = 64, .static = 19504, .bound = 1024 }, .{ .regs = 64, .static = 19504, .bound = 1024 } } }, + .{ .launch = .{ .name = "nemotron_ops tf_nemo_gather_rows", .symbol = "tf_nemo_gather_rows", .image = "nemotron_ops", .threads = 256 }, .usage = .{ .{ .regs = 24, .static = 0, .bound = 0 }, .{ .regs = 24, .static = 0, .bound = 0 }, .{ .regs = 24, .static = 0, .bound = 0 }, .{ .regs = 22, .static = 0, .bound = 0 }, .{ .regs = 22, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "nemotron_ops tf_nemo_gather_last", .symbol = "tf_nemo_gather_last", .image = "nemotron_ops", .threads = 256 }, .usage = .{ .{ .regs = 22, .static = 0, .bound = 0 }, .{ .regs = 22, .static = 0, .bound = 0 }, .{ .regs = 22, .static = 0, .bound = 0 }, .{ .regs = 36, .static = 0, .bound = 0 }, .{ .regs = 36, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "nemotron_ops tf_nemo_scatter_rows", .symbol = "tf_nemo_scatter_rows", .image = "nemotron_ops", .threads = 32 }, .usage = .{ .{ .regs = 14, .static = 0, .bound = 0 }, .{ .regs = 14, .static = 0, .bound = 0 }, .{ .regs = 14, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 } } }, +}; diff --git a/zig/src/core/contract/registry_joins.zig b/zig/src/core/contract/registry_joins.zig index 1e60067bc12..967c269a3a4 100644 --- a/zig/src/core/contract/registry_joins.zig +++ b/zig/src/core/contract/registry_joins.zig @@ -42,7 +42,9 @@ pub const nvcc_133_after = @import("flashnext_tile_records.zig").cuda_133 ++ @import("paging_pending.zig").cuda_133 ++ @import("experts_bf16_records.zig").cuda_133; pub const cuda_pending = @import("qwen_whole_records.zig").records ++ + @import("flashnext_tile_records.zig").pending ++ @import("exl3_prompt_pending.zig").records ++ + @import("nemotron_draw_records.zig").records ++ @import("cuda_lane_pending.zig").records ++ @import("weight_only_records.zig").cuda ++ @import("hc_activation_records.zig").cuda ++ diff --git a/zig/src/core/engine_api.zig b/zig/src/core/engine_api.zig index 00b7ef014c2..fb96b413edc 100644 --- a/zig/src/core/engine_api.zig +++ b/zig/src/core/engine_api.zig @@ -387,7 +387,7 @@ pub const Status = @import("engine_status.zig").Status; pub const SubmitError = error{ Closed, Busy, InvalidSpans, Stale, InvalidRequest, MemoryPressure }; // Stale: put-back has not reached the device /// What a request refused under critical memory pressure says (a 503). -pub const pressure_message = "this Mac is under critical memory pressure: the server takes no new requests until it eases; retry shortly"; +pub const pressure_message = "the system is under critical memory pressure: the server takes no new requests until it eases; retry shortly"; /// What a reply refused or ended for `Stale` says, a submit's error and a queued job's failure alike. pub const stale_message = "a Living Weights delete could not be put back on the device: send the delete again to retry it, or restart the server"; diff --git a/zig/src/core/lane_host.zig b/zig/src/core/lane_host.zig index d883f1d8acb..dbd26159689 100644 --- a/zig/src/core/lane_host.zig +++ b/zig/src/core/lane_host.zig @@ -89,7 +89,7 @@ pub const LaneHost = struct { decode_cap: bool = false, // --decode-share given by flag (the env never opts in): a chunk-invariant family may cap prefix: @import("lane_host_prefix.zig").Wait = .{}, // a request's wait for a cut another prompt is filling finals: std.ArrayList(usize) = .empty, - pressure: ?@import("memory_pressure.zig").Governor = null, // macOS memory pressure (lane_host_pressure.zig); null: off + pressure: ?@import("memory_pressure.zig").Governor = null, // OS memory pressure (lane_host_pressure.zig); null: off activity: ?@import("lane_activity.zig").Activity = null, // owned work scopes for a backend's watchdog; null: off failure: ?@import("lane_activity.zig").Failure = null, // hears a round's or request's error; null: off load: load.State = .{}, // this host's part of the server's load ledger (lane_host_load.zig) diff --git a/zig/src/core/lane_host_strand_test.zig b/zig/src/core/lane_host_strand_test.zig new file mode 100644 index 00000000000..d635e0f9dc0 --- /dev/null +++ b/zig/src/core/lane_host_strand_test.zig @@ -0,0 +1,600 @@ +//! Requests that end without finishing, 200 in a row down each path: every lane, page and slot comes back. +const std = @import("std"); +const lanes = @import("lanes"); +const api = @import("engine_api.zig"); +const kv = @import("kv_pool.zig"); +const mp = @import("memory_pressure.zig"); +const LaneHost = api.LaneHost; +const Ledger = api.load_ledger.Ledger; +const Reason = api.Reason; +const Request = api.Request; +const t = std.testing; +const a = t.allocator; +const io = t.io; + +const runs = 200; +const lanes_n = 2; +const pool_pages = 8192; +const long_reply = 4096; // pages(8 + 4096 + 1) = 1027: runs until cancelled or failed, fits the pool twice over +const huge_reply = 40000; // pages(8 + 40000 + 1) = 10003: more than the whole pool +const layout: kv.Layout = .{ .fixed_bytes = 0, .token_bytes = 1, .page_tokens = 4, .snap_bytes = 1 }; +const window = 1; +const pause_word = 2; // a prompt starting with it pauses in its prompt pass and holds its lane until cancelled + +const prompt = [_]u32{ 3, 1, 4, 1, 5, 9, 2, 6 }; +const paused_prompt = [_]u32{ pause_word, 7, 1, 8, 2, 8, 1, 8 }; +const bad_spans = [_][2]u32{.{ 3, 1 }}; +const plain: Request = .{ .prompt = &prompt, .max_tokens = 12 }; +const running: Request = .{ .prompt = &prompt, .max_tokens = long_reply }; +const huge: Request = .{ .prompt = &prompt, .max_tokens = huge_reply }; +const holder: Request = .{ .prompt = &paused_prompt, .max_tokens = long_reply }; +const spanned: Request = .{ .prompt = &prompt, .max_tokens = 12, .decode_spans = &bad_spans }; + +/// The host's allocator: it refuses the test thread's allocations while shut, as a host out of memory does. +const Gate = struct { + owner: std.Thread.Id, + shut: std.atomic.Value(bool) = .init(false), + + fn allocator(g: *Gate) std.mem.Allocator { + return .{ .ptr = g, .vtable = &.{ .alloc = alloc, .resize = resize, .remap = remap, .free = free } }; + } + fn alloc(ctx: *anyopaque, n: usize, al: std.mem.Alignment, ra: usize) ?[*]u8 { + const g: *Gate = @ptrCast(@alignCast(ctx)); + if (g.shut.load(.acquire) and std.Thread.getCurrentId() == g.owner) return null; + return a.rawAlloc(n, al, ra); + } + fn resize(_: *anyopaque, bytes: []u8, al: std.mem.Alignment, n: usize, ra: usize) bool { + return a.rawResize(bytes, al, n, ra); + } + fn remap(_: *anyopaque, bytes: []u8, al: std.mem.Alignment, n: usize, ra: usize) ?[*]u8 { + return a.rawRemap(bytes, al, n, ra); + } + fn free(_: *anyopaque, bytes: []u8, al: std.mem.Alignment, ra: usize) void { + a.rawFree(bytes, al, ra); + } +}; + +/// A backend's pool as the fake target reserves from it: a stream's lease at its prefill, back at its release. +const Pages = struct { + pool: kv.Pool, + leases: std.AutoHashMapUnmanaged(*const lanes.Stream, kv.Lease) = .empty, + + fn of(ctx: *anyopaque) *Pages { + return @ptrCast(@alignCast(ctx)); + } + fn take(ctx: *anyopaque, s: *lanes.Stream) anyerror!void { + const p = of(ctx); + var l: kv.Lease = .{}; + errdefer p.pool.finish(&l); + const need = layout.need(s.prompt().len, s.max_new, window); + try p.pool.promise(&l, need); + try p.pool.cover(&l, need, null); + try p.leases.put(a, s, l); + } + fn give(ctx: *anyopaque, s: *lanes.Stream) void { + const p = of(ctx); + var kv_ = p.leases.fetchRemove(s) orelse return; + p.pool.finish(&kv_.value); + } + fn reserve(p: *Pages) lanes.fake.Reserve { + return .{ .ctx = p, .take = take, .give = give }; + } + fn deinit(p: *Pages) void { + p.leases.deinit(a); + p.pool.deinit(); + } +}; + +/// A pressure source the test thread sets while the engine thread reads it. +const Dial = struct { + level: std.atomic.Value(u8) = .init(@backingInt(mp.Level.normal)), + fn set(d: *Dial, l: mp.Level) void { + d.level.store(@backingInt(l), .release); + } + fn read(ctx: ?*anyopaque) ?mp.Level { + const d: *Dial = @ptrCast(@alignCast(ctx.?)); + return @fromBackingInt(@intCast(d.level.load(.acquire))); + } +}; + +/// The backend's readiness, which the test thread turns off for a refusal. +const Health = struct { + up: std.atomic.Value(bool) = .init(true), + fn read(ctx: *anyopaque) bool { + const h: *Health = @ptrCast(@alignCast(ctx)); + return h.up.load(.acquire); + } +}; + +const Mode = enum(u8) { serve, cancel_prompt, fail_prompt }; + +/// The fake target's prompt calls, which cancel the request or fail after the lane and its pages are taken. +const Driver = struct { + base: *const lanes.backend.Backend.VTable, + vt: lanes.backend.Backend.VTable, + engine: api.Engine, + mode: std.atomic.Value(u8) = .init(0), + id: std.atomic.Value(api.Id) = .init(0), + + fn of(ptr: *anyopaque) *Driver { + const f: *lanes.fake.Fake = @ptrCast(@alignCast(ptr)); + return @ptrCast(@alignCast(f.prefill_hook_ctx.?)); + } + fn is(d: *const Driver, m: Mode) bool { + return d.mode.load(.acquire) == @backingInt(m); + } + fn set(d: *Driver, m: Mode) void { + d.mode.store(@backingInt(m), .release); + } + fn hook(ctx: *anyopaque, s: *lanes.Stream, chunk: usize) void { + const d: *Driver = @ptrCast(@alignCast(ctx)); + if (chunk == 0 and s.prompt()[0] == pause_word) s.paused = true; + if (chunk == 0 and d.is(.cancel_prompt)) d.engine.cancel(d.id.load(.acquire)); + } + fn prefill(ptr: *anyopaque, s: *lanes.Stream) anyerror!void { + const d = of(ptr); + try d.base.prefill(ptr, s); + if (d.is(.fail_prompt)) return error.GpuFailed; + } + fn step(ptr: *anyopaque, s: *lanes.Stream, max_rows: u32) anyerror!bool { + const d = of(ptr); + const done = try d.base.prefill_step.?(ptr, s, max_rows); + if (d.is(.fail_prompt)) return error.GpuFailed; + return done; + } +}; + +/// One request's events; `cancel` cancels it at its first tokens. +const Box = struct { + mutex: std.Io.Mutex = .init, + done: ?Reason = null, + message: []const u8 = "", + tokens: usize = 0, + events: usize = 0, + cancel: ?api.Engine = null, + + fn event(ctx: *anyopaque, id: api.Id, e: *const api.Event) void { + const b: *Box = @ptrCast(@alignCast(ctx)); + var stop: ?api.Engine = null; + b.mutex.lockUncancelable(io); + b.events += 1; + switch (e.*) { + .tokens => |ids| { + b.tokens += ids.len; + stop = b.cancel; + b.cancel = null; + }, + .finished => |f| { + b.done = f.reason; + b.message = f.message; + }, + else => {}, + } + b.mutex.unlock(io); + if (stop) |engine| engine.cancel(id); + } + fn state(b: *Box) struct { usize, ?Reason } { + b.mutex.lockUncancelable(io); + defer b.mutex.unlock(io); + return .{ b.tokens, b.done }; + } + fn waitFor(b: *Box, ms: usize) ?Reason { + for (0..ms) |_| { + if (b.state()[1]) |r| return r; + std.Io.sleep(io, .fromMilliseconds(1), .awake) catch {}; + } + return b.state()[1]; + } + fn startsWithin(b: *Box, ms: usize) bool { + for (0..ms) |_| { + if (b.state()[0] > 0) return true; + std.Io.sleep(io, .fromMilliseconds(1), .awake) catch {}; + } + return b.state()[0] > 0; + } + fn sink(b: *Box) api.Sink { + return .{ .ctx = b, .event = event }; + } +}; + +/// The host's lists and its load-ledger groups, read under its lock. +const HostSide = struct { + queued: usize, + admitted: usize, + filling: usize, + cancels: usize, + running: u32, + waiting: u32, + filling_left: ?u64, + lanes_free: u32, +}; + +/// The core's live streams, the fake's lanes, the pool's pages and leases, and the host's KV ledger. +const BackendSide = struct { + live: usize, + lanes: usize, + leases: usize, + pages_free: usize, + pages_promised: usize, + pages_leased: usize, + kv_free: u64, +}; + +const Counts = struct { host: HostSide, backend: ?BackendSide }; + +const Kind = enum { whole, stepped }; + +const Path = enum { served, busy, closed, stale, pressure, invalid, spans, cancel_at_once, cancel_prompt, cancel_decode, fail_prompt, fail_round, no_memory }; + +/// A lane host on the fake target whose lanes reserve pages from a pool its ledger counts. +const Rig = struct { + gate: Gate, + cfg: lanes.Config, + pages: Pages, + target: lanes.fake.Fake, + clock: lanes.fake.FixedClock, + driver: Driver, + core: lanes.Engine, + host: LaneHost, + ledger: Ledger, + health: Health, + dial: Dial, + box: Box, + blockers: [lanes_n]Box, + next: api.Id, + base: Counts, + stopped: bool, + + fn init(r: *Rig, kind: Kind, governed: bool) !void { + r.gate = .{ .owner = std.Thread.getCurrentId() }; + r.cfg = try lanes.Config.init(a, .{ .exact_width = 8, .hidden_rows = true }, 8, 7); // every round verifies + errdefer r.cfg.deinit(a); + r.pages = .{ .pool = try kv.Pool.init(a, pool_pages, 4) }; + errdefer r.pages.deinit(); + r.target = .{ .gpa = a, .prefill_chunks = 2, .reserve = r.pages.reserve() }; + errdefer r.target.deinit(); + const base = switch (kind) { + .whole => r.target.backend(), + .stepped => r.target.stepped(), + }; + r.driver = .{ .base = base.vtable, .vt = base.vtable.*, .engine = undefined }; + r.driver.vt.prefill = Driver.prefill; + if (kind == .stepped) r.driver.vt.prefill_step = Driver.step; + r.target.prefill_hook = Driver.hook; + r.target.prefill_hook_ctx = &r.driver; + r.clock = .{}; + r.core = lanes.Engine.init(a, &r.cfg, .{ .ptr = &r.target, .vtable = &r.driver.vt, .chunk_invariant = true }, r.clock.clock()); + errdefer r.core.deinit(); + r.health = .{}; + r.dial = .{}; + r.box = .{}; + r.blockers = .{ .{}, .{} }; + r.next = 1; + r.stopped = false; + r.host = LaneHost.init(r.gate.allocator(), io, &r.core, .{ .lanes = lanes_n }); + r.host.capacity = .{ .mode = .paged }; + r.host.health = .{ .ctx = &r.health, .read = Health.read }; + if (governed) r.host.pressure = .{ .source = .{ .ctx = &r.dial, .read = Dial.read }, .calm_ns = 0, .every_ns = 0 }; + r.driver.engine = r.host.engine(); + try r.host.countPool(&r.pages.pool); + errdefer r.host.uncountPool(); + LaneHost.Load.poolChanged(&r.host, .{ .capacity = pool_pages * layout.page_tokens, .available = pool_pages * layout.page_tokens }); // paged needs a census + try r.host.start(); + r.ledger = .init(io); + r.ledger.attach(r.host.engine()); + } + + /// The start values every path must come back to, checked against an idle host first. + fn mark(r: *Rig) !void { + r.base = try r.counts(true); + try t.expectEqual(@as(usize, 0), r.base.host.admitted + r.base.host.queued + r.base.backend.?.live); + try t.expectEqual(@as(u32, lanes_n), r.base.host.lanes_free); + try t.expectEqual(@as(usize, pool_pages), r.base.backend.?.pages_free); + try t.expectEqual(@as(u64, pool_pages * 4), r.base.backend.?.kv_free); + } + + /// Stops the host, then the pool shows nothing promised, leased or held. + fn close(r: *Rig) !void { + r.ledger.detach(false); + r.host.stop(); + r.stopped = true; + try t.expect(r.pages.pool.idle()); + try t.expectEqual(@as(usize, 0), r.pages.leases.count()); + try t.expectEqual(@as(usize, 0), r.target.lanes.count()); + } + + fn deinit(r: *Rig) void { + if (!r.stopped) { + r.ledger.detach(false); + r.host.stop(); + } + r.core.deinit(); + r.target.deinit(); + r.pages.deinit(); + r.cfg.deinit(a); + } + + fn engine(r: *Rig) api.Engine { + return r.host.engine(); + } + + fn id(r: *Rig) api.Id { + r.next += 1; + return r.next; + } + + /// The counts now; the backend side only when asked (read while no request runs on the engine thread). + fn counts(r: *Rig, backend: bool) !Counts { + const snap = r.ledger.read(); + const req = snap.requests orelse return error.NoRequestsGroup; + const cap = snap.capacity orelse return error.NoCapacityGroup; + r.host.lock(); + defer r.host.unlock(); + const census = r.pages.pool.census(); + return .{ + .host = .{ + .queued = r.host.queued.items.len, + .admitted = r.host.admitted.items.len, + .filling = r.host.filling.items.len, + .cancels = r.host.cancels.items.len, + .running = req.running, + .waiting = req.waiting, + .filling_left = req.filling_left, + .lanes_free = cap.lanes_free, + }, + .backend = if (!backend) null else .{ + .live = r.core.live.items.len, + .lanes = r.target.lanes.count(), + .leases = r.pages.leases.count(), + .pages_free = census.free, + .pages_promised = census.promised, + .pages_leased = census.leased, + .kv_free = r.host.kv.?.free(), + }, + }; + } + + /// Waits up to 2 s for the counts to equal `want`, then checks them. + fn settle(r: *Rig, want: Counts) !void { + const backend = want.backend != null; + var now = try r.counts(backend); + for (0..2000) |_| { + if (std.meta.eql(now, want)) return; + std.Io.sleep(io, .fromMilliseconds(1), .awake) catch {}; + now = try r.counts(backend); + } + try t.expectEqual(want, now); + } + + /// Waits for the engine thread to govern at `want`, waking it from its idle wait to read the dial. + fn reach(r: *Rig, want: mp.Level) !void { + for (0..4000) |_| { + r.host.lock(); + const now = r.host.pressure.?.level; + if (now != want) r.host.wake.signal(io); + r.host.unlock(); + if (now == want) return; + std.Io.sleep(io, .fromMilliseconds(1), .awake) catch {}; + } + return error.LevelNotReached; + } + + fn setStale(r: *Rig, on: bool) void { + r.host.lock(); + defer r.host.unlock(); + r.host.stale = on; + } + + fn setFailRound(r: *Rig, on: bool) void { + r.host.lock(); + defer r.host.unlock(); + r.target.fail_round = if (on) r.target.rounds + 1 else null; + } + + /// One request down `path`, its end checked; the counts are the caller's to check. + fn drive(r: *Rig, path: Path) !void { + const e = r.engine(); + const n = r.id(); + r.box = .{}; + const sink = r.box.sink(); + switch (path) { + .served => { + try e.submit(n, &plain, sink); + try t.expectEqual(@as(?Reason, .length), r.box.waitFor(5000)); + try t.expectEqual(@as(usize, 12), r.box.state()[0]); + }, + .busy => { + r.gate.shut.store(true, .release); + defer r.gate.shut.store(false, .release); + try t.expectError(error.Busy, e.submit(n, &plain, sink)); + }, + .closed => { + r.health.up.store(false, .release); + defer r.health.up.store(true, .release); + try t.expectError(error.Closed, e.submit(n, &plain, sink)); + }, + .stale => { + r.setStale(true); + defer r.setStale(false); + try t.expectError(error.Stale, e.submit(n, &plain, sink)); + }, + .pressure => { + r.dial.set(.critical); + try r.reach(.critical); + try t.expectError(error.MemoryPressure, e.submit(n, &plain, sink)); + r.dial.set(.normal); + try r.reach(.normal); + }, + .invalid => { + var out: [2]f32 = @splat(0); + const ends = [_]u32{prompt.len}; + const embed: Request = .{ .prompt = &prompt, .max_tokens = 0, .drafts = false, .embedding = .{ .ends = &ends, .dimensions = 2, .output = &out } }; + // the host's own refusal on odd ids, the engine API's check before it on even ones + const got = if (n % 2 == 1) e.vtable.submit(e.ctx, n, &embed, sink) else e.submit(n, &embed, sink); + try t.expectError(error.InvalidRequest, got); + }, + .spans => try t.expectError(error.InvalidSpans, e.submit(n, &spanned, sink)), + .cancel_at_once => { + try e.submit(n, &holder, sink); // it waits for the cancel: `running` can reply in full first on a loaded runner + e.cancel(n); + try t.expectEqual(@as(?Reason, .cancelled), r.box.waitFor(5000)); + }, + .cancel_prompt => { + r.driver.id.store(n, .release); + r.driver.set(.cancel_prompt); + defer r.driver.set(.serve); + try e.submit(n, &running, sink); + try t.expectEqual(@as(?Reason, .cancelled), r.box.waitFor(5000)); + try t.expectEqual(@as(usize, 0), r.box.state()[0]); + }, + .cancel_decode => { + r.box.cancel = e; + try e.submit(n, &running, sink); + try t.expectEqual(@as(?Reason, .cancelled), r.box.waitFor(5000)); + try t.expect(r.box.state()[0] > 0); + }, + .fail_prompt => { + r.driver.set(.fail_prompt); + defer r.driver.set(.serve); + try e.submit(n, &running, sink); + try t.expectEqual(@as(?Reason, .failed), r.box.waitFor(5000)); + try t.expectEqualStrings("GpuFailed", r.box.message); + }, + .fail_round => { + r.setFailRound(true); + defer r.setFailRound(false); + try e.submit(n, &running, sink); + try t.expectEqual(@as(?Reason, .failed), r.box.waitFor(5000)); + try t.expectEqualStrings("GpuFailed", r.box.message); + }, + .no_memory => { + try e.submit(n, &huge, sink); + try t.expectEqual(@as(?Reason, .failed), r.box.waitFor(5000)); + try t.expect(std.mem.indexOf(u8, r.box.message, "no memory") != null); + }, + } + if (refusal(path)) try t.expectEqual(@as(usize, 0), r.box.events); // a refused request never reaches its sink + } + + /// `runs` requests down `path`, each followed by the start counts; then a normal request is served. + fn strand(r: *Rig, path: Path) !void { + for (0..runs) |_| { + try r.drive(path); + try r.settle(r.base); + } + try r.drive(.served); + try r.settle(r.base); + } +}; + +fn refusal(path: Path) bool { + return switch (path) { + .busy, .closed, .stale, .pressure, .invalid, .spans => true, + else => false, + }; +} + +/// A rig of `kind` with its start counts marked, for one test's paths. +fn rigged(r: *Rig, kind: Kind, governed: bool) !void { + try r.init(kind, governed); + errdefer r.deinit(); + try r.mark(); +} + +test "lane strand: 200 refusals of each code take no lane, page or slot, and the next request is served" { + var r: Rig = undefined; + try rigged(&r, .whole, true); + defer r.deinit(); + for ([_]Path{ .busy, .closed, .stale, .pressure, .invalid, .spans }) |path| try r.strand(path); + try t.expectEqual(@as(u64, 6), r.ledger.read().requests.?.started); // only the six served requests were queued + try r.close(); +} + +test "lane strand: 200 cancels while queued behind full lanes give every count back" { + var r: Rig = undefined; + try rigged(&r, .whole, false); + defer r.deinit(); + const e = r.engine(); + var ids: [lanes_n]api.Id = undefined; + for (&r.blockers, &ids) |*b, *n| { + n.* = r.id(); + try e.submit(n.*, &holder, b.sink()); + } + for (&r.blockers) |*b| try t.expect(b.startsWithin(5000)); + var held: Counts = .{ .host = r.base.host, .backend = null }; + held.host.admitted = lanes_n; + held.host.running = lanes_n; + held.host.lanes_free = 0; + try r.settle(held); + var waiting = held; + waiting.host.queued = 1; + waiting.host.waiting = 1; + for (0..runs) |_| { + const n = r.id(); + r.box = .{}; + try e.submit(n, &plain, r.box.sink()); + try r.settle(waiting); // it waits: no lane is free + e.cancel(n); + try t.expectEqual(@as(?Reason, .cancelled), r.box.waitFor(5000)); + try t.expectEqual(@as(usize, 0), r.box.state()[0]); + try r.settle(held); + } + for (ids) |n| e.cancel(n); + for (&r.blockers) |*b| try t.expectEqual(@as(?Reason, .cancelled), b.waitFor(5000)); + try r.settle(r.base); + try r.drive(.served); + try r.settle(r.base); + try r.close(); +} + +test "lane strand: 200 cancels at once, mid-prompt and mid-decode, whole and stepped prompts" { + for ([_]Kind{ .whole, .stepped }) |kind| { + var r: Rig = undefined; + try rigged(&r, kind, false); + defer r.deinit(); + for ([_]Path{ .cancel_at_once, .cancel_prompt, .cancel_decode }) |path| try r.strand(path); + try r.close(); + } +} + +test "lane strand: 200 backend errors in the prompt pass and in a round, whole and stepped prompts" { + const log_level = t.log_level; + t.log_level = .err; + defer t.log_level = log_level; + for ([_]Kind{ .whole, .stepped }) |kind| { + var r: Rig = undefined; + try rigged(&r, kind, false); + defer r.deinit(); + for ([_]Path{ .fail_prompt, .fail_round }) |path| try r.strand(path); + try r.close(); + } +} + +test "lane strand: 200 requests with no lane memory and nothing else running, whole and stepped prompts" { + for ([_]Kind{ .whole, .stepped }) |kind| { + var r: Rig = undefined; + try rigged(&r, kind, false); + defer r.deinit(); + try r.strand(.no_memory); + try r.close(); + } +} + +test "lane strand: 200 requests mixing every path, whole and stepped prompts" { + const log_level = t.log_level; + t.log_level = .err; + defer t.log_level = log_level; + const every = [_]Path{ .served, .cancel_prompt, .busy, .fail_round, .cancel_decode, .closed, .no_memory, .fail_prompt, .stale, .cancel_at_once, .invalid, .pressure, .spans }; + for ([_]Kind{ .whole, .stepped }) |kind| { + var r: Rig = undefined; + try rigged(&r, kind, true); + defer r.deinit(); + for (0..runs) |i| { + try r.drive(every[(i * 5) % every.len]); + try r.settle(r.base); + } + try r.drive(.served); + try r.settle(r.base); + try r.close(); + } +} diff --git a/zig/src/core/lanes/config.zig b/zig/src/core/lanes/config.zig index 5dd0a1fe0ee..b7f0f20e41f 100644 --- a/zig/src/core/lanes/config.zig +++ b/zig/src/core/lanes/config.zig @@ -38,6 +38,7 @@ pub const Model = struct { shared_step_ms: ?f64 = null, // a separate shared head step; null keeps mtp_step_ms draft_step_ms: f64 = 0.0, // a shared round's draft past a stream's first, as the backend's head runs it (0: priced free) streams_exact: bool = true, // shared forwards keep each stream's bits + plain_share: bool = false, // width-one streams may share a forward without a wider per-stream window hidden_rows: bool = false, // the backend runs several streams' windows in one forward batch_rows: u32 = 0, // a shared forward's rows at most (0: 32) max_streams: u32 = 0, // a shared forward's streams at most (0: 32) @@ -122,7 +123,7 @@ pub const Config = struct { const first_rows: i64 = if (m.first_copy_rows != 0) m.first_copy_rows else width; const first_copy: u32 = @intCast(@max(1, @min(@as(i64, max_copy), first_rows - 1))); const prior = if (m.draft_prior.len > 0) m.draft_prior else &default_prior; - const streams = width >= 2 and m.streams_exact and m.hidden_rows; + const streams = (width >= 2 or m.plain_share) and m.streams_exact and m.hidden_rows; const batch_rows: u32 = if (m.batch_rows != 0) m.batch_rows else 32; var family_costs: Table = .{}; errdefer family_costs.deinit(gpa); diff --git a/zig/src/core/lanes/lanes.zig b/zig/src/core/lanes/lanes.zig index 34073e2e6ef..79e83a57eb2 100644 --- a/zig/src/core/lanes/lanes.zig +++ b/zig/src/core/lanes/lanes.zig @@ -62,6 +62,7 @@ pub const Trim = trim.Trim; test { std.testing.refAllDecls(@This()); _ = @import("engine_test.zig"); + _ = @import("plain_streams_test.zig"); _ = @import("late_draft_test.zig"); _ = @import("long_loop.zig"); _ = @import("long_loop_test.zig"); diff --git a/zig/src/core/lanes/plain_streams_test.zig b/zig/src/core/lanes/plain_streams_test.zig new file mode 100644 index 00000000000..3b7301366f3 --- /dev/null +++ b/zig/src/core/lanes/plain_streams_test.zig @@ -0,0 +1,100 @@ +//! Plain cross-stream sharing has its own capability, without widening a stream's verification window. +const std = @import("std"); +const setup = @import("config.zig"); +const Engine = @import("engine.zig").Engine; +const be = @import("backend.zig"); +const sm = @import("stream.zig"); +const fake = @import("fake.zig"); +const a = std.testing.allocator; + +const Watch = struct { + var inner_verify: *const fn (*anyopaque, []const be.Window, []be.Verified) anyerror!void = undefined; + var inner_queue: *const fn (*anyopaque, *sm.Stream, be.Feed, u64) anyerror!u64 = undefined; + var widest: usize = 0; + var queues: usize = 0; + fn verify(ptr: *anyopaque, windows: []const be.Window, out: []be.Verified) !void { + widest = @max(widest, windows.len); + for (windows) |w| try std.testing.expectEqual(@as(usize, 1), w.rows()); + try inner_verify(ptr, windows, out); + } + fn queue(ptr: *anyopaque, s: *sm.Stream, feed: be.Feed, position: u64) !u64 { + queues += 1; + return inner_queue(ptr, s, feed, position); + } +}; +const Result = struct { tokens: [4][32]u32 = undefined, widest: usize, queues: usize }; +fn run(n: usize, sharing: bool, sampled: bool, drafts: bool, staggered: bool) !Result { + var target: fake.Fake = .{ .gpa = a }; + defer target.deinit(); + var backend = target.backend(); + var hooks = backend.vtable.*; + Watch.inner_verify = hooks.verify; + Watch.inner_queue = hooks.queue; + Watch.widest = 0; + Watch.queues = 0; + hooks.verify = Watch.verify; + hooks.queue = Watch.queue; + backend.vtable = &hooks; + var cfg = try setup.Config.init(a, .{ .plain_share = sharing, .gpu_tokens = true, .hidden_rows = true, .batch_rows = 4, .max_streams = 4 }, 16, 15); + defer cfg.deinit(a); + var clock: fake.FixedClock = .{}; + var engine = Engine.init(a, &cfg, backend, clock.clock()); + defer engine.deinit(); + var streams: [4]sm.Stream = undefined; + const prompt = [_]u32{ 1, 5, 9, 2, 8, 3, 7 }; + for (streams[0..n], 0..) |*s, i| s.* = try sm.Stream.init(a, .{ .id = "plain", .prompt = prompt[0 .. 3 + i], .max_new = 32, .drafts = drafts, .sampling = if (sampled) .{ .seed = 7 + i, .temperature = 0.7, .top_k = 20, .top_p = 0.95 } else null }); + defer for (streams[0..n]) |*s| s.deinit(a); + for (streams[0..n], 0..) |*s, i| { + try engine.addStream(s); + if (staggered and i == 0) for (0..4) |_| try engine.step(); + } + var steps: usize = 0; + while (engine.activeCount() > 0) : (steps += 1) { + if (steps > 256) return error.RoundLoopDidNotFinish; + try engine.step(); + } + var result: Result = .{ .widest = Watch.widest, .queues = Watch.queues }; + for (streams[0..n], 0..) |*s, i| { + try std.testing.expectEqual(@as(usize, 32), s.emitted().len); + @memcpy(&result.tokens[i], s.emitted()); + } + try std.testing.expectEqual(@as(usize, 0), target.drafts_calls); + try std.testing.expectEqual(@as(u64, 0), engine.drafted); + return result; +} + +test "plain sharing: width one may share streams without increasing drafts or copies" { + var c = try setup.Config.init(a, .{ .plain_share = true, .gpu_tokens = true, .hidden_rows = true, .batch_rows = 4, .max_streams = 4 }, 16, 15); + defer c.deinit(a); + try std.testing.expect(c.family_streams and c.pipelined); + try std.testing.expectEqual(@as(u32, 4), c.batch_streams); + try std.testing.expectEqual(@as(u32, 1), c.family_width); + try std.testing.expectEqual(@as(u32, 1), c.base_width); + try std.testing.expectEqual(@as(u32, 0), c.max_copy); + try std.testing.expectEqual(@as(u32, 0), c.most_drafts); + try std.testing.expect(!c.family_mtp); + for ([_]setup.Model{ + .{ .hidden_rows = true }, + .{ .plain_share = true }, + .{ .plain_share = true, .hidden_rows = true, .streams_exact = false }, + }) |m| { + var off = try setup.Config.init(a, m, 16, 15); + defer off.deinit(a); + try std.testing.expect(!off.family_streams); + try std.testing.expectEqual(@as(u32, 1), off.batch_streams); + } +} + +test "plain sharing: synchronous streams equal pipelined solo and keep the lone path" { + for ([_]bool{ false, true }) |sampled| for ([_]bool{ false, true }) |drafts| { + for ([_]usize{ 1, 2, 3, 4 }) |n| for ([_]bool{ false, true }) |staggered| { + const before = try run(n, false, sampled, drafts, staggered); + const after = try run(n, true, sampled, drafts, staggered); + for (0..n) |i| try std.testing.expectEqualSlices(u32, &before.tokens[i], &after.tokens[i]); + if (n > 1) try std.testing.expectEqual(n, after.widest) else { + try std.testing.expectEqual(@as(usize, 0), after.widest); + try std.testing.expectEqual(before.queues, after.queues); + } + }; + }; +} diff --git a/zig/src/core/memory_pressure.zig b/zig/src/core/memory_pressure.zig index 70ba9e45684..d254a1f04c1 100644 --- a/zig/src/core/memory_pressure.zig +++ b/zig/src/core/memory_pressure.zig @@ -1,4 +1,4 @@ -//! macOS memory pressure as the lane host acts on it: a rise takes effect at once, a fall only after a calm spell. +//! OS memory pressure as the lane host acts on it: a rise takes effect at once, a fall only after a calm spell. const std = @import("std"); const builtin = @import("builtin"); const platform = @import("sys"); @@ -10,7 +10,7 @@ pub fn ofKernel(v: u32) Level { return if (v >= 4) .critical else if (v >= 2) .warning else .normal; } -/// Where readings come from: the kernel's sysctl, or a test's fake (null: no reading, taken as normal). +/// Where readings come from: the kernel's metrics, or a test's fake (null: no reading, taken as normal). pub const Source = struct { ctx: ?*anyopaque = null, read: *const fn (ctx: ?*anyopaque) ?Level, @@ -45,6 +45,16 @@ pub const Settings = struct { const p = std.fmt.parseInt(u8, std.mem.trim(u8, percent_text orelse "", " \t"), 10) catch default_percent; return .{ .on = !off, .percent = if (p <= 100) p else default_percent }; } + + /// Linux is experimental and explicitly enabled; macOS keeps its existing default and switch behavior. + pub fn forOs(os: std.Target.Os.Tag, switch_text: ?[]const u8, percent_text: ?[]const u8) ?Settings { + const s = fromText(switch_text, percent_text); + if (!s.on) return null; + if (os == .macos) return s; + if (os != .linux) return null; + const text = std.mem.trim(u8, switch_text orelse "", " \t"); + return if (std.mem.eql(u8, text, "1") or std.ascii.eqlIgnoreCase(text, "on")) s else null; + } }; pub const Governor = struct { @@ -57,11 +67,11 @@ pub const Governor = struct { read_at: ?i96 = null, calm_since: ?i96 = null, // the first reading below `level` in the current calm spell - /// The lane host's governor on a Mac where the kernel reads (null: off, a test, or another OS). + /// The shared governor where kernel metrics are available; Linux requires explicit enablement. pub fn fromEnv() ?Governor { - if (builtin.is_test or builtin.os.tag != .macos) return null; // host tests give their own source - const s = Settings.fromText(platform.getenv("TENSORFOLD_MEMORY_PRESSURE"), platform.getenv("TENSORFOLD_PRESSURE_CACHE_PERCENT")); - if (!s.on or Source.kernel.read(null) == null) return null; + if (builtin.is_test) return null; // host tests give their own source + const s = Settings.forOs(builtin.os.tag, platform.getenv("TENSORFOLD_MEMORY_PRESSURE"), platform.getenv("TENSORFOLD_PRESSURE_CACHE_PERCENT")) orelse return null; + if (Source.kernel.read(null) == null) return null; return .{ .source = Source.kernel, .percent = s.percent }; } diff --git a/zig/src/core/memory_pressure_linux_test.zig b/zig/src/core/memory_pressure_linux_test.zig new file mode 100644 index 00000000000..b2093b48389 --- /dev/null +++ b/zig/src/core/memory_pressure_linux_test.zig @@ -0,0 +1,187 @@ +//! Real planted proc files through the Linux reader and the existing governor and cache operations. +const std = @import("std"); +const builtin = @import("builtin"); +const mp = @import("memory_pressure.zig"); +const linux = @import("sys").memory_policy.linux_pressure; +const pc = @import("prompt_cache.zig"); +const shed = @import("prompt_cache_shed.zig").shed; +const Fake = @import("prompt_cache_fake.zig").Fake; +const a = std.testing.allocator; +const io = std.testing.io; +const quiet = "some avg10=0.00 avg60=0 avg300=0 total=0\nfull avg10=0.00 avg60=0 avg300=0 total=0\n"; +const healthy = "MemTotal: 1000000 kB\nMemFree: 1 kB\nMemAvailable: 400000 kB\nCached: 500000 kB\n"; + +fn psi(out: []u8, some: f64, full: f64) ![]const u8 { + return std.fmt.bufPrint(out, "some avg10={d:.3} total=0\nfull avg10={d:.3} total=0\n", .{ some, full }); +} +fn mem(out: []u8, available: u64) ![]const u8 { + return std.fmt.bufPrint(out, "MemTotal: 1000000 kB\nMemAvailable: {d} kB\n", .{available}); +} +fn plant(dir: std.Io.Dir, p: []const u8, m: []const u8) !void { + try dir.createDirPath(io, "pressure"); + try dir.writeFile(io, .{ .sub_path = "pressure/memory", .data = p }); + try dir.writeFile(io, .{ .sub_path = "meminfo", .data = m }); +} + +test "memory pressure: a normally budgeted Linux host at low MemAvailable stays normal" { + if (builtin.os.tag == .windows) return error.SkipZigTest; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const root = try tmp.dir.realPathFileAlloc(io, ".", a); + defer a.free(root); + const full = "MemTotal: 126877696 kB\nMemAvailable: 4194304 kB\nMemFree: 1 kB\nCached: 2097152 kB\n"; + try plant(tmp.dir, quiet, full); + const reading = linux.readAt(root).?; + try std.testing.expectEqual(@as(u64, 4) << 30, reading.available); + try std.testing.expectEqual(@as(u32, 1), reading.level()); + var files: Files = .{ .root = root }; + var g: mp.Governor = .{ .source = .{ .ctx = &files, .read = Files.read } }; + try std.testing.expect(g.poll(0) == null); + try std.testing.expectEqual(mp.Level.normal, g.level); +} + +test "memory pressure: Linux planted files classify PSI boundaries and retain available-memory diagnostics" { + if (builtin.os.tag == .windows) return error.SkipZigTest; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const root = try tmp.dir.realPathFileAlloc(io, ".", a); + defer a.free(root); + try plant(tmp.dir, quiet, healthy); + try std.testing.expectEqual(@as(u32, 1), linux.readAt(root).?.level()); + const Case = struct { available: u64, some: f64 = 0, full: f64 = 0, want: ?u32, p: ?[]const u8 = null, m: ?[]const u8 = null }; + const cases = [_]Case{ + .{ .available = 100001, .want = 1 }, .{ .available = 100000, .want = 1 }, + .{ .available = 50001, .want = 1 }, .{ .available = 50000, .want = 1 }, + .{ .available = 0, .want = 1 }, .{ .available = 1000000, .want = 1 }, + .{ .available = 400000, .some = 9.999, .want = 1 }, .{ .available = 400000, .some = 10, .want = 2 }, + .{ .available = 400000, .full = 0.999, .want = 1 }, .{ .available = 400000, .full = 1, .want = 2 }, + .{ .available = 400000, .full = 9.999, .want = 2 }, .{ .available = 400000, .full = 10, .want = 4 }, + .{ .available = 400000, .want = 4, .p = "some avg10=12.34 avg60=5.67 avg300=1.23 total=987654321\nfull avg60=5.67 total=987654321 avg300=1.23 avg10=12.34\n" }, .{ .available = 400000, .want = null, .p = "some avg10=0.00 avg60=0.00 avg300=0.00 total=987654321\n" }, + .{ .available = 400000, .want = null, .m = "MemTotal: 1000000 kB\nMemFree: 1 kB\nBuffers: 500 kB\nCached: 500000 kB\n" }, + }; + var p: [256]u8 = undefined; + var m: [128]u8 = undefined; + for (cases) |c| { + try plant(tmp.dir, c.p orelse try psi(&p, c.some, c.full), c.m orelse try mem(&m, c.available)); + const reading = linux.readAt(root); + if (c.want) |want| { + const got = reading.?; + try std.testing.expectEqual(want, got.level()); + try std.testing.expectEqual(c.available * 1024, got.available); + } else try std.testing.expect(reading == null); + } +} + +test "memory pressure: Linux malformed, missing, truncated and oversized proc files never reuse a prior level" { + if (builtin.os.tag == .windows) return error.SkipZigTest; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const root = try tmp.dir.realPathFileAlloc(io, ".", a); + defer a.free(root); + try std.testing.expect(linux.readAt(root) == null); + for ([_][]const u8{ + "", "some avg10=1\n", "some avg10=1\nfull total=0\n", + "some avg10=nan\nfull avg10=0\n", "some avg10=inf\nfull avg10=0\n", "some avg10=-1\nfull avg10=0\n", + "some avg10=101\nfull avg10=0\n", "some avg10=0 avg10=1\nfull avg10=0\n", "some avg10=0\nsome avg10=1\nfull avg10=0\n", + }) |bad| { + try plant(tmp.dir, "some avg10=10\nfull avg10=10\n", healthy); + try std.testing.expectEqual(@as(u32, 4), linux.readAt(root).?.level()); + try plant(tmp.dir, bad, healthy); + try std.testing.expect(linux.readAt(root) == null); + } + for ([_][]const u8{ + "", "MemTotal: 100 kB\n", "MemTotal: 0 kB\nMemAvailable: 0 kB\n", + "MemTotal: 100 kB\nMemAvailable: 101 kB\n", "MemTotal: 100 MB\nMemAvailable: 1 kB\n", "MemTotal: 100 kB\nMemAvailable: -1 kB\n", + "MemTotal: 18446744073709551615 kB\nMemAvailable: 1 kB\n", "MemTotal: 100 kB\nMemAvailable: 1 kB\nMemAvailable: 2 kB\n", + }) |bad| { + try plant(tmp.dir, quiet, bad); + try std.testing.expect(linux.readAt(root) == null); + } + var huge: [16385]u8 = @splat(' '); + @memcpy(huge[0..healthy.len], healthy); + try plant(tmp.dir, quiet, &huge); + try std.testing.expect(linux.readAt(root) == null); + @memset(&huge, ' '); + @memcpy(huge[0..quiet.len], quiet); + try plant(tmp.dir, huge[0..1025], healthy); + try std.testing.expect(linux.readAt(root) == null); + try plant(tmp.dir, quiet, healthy); + try std.testing.expectEqual(@as(u32, 1), linux.readAt(root).?.level()); + try tmp.dir.deleteFile(io, "pressure/memory"); + try std.testing.expect(linux.readAt(root) == null); +} + +test "memory pressure: Linux is explicitly enabled while macOS and disabled/unsupported paths keep their settings" { + try std.testing.expect(mp.Settings.forOs(.linux, null, null) == null); + for ([_]?[]const u8{ "0", "off", "OFF", "", "true", "2" }) |v| try std.testing.expect(mp.Settings.forOs(.linux, v, null) == null); + for ([_][]const u8{ "1", "on", "ON", " on " }) |v| { + const s = mp.Settings.forOs(.linux, v, "25").?; + try std.testing.expect(s.on and s.percent == 25); + } + try std.testing.expectEqualDeep(mp.Settings.fromText(null, null), mp.Settings.forOs(.macos, null, null).?); + try std.testing.expect(mp.Settings.forOs(.macos, "off", null) == null); + try std.testing.expect(mp.Settings.forOs(.windows, "1", null) == null); + try std.testing.expect(mp.Governor.fromEnv() == null); +} + +const Files = struct { + root: []const u8, + reads: usize = 0, + fn read(ctx: ?*anyopaque) ?mp.Level { + const f: *Files = @ptrCast(@alignCast(ctx.?)); + f.reads += 1; + return mp.ofKernel((linux.readAt(f.root) orelse return null).level()); + } +}; + +test "memory pressure: planted Linux pressure sheds optional state, protects borrowed state, recovers without flapping" { + if (builtin.os.tag == .windows) return error.SkipZigTest; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const root = try tmp.dir.realPathFileAlloc(io, ".", a); + defer a.free(root); + var files: Files = .{ .root = root }; + var g: mp.Governor = .{ .source = .{ .ctx = &files, .read = Files.read } }; + var fake: Fake = .{ .gpa = a }; + var store = pc.Store.init(a, fake.snapshots(), .{ .min_prompt = 0 }, 1 << 20); + defer store.deinit(); + var arena: std.heap.ArenaAllocator = .init(a); + defer arena.deinit(); + const mem_a = arena.allocator(); + const one = [_]u32{ 1, 1, 1, 1, 9 }; + const two = [_]u32{ 2, 2, 2, 2, 2, 2, 2, 2, 9 }; + const next = [_]u32{ 2, 2, 2, 2, 2, 2, 2, 2, 9, 4, 9 }; + _ = fake.pass(&store, &one, try store.begin(mem_a, &one, 4, &.{}, &.{}, null, &.{})); + _ = fake.pass(&store, &two, try store.begin(mem_a, &two, 8, &.{}, &.{}, null, &.{})); + const borrowed = try store.lookup(mem_a, &next, 9, &.{}, &.{}, &.{}); + store.budget = store.held; + try plant(tmp.dir, quiet, healthy); + try std.testing.expect(g.poll(0) == null); + try plant(tmp.dir, "some avg10=10\nfull avg10=0\n", healthy); + try std.testing.expect(g.poll(100 * std.time.ns_per_ms) == null); + try std.testing.expectEqual(@as(usize, 1), files.reads); + try std.testing.expectEqual(mp.Level.warning, g.poll(250 * std.time.ns_per_ms).?.to); + try plant(tmp.dir, "some avg10=10\nfull avg10=10\n", healthy); + try std.testing.expectEqual(mp.Level.critical, g.poll(500 * std.time.ns_per_ms).?.to); + store.hold = g.level != .normal; + const held = store.held; + while (shed(&store, g.mark(store.budget))) {} + try std.testing.expect(store.held < held); + try std.testing.expectEqual(@as(usize, 1), store.entries.items.len); + try std.testing.expect(!shed(&store, 0)); + const resumed = fake.pass(&store, &next, try store.begin(mem_a, &next, 9, &.{}, &.{}, null, &.{})); + var fresh: u64 = 0; + for (next) |id| fresh = fresh *% 31 +% id; + try std.testing.expectEqual(fresh, resumed); + store.resumed(borrowed.entry.?, &next, true); + try plant(tmp.dir, quiet, healthy); + try std.testing.expect(g.poll(std.time.ns_per_s) == null); + try plant(tmp.dir, "some avg10=10\nfull avg10=10\n", healthy); + try std.testing.expect(g.poll(2 * std.time.ns_per_s) == null); + try plant(tmp.dir, quiet, healthy); + try std.testing.expect(g.poll(3 * std.time.ns_per_s) == null); + try std.testing.expect(g.poll(7 * std.time.ns_per_s) == null); + try std.testing.expectEqual(mp.Level.normal, g.poll(8 * std.time.ns_per_s).?.to); + store.hold = g.level != .normal; + try std.testing.expect(!store.hold); +} diff --git a/zig/src/core/memory_pressure_test.zig b/zig/src/core/memory_pressure_test.zig index 9c308a2bdfd..f40afcc417b 100644 --- a/zig/src/core/memory_pressure_test.zig +++ b/zig/src/core/memory_pressure_test.zig @@ -90,7 +90,7 @@ test "memory pressure: settings, the watermark and the kernel's levels" { try std.testing.expectEqual(Level.critical, mp.ofKernel(4)); try std.testing.expect(mp.Governor.fromEnv() == null); // host tests never read the kernel's level const raw = platform.memory_policy.pressure(); - if (builtin.os.tag == .macos) try std.testing.expect(raw != null) else try std.testing.expect(raw == null); + if (builtin.os.tag == .macos) try std.testing.expect(raw != null) else if (builtin.os.tag != .linux) try std.testing.expect(raw == null); } const c1 = [_]u32{ 1, 1, 1, 1, 9 }; @@ -181,3 +181,7 @@ test "memory pressure: a held store keeps nothing new and plans no marks, yet st try std.testing.expectEqual(fresh(&c2), f.pass(&s, &c2, q)); try std.testing.expectEqual(@as(usize, 2), s.entries.items.len); } + +test { + _ = @import("memory_pressure_linux_test.zig"); +} diff --git a/zig/src/cuda/context.zig b/zig/src/cuda/context.zig index 1287ca27ae2..3f82a4d9c2c 100644 --- a/zig/src/cuda/context.zig +++ b/zig/src/cuda/context.zig @@ -28,6 +28,15 @@ pub const Context = struct { std.log.err("{s}", .{why}); return error.WrongGpu; } + } else if (@import("kernels.zig").target_sms.len > 0) { + const actual_sm = try d.capability(ordinal); + var gpu_name: [256]u8 = undefined; + var message: [1024]u8 = undefined; + if (@import("kernels.zig").supports(actual_sm) == false) { + const gpu = d.deviceName(ordinal, &gpu_name) catch "unknown NVIDIA GPU"; + std.log.err("{s}", .{releaseRefusal(gpu, actual_sm, ordinal, @import("kernels.zig").target_sms, &message)}); + return error.WrongGpu; + } } var dev: abi.Device = 0; try d.check(d.api.cuDeviceGet(&dev, ordinal), "cuDeviceGet"); @@ -118,3 +127,12 @@ pub const Context = struct { return m; } }; + +/// The release refusal is composed before retaining a context or loading any module. +pub fn releaseRefusal(name: []const u8, capability: u32, ordinal: c_int, sms: []const u32, buffer: []u8) []const u8 { + var w = std.Io.Writer.fixed(buffer); + w.print("CUDA device {d} ({s}) has compute capability {d}.{d} (sm_{d}); this build has kernels for SMs [", .{ ordinal, name, capability / 10, capability % 10, capability }) catch return "this build has no kernels for the selected GPU"; + for (sms, 0..) |sm, i| w.print("{s}{d}", .{ if (i == 0) "" else ",", sm }) catch break; + w.writeAll("]: use a build with kernels for this GPU") catch {}; + return w.buffered(); +} diff --git a/zig/src/cuda/kernels.zig b/zig/src/cuda/kernels.zig index c8eb892ca12..58512acd76c 100644 --- a/zig/src/cuda/kernels.zig +++ b/zig/src/cuda/kernels.zig @@ -13,6 +13,23 @@ fn Blob(comptime import_name: []const u8) type { pub const available = options.with_kernels; /// The one SM (10 * major + minor) every image is built for (-Dgpu), or null for a build that holds several. pub const built_sm: ?u32 = options.built_sm; +/// The embedded images' declared SASS capabilities; empty means unknown for a custom prebuilt bundle. +pub const target_sms: []const u32 = options.sms; + +pub fn supports(capability: u32) ?bool { + if (!available) return false; + if (target_sms.len == 0) return null; + return covers(target_sms, capability); +} + +/// Whether SASS for one of `sms` runs on a `capability` GPU: the same SM or, below sm_90, a lower minor of its major. +pub fn covers(sms: []const u32, capability: u32) bool { + for (sms) |sm| { + if (sm == capability) return true; + if (sm < 90 and sm / 10 == capability / 10 and sm % 10 <= capability % 10) return true; + } + return false; +} pub const qwen4_hc: []const u8 = if (available) &Blob("fatbin_qwen4_hc").bytes else &.{}; pub const qwen4_ple: []const u8 = if (available) &Blob("fatbin_qwen4_ple").bytes else &.{}; diff --git a/zig/src/cuda/sample.zig b/zig/src/cuda/sample.zig index 15074d9de34..c29fbe18011 100644 --- a/zig/src/cuda/sample.zig +++ b/zig/src/cuda/sample.zig @@ -69,6 +69,8 @@ pub const Draws = struct { topk_merge_fn: Function, /// tf_draw_rows; null in a kernel set built before it, where drawRows falls back to one launch a row. draw_rows_fn: ?Function = null, + /// tf_draw_ids_rows: rows under per-row rules at an offset, columns mapped by IDS (null: whole head). + draw_ids_rows_fn: ?Function = null, /// tf_draw_slice_top and tf_draw_rows_finish: a window's rows over slices (null: one block a row). slices: ?[2]Function = null, /// tf_penalize_rows; null in a kernel set built before it, where penalties are not offered. @@ -83,7 +85,7 @@ pub const Draws = struct { pub const topk_slice = 4096; pub fn resolve(mod: Module) !Draws { - return .{ .draw_fn = try mod.function("tf_draw"), .draw_ids_fn = try mod.function("tf_draw_ids"), .logprob_rows_fn = try mod.function("tf_logprob_rows"), .topk_slices_fn = try mod.function("tf_topk_slices"), .topk_merge_fn = try mod.function("tf_topk_merge"), .draw_rows_fn = mod.function("tf_draw_rows") catch null, .slices = slicesOf(mod), .penalize_fn = mod.function("tf_penalize_rows") catch null }; + return .{ .draw_fn = try mod.function("tf_draw"), .draw_ids_fn = try mod.function("tf_draw_ids"), .logprob_rows_fn = try mod.function("tf_logprob_rows"), .topk_slices_fn = try mod.function("tf_topk_slices"), .topk_merge_fn = try mod.function("tf_topk_merge"), .draw_rows_fn = mod.function("tf_draw_rows") catch null, .draw_ids_rows_fn = mod.function("tf_draw_ids_rows") catch null, .slices = slicesOf(mod), .penalize_fn = mod.function("tf_penalize_rows") catch null }; } fn slicesOf(mod: Module) ?[2]Function { @@ -167,6 +169,17 @@ pub const Draws = struct { try launch_.launch(f, .{ .grid = .{ .x = @intCast(rows), .y = 1, .z = 1 }, .block = .{ .x = 1024 } }, s, &a); } + /// `rows` logits rows, row r under rule[r] at position meta[r] + 1 + offset, columns mapped by `ids` (null: head). + pub fn drawIdsRows(d: *const Draws, s: Stream, logits: u64, vocab: usize, rule_ptr: u64, meta: u64, offset: usize, out: u64, rows: usize, ids: ?u64, prob: ?u64) !void { + if (rows == 0) return; + if (d.draw_ids_rows_fn) |f| { + var a: launch_.Args = .{}; + inline for (.{ logits, @as(u32, @intCast(vocab)), rule_ptr, meta, int(offset), out, ids orelse 0, prob orelse 0 }) |v| a.add(v); + return launch_.launch(f, .{ .grid = .{ .x = @intCast(rows), .y = 1, .z = 1 }, .block = .{ .x = 1024 } }, s, &a); + } + for (0..rows) |i| try d.draw(s, logits + i * vocab * 2, vocab, rule_ptr + i * @sizeOf(Rule), meta + i * 4, offset, out + i * 4, 1, ids, if (prob) |p| p + i * 4 else null); + } + /// `n` entries at `entries` (n rows, n tokens, then n fp32 amounts): each takes its amount from its row's logit. pub fn penalize(d: *const Draws, s: Stream, logits: u64, vocab: usize, entries: u64, n: usize) !void { if (n == 0) return; diff --git a/zig/src/fabric/tp/README.md b/zig/src/fabric/tp/README.md index 4c3d14eccca..05746e7c006 100644 --- a/zig/src/fabric/tp/README.md +++ b/zig/src/fabric/tp/README.md @@ -63,12 +63,13 @@ zig/src/fabric/tp/run_hosts.sh 1 192.0.2.1 ./zig-out/bin/tf-tp-test out-rank1 ## TCP between two hosts without RDMA `tcp.zig` is the `Collective` contract over one stream socket a pair of ranks, `Kind.tcp`, for hosts with no RDMA -(two AMD boxes on USB4 networking, or plain Ethernet). It moves host memory; a device side that stages through it comes -in a later pull request. It is not a `TF_COMM_BACKEND` value yet: only its tests and `tf-tp-test tcp-host` open it. +(two AMD boxes on USB4 networking, or plain Ethernet). It moves host memory; `stage.zig`, below, puts device memory +behind it. It is not a `TF_COMM_BACKEND` value yet: only its tests and `tf-tp-test tcp-host` and `tcp-hip` open it. -- Every frame starts with a header both ranks check: call, element type, operation, count and the link's frame - number; a variable-length gather sends every rank's lengths first in its payload, and those are compared too. A - call one rank makes differently fails as `Invalid`, or `Aborted` where the other rank refused it first. +- Every frame starts with a header both ranks check: call, element type, operation, count, the link's frame number + and the part of a staged call; a variable-length gather sends every rank's lengths first in its payload, and those + are compared too. A call one rank makes differently fails as `Invalid`, or `Aborted` where the other rank refused it + first. Exchange partners that disagree (rank 0 trades with 1 while 1 trades with 2) wait on frames that never come and fail as `Timeout`. - A frame that has not arrived by the call's deadline (`Options.timeout_ns`) is `Timeout`, and the communicator is @@ -98,6 +99,32 @@ TF_TP_RANK=0 ./zig-out/bin/tf-tp-test tcp-host # host A TF_TP_RANK=1 ./zig-out/bin/tf-tp-test tcp-host # host B ``` +## Device memory over the TCP Kind + +`stage.zig` stages device memory through `tcp.zig`, still `Kind.tcp`. A call only queues on its stream and returns: +the stream writes the call's `ready` word, then waits until its `done` word is set (64-bit words in pinned host memory). +A proxy thread sees `ready`, copies the input into a pinned slab on a stream of its own, moves it with `tcp.zig`, copies +the result back and sets `done`. `stage_hip.zig` is the HIP side: `hipStreamWriteValue64` and `hipStreamWaitValue64` on +mapped coherent host memory; a GPU without them is refused by name. + +- The caller's stream gets no copies of ours, only the two words. With the copies queued on it around the wait, two + ranks of one process hung, or read stale bytes, once a call reached 16 KiB (ROCm 10.0, gfx1151). +- A call larger than `Options.part_bytes` (default 4 MiB, the same on every rank or the open fails) moves in parts. + Each frame names its part, so one call in two parts never pairs with two whole calls. +- The stream writes `ready` only after the work queued before it on that stream has finished, so when the proxy sees + it the input is complete in device memory, and the proxy's own stream reads it from there. +- A failure, the peer's, a timeout or a device call's, sets every `done` word, so no stream waits on it; it shows at + the next call or at `check`, and the outputs of the calls in flight are not defined. +- The proxy waits for each of its copies at most `Hip.limit_ns` (30 s), then fails the call: past the runtime's + hardware queues (`GPU_MAX_HW_QUEUES`, 4 by default) its stream can share one with a stream parked on a word. +- A capturing stream is refused (`Unsupported`): a replay would write and wait on the words' old values. +- `allGatherV` moves whole strides, as `Collective` does for a transport without its own. +- `deinit` frees the slab once every stream has passed its last call; the caller synchronises its streams first. + +`tf-tp-test tcp-hip` runs `tcp-host`'s checks and timings from HIP memory on the GPU of `TF_TP_DEVICE`: each call is +checked after its stream synchronised, and each time is a call and its stream's synchronisation (`queue_p50_us` is the +call alone). Its results name the link from `TF_TP_LINK` too. + ## RoCE limits and the failed-transport check No RDMA write is larger than 1 MiB, so on `TF_COMM_BACKEND=roce` a `TF_TP_MAILBOX_MAX_KB` above 1024 fails at boot. diff --git a/zig/src/fabric/tp/gpu_cli.zig b/zig/src/fabric/tp/gpu_cli.zig index 492da6e946d..008ec7db4a0 100644 --- a/zig/src/fabric/tp/gpu_cli.zig +++ b/zig/src/fabric/tp/gpu_cli.zig @@ -1,22 +1,23 @@ //! Validate the runner's command before opening a driver, bootstrap or fate channel. const std = @import("std"); -pub const usage = "usage: tf-tp-test suite | device | failfast RANK fatal|kill|transport [N [HOLD_S]] | roce-host | tcp-host | hca | kernel\n"; +pub const usage = "usage: tf-tp-test suite | device | failfast RANK fatal|kill|transport [N [HOLD_S]] | roce-host | tcp-host | tcp-hip | hca | kernel\n"; pub const Mode = enum { fatal, kill, transport }; pub const Failure = struct { victim: u32, mode: Mode, n: u32 = 50, hold: ?u32 = null }; -pub const Command = union(enum) { suite, device, failfast: Failure, @"roce-host", @"tcp-host", hca, kernel }; +pub const Command = union(enum) { suite, device, failfast: Failure, @"roce-host", @"tcp-host", @"tcp-hip", hca, kernel }; pub fn parse(args: []const []const u8) error{InvalidArguments}!Command { if (args.len == 0) return error.InvalidArguments; const tag = std.meta.stringToEnum(std.meta.Tag(Command), args[0]) orelse return error.InvalidArguments; switch (tag) { - .suite, .device, .@"roce-host", .@"tcp-host", .hca, .kernel => { + .suite, .device, .@"roce-host", .@"tcp-host", .@"tcp-hip", .hca, .kernel => { if (args.len != 1) return error.InvalidArguments; return switch (tag) { .suite => .suite, .device => .device, .@"roce-host" => .@"roce-host", .@"tcp-host" => .@"tcp-host", + .@"tcp-hip" => .@"tcp-hip", .hca => .hca, .kernel => .kernel, else => unreachable, @@ -46,7 +47,7 @@ pub const invalid = [_][]const []const u8{ &.{ "device", "extra" }, &.{ "hca", "extra" }, &.{ "roce-host", "extra" }, &.{"failfast"}, &.{ "failfast", "0" }, &.{ "failfast", "0", "typo" }, &.{ "failfast", "bad", "fatal" }, &.{ "failfast", "-1", "kill" }, &.{ "failfast", "4294967296", "fatal" }, &.{ "failfast", "0", "fatal", "50" }, &.{ "failfast", "0", "kill", "50" }, &.{ "failfast", "0", "transport", "bad" }, - &.{ "failfast", "0", "transport", "50", "bad" }, &.{ "failfast", "0", "transport", "50", "0", "extra" }, &.{ "tcp-host", "extra" }, + &.{ "failfast", "0", "transport", "50", "bad" }, &.{ "failfast", "0", "transport", "50", "0", "extra" }, &.{ "tcp-host", "extra" }, &.{ "tcp-hip", "extra" }, }; test "invalid commands are refused before resources open" { @@ -54,7 +55,7 @@ test "invalid commands are refused before resources open" { } test "documented commands and failfast defaults" { - inline for (.{ "suite", "device", "roce-host", "tcp-host", "hca", "kernel" }) |name| { + inline for (.{ "suite", "device", "roce-host", "tcp-host", "tcp-hip", "hca", "kernel" }) |name| { try std.testing.expectEqualStrings(name, @tagName(try parse(&.{name}))); } inline for (.{ Mode.fatal, Mode.kill, Mode.transport }) |mode| { diff --git a/zig/src/fabric/tp/gpu_main.zig b/zig/src/fabric/tp/gpu_main.zig index b18bfe5faaf..56a6ccaed45 100644 --- a/zig/src/fabric/tp/gpu_main.zig +++ b/zig/src/fabric/tp/gpu_main.zig @@ -1,4 +1,4 @@ -//! `tf-tp-test suite | device | failfast RANK fatal|kill|transport [N [HOLD_S]] | roce-host | tcp-host | hca | kernel` +//! `tf-tp-test`: suite, device, failfast, roce-host, tcp-host, tcp-hip, hca or kernel, as gpu_cli.zig's usage spells const std = @import("std"); const cuda = @import("cuda"); const tp = @import("tp"); @@ -23,6 +23,7 @@ pub fn main(init: std.process.Init) !u8 { const cfg = try tp.Config.fromEnv(); if (command == .@"roce-host") return @import("roce_host.zig").run(cfg, init.gpa); if (command == .@"tcp-host") return @import("tcp_host.zig").run(cfg, init.gpa); + if (command == .@"tcp-hip") return @import("tcp_hip.zig").run(cfg, init.gpa); if (command == .hca) return hca(cfg, init.io); if (command == .device) return device(cfg); if (command == .failfast and (!cfg.failfast or command.failfast.hold != null) and !hostOnlyAllowed(cfg)) { diff --git a/zig/src/fabric/tp/hip_rig.zig b/zig/src/fabric/tp/hip_rig.zig new file mode 100644 index 00000000000..761718f818d --- /dev/null +++ b/zig/src/fabric/tp/hip_rig.zig @@ -0,0 +1,105 @@ +//! What the HIP staging tests and `tf-tp-test tcp-hip` call themselves: the runtime, streams, buffers and copies. +const std = @import("std"); +const sys = @import("sys"); +const collective = @import("collective.zig"); +const DevicePtr = collective.DevicePtr; +const Stream = collective.Stream; + +const Result = c_int; +const P = ?*anyopaque; + +const Api = struct { + hipInit: *const fn (c_uint) callconv(.c) Result, + hipGetDeviceCount: *const fn (*c_int) callconv(.c) Result, + hipSetDevice: *const fn (c_int) callconv(.c) Result, + hipStreamCreateWithFlags: *const fn (*Stream, c_uint) callconv(.c) Result, + hipStreamDestroy: *const fn (Stream) callconv(.c) Result, + hipStreamSynchronize: *const fn (Stream) callconv(.c) Result, + hipStreamBeginCapture: *const fn (Stream, c_int) callconv(.c) Result, + hipStreamEndCapture: *const fn (Stream, *P) callconv(.c) Result, + hipGraphDestroy: *const fn (P) callconv(.c) Result, + hipMalloc: *const fn (*P, usize) callconv(.c) Result, + hipFree: *const fn (P) callconv(.c) Result, + hipMemcpyHtoD: *const fn (P, ?*const anyopaque, usize) callconv(.c) Result, + hipMemcpyDtoH: *const fn (P, P, usize) callconv(.c) Result, +}; + +pub const Error = error{ NoHip, HipFailed }; + +/// hipStreamNonBlocking: a test's copies on the null stream never wait for a stream a test holds. +const non_blocking: c_uint = 1; + +pub const Rig = struct { + lib: sys.DynLib, + api: Api, + + /// The HIP runtime by its usual name, with a GPU; `NoHip` when either is absent. + pub fn open() Error!Rig { + var lib = sys.DynLib.open("libamdhip64.so") catch return error.NoHip; + errdefer lib.close(); + var api: Api = undefined; + const info = @typeInfo(Api).@"struct"; + inline for (info.field_names, info.field_types) |name, T| @field(api, name) = lib.lookup(T, name) orelse return error.NoHip; + var n: c_int = 0; + if (api.hipInit(0) != 0 or api.hipGetDeviceCount(&n) != 0 or n == 0) return error.NoHip; + return .{ .lib = lib, .api = api }; + } + + pub fn close(r: *Rig) void { + r.lib.close(); + } + + fn ok(res: Result) Error!void { + if (res != 0) return error.HipFailed; + } + + pub fn use(r: *Rig, device: u32) Error!void { + return ok(r.api.hipSetDevice(@intCast(device))); + } + + pub fn stream(r: *Rig) Error!Stream { + var s: Stream = null; + try ok(r.api.hipStreamCreateWithFlags(&s, non_blocking)); + return s; + } + + pub fn destroy(r: *Rig, s: Stream) void { + _ = r.api.hipStreamDestroy(s); + } + + pub fn sync(r: *Rig, s: Stream) Error!void { + return ok(r.api.hipStreamSynchronize(s)); + } + + /// Starts capturing `s` (relaxed mode); `endCapture` drops the graph. + pub fn capture(r: *Rig, s: Stream) Error!void { + return ok(r.api.hipStreamBeginCapture(s, 2)); + } + + pub fn endCapture(r: *Rig, s: Stream) Error!void { + var g: P = null; + try ok(r.api.hipStreamEndCapture(s, &g)); + if (g != null) _ = r.api.hipGraphDestroy(g); + } + + pub fn alloc(r: *Rig, n: usize) Error!DevicePtr { + var p: P = null; + try ok(r.api.hipMalloc(&p, @max(n, 1))); + return @intFromPtr(p); + } + + pub fn free(r: *Rig, p: DevicePtr) void { + _ = r.api.hipFree(@ptrFromInt(p)); + } + + /// dev <- host, landed: a copy from pageable memory may return before its DMA ends, so the null stream syncs too. + pub fn put(r: *Rig, dev: DevicePtr, host: []const u8) Error!void { + if (host.len == 0) return; + try ok(r.api.hipMemcpyHtoD(@ptrFromInt(dev), host.ptr, host.len)); + try ok(r.api.hipStreamSynchronize(null)); + } + + pub fn get(r: *Rig, host: []u8, dev: DevicePtr) Error!void { + if (host.len > 0) try ok(r.api.hipMemcpyDtoH(host.ptr, @ptrFromInt(dev), host.len)); + } +}; diff --git a/zig/src/fabric/tp/portable_test.zig b/zig/src/fabric/tp/portable_test.zig index 1a44731bc20..910a20293b5 100644 --- a/zig/src/fabric/tp/portable_test.zig +++ b/zig/src/fabric/tp/portable_test.zig @@ -6,6 +6,8 @@ test { _ = @import("host_test.zig"); _ = @import("device_test.zig"); _ = @import("tcp_test.zig"); + _ = @import("stage_test.zig"); + _ = @import("stage_hip_test.zig"); _ = @import("roce_guard.zig"); _ = @import("bootstrap.zig"); _ = @import("fate_test.zig"); diff --git a/zig/src/fabric/tp/stage.zig b/zig/src/fabric/tp/stage.zig new file mode 100644 index 00000000000..24b67ce6dbf --- /dev/null +++ b/zig/src/fabric/tp/stage.zig @@ -0,0 +1,371 @@ +//! The TCP Kind for device memory: a call's stream waits on a word while a proxy thread copies and moves its bytes. +const std = @import("std"); +const collective = @import("collective.zig"); +const log = @import("log.zig"); +const sock = @import("sock.zig"); +const tcp = @import("tcp.zig"); +const DevicePtr = collective.DevicePtr; +const Stream = collective.Stream; +const DType = collective.DType; +const Op = collective.Op; +const Error = collective.Error; + +/// What staging asks of a GPU backend: the proxy's own copies, and 64-bit words written and awaited on a stream. +pub const Device = struct { + ptr: *anyopaque, + vtable: *const VTable, + + pub const VTable = struct { + /// host[0..n] <- dev[0..n], finished on return (the proxy thread's copy, on the backend's own stream). + download: *const fn (ptr: *anyopaque, host: [*]u8, dev: DevicePtr, n: usize) Error!void, + /// dev[0..n] <- host[0..n], finished on return. + upload: *const fn (ptr: *anyopaque, dev: DevicePtr, host: [*]const u8, n: usize) Error!void, + /// The stream sets a slab word to `value` once its earlier work is done. + write: *const fn (ptr: *anyopaque, word: *u64, value: u64, stream: Stream) Error!void, + /// The stream's later work waits until a slab word is at least `value`. + wait: *const fn (ptr: *anyopaque, word: *u64, value: u64, stream: Stream) Error!void, + /// Whether the stream is capturing a graph (refused: a replay would repeat the words' values). + capturing: *const fn (ptr: *anyopaque, stream: Stream) Error!bool, + /// Pinned host memory the device copies to and from and whose words it reads and writes. + alloc: *const fn (ptr: *anyopaque, n: usize) Error![]align(64) u8, + free: *const fn (ptr: *anyopaque, slab: []align(64) u8) void, + }; +}; + +pub const Options = struct { + /// Bytes the proxy stages each way at a time; a larger call moves in parts, split alike on every rank. + part_bytes: usize = 4 << 20, +}; + +/// Calls the host may queue ahead of the proxy, each with its own words. +const ring = 256; +/// A done word past every call: a failed or stopped proxy frees every stream's wait with it. +const released: u64 = 1 << 62; +/// How long an idle proxy or host wait spins before it naps between looks. +const spin_ns = 20 * std.time.ns_per_ms; +const nap_ns = 50 * std.time.ns_per_us; + +/// A call's words, one cache line: the stream writes ready and passed, the proxy writes done. +const Words = extern struct { ready: u64, done: u64, passed: u64, pad: [5]u64 }; + +const Call = enum(u8) { all_reduce, all_gather, exchange, send, recv, barrier }; + +/// A queued call as the proxy runs it: device addresses in, parts over `tcp`, device addresses out. +const Job = struct { + call: Call, + t: DType = .u8, + op: Op = .sum, + count: usize = 0, + peer: u32 = 0, + s: DevicePtr = 0, + d: DevicePtr = 0, +}; + +/// Own failures, beside the ones `tcp` keeps. +const Fail = enum(u8) { none, backend }; + +/// Waits that spin while work is recent, then nap, so an idle rank costs no core. +const Idle = struct { + since: u64 = 0, + + fn pause(i: *Idle) void { + const now = sock.nowNs(); + if (i.since == 0) i.since = now; + if (now - i.since < spin_ns) std.atomic.spinLoopHint() else sock.sleepNs(nap_ns); + } +}; + +/// Each call returns once queued on its stream; a failure shows at a later call or `check`, and frees the streams. +pub const Rank = struct { + net: *tcp.Rank, + dev: Device, + opts: Options, + /// `ring` calls' words, then the bytes the proxy sends and receives. + slab: []align(64) u8 = &.{}, + jobs: [ring]Job = undefined, + /// Calls the host queued and the proxy finished, counted from 1; call q uses words and jobs [q % ring]. + queued: std.atomic.Value(u64) = .init(0), + finished: std.atomic.Value(u64) = .init(0), + fail: std.atomic.Value(Fail) = .init(.none), + stop: std.atomic.Value(bool) = .init(false), + proxy: ?std.Thread = null, + + /// Staging over `net`, used only by the proxy from here on; every rank opens alike and checks the part size. + pub fn open(r: *Rank, net: *tcp.Rank, dev: Device, opts: Options) Error!void { + r.* = .{ .net = net, .dev = dev, .opts = opts }; + // sizes first, then the checks: a bad size is refused on every rank, not left to a peer's deadline + const mine = [1]u64{opts.part_bytes}; + var all: [tcp.max_ranks]u64 = undefined; + try net.iface().allGather(@intFromPtr(&mine), @intFromPtr(&all), 1, .i64, null); + for (all[0..net.world]) |p| if (p != opts.part_bytes or p % 64 != 0 or p < 8 * @as(u64, net.world)) return error.Invalid; + r.slab = try dev.vtable.alloc(dev.ptr, ring * @sizeOf(Words) + 2 * opts.part_bytes); + @memset(r.words()[0..ring], std.mem.zeroes(Words)); + r.proxy = std.Thread.spawn(.{}, loop, .{r}) catch { + dev.vtable.free(dev.ptr, r.slab); + return error.BackendFailed; + }; + } + + /// Stops the proxy and frees the slab once the streams are past their last calls (the caller synchronised them). + pub fn deinit(r: *Rank) void { + r.stop.store(true, .release); + if (r.proxy) |t| t.join(); + r.proxy = null; + // a stream still in a call has until the deadline to pass it; past that the slab leaks, never freed early + const deadline = sock.nowNs() +| r.net.opts.timeout_ns; + const last = r.queued.raw; + var q = @max(1, last -| (ring - 1)); + while (q <= last) { + if (r.jobs[q % ring].call == .barrier or @atomicLoad(u64, &r.words()[q % ring].passed, .acquire) >= q) { + q += 1; + } else if (sock.nowNs() > deadline) { + log.warn("[tensorfold] tp: a stream never passed its staged call {d}; the slab of {d} bytes is kept", .{ q, r.slab.len }); + return; + } else std.Thread.yield() catch {}; + } + r.dev.vtable.free(r.dev.ptr, r.slab); + } + + pub fn iface(r: *Rank) collective.Collective { + return .{ .ptr = r, .vtable = &vtable }; + } + + const vtable: collective.Collective.VTable = .{ + .kind = .tcp, + .rank = rankOf, + .world = worldOf, + .all_reduce = allReduce, + .all_gather = allGather, + .exchange = exchange, + .send = send, + .recv = recv, + .barrier = barrier, + .check = check, + .abort = abort, + }; + + fn self_(ptr: *anyopaque) *Rank { + return @ptrCast(@alignCast(ptr)); + } + + fn rankOf(ptr: *anyopaque) u32 { + return self_(ptr).net.me; + } + + fn worldOf(ptr: *anyopaque) u32 { + return self_(ptr).net.world; + } + + fn words(r: *Rank) [*]Words { + return @ptrCast(r.slab.ptr); + } + + /// The bytes the proxy sends; the bytes it receives follow them. + fn tx(r: *Rank) [*]u8 { + return r.slab.ptr + ring * @sizeOf(Words); + } + + fn rx(r: *Rank) [*]u8 { + return r.tx() + r.opts.part_bytes; + } + + fn failed(r: *Rank) bool { + if (r.fail.load(.acquire) != .none) return true; + r.net.iface().check() catch return true; + return false; + } + + fn check(ptr: *anyopaque) Error!void { + const r = self_(ptr); + if (r.fail.load(.acquire) == .backend) return error.BackendFailed; + return r.net.iface().check(); + } + + fn abort(ptr: *anyopaque) void { + self_(ptr).net.iface().abort(); + } + + /// A device call that failed: the communicator fails here and at the peers, and the streams are freed. + fn device(r: *Rank, res: Error!void) Error!void { + res catch { + _ = r.fail.cmpxchgStrong(.none, .backend, .acq_rel, .acquire); + r.net.iface().abort(); + r.release(); + return error.BackendFailed; + }; + } + + /// Every done word past any call, so no stream waits on a proxy that will not answer. + fn release(r: *Rank) void { + for (r.words()[0..ring]) |*w| @atomicStore(u64, &w.done, released, .release); + } + + fn loop(r: *Rank) void { + var q: u64 = 1; + var idle: Idle = .{}; + while (true) { + if (r.stop.load(.acquire)) return r.release(); + if (r.queued.load(.acquire) < q) { + idle.pause(); + continue; + } + idle = .{}; + const j = r.jobs[q % ring]; + const moved = !r.failed() and (j.call == .barrier or r.ready(q)); + if (moved) r.move(j) catch {}; // the failure stays in `tcp` or `fail`, for `check` + if (!moved or r.failed()) r.release() else if (j.call != .barrier) @atomicStore(u64, &r.words()[q % ring].done, q, .release); + r.finished.store(q, .release); + q += 1; + } + } + + /// Waits for the stream to reach call `q`; false on a failure or a stop. + fn ready(r: *Rank, q: u64) bool { + var idle: Idle = .{}; + while (@atomicLoad(u64, &r.words()[q % ring].ready, .acquire) < q) { + if (r.stop.load(.acquire) or r.failed()) return false; + idle.pause(); + } + return true; + } + + /// One call in parts of at most `part_bytes`: each part copied out, moved over `tcp`, and copied back. + fn move(r: *Rank, j: Job) Error!void { + const c = r.net.iface(); + r.net.part = 0; + if (j.call == .barrier) return c.barrier(); + const d = r.dev; + const w = r.net.world; + const size = j.t.size(); + const n = j.count * size; + const per = (if (j.call == .all_gather) r.opts.part_bytes / w else r.opts.part_bytes) / size; + const s = @intFromPtr(r.tx()); + const o = @intFromPtr(r.rx()); + var a: usize = 0; + var k: u32 = 0; + while (true) : (k += 1) { + const m = @min(per, j.count - a); + const off = a * size; + const b = m * size; + r.net.part = k; + if (j.call != .recv and b > 0) try r.device(d.vtable.download(d.ptr, r.tx(), j.s + off, b)); + switch (j.call) { + .all_reduce => try c.allReduce(s, o, m, j.t, j.op, null), + .all_gather => try c.allGather(s, o, m, j.t, null), + .exchange => try c.exchange(s, o, m, j.t, j.peer, null), + .send => try c.send(s, m, j.t, j.peer, null), + .recv => try c.recv(o, m, j.t, j.peer, null), + .barrier => unreachable, + } + if (b > 0) switch (j.call) { + .all_gather => for (0..w) |i| try r.device(d.vtable.upload(d.ptr, j.d + i * n + off, r.rx() + i * b, b)), + .send => {}, + else => try r.device(d.vtable.upload(d.ptr, j.d + off, r.rx(), b)), + }; + a += m; + if (a >= j.count) return; + } + } + + /// Queues `j` for the proxy; with a stream, the stream marks it ready, waits for its done word and passes it. + fn hand(r: *Rank, j: Job, stream: ?Stream) Error!u64 { + const q = r.queued.raw + 1; + // call q takes the words of call q - ring, which the proxy must have finished + var idle: Idle = .{}; + while (r.finished.load(.acquire) + ring < q) { + if (r.failed()) return error.Aborted; + idle.pause(); + } + const d = r.dev; + const w = &r.words()[q % ring]; + if (stream) |s| try r.device(d.vtable.write(d.ptr, &w.ready, q, s)); + r.jobs[q % ring] = j; + r.queued.store(q, .release); + if (stream) |s| { + try r.device(d.vtable.wait(d.ptr, &w.done, q, s)); + try r.device(d.vtable.write(d.ptr, &w.passed, q, s)); + } + return q; + } + + fn staged(r: *Rank, j: Job, stream: Stream) Error!void { + if (r.failed()) return error.Aborted; + if (try r.dev.vtable.capturing(r.dev.ptr, stream)) return error.Unsupported; + _ = try r.hand(j, stream); + if (r.failed()) return check(r); + } + + fn allReduce(ptr: *anyopaque, s: DevicePtr, d: DevicePtr, count: usize, t: DType, op: Op, stream: Stream) Error!void { + return self_(ptr).staged(.{ .call = .all_reduce, .t = t, .op = op, .count = count, .s = s, .d = d }, stream); + } + + fn allGather(ptr: *anyopaque, s: DevicePtr, d: DevicePtr, count: usize, t: DType, stream: Stream) Error!void { + return self_(ptr).staged(.{ .call = .all_gather, .t = t, .count = count, .s = s, .d = d }, stream); + } + + /// Two ranks trade; as with NCCL, `s` and `d` must not overlap. + fn exchange(ptr: *anyopaque, s: DevicePtr, d: DevicePtr, count: usize, t: DType, peer: u32, stream: Stream) Error!void { + const r = self_(ptr); + try collective.checkPeer(r.net.me, r.net.world, peer); + return r.staged(.{ .call = .exchange, .t = t, .count = count, .peer = peer, .s = s, .d = d }, stream); + } + + fn send(ptr: *anyopaque, buf: DevicePtr, count: usize, t: DType, peer: u32, stream: Stream) Error!void { + const r = self_(ptr); + try collective.checkPeer(r.net.me, r.net.world, peer); + return r.staged(.{ .call = .send, .t = t, .count = count, .peer = peer, .s = buf }, stream); + } + + fn recv(ptr: *anyopaque, buf: DevicePtr, count: usize, t: DType, peer: u32, stream: Stream) Error!void { + const r = self_(ptr); + try collective.checkPeer(r.net.me, r.net.world, peer); + return r.staged(.{ .call = .recv, .t = t, .count = count, .peer = peer, .d = buf }, stream); + } + + /// Returns once every rank has called it and the proxy has moved this rank's earlier calls. + fn barrier(ptr: *anyopaque) Error!void { + const r = self_(ptr); + if (r.failed()) return error.Aborted; + const q = try r.hand(.{ .call = .barrier }, null); + var idle: Idle = .{}; + while (r.finished.load(.acquire) < q) idle.pause(); + if (r.failed()) return check(r); + } +}; + +/// Runs `body` on `world` threads, rank i a staged rank on `devs[i]` over loopback; the first error returns. +pub fn run(gpa: std.mem.Allocator, net: tcp.Options, devs: []const Device, opts: Options, ctx: anytype, comptime body: fn (collective.Collective, u32, @TypeOf(ctx)) anyerror!void) !void { + const world: u32 = @intCast(devs.len); + const fds = try tcp.loopback(world); + var nets: [tcp.max_ranks]tcp.Rank = undefined; + var row: [tcp.max_ranks]sock.Fd = undefined; + for (0..world) |i| { + for (0..world) |j| row[j] = fds[i][j]; + nets[i] = tcp.Rank.init(gpa, @intCast(i), world, row[0..world], net); + } + defer for (nets[0..world]) |*n| n.deinit(); + var errs: [tcp.max_ranks]?anyerror = @splat(null); + var threads: [tcp.max_ranks]std.Thread = undefined; + const Wrap = struct { + fn go(n: *tcp.Rank, d: Device, o: Options, cx: @TypeOf(ctx), e: *?anyerror) void { + var r: Rank = undefined; + r.open(n, d, o) catch |err| { + e.* = err; + n.iface().abort(); + return; + }; + defer r.deinit(); + body(r.iface(), n.me, cx) catch |err| { + e.* = err; + r.iface().abort(); + }; + } + }; + var started: usize = 0; + defer for (threads[0..started]) |t| t.join(); + errdefer for (nets[0..world]) |*n| n.iface().abort(); + while (started < world) : (started += 1) threads[started] = try std.Thread.spawn(.{}, Wrap.go, .{ &nets[started], devs[started], opts, ctx, &errs[started] }); + for (threads[0..started]) |t| t.join(); + started = 0; + for (errs[0..world]) |e| if (e) |err| return err; +} diff --git a/zig/src/fabric/tp/stage_hip.zig b/zig/src/fabric/tp/stage_hip.zig new file mode 100644 index 00000000000..f42ba3e7ea8 --- /dev/null +++ b/zig/src/fabric/tp/stage_hip.zig @@ -0,0 +1,152 @@ +//! HIP's `stage.Device`: the proxy's copies on a stream of its own, and 64-bit words written and awaited on a stream. +const std = @import("std"); +const sys = @import("sys"); +const collective = @import("collective.zig"); +const log = @import("log.zig"); +const stage = @import("stage.zig"); +const sock = @import("sock.zig"); +const DevicePtr = collective.DevicePtr; +const Stream = collective.Stream; +const Error = collective.Error; + +const Result = c_int; +const P = ?*anyopaque; + +/// What staging calls, each the HIP runtime's exact export. +const Api = struct { + hipGetDevice: *const fn (*c_int) callconv(.c) Result, + hipDeviceGetAttribute: *const fn (*c_int, c_int, c_int) callconv(.c) Result, + hipStreamCreateWithFlags: *const fn (*Stream, c_uint) callconv(.c) Result, + hipStreamDestroy: *const fn (Stream) callconv(.c) Result, + hipStreamQuery: *const fn (Stream) callconv(.c) Result, + hipMemcpyDtoHAsync: *const fn (P, P, usize, Stream) callconv(.c) Result, + hipMemcpyHtoDAsync: *const fn (P, ?*const anyopaque, usize, Stream) callconv(.c) Result, + hipStreamWriteValue64: *const fn (Stream, P, u64, c_uint) callconv(.c) Result, + hipStreamWaitValue64: *const fn (Stream, P, u64, c_uint, u64) callconv(.c) Result, + hipStreamIsCapturing: *const fn (Stream, *c_int) callconv(.c) Result, + hipHostMalloc: *const fn (*P, usize, c_uint) callconv(.c) Result, + hipHostFree: *const fn (P) callconv(.c) Result, +}; + +/// hipDeviceAttributeCanUseStreamWaitValue. +const can_wait_value: c_int = 10013; +/// hipHostMallocMapped | hipHostMallocCoherent: the GPU sees the proxy's words as the proxy writes them. +const pinned: c_uint = 0x2 | 0x40000000; +/// hipStreamWaitValueGte. +const at_least: c_uint = 0; +/// hipStreamNonBlocking: the proxy's copies never wait for the legacy null stream. +const non_blocking: c_uint = 1; +/// hipErrorNotReady: the stream still has work queued. +const not_ready: Result = 600; +/// The proxy asks the runtime about a copy every copy_look_ns, spinning between asks, then naps once copy_spin_ns pass. +const copy_look_ns = 3 * std.time.ns_per_us; +const copy_spin_ns = 500 * std.time.ns_per_us; +const copy_nap_ns = 10 * std.time.ns_per_us; + +/// The proxy copies on a stream of its own and waits for each copy; the caller's stream only writes and waits. +pub const Hip = struct { + api: Api, + own: Stream = null, + /// A copy still queued past this fails its call and frees every stream: its queue may be one a parked stream holds. + limit_ns: u64 = 30 * std.time.ns_per_s, + + /// The current GPU, through the HIP runtime `lib` the caller opened; refuses one whose streams cannot wait. + pub fn init(lib: *sys.DynLib) Error!Hip { + var api: Api = undefined; + const info = @typeInfo(Api).@"struct"; + inline for (info.field_names, info.field_types) |name, T| { + @field(api, name) = lib.lookup(T, name) orelse { + log.warn("[tensorfold] tp: the HIP runtime has no {s}; TCP staging needs it", .{name}); + return error.Unsupported; + }; + } + var dev: c_int = 0; + var can: c_int = 0; + try call(api.hipGetDevice(&dev), "hipGetDevice"); + try call(api.hipDeviceGetAttribute(&can, can_wait_value, dev), "hipDeviceGetAttribute"); + if (can == 0) { + log.warn("[tensorfold] tp: HIP device {d} cannot wait on a stream value; TCP staging refuses it", .{dev}); + return error.Unsupported; + } + var h: Hip = .{ .api = api }; + try call(api.hipStreamCreateWithFlags(&h.own, non_blocking), "hipStreamCreateWithFlags"); + return h; + } + + pub fn deinit(h: *Hip) void { + _ = h.api.hipStreamDestroy(h.own); + } + + pub fn device(h: *Hip) stage.Device { + return .{ .ptr = h, .vtable = &vtable }; + } + + const vtable: stage.Device.VTable = .{ .download = download, .upload = upload, .write = write, .wait = wait, .capturing = capturing, .alloc = alloc, .free = free }; + + fn of(ptr: *anyopaque) *Hip { + return @ptrCast(@alignCast(ptr)); + } + + fn call(res: Result, comptime what: []const u8) Error!void { + if (res == 0) return; + log.err("[tensorfold] tp: " ++ what ++ " failed (HIP error {d})", .{res}); + return error.BackendFailed; + } + + fn download(ptr: *anyopaque, host: [*]u8, dev: DevicePtr, n: usize) Error!void { + const h = of(ptr); + try call(h.api.hipMemcpyDtoHAsync(host, @ptrFromInt(dev), n, h.own), "hipMemcpyDtoHAsync"); + return h.settle(); + } + + fn upload(ptr: *anyopaque, dev: DevicePtr, host: [*]const u8, n: usize) Error!void { + const h = of(ptr); + try call(h.api.hipMemcpyHtoDAsync(@ptrFromInt(dev), host, n, h.own), "hipMemcpyHtoDAsync"); + return h.settle(); + } + + /// The proxy's stream has finished its copy, or the copy failed, or `limit_ns` passed without it. + fn settle(h: *Hip) Error!void { + const t0 = sock.nowNs(); + while (true) { + const res = h.api.hipStreamQuery(h.own); + if (res != not_ready) return call(res, "hipStreamQuery"); + const waited = sock.nowNs() - t0; + if (waited > h.limit_ns) { + log.err("[tensorfold] tp: a staged copy was still queued after {d} ms", .{waited / std.time.ns_per_ms}); + return error.BackendFailed; + } + if (waited >= copy_spin_ns) { + sock.sleepNs(copy_nap_ns); + continue; + } + const next = sock.nowNs() + copy_look_ns; // asking too often slows the copy itself + while (sock.nowNs() < next) std.atomic.spinLoopHint(); + } + } + + fn write(ptr: *anyopaque, word: *u64, value: u64, s: Stream) Error!void { + return call(of(ptr).api.hipStreamWriteValue64(s, word, value, 0), "hipStreamWriteValue64"); + } + + fn wait(ptr: *anyopaque, word: *u64, value: u64, s: Stream) Error!void { + return call(of(ptr).api.hipStreamWaitValue64(s, word, value, at_least, std.math.maxInt(u64)), "hipStreamWaitValue64"); + } + + fn capturing(ptr: *anyopaque, s: Stream) Error!bool { + var status: c_int = 0; + try call(of(ptr).api.hipStreamIsCapturing(s, &status), "hipStreamIsCapturing"); + return status != 0; + } + + fn alloc(ptr: *anyopaque, n: usize) Error![]align(64) u8 { + var p: P = null; + try call(of(ptr).api.hipHostMalloc(&p, n, pinned), "hipHostMalloc"); + const base: [*]align(64) u8 = @ptrCast(@alignCast(p orelse return error.BackendFailed)); + return base[0..n]; + } + + fn free(ptr: *anyopaque, slab: []align(64) u8) void { + _ = of(ptr).api.hipHostFree(slab.ptr); + } +}; diff --git a/zig/src/fabric/tp/stage_hip_test.zig b/zig/src/fabric/tp/stage_hip_test.zig new file mode 100644 index 00000000000..2ea4ee5fedb --- /dev/null +++ b/zig/src/fabric/tp/stage_hip_test.zig @@ -0,0 +1,236 @@ +//! Staging HIP memory on a real GPU: two ranks of one device over loopback, each on its own stream; skips without HIP. +const std = @import("std"); +const collective = @import("collective.zig"); +const reference = @import("reference.zig"); +const sock = @import("sock.zig"); +const stage = @import("stage.zig"); +const tcp = @import("tcp.zig"); +const Hip = @import("stage_hip.zig").Hip; +const Rig = @import("hip_rig.zig").Rig; +const Collective = collective.Collective; +const DType = collective.DType; +const DevicePtr = collective.DevicePtr; + +const gpa = std.testing.allocator; +const net: tcp.Options = .{ .timeout_ns = 10 * std.time.ns_per_s }; +/// 64 KiB parts: the larger calls below move in several. +const small: stage.Options = .{ .part_bytes = 64 << 10 }; +const max_bytes = 1 << 21; + +/// The runtime, and each rank's HIP device with the stream its proxy copies on. +const Gpu = struct { + rig: Rig, + hips: [2]Hip, + + fn open() !Gpu { + var rig = Rig.open() catch return error.SkipZigTest; + errdefer rig.close(); + var a = Hip.init(&rig.lib) catch |e| return if (e == error.Unsupported) error.SkipZigTest else e; + errdefer a.deinit(); + return .{ .rig = rig, .hips = .{ a, Hip.init(&rig.lib) catch |e| return if (e == error.Unsupported) error.SkipZigTest else e } }; + } + + fn close(g: *Gpu) void { + for (&g.hips) |*h| h.deinit(); + g.rig.close(); + } + + fn run(g: *Gpu, opts: stage.Options, comptime body: fn (Collective, u32, *Gpu) anyerror!void) !void { + const devs = [2]stage.Device{ g.hips[0].device(), g.hips[1].device() }; + try stage.run(gpa, net, &devs, opts, g, body); + } +}; + +/// A rank's stream and buffers: `in` and `out` on the device, `host` and `want` to fill and compare. +const Bufs = struct { + s: collective.Stream, + in: DevicePtr, + out: DevicePtr, + host: []u8, + want: []u8, + + fn init(rig: *Rig) !Bufs { + const s = try rig.stream(); + return .{ .s = s, .in = try rig.alloc(max_bytes), .out = try rig.alloc(2 * max_bytes), .host = try gpa.alloc(u8, 2 * max_bytes), .want = try gpa.alloc(u8, 3 * max_bytes) }; + } + + fn deinit(b: *Bufs, rig: *Rig) void { + rig.free(b.in); + rig.free(b.out); + rig.destroy(b.s); + gpa.free(b.host); + gpa.free(b.want); + } +}; + +/// Sums, gathers, trades and sends of 0 B to 1 MiB, each checked bit for bit after its stream synchronised. +const Calls = struct { + fn go(c: Collective, rank: u32, g: *Gpu) !void { + const rig = &g.rig; + var b = try Bufs.init(rig); + defer b.deinit(rig); + const peer = rank ^ 1; + const counts = [_]usize{ 0, 1, 7, 96, 4099, 65536 + 3, 262144 }; + for (counts, 0..) |n, k| inline for (.{ DType.f32, DType.bf16, DType.f16, DType.i32 }) |t| { + const len = n * t.size(); + reference.fill(b.host[0..len], t, rank, k); + try rig.put(b.in, b.host[0..len]); + try c.allReduce(b.in, b.out, n, t, .sum, b.s); + try c.allGather(b.in, b.out + max_bytes, n, t, b.s); + try rig.sync(b.s); + try c.check(); + var views: [2][]const u8 = undefined; + for (0..2) |r| { + reference.fill(b.want[(r + 1) * max_bytes ..][0..len], t, @intCast(r), k); + views[r] = b.want[(r + 1) * max_bytes ..][0..len]; + } + reference.reduce(b.want[0..len], &views, t, .sum); + try rig.get(b.host[0..len], b.out); + try std.testing.expectEqualSlices(u8, b.want[0..len], b.host[0..len]); + try rig.get(b.host[0 .. 2 * len], b.out + max_bytes); + for (0..2) |r| try std.testing.expectEqualSlices(u8, views[r], b.host[r * len ..][0..len]); + // in place, then a trade and a send beside it + try rig.put(b.out, views[rank]); + try c.allReduce(b.out, b.out, n, t, .sum, b.s); + try c.exchange(b.in, b.out + max_bytes, n, t, peer, b.s); + if (rank == 0) try c.send(b.in, n, t, 1, b.s) else try c.recv(b.out + max_bytes + len, n, t, 0, b.s); + try rig.sync(b.s); + try c.check(); + try rig.get(b.host[0..len], b.out); + try std.testing.expectEqualSlices(u8, b.want[0..len], b.host[0..len]); + try rig.get(b.host[0..len], b.out + max_bytes); + try std.testing.expectEqualSlices(u8, views[peer], b.host[0..len]); + if (rank == 1) { + try rig.get(b.host[0..len], b.out + max_bytes + len); + try std.testing.expectEqualSlices(u8, views[0], b.host[0..len]); + } + }; + try c.barrier(); + try c.check(); + } +}; + +test "every staged call on HIP memory equals the reference, whole and in parts" { + var g = try Gpu.open(); + defer g.close(); + try g.run(.{}, Calls.go); + try g.run(small, Calls.go); +} + +const rounds = 20; + +/// The stream waits on a gate word first: every call returns while nothing has run, and then all land. +const Held = struct { + fn go(c: Collective, rank: u32, g: *Gpu) !void { + const rig = &g.rig; + var b = try Bufs.init(rig); + defer b.deinit(rig); + const dev = g.hips[rank].device(); + const gate = try dev.vtable.alloc(dev.ptr, 64); + defer dev.vtable.free(dev.ptr, gate); + const word: *u64 = @ptrCast(gate.ptr); + @atomicStore(u64, word, 0, .release); + const n = 24576; // 96 KiB of f32: two parts a call at 64 KiB + const len = n * 4; + @memset(b.host[0 .. 2 * max_bytes], 0xEE); + try rig.put(b.out, b.host[0 .. 2 * max_bytes]); + reference.fill(b.host[0..len], .f32, rank, 5); + try rig.put(b.in, b.host[0..len]); + try dev.vtable.wait(dev.ptr, word, 1, b.s); + defer @atomicStore(u64, word, 1, .release); // a failed check below still lets the stream go before cleanup + for (0..rounds) |k| try c.allGather(b.in, b.out + k * 2 * len, n, .f32, b.s); + sock.sleepNs(50 * std.time.ns_per_ms); + try rig.get(b.host[0 .. rounds * 2 * len], b.out); + try std.testing.expect(std.mem.allEqual(u8, b.host[0 .. rounds * 2 * len], 0xEE)); + @atomicStore(u64, word, 1, .release); + try rig.sync(b.s); + try c.check(); + try rig.get(b.host[0 .. rounds * 2 * len], b.out); + for (0..2) |r| reference.fill(b.want[r * len ..][0..len], .f32, @intCast(r), 5); + for (0..rounds) |k| try std.testing.expectEqualSlices(u8, b.want[0 .. 2 * len], b.host[k * 2 * len ..][0 .. 2 * len]); + } +}; + +test "staged calls on a HIP stream return before the GPU reaches them" { + var g = try Gpu.open(); + defer g.close(); + try g.run(small, Held.go); +} + +/// Rank 1 aborts instead of calling; rank 0's stream must still finish its queued calls. +const Freed = struct { + fn go(c: Collective, rank: u32, g: *Gpu) !void { + if (rank == 1) { + sock.sleepNs(20 * std.time.ns_per_ms); + return c.abort(); + } + const rig = &g.rig; + var b = try Bufs.init(rig); + defer b.deinit(rig); + for (0..rounds) |k| c.allGather(b.in, b.out + k * 8192, 1024, .f32, b.s) catch |e| try std.testing.expectEqual(error.Aborted, e); + try rig.sync(b.s); + try std.testing.expectError(error.Aborted, c.check()); + } +}; + +test "an abort lets a HIP stream with staged calls finish" { + var g = try Gpu.open(); + defer g.close(); + try g.run(small, Freed.go); +} + +const Capture = struct { + fn go(c: Collective, _: u32, g: *Gpu) !void { + const rig = &g.rig; + var b = try Bufs.init(rig); + defer b.deinit(rig); + try rig.capture(b.s); + const r = c.allGather(b.in, b.out, 16, .f32, b.s); + try rig.endCapture(b.s); + try std.testing.expectError(error.Unsupported, r); + } +}; + +test "a capturing HIP stream is refused" { + var g = try Gpu.open(); + defer g.close(); + try g.run(.{}, Capture.go); +} + +/// A HIP runtime whose copies queue and whose stream finishes only when told: the proxy's wait without a GPU. +const Stuck = struct { + var finished = false; + + fn down(_: ?*anyopaque, _: ?*anyopaque, _: usize, _: collective.Stream) callconv(.c) c_int { + return 0; + } + + fn up(_: ?*anyopaque, _: ?*const anyopaque, _: usize, _: collective.Stream) callconv(.c) c_int { + return 0; + } + + fn query(_: collective.Stream) callconv(.c) c_int { + return if (finished) 0 else 600; // hipErrorNotReady + } + + fn hip(limit_ns: u64) Hip { + var h: Hip = .{ .api = undefined, .limit_ns = limit_ns }; + h.api.hipMemcpyDtoHAsync = &down; + h.api.hipMemcpyHtoDAsync = &up; + h.api.hipStreamQuery = &query; + return h; + } +}; + +test "a proxy copy still queued past its limit fails its call instead of waiting forever" { + var buf: [64]u8 = undefined; + var h = Stuck.hip(5 * std.time.ns_per_ms); + const d = h.device(); + Stuck.finished = false; + const t0 = sock.nowNs(); + try std.testing.expectError(error.BackendFailed, d.vtable.download(d.ptr, &buf, 0x1000, buf.len)); + try std.testing.expectError(error.BackendFailed, d.vtable.upload(d.ptr, 0x1000, &buf, buf.len)); + try std.testing.expect(sock.nowNs() - t0 < 2 * std.time.ns_per_s); + Stuck.finished = true; + try d.vtable.download(d.ptr, &buf, 0x1000, buf.len); +} diff --git a/zig/src/fabric/tp/stage_later_test.zig b/zig/src/fabric/tp/stage_later_test.zig new file mode 100644 index 00000000000..521f4ed0cae --- /dev/null +++ b/zig/src/fabric/tp/stage_later_test.zig @@ -0,0 +1,173 @@ +//! Staging over streams that run later: calls return before their bytes move, and a failure still frees a held stream. +const std = @import("std"); +const collective = @import("collective.zig"); +const reference = @import("reference.zig"); +const sock = @import("sock.zig"); +const stage = @import("stage.zig"); +const tcp = @import("tcp.zig"); +const Collective = collective.Collective; +const DevicePtr = collective.DevicePtr; +const Stream = collective.Stream; +const Error = collective.Error; + +const gpa = std.testing.allocator; +const net: tcp.Options = .{ .timeout_ns = 5 * std.time.ns_per_s }; +const tiny: stage.Options = .{ .part_bytes = 64 }; + +fn addr(b: []u8) DevicePtr { + return @intFromPtr(b.ptr); +} + +/// A stream: its own thread runs the words queued on it in order, once it is no longer held; copies are the proxy's. +const Later = struct { + const Item = union(enum) { + write: struct { word: *u64, value: u64 }, + wait: struct { word: *u64, value: u64 }, + }; + items: [1 << 12]Item = undefined, + head: std.atomic.Value(usize) = .init(0), + tail: std.atomic.Value(usize) = .init(0), + held: std.atomic.Value(bool) = .init(true), + quit: std.atomic.Value(bool) = .init(false), + thread: ?std.Thread = null, + + fn of(s: Stream) *Later { + return @ptrCast(@alignCast(s.?)); + } + + fn stream(l: *Later) Stream { + return @ptrCast(l); + } + + fn push(l: *Later, it: Item) void { + const t = l.tail.raw; + while (t - l.head.load(.acquire) >= l.items.len) std.Thread.yield() catch {}; + l.items[t % l.items.len] = it; + l.tail.store(t + 1, .release); + } + + fn loop(l: *Later) void { + while (true) { + const h = l.head.raw; + if (l.held.load(.acquire) or h == l.tail.load(.acquire)) { + if (l.quit.load(.acquire)) return; + std.Thread.yield() catch {}; + continue; + } + switch (l.items[h % l.items.len]) { + .write => |w| @atomicStore(u64, w.word, w.value, .release), + .wait => |w| while (@atomicLoad(u64, w.word, .acquire) < w.value) std.Thread.yield() catch {}, + } + l.head.store(h + 1, .release); + } + } + + fn sync(l: *Later) void { + while (l.head.load(.acquire) != l.tail.load(.acquire)) std.Thread.yield() catch {}; + } + + const devs = [2]stage.Device{ device(), device() }; + + fn device() stage.Device { + return .{ .ptr = undefined, .vtable = &.{ .download = download, .upload = upload, .write = write, .wait = wait, .capturing = capture, .alloc = alloc, .free = free } }; + } + fn download(_: *anyopaque, host: [*]u8, dev: DevicePtr, n: usize) Error!void { + @memcpy(host[0..n], @as([*]const u8, @ptrFromInt(dev))[0..n]); + } + fn upload(_: *anyopaque, dev: DevicePtr, host: [*]const u8, n: usize) Error!void { + @memcpy(@as([*]u8, @ptrFromInt(dev))[0..n], host[0..n]); + } + fn write(_: *anyopaque, word: *u64, value: u64, s: Stream) Error!void { + of(s).push(.{ .write = .{ .word = word, .value = value } }); + } + fn wait(_: *anyopaque, word: *u64, value: u64, s: Stream) Error!void { + of(s).push(.{ .wait = .{ .word = word, .value = value } }); + } + fn capture(_: *anyopaque, _: Stream) Error!bool { + return false; + } + fn alloc(_: *anyopaque, n: usize) Error![]align(64) u8 { + return gpa.alignedAlloc(u8, .@"64", n) catch error.BackendFailed; + } + fn free(_: *anyopaque, slab: []align(64) u8) void { + gpa.free(slab); + } +}; + +const rounds = 10; +const count = 96; + +/// Ten rounds of a sum, a gather and a trade queued on a held stream, each moved in 64-byte parts. +const Queued = struct { + fn go(c: Collective, rank: u32, _: void) !void { + var l: Later = .{}; + l.thread = try std.Thread.spawn(.{}, Later.loop, .{&l}); + defer { + l.held.store(false, .release); + l.sync(); + l.quit.store(true, .release); + l.thread.?.join(); + } + const peer = rank ^ 1; + var ins: [rounds][count * 4]u8 = undefined; + var sums: [rounds][count * 4]u8 = @splat(@splat(0xEE)); + var all: [rounds][2 * count * 4]u8 = @splat(@splat(0xEE)); + var trades: [rounds][count * 4]u8 = @splat(@splat(0xEE)); + for (0..rounds) |k| { + reference.fill(&ins[k], .f32, rank, k); + try c.allReduce(addr(&ins[k]), addr(&sums[k]), count, .f32, .sum, l.stream()); + try c.allGather(addr(&ins[k]), addr(&all[k]), count, .f32, l.stream()); + try c.exchange(addr(&ins[k]), addr(&trades[k]), count, .f32, peer, l.stream()); + } + // every call returned while its stream was held, and a while later still no byte has moved + sock.sleepNs(50 * std.time.ns_per_ms); + for (0..rounds) |k| { + try std.testing.expect(std.mem.allEqual(u8, &sums[k], 0xEE)); + try std.testing.expect(std.mem.allEqual(u8, &all[k], 0xEE)); + try std.testing.expect(std.mem.allEqual(u8, &trades[k], 0xEE)); + } + l.held.store(false, .release); + l.sync(); + try c.check(); + for (0..rounds) |k| { + var each: [2][count * 4]u8 = undefined; + for (0..2) |r| reference.fill(&each[r], .f32, @intCast(r), k); + var want: [count * 4]u8 = undefined; + reference.reduce(&want, &[_][]const u8{ &each[0], &each[1] }, .f32, .sum); + try std.testing.expectEqualSlices(u8, &want, &sums[k]); + try std.testing.expectEqualSlices(u8, &(each[0] ++ each[1]), &all[k]); + try std.testing.expectEqualSlices(u8, &each[peer], &trades[k]); + } + } +}; + +test "staged calls return before their stream runs, and the stream then gives every one the reference's bytes" { + try stage.run(gpa, net, &Later.devs, tiny, {}, Queued.go); +} + +/// Rank 0 queues calls on a held stream; rank 1 aborts instead of calling. The stream must still drain. +const Freed = struct { + fn go(c: Collective, rank: u32, _: void) !void { + if (rank == 1) { + sock.sleepNs(20 * std.time.ns_per_ms); + return c.abort(); + } + var l: Later = .{}; + l.thread = try std.Thread.spawn(.{}, Later.loop, .{&l}); + defer { + l.quit.store(true, .release); + l.thread.?.join(); + } + var a: [count * 4]u8 = @splat(1); + var b: [rounds][2 * count * 4]u8 = undefined; + for (0..rounds) |k| c.allGather(addr(&a), addr(&b[k]), count, .f32, l.stream()) catch |e| try std.testing.expectEqual(error.Aborted, e); + sock.sleepNs(50 * std.time.ns_per_ms); + l.held.store(false, .release); + l.sync(); + try std.testing.expectError(error.Aborted, c.check()); + } +}; + +test "an abort while staged calls wait on a held stream lets the stream drain" { + try stage.run(gpa, net, &Later.devs, tiny, {}, Freed.go); +} diff --git a/zig/src/fabric/tp/stage_test.zig b/zig/src/fabric/tp/stage_test.zig new file mode 100644 index 00000000000..5033e158ae8 --- /dev/null +++ b/zig/src/fabric/tp/stage_test.zig @@ -0,0 +1,208 @@ +//! Staging over fake devices: the `Collective` contract with copies done at once, then streams that run later. +const std = @import("std"); +const collective = @import("collective.zig"); +const reference = @import("reference.zig"); +const stage = @import("stage.zig"); +const tcp = @import("tcp.zig"); +const contract = @import("host_test.zig"); +const Collective = collective.Collective; +const DevicePtr = collective.DevicePtr; +const Stream = collective.Stream; +const Error = collective.Error; + +const gpa = std.testing.allocator; +const net: tcp.Options = .{ .timeout_ns = 5 * std.time.ns_per_s }; +/// Parts of 64 bytes: the contract's calls go in many parts. +const tiny: stage.Options = .{ .part_bytes = 64 }; + +fn addr(b: []u8) DevicePtr { + return @intFromPtr(b.ptr); +} + +fn bytes(p: DevicePtr, n: usize) []u8 { + return @as([*]u8, @ptrFromInt(p))[0..n]; +} + +/// A device whose memory is host memory and whose stream is the caller: each operation is done when it returns. +const Now = struct { + capturing: bool = false, + /// A stream whose words cannot be written, and a device address that cannot be copied, as device errors. + const failing: Stream = @ptrFromInt(0xbad0); + const unreadable: DevicePtr = 0xbad0; + + fn device(f: *Now) stage.Device { + return .{ .ptr = f, .vtable = &.{ .download = download, .upload = upload, .write = write, .wait = wait, .capturing = capture, .alloc = alloc, .free = free } }; + } + fn download(_: *anyopaque, host: [*]u8, dev: DevicePtr, n: usize) Error!void { + if (dev == unreadable) return error.BackendFailed; + @memcpy(host[0..n], bytes(dev, n)); + } + fn upload(_: *anyopaque, dev: DevicePtr, host: [*]const u8, n: usize) Error!void { + @memcpy(bytes(dev, n), host[0..n]); + } + fn write(_: *anyopaque, word: *u64, value: u64, s: Stream) Error!void { + if (s == failing) return error.BackendFailed; + @atomicStore(u64, word, value, .release); + } + fn wait(_: *anyopaque, word: *u64, value: u64, _: Stream) Error!void { + while (@atomicLoad(u64, word, .acquire) < value) std.Thread.yield() catch {}; + } + fn capture(ptr: *anyopaque, _: Stream) Error!bool { + return @as(*Now, @ptrCast(@alignCast(ptr))).capturing; + } + fn alloc(_: *anyopaque, n: usize) Error![]align(64) u8 { + return gpa.alignedAlloc(u8, .@"64", n) catch error.BackendFailed; + } + fn free(_: *anyopaque, slab: []align(64) u8) void { + gpa.free(slab); + } + + /// The same device for each of `world` ranks. + fn all(f: *Now, world: usize) []const stage.Device { + const S = struct { + var devs: [tcp.max_ranks]stage.Device = undefined; + }; + for (S.devs[0..world]) |*d| d.* = f.device(); + return S.devs[0..world]; + } +}; + +test "every call on two, three and four staged ranks equals the reference, whole and in parts" { + var f: Now = .{}; + for ([_]u32{ 2, 3, 4 }) |w| { + try stage.run(gpa, net, f.all(w), .{}, {}, contract.Calls.go); + try stage.run(gpa, net, f.all(w), tiny, {}, contract.Calls.go); + } +} + +test "staged exchange, send and recv between two ranks, and in pairs of four" { + var f: Now = .{}; + for ([_]u32{ 2, 4 }) |w| { + try stage.run(gpa, net, f.all(w), .{}, {}, contract.Pairwise.go); + try stage.run(gpa, net, f.all(w), tiny, {}, contract.Pairwise.go); + } +} + +test "a desynchronised staged call is refused on every rank, and abort frees a waiting peer" { + var f: Now = .{}; + try stage.run(gpa, net, f.all(2), .{}, {}, contract.Desync.go); + try stage.run(gpa, net, f.all(2), .{}, {}, contract.Aborts.go); +} + +const KindOk = struct { + fn go(c: Collective, _: u32, _: void) !void { + try std.testing.expectEqual(collective.Kind.tcp, c.kind()); + try c.barrier(); + } +}; + +test "staging is the TCP Kind" { + var f: Now = .{}; + try stage.run(gpa, net, f.all(2), .{}, {}, KindOk.go); +} + +/// Rank 0 makes one call of 128 bytes, rank 1 two of 64: in 64-byte parts the counts agree, the part numbers do not. +const Parts = struct { + fn go(c: Collective, rank: u32, _: void) !void { + var a: [128]u8 = @splat(1); + var b: [128]u8 = undefined; + const r = if (rank == 0) c.allReduce(addr(&a), addr(&b), 128, .u8, .sum, null) else blk: { + c.allReduce(addr(&a), addr(&b), 64, .u8, .sum, null) catch |e| break :blk e; + break :blk c.allReduce(addr(a[64..]), addr(b[64..]), 64, .u8, .sum, null); + }; + if (r) |_| return error.ShouldHaveFailed else |e| if (e != error.Invalid and e != error.Aborted) return e; + } +}; + +test "one call in two parts against two whole calls is refused, though every part's count agrees" { + var f: Now = .{}; + try stage.run(gpa, net, f.all(2), tiny, {}, Parts.go); +} + +const Opens = struct { + fn go(_: Collective, _: u32, _: void) !void { + return error.ShouldHaveFailed; + } +}; + +test "ranks that differ in their part size refuse to open" { + var f: Now = .{}; + const fds = try tcp.loopback(2); + var nets = [2]tcp.Rank{ tcp.Rank.init(gpa, 0, 2, &.{ -1, fds[0][1] }, net), tcp.Rank.init(gpa, 1, 2, &.{ fds[1][0], -1 }, net) }; + defer for (&nets) |*n| n.deinit(); + const Open = struct { + fn go(n: *tcp.Rank, d: stage.Device, part: usize, out: *?anyerror) void { + var r: stage.Rank = undefined; + r.open(n, d, .{ .part_bytes = part }) catch |e| { + out.* = e; + return; + }; + r.deinit(); + } + }; + var errs: [2]?anyerror = .{ null, null }; + const t = try std.Thread.spawn(.{}, Open.go, .{ &nets[1], f.device(), 128, &errs[1] }); + Open.go(&nets[0], f.device(), 64, &errs[0]); + t.join(); + try std.testing.expectEqual(@as(?anyerror, error.Invalid), errs[0]); + try std.testing.expectEqual(@as(?anyerror, error.Invalid), errs[1]); + try std.testing.expectError(error.Invalid, stage.run(gpa, net, f.all(2), .{ .part_bytes = 8 }, {}, Opens.go)); +} + +const Capture = struct { + fn go(c: Collective, _: u32, _: void) !void { + var a: [16]u8 = @splat(0); + var b: [32]u8 = undefined; + try std.testing.expectError(error.Unsupported, c.allGather(addr(&a), addr(&b), 16, .u8, null)); + } +}; + +test "a capturing stream is refused before anything is queued" { + var f: Now = .{ .capturing = true }; + try stage.run(gpa, net, f.all(2), .{}, {}, Capture.go); +} + +/// No variable-length gather of its own: `allGatherV` moves whole strides, and the ranks agree it does. +const Whole = struct { + fn go(c: Collective, rank: u32, _: void) !void { + try std.testing.expect(!c.varFits(200)); + try std.testing.expect(!try c.varAgreed()); + var ins: [2][200]u8 = undefined; + for (0..2) |r| reference.fill(&ins[r], .u8, @intCast(r), 11); + var out: [400]u8 = @splat(0xEE); + const lens = [2]i32{ 17, 200 }; + try c.allGatherV(addr(&ins[rank]), addr(&out), 200, @intFromPtr(&lens), .u8, null); + try std.testing.expectEqualSlices(u8, &ins[0], out[0..200]); + try std.testing.expectEqualSlices(u8, &ins[1], out[200..]); + } +}; + +test "a staged variable-length all-gather moves whole strides" { + var f: Now = .{}; + try stage.run(gpa, net, f.all(2), tiny, {}, Whole.go); +} + +/// Rank 1's stream cannot take its word (`host`), or its proxy cannot copy the input (`proxy`). +const Broken = struct { + fn go(c: Collective, rank: u32, proxy: bool) !void { + var a: [16]u8 = @splat(0); + var b: [32]u8 = undefined; + if (rank == 1) { + const r = if (proxy) c.allGather(Now.unreadable, addr(&b), 16, .u8, null) else c.allGather(addr(&a), addr(&b), 16, .u8, Now.failing); + try std.testing.expectError(error.BackendFailed, r); + return std.testing.expectError(error.BackendFailed, c.check()); + } + const r = c.allGather(addr(&a), addr(&b), 16, .u8, null); + if (r) |_| return error.ShouldHaveFailed else |e| if (e != error.Aborted and e != error.PeerFailed) return e; + } +}; + +test "a device call that fails, on the stream or in the proxy, is BackendFailed here and ends the peer's call" { + var f: Now = .{}; + try stage.run(gpa, net, f.all(2), .{}, false, Broken.go); + try stage.run(gpa, net, f.all(2), .{}, true, Broken.go); +} + +test { + _ = @import("stage_later_test.zig"); +} diff --git a/zig/src/fabric/tp/tcp.zig b/zig/src/fabric/tp/tcp.zig index 2d66c0e22de..2dc60d92ed6 100644 --- a/zig/src/fabric/tp/tcp.zig +++ b/zig/src/fabric/tp/tcp.zig @@ -32,7 +32,8 @@ const Header = extern struct { /// Payload bytes after the header. bytes: u64 = 0, sender: u32, - pad2: u32 = 0, + /// Which slot-sized part of a staged call this is (`stage.zig`), 0 for a whole call. + part: u32 = 0, }; /// The first failure, kept for `check` (later calls are `Aborted`: the streams are out of step). @@ -59,6 +60,8 @@ pub const Rank = struct { fail: std.atomic.Value(Fail) = .init(.none), scratch: std.ArrayList(u8) = .empty, var_agreed: ?bool = null, + /// The part the next frames carry and expect: a staged call split alike on every rank (`stage.zig`). + part: u32 = 0, /// A rank over connected sockets (`fds[peer]`, -1 at `me`); it owns them from here and makes them non-blocking. pub fn init(gpa: std.mem.Allocator, me: u32, world: u32, fds: []const sock.Fd, opts: Options) Rank { @@ -346,7 +349,7 @@ pub const Rank = struct { if (h.magic != magic) return r.close(.invalid); if (h.call == @backingInt(Call.abort)) return r.close(.aborted); if (h.sender != l.peer or h.seq != r.got[l.peer] or h.call != w.call or h.t != w.t or h.op != w.op or - h.count != w.count or h.bytes != plen + l.into.len) return r.close(.invalid); + h.count != w.count or h.part != w.part or h.bytes != plen + l.into.len) return r.close(.invalid); } if (plen > 0 and before < hlen + plen and l.got >= hlen + plen) { if (!std.mem.eql(u8, l.prefix_buf[0..plen], l.want_prefix)) return r.close(.invalid); @@ -357,8 +360,8 @@ pub const Rank = struct { } fn leg(r: *Rank, peer: u32, call: Call, t: DType, op: Op, count: usize, out: []const u8, into: []u8) Leg { - const h: Header = .{ .call = @backingInt(call), .t = @backingInt(t), .op = @backingInt(op), .seq = r.sent[peer], .count = count, .bytes = out.len, .sender = r.me }; - return .{ .peer = peer, .out_hdr = h, .out = out, .want = .{ .call = @backingInt(call), .t = @backingInt(t), .op = @backingInt(op), .seq = 0, .count = count, .sender = peer }, .into = into }; + const h: Header = .{ .call = @backingInt(call), .t = @backingInt(t), .op = @backingInt(op), .seq = r.sent[peer], .count = count, .bytes = out.len, .sender = r.me, .part = r.part }; + return .{ .peer = peer, .out_hdr = h, .out = out, .want = .{ .call = @backingInt(call), .t = @backingInt(t), .op = @backingInt(op), .seq = 0, .count = count, .sender = peer, .part = r.part }, .into = into }; } fn bytesAt(p: DevicePtr, n: usize) []u8 { diff --git a/zig/src/fabric/tp/tcp_hip.zig b/zig/src/fabric/tp/tcp_hip.zig new file mode 100644 index 00000000000..2e0f94b3b45 --- /dev/null +++ b/zig/src/fabric/tp/tcp_hip.zig @@ -0,0 +1,147 @@ +//! `tf-tp-test tcp-hip`: `tcp-host`'s checks and timings on HIP memory, staged through the TCP Kind (TF_TP_LINK). +const std = @import("std"); +const tp = @import("tp"); + +/// The sizes `tcp-host` times, a rank's shard in bytes. +const sizes = [_]usize{ 16, 4096, 8192, 32768, 131072, 262144, 1048576, 4194304 }; +const edges = [_]usize{ 1, 2, 3, 4, 7, 8, 15, 31, 63, 255, 1023, 3145, 65535, 65536, 65537 }; +const max_bytes = 4 << 20; + +pub fn run(cfg: tp.Config, gpa: std.mem.Allocator) !u8 { + if (cfg.world != 2) { + std.debug.print("tcp-hip runs two ranks (TF_TP_WORLD=2)\n", .{}); + return 2; + } + var rig = tp.hip_rig.Rig.open() catch { + std.debug.print("FAIL tcp-hip rank {d}: no HIP runtime (libamdhip64.so) or no GPU\n", .{cfg.rank}); + return 1; + }; + defer rig.close(); + try rig.use(cfg.device); + var hip = try tp.stage_hip.Hip.init(&rig.lib); + defer hip.deinit(); + var link_buf: [256]u8 = undefined; + const link = cfg.linkLabel(&link_buf); + var b = try tp.Bootstrap.open(cfg); + defer b.close(); + const plan = b.releasePlan(); + var fds = [2]tp.sock.Fd{ -1, -1 }; + fds[1 - cfg.rank] = plan[if (cfg.rank == 0) 1 else 0]; + var net = tp.tcp.Rank.init(gpa, cfg.rank, 2, &fds, .{}); + defer net.deinit(); + var r: tp.stage.Rank = undefined; + try r.open(&net, hip.device(), .{}); + defer r.deinit(); + const c = r.iface(); + const peer: u32 = 1 - cfg.rank; + const s = try rig.stream(); + defer rig.destroy(s); + const in = try rig.alloc(max_bytes); + defer rig.free(in); + const out = try rig.alloc(2 * max_bytes); + defer rig.free(out); + const host = try gpa.alloc(u8, 2 * max_bytes); + defer gpa.free(host); + const want = try gpa.alloc(u8, 3 * max_bytes); // the sum, then rank 0's and rank 1's inputs + defer gpa.free(want); + // 1. bit for bit against the reference: every timed size, the edges, and a spread up to exactly 4 MiB + var lens: [400]usize = undefined; + for (&lens, 0..) |*l, k| l.* = if (k < sizes.len) sizes[k] else if (k < sizes.len + edges.len) edges[k - sizes.len] else 1 + (k * 7919 * 13) % max_bytes; + lens[lens.len - 1] = max_bytes; + var gathers: u32 = 0; + var sums: u32 = 0; + var trades: u32 = 0; + for (lens, 0..) |len, k| { + tp.reference.fill(host[0..len], .u8, cfg.rank, k); + try rig.put(in, host[0..len]); + try c.allGather(in, out, len, .u8, s); + try settle(&rig, c, s); + try rig.get(host[0 .. 2 * len], out); + for (0..2) |q| { + tp.reference.fill(want[0..len], .u8, @intCast(q), k); + if (!std.mem.eql(u8, host[q * len ..][0..len], want[0..len])) return fail(cfg.rank, "all-gather", k, len); + } + gathers += 1; + inline for (.{ tp.DType.f32, tp.DType.bf16 }) |t| { + const n = (len / t.size()) * t.size(); + if (n > 0) { + tp.reference.fill(host[0..n], t, cfg.rank, k); + try rig.put(in, host[0..n]); + tp.reference.fill(want[max_bytes..][0..n], t, 0, k); + tp.reference.fill(want[2 * max_bytes ..][0..n], t, 1, k); + const views = [_][]const u8{ want[max_bytes..][0..n], want[2 * max_bytes ..][0..n] }; + tp.reference.reduce(want[0..n], &views, t, .sum); + try c.allReduce(in, out, n / t.size(), t, .sum, s); + try settle(&rig, c, s); + try rig.get(host[0..n], out); + if (!std.mem.eql(u8, host[0..n], want[0..n])) return fail(cfg.rank, @tagName(t) ++ " sum", k, n); + sums += 1; + } + } + // exchange, then send and recv, and a variable-length gather (whole strides here), on every fourth length + if (k % 4 == 0) { + tp.reference.fill(host[0..len], .u8, cfg.rank, k + 1); + try rig.put(in, host[0..len]); + try c.exchange(in, out, len, .u8, peer, s); + if (cfg.rank == 0) try c.send(in, len, .u8, 1, s) else try c.recv(out + len, len, .u8, 0, s); + try settle(&rig, c, s); + try rig.get(host[0 .. 2 * len], out); + tp.reference.fill(want[0..len], .u8, peer, k + 1); + if (!std.mem.eql(u8, host[0..len], want[0..len])) return fail(cfg.rank, "exchange", k, len); + tp.reference.fill(want[0..len], .u8, 0, k + 1); + if (cfg.rank == 1 and !std.mem.eql(u8, host[len..][0..len], want[0..len])) return fail(cfg.rank, "send/recv", k, len); + const vl = [2]i32{ @intCast(len), @intCast(len / 3) }; + tp.reference.fill(host[0..len], .u8, cfg.rank, k + 2); + try rig.put(in, host[0..len]); + try c.allGatherV(in, out, len, @intFromPtr(&vl), .u8, s); + try settle(&rig, c, s); + try rig.get(host[0 .. 2 * len], out); + for (0..2) |q| { + const ql: usize = @intCast(vl[q]); + tp.reference.fill(want[0..ql], .u8, @intCast(q), k + 2); + if (!std.mem.eql(u8, host[q * len ..][0..ql], want[0..ql])) return fail(cfg.rank, "variable all-gather", k, len); + } + trades += 1; + } + } + try c.check(); + std.debug.print("PASS tcp-hip rank {d}/2: {d} all-gathers (1 B to 4 MiB), {d} fp32 and bf16 sums, {d} exchanges, send/recv and variable all-gathers bit-exact from HIP memory over {s}\n", .{ cfg.rank, gathers, sums, trades, link }); + // 2. by size, median and p90 of a call queued then its stream synchronised, and of the queueing alone + var times: [500]u64 = undefined; + var queued: [500]u64 = undefined; + for (sizes) |len| { + inline for (.{ "all_gather", "exchange" }) |what| { + for (×, &queued) |*t, *e| { + const t0 = tp.sock.nowNs(); + if (comptime std.mem.eql(u8, what, "all_gather")) try c.allGather(in, out, len, .u8, s) else try c.exchange(in, out, len, .u8, peer, s); + e.* = tp.sock.nowNs() - t0; + try settle(&rig, c, s); + t.* = tp.sock.nowNs() - t0; + } + std.mem.sort(u64, ×, {}, std.sort.asc(u64)); + std.mem.sort(u64, &queued, {}, std.sort.asc(u64)); + if (cfg.rank == 0) std.debug.print("RESULT {{\"backend\":\"tcp-hip\",\"link\":\"{s}\",\"world\":2,\"call\":\"{s}\",\"bytes\":{d},\"p50_us\":{d:.2},\"p90_us\":{d:.2},\"gb_s_p50\":{d:.2},\"queue_p50_us\":{d:.2}}}\n", .{ + link, what, len, us(times[250]), us(times[450]), + @as(f64, @floatFromInt(len)) / @as(f64, @floatFromInt(@max(times[250], 1))), us(queued[250]), + }); + } + } + try c.check(); + try b.agree("done", "tcp-hip end"); + return 0; +} + +/// The stream's calls done, and the communicator still sound: a failure is its error by name, never compared bytes. +fn settle(rig: *tp.hip_rig.Rig, c: tp.Collective, s: tp.collective.Stream) !void { + try rig.sync(s); + try c.check(); +} + +fn us(ns: u64) f64 { + return @as(f64, @floatFromInt(ns)) / 1000.0; +} + +fn fail(rank: u32, what: []const u8, k: usize, len: usize) u8 { + std.debug.print("FAIL tcp-hip rank {d}: {s} {d} of {d} bytes differs from the reference\n", .{ rank, what, k, len }); + return 1; +} diff --git a/zig/src/fabric/tp/tcp_test.zig b/zig/src/fabric/tp/tcp_test.zig index 39370069605..c1498b96ca2 100644 --- a/zig/src/fabric/tp/tcp_test.zig +++ b/zig/src/fabric/tp/tcp_test.zig @@ -88,6 +88,20 @@ test "ranks that differ only in the call, the op or the type are refused over TC for (0..3) |f| try tcp.run(gpa, 2, opts, @as(u8, @intCast(f)), FieldDesync.go); } +/// The ranks make the same call but name different parts of a staged call (`stage.zig`): both refuse it. +const PartDesync = struct { + fn go(c: Collective, rank: u32, _: void) !void { + @as(*tcp.Rank, @ptrCast(@alignCast(c.ptr))).part = rank; + var a: [8]u8 = @splat(0); + var b: [16]u8 = undefined; + if (c.allGather(addr(&a), addr(&b), 8, .u8, null)) |_| return error.ShouldHaveFailed else |e| if (e != error.Invalid and e != error.Aborted) return e; + } +}; + +test "ranks that differ only in the part number are refused over TCP" { + try tcp.run(gpa, 2, opts, {}, PartDesync.go); +} + test "abort over TCP frees a peer waiting in a collective" { try tcp.run(gpa, 2, opts, {}, host_test.Aborts.go); } diff --git a/zig/src/fabric/tp/tp.zig b/zig/src/fabric/tp/tp.zig index 760f9a12db5..8bb4d42ac6f 100644 --- a/zig/src/fabric/tp/tp.zig +++ b/zig/src/fabric/tp/tp.zig @@ -12,6 +12,9 @@ pub const fate = @import("fate.zig"); pub const host = @import("host.zig"); pub const device = @import("device.zig"); pub const tcp = @import("tcp.zig"); +pub const stage = @import("stage.zig"); +pub const stage_hip = @import("stage_hip.zig"); +pub const hip_rig = @import("hip_rig.zig"); // tf-tp-test's tcp-hip opens the HIP runtime and a device with it pub const nccl = @import("nccl.zig"); pub const group = @import("group.zig"); pub const mailbox = @import("mailbox.zig"); @@ -248,6 +251,8 @@ test { _ = @import("host_test.zig"); _ = @import("device_test.zig"); _ = @import("tcp_test.zig"); + _ = @import("stage_test.zig"); + _ = @import("stage_hip_test.zig"); _ = @import("fate_test.zig"); _ = @import("fate_lifetime_test.zig"); } diff --git a/zig/src/families/flashnext/cuda_draft_draw.zig b/zig/src/families/flashnext/cuda_draft_draw.zig new file mode 100644 index 00000000000..785fc08facd --- /dev/null +++ b/zig/src/families/flashnext/cuda_draft_draw.zig @@ -0,0 +1,66 @@ +//! Draft lanes reduce the same gathered rows once, then draw with each lane's original seed and position. +const std = @import("std"); +const cuda = @import("cuda"); +const mtp = @import("cuda_mtp.zig"); +const draw = @import("cuda_mtp_draw.zig"); +const nrows = mtp.max_rows; +const vals_at = nrows * 16; +const cols_at = vals_at + nrows * draw.topk_max * 2; +const bytes = @import("cuda_mtp_draft.zig").best_bytes; +pub const lanes_max = 16; +pub fn scoreBytes(v: usize) usize { + return lanes_max * v * 2; +} + +pub const Ready = struct { + words: [bytes / 8]u64 = undefined, + k: usize, + fn best(r: *const Ready, row: usize) [4]f32 { + return std.mem.bytesToValue([4]f32, std.mem.asBytes(&r.words)[row * 16 ..][0..16]); + } + pub fn pick(r: *const Ready, h: *const mtp.Head, st: cuda.Stream, a: std.mem.Allocator, d: *mtp.Draft, row: usize, position: u64, sm: ?mtp.Sampling, batched: bool) !mtp.Pick { + const b = r.best(row); + if (mtp.isSampled(sm) and (!draw.usable(sm.?) or sm.?.top_k != r.k)) return draw.pick(h, st, a, d, b, position, sm, batched); + const data = std.mem.asBytes(&r.words); + const vals: []const u16 = @alignCast(std.mem.bytesAsSlice(u16, data[vals_at + row * r.k * 2 ..][0 .. r.k * 2])); + const cols: []const i32 = @alignCast(std.mem.bytesAsSlice(i32, data[cols_at + row * r.k * 4 ..][0 .. r.k * 4])); + return draw.pickFrom(h, a, b, vals, cols, position, sm) catch |err| { + if (err == error.ProposalNonfinite) draw.badRow(st, d, b, batched, d.dlogits.ptr, h.ids.len); + return err; + }; + } + fn load(r: *Ready, st: cuda.Stream, ptr: u64, rows: usize) !void { + const n = if (r.k == 0) rows * 16 else cols_at + rows * r.k * 4; + if (n > bytes) return error.ProposalScoreShape; + try st.synchronize(); + try cuda.memory.download(st.d, ptr, std.mem.asBytes(&r.words)[0..n]); + } +}; + +pub fn single(h: *const mtp.Head, st: cuda.Stream, a: std.mem.Allocator, d: *mtp.Draft, position: u64, sm: ?mtp.Sampling, batch_on: bool) !mtp.Pick { + const n = h.ids.len; + try h.best(st, d.dlogits.ptr, n, n, 1, d.best.ptr); + if (!batch_on) { + try st.synchronize(); + try cuda.memory.download(st.d, d.best.ptr, std.mem.sliceAsBytes(d.best_host[0..4])); + return draw.pick(h, st, a, d, d.best_host[0..4].*, position, sm, false); + } + var ready = Ready{ .k = if (mtp.isSampled(sm) and draw.usable(sm.?)) sm.?.top_k else 0 }; + if (ready.k != 0) try h.topk(st, d.dlogits.ptr, n, n, 1, ready.k, d.best.ptr + vals_at, d.best.ptr + cols_at); + try ready.load(st, d.best.ptr, 1); + return ready.pick(h, st, a, d, 0, position, sm, false); +} + +pub fn gather(h: *const mtp.Head, st: cuda.Stream, ds: []const *mtp.Draft, active: []const usize, sms: []const ?mtp.Sampling) !Ready { + const n = h.ids.len; + if (active.len > lanes_max or active.len > nrows) return error.ProposalScoreShape; + var ready = Ready{ .k = 0 }; + for (active, 0..) |i, row| { + try st.d.check(st.d.api.cuMemcpyDtoDAsync_v2(h.draw_batch.scores.ptr + row * n * 2, ds[i].dlogits.ptr, n * 2, st.handle), "cuMemcpyDtoDAsync"); + if (ready.k == 0 and mtp.isSampled(sms[i]) and draw.usable(sms[i].?)) ready.k = sms[i].?.top_k; + } + try h.best(st, h.draw_batch.scores.ptr, n, n, active.len, ds[0].best.ptr); + if (ready.k != 0) try h.topk(st, h.draw_batch.scores.ptr, n, n, active.len, ready.k, ds[0].best.ptr + vals_at, ds[0].best.ptr + cols_at); + try ready.load(st, ds[0].best.ptr, active.len); + return ready; +} diff --git a/zig/src/families/flashnext/cuda_draw_batch.zig b/zig/src/families/flashnext/cuda_draw_batch.zig new file mode 100644 index 00000000000..85c5fa75f18 --- /dev/null +++ b/zig/src/families/flashnext/cuda_draw_batch.zig @@ -0,0 +1,101 @@ +//! Shared verify reductions have one completion; row checks and draws retain stream order. +const std = @import("std"); +const cuda = @import("cuda"); +const mtp = @import("cuda_mtp.zig"); +const draw = @import("cuda_mtp_draw.zig"); +const vocab = @import("cuda_prompt_wt.zig").vocab; +const environment = @import("sys").environment; +const full = @import("core").proposal_rows.Scores{ .vocab = vocab, .logical = vocab, .stride = vocab }; +pub const rows_max = mtp.round_rows; +pub const vals_at = rows_max * 16; +pub const cols_at = vals_at + rows_max * draw.topk_max * 2; +pub const bytes = cols_at + rows_max * draw.topk_max * 4; + +pub fn setting(raw: ?[]const u8) !bool { + return environment.value(bool, "TF_FLASHNEXT_BATCH_DRAWS", raw, true); +} +pub fn enabled() !bool { + return environment.read(bool, "TF_FLASHNEXT_BATCH_DRAWS", true); +} + +pub const Batch = struct { + device: cuda.DeviceBuffer, + scores: cuda.DeviceBuffer, + host: []align(8) u8, + on: bool, + pub fn init(a: std.mem.Allocator, driver: *cuda.Driver, on: bool, columns: usize) !Batch { + var b = try cuda.DeviceBuffer.alloc(driver, bytes); + errdefer b.free(); + var scores = try cuda.DeviceBuffer.alloc(driver, @import("cuda_draft_draw.zig").scoreBytes(columns)); + errdefer scores.free(); + return .{ .scores = scores, .device = b, .host = std.mem.sliceAsBytes(try a.alloc(u64, bytes / 8)), .on = on }; + } + pub fn deinit(b: *Batch, a: std.mem.Allocator) void { + b.scores.free(); + b.device.free(); + a.free(std.mem.bytesAsSlice(u64, b.host)); + } + pub fn best(b: Batch, row: usize) [4]f32 { + return std.mem.bytesToValue([4]f32, b.host[row * 16 ..][0..16]); + } + pub fn vals(b: Batch, row: usize, k: usize) []const u16 { + return @alignCast(std.mem.bytesAsSlice(u16, b.host[vals_at + row * k * 2 ..][0 .. k * 2])); + } + pub fn cols(b: Batch, row: usize, k: usize) []const i32 { + return @alignCast(std.mem.bytesAsSlice(i32, b.host[cols_at + row * k * 4 ..][0 .. k * 4])); + } +}; + +/// A different top_k falls back; a prefix of another K's column-ordered set would change the draw. +pub fn matching(sm: ?mtp.Sampling, masks: []const u32, k: usize) bool { + return masks.len == 0 and (!mtp.isSampled(sm) or (draw.usable(sm.?) and sm.?.top_k == k)); +} + +pub fn drawsMany(h: *const mtp.Head, st: cuda.Stream, a: std.mem.Allocator, scores: u64, ds: []const *mtp.Draft, sms: []const ?mtp.Sampling, masks: []const []const u32, outs: []const []u32) !void { + if (ds.len != sms.len or ds.len != masks.len or ds.len != outs.len) return error.ProposalScoreShape; + const b = h.draw_batch; + var rows: usize = 0; + var k: usize = 0; + var greedy = false; + for (ds, sms, masks) |d, sm, mask| { + rows += d.rows; + if (mask.len != 0) continue; + if (!mtp.isSampled(sm)) greedy = true else if (k == 0 and draw.usable(sm.?)) k = sm.?.top_k; + } + if (rows > rows_max) return error.ProposalScoreShape; + if (b.on and (greedy or k != 0)) { + if (greedy) try h.best(st, scores, vocab, vocab, rows, b.device.ptr); + if (k != 0) try h.topk(st, scores, vocab, vocab, rows, k, b.device.ptr + vals_at, b.device.ptr + cols_at); + try st.synchronize(); + try cuda.memory.download(st.d, b.device.ptr, b.host); + } + var row0: usize = 0; + for (ds, sms, masks, outs) |d, sm, mask, out| { + defer row0 += d.rows; + if (!b.on or !matching(sm, mask, k)) { + try draw.draws(h, st, a, d, sm, mask, out); + continue; + } + var pending: [mtp.max_rows]u32 = undefined; + if (mtp.isSampled(sm)) { + for (pending[0..d.rows], 0..) |*tok, r| tok.* = draw.drawTopk(a, b.vals(row0 + r, k), b.cols(row0 + r, k), null, d.fed0 + 1 + r, sm.?) catch |err| { + if (err == error.ProposalNonfinite) try draw.badCandidates(h, st, d, r); + return err; + }; + } else { + for (0..d.rows) |r| _ = full.pickBest(b.best(row0 + r)) catch |err| { + draw.badVerify(d, r, b.best(row0 + r), null, false); + return err; + }; + for (pending[0..d.rows], 0..) |*tok, r| tok.* = try full.pickBest(b.best(row0 + r)); + } + @memcpy(out[0..d.rows], pending[0..d.rows]); + } +} + +test "Flash Next batch draws: the environment flag rejects bad values by name" { + try std.testing.expect(try setting(null)); + try std.testing.expect(try setting("1")); + try std.testing.expect(!try setting("0")); + for ([_][]const u8{ "", "2", "true", "-1", " 1" }) |s| try std.testing.expectError(error.InvalidEnvironment, setting(s)); +} diff --git a/zig/src/families/flashnext/cuda_draw_batch_test.zig b/zig/src/families/flashnext/cuda_draw_batch_test.zig new file mode 100644 index 00000000000..6a62cc587be --- /dev/null +++ b/zig/src/families/flashnext/cuda_draw_batch_test.zig @@ -0,0 +1,122 @@ +//! Shared verify draws compared with the production per-stream path on the recording device. +const std = @import("std"); +const cuda = @import("cuda"); +const mtp = @import("cuda_mtp.zig"); +const draw = @import("cuda_mtp_draw.zig"); +const batch = @import("cuda_draw_batch.zig"); +const f = @import("cuda_mtp_nonfinite_fixture.zig"); +const vocab = @import("cuda_prompt_wt.zig").vocab; +const D = f.Device; +const t = std.testing; +const a = t.allocator; + +test "Flash Next batch draws: eight mixed streams match serial draws, two grids and two waits" { + var driver = D.driver(); + defer cuda.download_stage.closeDriver(&driver); + var h = try f.head(&driver); + defer h.artifact.deinit(); + const host = try a.alloc(u16, 8 * vocab); + defer a.free(host); + const scores = try a.alloc(u16, 8 * vocab); + defer a.free(scores); + @memset(scores, 0xff80); + var vals: [8 * 20]u16 = undefined; + var cols: [8 * 20]i32 = undefined; + for (0..8) |r| for (0..20) |i| { + const v: u16 = @intCast(@as(u32, @bitCast(@as(f32, @floatFromInt(i)) / 10)) >> 16); + vals[r * 20 + i] = v; + cols[r * 20 + i] = @intCast(i); + scores[r * vocab + i] = v; + }; + D.verify_rows = scores; + D.vals = &vals; + D.cols = &cols; + D.best = f.reduction(mtp.promote(vals[19]), 4, 19); + var ds: [8]mtp.Draft = undefined; + var refs: [8]*mtp.Draft = undefined; + var sms: [8]?mtp.Sampling = undefined; + var masks: [8][]const u32 = @splat(&.{}); + var baseline: [8][1]u32 = undefined; + var got: [8][1]u32 = undefined; + var outs: [8][]u32 = undefined; + for (&ds, &refs, &sms, &outs, 0..) |*d, *ref, *sm, *out, i| { + d.* = f.draft(&driver, host[i * vocab ..][0..vocab]); + d.logits.ptr += i * vocab * 2; + d.fed0 += 13 * i; + ref.* = d; + sm.* = if (i == 6) null else .{ .seed = i * 7 + 19, .temperature = 0.7, .top_k = 20, .top_p = 0.95 }; + out.* = &got[i]; + } + masks[7] = &.{1 << 19}; + const st: cuda.Stream = .{ .d = &driver, .handle = null }; + for (refs, sms, masks, &baseline) |d, sm, mask, *out| try draw.draws(&h, st, a, d, sm, mask, out); + D.reset(); + try batch.drawsMany(&h, st, a, 0x4000, &refs, &sms, &masks, &outs); + try t.expectEqualDeep(baseline, got); + try t.expectEqualSlices(usize, &.{ 1, 2 }, D.functions[0..D.launches]); + try t.expectEqualSlices(u32, &.{ 8, 8 }, D.grids[0..D.launches]); + try t.expectEqual(@as(usize, 2), D.waits); + try t.expectEqual(@as(usize, 2), D.reads); + // A mismatched K uses its complete smaller set; never a prefix of the larger column-ordered set. + sms[1].?.top_k = 2; + sms[1].?.top_p = 1; + D.single_vals = vals[18..20]; + D.single_cols = cols[18..20]; + try draw.draws(&h, st, a, refs[1], sms[1], &.{}, &baseline[1]); + // The recording per-stream result and the batch result both see that explicit two-candidate set. + D.reset(); + try batch.drawsMany(&h, st, a, 0x4000, &refs, &sms, &masks, &outs); + try t.expectEqualDeep(baseline[1], got[1]); + try t.expectEqual(@as(usize, 3), D.waits); + // Switch off restores each window's actual path; no group reduction is queued. + h.draw_batch.on = false; + D.reset(); + try batch.drawsMany(&h, st, a, 0x4000, &refs, &sms, &masks, &outs); + try t.expectEqual(@as(usize, 8), D.waits); +} + +test "Flash Next batch draws: a later bad row keeps stream publication order and leaves its output untouched" { + var driver = D.driver(); + defer cuda.download_stage.closeDriver(&driver); + var h = try f.head(&driver); + defer h.artifact.deinit(); + var hosts: [2][mtp.max_rows * draw.topk_max * 3]u16 = undefined; + var ds = [2]mtp.Draft{ f.draft(&driver, &hosts[0]), f.draft(&driver, &hosts[1]) }; + ds[1].rows = 2; + ds[1].logits.ptr += vocab * 2; + const sm: mtp.Sampling = .{ .seed = 71, .temperature = 1, .top_k = 2 }; + D.vals = &.{ 0x3f80, 0, 0x3f80, 0, 0x3f80, 0 }; + D.cols = &.{ 17, 5, 17, 5, -1, 5 }; + var first = [_]u32{99}; + var last = [_]u32{ 42, 43 }; + const st: cuda.Stream = .{ .d = &driver, .handle = null }; + try t.expectError(error.ProposalNonfinite, batch.drawsMany(&h, st, a, 0x4000, &.{ &ds[0], &ds[1] }, &.{ sm, sm }, &.{ &.{}, &.{} }, &.{ &first, &last })); + try t.expect(first[0] != 99); + try t.expectEqualSlices(u32, &.{ 42, 43 }, &last); + try t.expectEqualSlices(usize, &.{ 2, 1 }, D.functions[0..D.launches]); + try t.expectEqualSlices(u32, &.{ 3, 2 }, D.grids[0..D.launches]); +} + +test "Flash Next batch draws: all 64 verify rows share one reduction without using a draft's 32-row scratch" { + var driver = D.driver(); + defer cuda.download_stage.closeDriver(&driver); + var h = try f.head(&driver); + defer h.artifact.deinit(); + var host: [1]u16 = undefined; + var x = f.draft(&driver, &host); + var y = f.draft(&driver, &host); + x.rows = 32; + y.rows = 32; + D.best = f.reduction(1, 2, 17); + var first: [32]u32 = undefined; + var second: [32]u32 = undefined; + const st: cuda.Stream = .{ .d = &driver, .handle = null }; + try batch.drawsMany(&h, st, a, 0x4000, &.{ &x, &y }, &.{ null, null }, &.{ &.{}, &.{} }, &.{ &first, &second }); + try t.expectEqualSlices(u32, &@as([32]u32, @splat(17)), &first); + try t.expectEqualSlices(u32, &first, &second); + try t.expectEqualSlices(u32, &.{64}, D.grids[0..D.launches]); + try t.expectEqual(@as(usize, 1), D.waits); + try t.expectEqual(@as(usize, 1), D.reads); + y.rows = 33; + try t.expectError(error.ProposalScoreShape, batch.drawsMany(&h, st, a, 0x4000, &.{ &x, &y }, &.{ null, null }, &.{ &.{}, &.{} }, &.{ &first, &second })); +} diff --git a/zig/src/families/flashnext/cuda_lanes_verify.zig b/zig/src/families/flashnext/cuda_lanes_verify.zig index e6f2554ff13..3c67b79f52f 100644 --- a/zig/src/families/flashnext/cuda_lanes_verify.zig +++ b/zig/src/families/flashnext/cuda_lanes_verify.zig @@ -30,7 +30,17 @@ pub fn windows(self: anytype, wins: []const be.Window, out: []be.Verified, draft } else if (self.ranks) |r| { try r.verifyMany(@TypeOf(self.tri()), self.tri(), seqs[0..n], ds[0..n], idss[0..n], self.logits.ptr); } else try self.ops().verifyMany(seqs[0..n], ds[0..n], idss[0..n], self.logits.ptr); - for (drafted[at..][0..n], ds[0..n]) |wi, d| try self.ops().draws(d, wins[wi].stream.sampling, wins[wi].masks, out[wi].sampled[0..wins[wi].rows()]); + if (n > 1 and cap > 1 and self.ranks == null) { + var sms: [round_streams]?mtp.Sampling = undefined; + var masks: [round_streams][]const u32 = undefined; + var outputs: [round_streams][]u32 = undefined; + for (drafted[at..][0..n], 0..) |wi, i| { + sms[i] = wins[wi].stream.sampling; + masks[i] = wins[wi].masks; + outputs[i] = out[wi].sampled[0..wins[wi].rows()]; + } + try self.ops().drawsMany(self.logits.ptr, ds[0..n], sms[0..n], masks[0..n], outputs[0..n]); + } else for (drafted[at..][0..n], ds[0..n]) |wi, d| try self.ops().draws(d, wins[wi].stream.sampling, wins[wi].masks, out[wi].sampled[0..wins[wi].rows()]); at += n; } } diff --git a/zig/src/families/flashnext/cuda_lanes_verify_test.zig b/zig/src/families/flashnext/cuda_lanes_verify_test.zig index 038d9dd7caf..0ad18df5dd6 100644 --- a/zig/src/families/flashnext/cuda_lanes_verify_test.zig +++ b/zig/src/families/flashnext/cuda_lanes_verify_test.zig @@ -11,6 +11,7 @@ const t = std.testing; const Log = struct { calls: [16]usize = undefined, n: usize = 0, + draw_groups: usize = 0, fn add(l: *Log, v: usize) void { l.calls[l.n] = v; l.n += 1; @@ -34,6 +35,9 @@ const Owner = struct { pub fn verifyMany(o: Ops, seqs: []const *prompt.Seq, _: []const *mtp.Draft, _: []const []const u32, _: u64) !void { o.log.add(seqs.len); } + pub fn drawsMany(o: Ops, _: u64, _: []const *mtp.Draft, _: []const ?mtp.Sampling, _: []const []const u32, _: []const []u32) !void { + o.log.draw_groups += 1; + } pub fn draws(_: Ops, _: *mtp.Draft, _: anytype, _: []const u32, _: []u32) !void {} }; log: Log = .{}, @@ -80,6 +84,7 @@ test "shared verify dispatch: at TP=2 a group goes to the ranks, a lone window a try t.expectEqual(@as(usize, 1), log.n); try t.expectEqual(@as(usize, 103), log.calls[0]); try t.expectEqual(@as(usize, 0), o.log.n); + try t.expectEqual(@as(usize, 0), o.log.draw_groups); log = .{}; try run(&o, &.{4}, 64); try t.expectEqual(@as(usize, 0), log.n); @@ -92,4 +97,5 @@ test "shared verify dispatch: at TP=2 a group goes to the ranks, a lone window a o.ranks = null; try run(&o, &.{ 2, 3, 2 }, 64); try t.expectEqualSlices(usize, &.{3}, o.log.calls[0..o.log.n]); + try t.expectEqual(@as(usize, 1), o.log.draw_groups); } diff --git a/zig/src/families/flashnext/cuda_mtp.zig b/zig/src/families/flashnext/cuda_mtp.zig index 9f176e5e959..4d6f0424b4e 100644 --- a/zig/src/families/flashnext/cuda_mtp.zig +++ b/zig/src/families/flashnext/cuda_mtp.zig @@ -212,9 +212,11 @@ pub const Head = struct { service: lanes.proposal_head.Service, module: cuda.Module, best_fn: cuda.Function, + draw_batch: @import("cuda_draw_batch.zig").Batch, topk_fn: cuda.Function, // fn_row_topk: a row's top_k candidates as drawRow ranks them (cuda_mtp_draw.zig) pub fn init(gpa: std.mem.Allocator, io: std.Io, driver: *cuda.Driver, stream: *cuda.Stream, dir: []const u8) !*Head { + const batch_on = try @import("cuda_draw_batch.zig").enabled(); if (!cuda.kernels.available) return error.BuiltWithoutKernels; const h = try gpa.create(Head); errdefer gpa.destroy(h); @@ -261,6 +263,7 @@ pub const Head = struct { errdefer h.module.unload(); h.best_fn = try h.module.function("fn_row_best"); h.topk_fn = try h.module.function("fn_row_topk"); + h.draw_batch = try @import("cuda_draw_batch.zig").Batch.init(gpa, driver, batch_on, h.ids.len); return h; } @@ -270,6 +273,7 @@ pub const Head = struct { } pub fn deinit(h: *Head) void { + h.draw_batch.deinit(h.gpa); h.module.unload(); h.draft.free(); h.artifact.deinit(); @@ -327,7 +331,7 @@ pub fn headBytes(fp8: bool) usize { const experts = wt.experts_n * routed + nvfp4; const attn = (wt.proj_n + dims) * dims / 2 * 5 / 4; const draft = 79_591 * dims / 2 * 5 / 4; - return experts + attn + draft + 2 * dims * dims / 2 * 5 / 4; + return experts + attn + draft + 2 * dims * dims / 2 * 5 / 4 + @import("cuda_draw_batch.zig").bytes + @import("cuda_draft_draw.zig").scoreBytes(79_591); } pub const Pick = @import("cuda_mtp_draft.zig").Pick; @@ -338,7 +342,7 @@ pub const check = @import("cuda_mtp_check.zig").check; test "the head's bytes: NVFP4 experts as before, FP8 routed experts a byte a weight and their f32 block scales" { const before = (wt.experts_n + 1) * 3 * wt.moe_w * dims / 2 * 5 / 4 + (wt.proj_n + dims) * dims / 2 * 5 / 4 + 79_591 * dims / 2 * 5 / 4 + 2 * dims * dims / 2 * 5 / 4; - try std.testing.expectEqual(before, headBytes(false)); + try std.testing.expectEqual(before + @import("cuda_draw_batch.zig").bytes + @import("cuda_draft_draw.zig").scoreBytes(79_591), headBytes(false)); // an expert's three projections: 640 x 2560 bytes and 5 x 20 scales each, against 5/8 of a byte a weight try std.testing.expectEqual(wt.experts_n * (3 * (640 * 2560 + 5 * 20 * 4) - 3 * 640 * 2560 * 5 / 8), headBytes(true) - headBytes(false)); } diff --git a/zig/src/families/flashnext/cuda_mtp_draw.zig b/zig/src/families/flashnext/cuda_mtp_draw.zig index 78f0adb61aa..5e8e1b9342f 100644 --- a/zig/src/families/flashnext/cuda_mtp_draw.zig +++ b/zig/src/families/flashnext/cuda_mtp_draw.zig @@ -58,7 +58,7 @@ pub fn pick(h: *const mtp.Head, st: cuda.Stream, gpa: std.mem.Allocator, d: *mtp } // Failure-only downloads leave the normal row selection and graph captures unchanged. -fn badRow(st: cuda.Stream, d: *mtp.Draft, best: [4]f32, batched: bool, scores: u64, n: usize) void { +pub fn badRow(st: cuda.Stream, d: *mtp.Draft, best: [4]f32, batched: bool, scores: u64, n: usize) void { var input: [wt.wide]u16 = undefined; const input_ok: ?bool = if (download(st, std.mem.sliceAsBytes(&input), d.out.ptr)) |_| finite(&input) else |_| null; const row = d.host[0..n]; @@ -94,7 +94,7 @@ pub fn pickHead(h: *const mtp.Head, st: cuda.Stream, gpa: std.mem.Allocator, d: } /// A verify failure names its own row; the head's stream activations are not a verify input capture. -fn badVerify(d: *const mtp.Draft, row: usize, best: ?[4]f32, row_ok: ?bool, masked: bool) void { +pub fn badVerify(d: *const mtp.Draft, row: usize, best: ?[4]f32, row_ok: ?bool, masked: bool) void { const top: ?f32 = if (best) |b| b[0] else null; const lse: ?f32 = if (best) |b| b[1] else null; std.debug.print("Flash Next ProposalNonfinite stream={s} kind=verify row={d} rows={d} len={d} cap={d} top={?} lse={?} cache={s} input=not_captured scores={s} row_finite={?}\n", .{ d.label, row, d.rows, d.len, d.cap, top, lse, if (d.pooled_lane) "pool" else "own", if (masked) "masked" else "raw", row_ok }); @@ -113,7 +113,7 @@ fn checkBest(st: cuda.Stream, d: *mtp.Draft, rows: ?[]const u16) !void { pub fn draws(h: *const mtp.Head, st: cuda.Stream, gpa: std.mem.Allocator, d: *mtp.Draft, sm: ?Sampling, masks: []const u32, out: []u32) !void { const n = d.rows; var pending: [max_rows]u32 = undefined; - if (masks.len == 0) try h.best(st, d.logits.ptr, vocab, vocab, n, d.best.ptr); + if (masks.len == 0 and (!mtp.isSampled(sm) or !usable(sm.?))) try h.best(st, d.logits.ptr, vocab, vocab, n, d.best.ptr); if (!mtp.isSampled(sm) and masks.len == 0) { try st.synchronize(); try checkBest(st, d, null); @@ -124,9 +124,10 @@ pub fn draws(h: *const mtp.Head, st: cuda.Stream, gpa: std.mem.Allocator, d: *mt if (masks.len == 0) if (sm) |s| if (usable(s)) { const k: usize = s.top_k; const c = try candidates(h, st, d, d.logits.ptr, vocab, vocab, n, k); - try checkBest(st, d, null); for (pending[0..n], 0..) |*t, r| t.* = drawTopk(gpa, c.vals[r * k ..][0..k], c.cols[r * k ..][0..k], null, d.fed0 + 1 + r, s) catch |err| { - if (err == error.ProposalNonfinite) badVerify(d, r, d.best_host[r * 4 ..][0..4].*, null, false); + if (err == error.ProposalNonfinite) { + try badCandidates(h, st, d, r); + } return err; }; @memcpy(out[0..n], pending[0..n]); @@ -164,3 +165,21 @@ fn download(st: cuda.Stream, dst: []u8, src: u64) !void { try st.synchronize(); try copyReady(st, dst, src); } + +/// Diagnostic reductions are only queued after a top-k sentinel refuses a verify row. +pub fn badCandidates(h: *const mtp.Head, st: cuda.Stream, d: *mtp.Draft, row: usize) !void { + try h.best(st, d.logits.ptr, vocab, vocab, d.rows, d.best.ptr); + try download(st, std.mem.sliceAsBytes(d.best_host[0 .. 4 * d.rows]), d.best.ptr); + badVerify(d, row, d.best_host[row * 4 ..][0..4].*, null, false); +} + +/// Device-free draft draw over the same reduced best and full top-k set as the per-stream path. +pub fn pickFrom(h: *const mtp.Head, a: std.mem.Allocator, best: [4]f32, vals: []const u16, cols: []const i32, position: u64, sm: ?Sampling) !Pick { + const tok = try h.view().pickBest(best); + if (!mtp.isSampled(sm)) return .{ .token = tok, .prob = @exp(@as(f64, best[0]) - @as(f64, best[1])) }; + if (!usable(sm.?)) return error.ProposalScoreShape; + const sampled = try drawTopk(a, vals, cols, h.ids, position, sm.?); + for (vals, cols) |v, col| if (h.ids[@intCast(col)] == sampled) + return .{ .token = sampled, .prob = @exp(@as(f64, mtp.promote(v)) - @as(f64, best[1])) }; + return .{ .token = sampled, .prob = 0 }; +} diff --git a/zig/src/families/flashnext/cuda_mtp_nonfinite_fixture.zig b/zig/src/families/flashnext/cuda_mtp_nonfinite_fixture.zig index a3587be9bb2..d8baa94dcb9 100644 --- a/zig/src/families/flashnext/cuda_mtp_nonfinite_fixture.zig +++ b/zig/src/families/flashnext/cuda_mtp_nonfinite_fixture.zig @@ -7,6 +7,7 @@ const draw = @import("cuda_mtp_draw.zig"); const wt = @import("cuda_prompt_wt.zig"); pub const Device = struct { + pub var batch_host: [@import("cuda_draw_batch.zig").bytes]u8 align(8) = undefined; pub var best: [4]f32 = undefined; pub var reductions: []const [4]f32 = &.{}; pub var vals: []const u16 = &.{ 0x3f80, 0 }; @@ -15,11 +16,21 @@ pub const Device = struct { pub var verify_rows: []const u16 = &.{}; pub var launches: usize = 0; pub var waits: usize = 0; + pub var grids: [512]u32 = undefined; + pub var functions: [512]usize = undefined; pub var sources: [mtp.max_rows]u64 = undefined; pub var best_calls: usize = 0; pub var best_bytes: usize = 0; pub var pending: bool = false; - pub const Event = enum { best, topk, wait, read_best, read_vals, read_cols, read_row }; + pub var top_k: usize = 0; + pub var single_vals: ?[]const u16 = null; + pub var single_cols: ?[]const i32 = null; + pub var reads: usize = 0; + pub var copies: usize = 0; + pub var copy_src: [512]u64 = undefined; + pub var copy_dst: [512]u64 = undefined; + pub var copy_bytes: [512]usize = undefined; + pub const Event = enum { best, topk, wait, read_best, read_vals, read_cols, read_row, read_batch }; pub var events: [512]Event = undefined; pub var events_n: usize = 0; @@ -35,16 +46,23 @@ pub const Device = struct { best_calls = 0; best_bytes = 0; pending = false; + reads = 0; + copies = 0; events_n = 0; } - fn launch(f: cuda.abi.Function, _: u32, _: u32, _: u32, _: u32, _: u32, _: u32, _: u32, _: cuda.abi.Stream, args: ?[*]?*anyopaque, _: ?[*]?*anyopaque) callconv(.c) c_int { + fn launch(f: cuda.abi.Function, gx: u32, _: u32, _: u32, _: u32, _: u32, _: u32, _: u32, _: cuda.abi.Stream, args: ?[*]?*anyopaque, _: ?[*]?*anyopaque) callconv(.c) c_int { + grids[launches] = gx; + functions[launches] = @intFromPtr(f); launches += 1; pending = true; if (@intFromPtr(f) == 1) { event(.best); sources[best_calls] = std.mem.bytesToValue(u64, @as([*]const u8, @ptrCast(args.?[0].?))[0..8]); best_calls += 1; - } else event(.topk); + } else { + event(.topk); + top_k = @intCast(std.mem.bytesToValue(c_int, @as([*]const u8, @ptrCast(args.?[3].?))[0..4])); + } return 0; } fn wait(_: cuda.abi.Stream) callconv(.c) c_int { @@ -54,23 +72,43 @@ pub const Device = struct { return 0; } fn read(dst: ?*anyopaque, src: u64, n: usize) callconv(.c) c_int { + reads += 1; std.debug.assert(!pending); const bytes = @as([*]u8, @ptrCast(dst.?))[0..n]; const tv = 0x1000 + mtp.max_rows * 16; const tc = tv + mtp.max_rows * draw.topk_max * 2; - if (src == 0x1000) { + if (src == 0x9000) { + event(.read_batch); + const b = @import("cuda_draw_batch.zig"); + std.debug.assert(n == b.bytes); + @memset(bytes, 0); + for (0..b.rows_max) |i| @memcpy(bytes[i * 16 ..][0..16], std.mem.asBytes(if (reductions.len > i) &reductions[i] else &best)); + @memcpy(bytes[b.vals_at..][0 .. vals.len * 2], std.mem.sliceAsBytes(vals)); + @memcpy(bytes[b.cols_at..][0 .. cols.len * 4], std.mem.sliceAsBytes(cols)); + } else if (src == 0x1000 and n > mtp.max_rows * 16) { + event(.read_batch); + @memset(bytes, 0); + const rows = mtp.max_rows; + for (0..rows) |i| @memcpy(bytes[i * 16 ..][0..16], std.mem.asBytes(if (reductions.len > i) &reductions[i] else &best)); + const va = rows * 16; + const ca = va + rows * draw.topk_max * 2; + @memcpy(bytes[va..][0..@min(vals.len * 2, ca - va)], std.mem.sliceAsBytes(vals)[0..@min(vals.len * 2, ca - va)]); + @memcpy(bytes[ca..][0..@min(cols.len * 4, n - ca)], std.mem.sliceAsBytes(cols)[0..@min(cols.len * 4, n - ca)]); + } else if (src == 0x1000) { event(.read_best); best_bytes = n; std.debug.assert(n % 16 == 0); for (0..n / 16) |i| @memcpy(bytes[i * 16 ..][0..16], std.mem.asBytes(if (reductions.len > i) &reductions[i] else &best)); } else if (src == tv) { event(.read_vals); - std.debug.assert(n <= vals.len * 2); - @memcpy(bytes, std.mem.sliceAsBytes(vals)[0..n]); + const v = if (single_vals) |v| (if (n <= v.len * 2) v else vals) else vals; + std.debug.assert(n <= v.len * 2); + @memcpy(bytes, std.mem.sliceAsBytes(v)[0..n]); } else if (src == tc) { event(.read_cols); - std.debug.assert(n <= cols.len * 4); - @memcpy(bytes, std.mem.sliceAsBytes(cols)[0..n]); + const v = if (single_cols) |v| (if (n <= v.len * 4) v else cols) else cols; + std.debug.assert(n <= v.len * 4); + @memcpy(bytes, std.mem.sliceAsBytes(v)[0..n]); } else if (src == 0x3000 and n <= head_row.len * 2) { event(.read_row); @memcpy(bytes, std.mem.sliceAsBytes(head_row)[0..n]); @@ -80,6 +118,13 @@ pub const Device = struct { } else @memset(bytes, 0); return 0; } + fn copy(dst: u64, src: u64, n: usize, _: cuda.abi.Stream) callconv(.c) c_int { + copy_dst[copies] = dst; + copy_src[copies] = src; + copy_bytes[copies] = n; + copies += 1; + return 0; + } fn context(out: *c_int) callconv(.c) c_int { out.* = 0; return 0; @@ -94,8 +139,11 @@ pub const Device = struct { d.api.cuLaunchKernel = launch; d.api.cuStreamSynchronize = wait; d.api.cuMemcpyDtoH_v2 = read; + d.api.cuMemcpyDtoDAsync_v2 = copy; d.api.cuCtxGetDevice = context; d.api.cuDeviceGetAttribute = attribute; + single_vals = null; + single_cols = null; reductions = &.{}; vals = &.{ 0x3f80, 0 }; cols = &.{ 0, 1 }; @@ -128,11 +176,15 @@ pub fn draft(d: *cuda.Driver, host: []u16) mtp.Draft { return x; } pub fn head(d: *cuda.Driver) !mtp.Head { + return headIds(d, &.{ 0, 3, 7 }); +} +pub fn headIds(d: *cuda.Driver, ids: []const u32) !mtp.Head { const gpa = std.testing.allocator; var h: mtp.Head = undefined; - h.artifact = try core.proposal_vocab.legacy.artifact(gpa, &.{ 0, 3, 7 }, .{ .vocab = wt.vocab, .hidden = wt.dims, .format = "bf16", .group = 0, .scale_recipe = "fixture" }); + h.artifact = try core.proposal_vocab.legacy.artifact(gpa, ids, .{ .vocab = wt.vocab, .hidden = wt.dims, .format = "bf16", .group = 0, .scale_recipe = "fixture" }); h.ids = h.artifact.ids(); h.service = try @import("lanes").proposal_head.Service.legacy(gpa, &h.artifact); + h.draw_batch = .{ .scores = .{ .d = d, .ptr = 0xA000, .len = @import("cuda_draft_draw.zig").scoreBytes(ids.len) }, .device = .{ .d = d, .ptr = 0x9000, .len = @import("cuda_draw_batch.zig").bytes }, .host = &Device.batch_host, .on = true }; h.best_fn = .{ .d = d, .handle = @ptrFromInt(1) }; h.topk_fn = .{ .d = d, .handle = @ptrFromInt(2) }; return h; diff --git a/zig/src/families/flashnext/cuda_mtp_nonfinite_more_test.zig b/zig/src/families/flashnext/cuda_mtp_nonfinite_more_test.zig index 01b0af9edfb..f6f05e0d772 100644 --- a/zig/src/families/flashnext/cuda_mtp_nonfinite_more_test.zig +++ b/zig/src/families/flashnext/cuda_mtp_nonfinite_more_test.zig @@ -11,14 +11,14 @@ const D = f.Device; const t = std.testing; const a = t.allocator; -fn joinedBeforeWait() !void { +fn joinedBeforeWait(want_best: bool) !void { var best = false; var topk = false; for (D.events[0..D.events_n]) |e| switch (e) { .best => best = true, .topk => topk = true, .wait => { - try t.expect(best and topk); + try t.expect(best == want_best and topk); return; }, else => {}, @@ -49,6 +49,7 @@ test "Flash Next nonfinite: draftMany drives two lanes through the actual shared var driver = D.driver(); defer cuda.download_stage.closeDriver(&driver); var h = try f.head(&driver); + h.draw_batch.on = false; defer h.artifact.deinit(); var host0: [3]u16 = undefined; var host1: [3]u16 = undefined; @@ -108,13 +109,14 @@ test "Flash Next nonfinite: a later bad verify reduction publishes no earlier to reductions[1] = f.reduction(1, std.math.nan(f32), 17); for ([_]?mtp.Sampling{ null, .{ .seed = 7, .temperature = 1, .top_k = 2 }, .{ .seed = 7, .temperature = 1, .top_k = 0 } }) |sm| { D.reset(); + D.cols = &.{ 17, 5, -1, 5 }; var out = [_]u32{ 42, 43 }; try t.expectError(error.ProposalNonfinite, draw.draws(&h, st, a, &x, sm, &.{}, &out)); try t.expectEqualSlices(u32, &.{ 42, 43 }, &out); try t.expectEqual(@as(usize, 32), D.best_bytes); - try t.expectEqual(@as(usize, 1), D.waits); + try t.expectEqual(@as(usize, if (sm != null and sm.?.top_k == 2) 2 else 1), D.waits); if (sm != null and sm.?.top_k == 2) { - try joinedBeforeWait(); + try joinedBeforeWait(false); } } } @@ -135,7 +137,7 @@ test "Flash Next nonfinite: a later bad candidate leaves the entire verify outpu const st: cuda.Stream = .{ .d = &driver, .handle = null }; try t.expectError(error.ProposalNonfinite, draw.draws(&h, st, a, &x, .{ .seed = 7, .temperature = 1, .top_k = 2 }, &.{}, &out)); try t.expectEqualSlices(u32, &.{ 42, 43 }, &out); - try t.expectEqual(@as(usize, 1), D.waits); + try t.expectEqual(@as(usize, 2), D.waits); } test "Flash Next nonfinite: finite head sampled candidates and full rows match the original draw and probability" { @@ -187,7 +189,12 @@ test "Flash Next nonfinite: finite verify top-k and full-row draws match keyed o try draw.draws(&h, st, a, &x, sm, &.{}, &out); try t.expectEqual(expected, out[0]); try t.expectEqual(@as(usize, 1), D.waits); - if (k == 2) try joinedBeforeWait(); + if (k == 2) { + try joinedBeforeWait(false); + try t.expectEqual(@as(usize, 1), D.launches); + try t.expectEqual(@as(usize, 0), D.best_calls); + try t.expectEqual(@as(u32, 1), D.grids[0]); + } }; } @@ -237,3 +244,126 @@ test "Flash Next nonfinite: candidate shape refuses empty mismatched and oversiz const cols: [draw.topk_max + 1]i32 = @splat(0); try t.expectError(error.ProposalScoreShape, draw.drawTopk(a, &vals, &cols, null, 1, sm)); } + +test "Flash Next nonfinite: folded NaN and infinity sentinels fetch best only after failure" { + var driver = D.driver(); + defer cuda.download_stage.closeDriver(&driver); + var h = try f.head(&driver); + defer h.artifact.deinit(); + const host = try a.alloc(u16, wt.vocab); + defer a.free(host); + const row = try a.alloc(u16, wt.vocab); + defer a.free(row); + @memset(row, 0); + var x = f.draft(&driver, host); + const st: cuda.Stream = .{ .d = &driver, .handle = null }; + for ([_]u16{ 0xffc1, 0x7fc1, 0x7f80 }) |bits| { + row[7] = bits; + D.verify_rows = row; + D.vals = &.{ 0x3f80, 0 }; + D.cols = &.{ -1, 5 }; + D.best = f.reduction(1, std.math.nan(f32), 17); + D.reset(); + var out = [_]u32{42}; + try t.expectError(error.ProposalNonfinite, draw.draws(&h, st, a, &x, .{ .seed = 71, .temperature = 1, .top_k = 2 }, &.{}, &out)); + try t.expectEqual(@as(u32, 42), out[0]); + try t.expectEqualSlices(usize, &.{ 2, 1 }, D.functions[0..D.launches]); + try t.expectEqualSlices(u32, &.{ 1, 1 }, D.grids[0..D.launches]); + try joinedBeforeWait(false); + try t.expectEqual(@as(usize, 2), D.waits); + } +} + +test "Flash Next batch draws: four draft steps preserve eight serial chains and every probability" { + var driver = D.driver(); + defer cuda.download_stage.closeDriver(&driver); + var ids: [32]u32 = undefined; + for (&ids, 0..) |*id, i| id.* = @intCast(i * 3); + var h = try f.headIds(&driver, &ids); + defer h.artifact.deinit(); + var vals: [8 * 20]u16 = undefined; + var cols: [8 * 20]i32 = undefined; + for (0..8) |r| for (0..20) |i| { + vals[r * 20 + i] = @intCast(@as(u32, @bitCast(@as(f32, @floatFromInt(i)) / 10)) >> 16); + cols[r * 20 + i] = @intCast(i); + }; + D.vals = &vals; + D.cols = &cols; + D.best = f.reduction(mtp.promote(vals[19]), 4, 19); + // candidates() reads i32 columns from host past its u16 values, so a stack buffer needs i32 alignment. + var host: [8][mtp.max_rows * draw.topk_max * 3]u16 align(4) = undefined; + var ds: [8]mtp.Draft = undefined; + var refs: [8]*mtp.Draft = undefined; + var sms: [8]?mtp.Sampling = undefined; + const nexts: [8][]const u32 = @splat(&.{11}); + const rows: [8]u64 = @splat(0); + var positions: [8]u64 = undefined; + var baseline: [8]mtp.Chain = @splat(.{}); + var got: [8]mtp.Chain = @splat(.{}); + var outs: [8]*mtp.Chain = undefined; + const st: cuda.Stream = .{ .d = &driver, .handle = null }; + var e: prompt.Engine = undefined; + e.gpa = a; + var calls: usize = 0; + var lanes: usize = 0; + const flow: Flow = .{ .e = &e, .h = &h, .st = st, .calls = &calls, .lanes = &lanes }; + for (0..2) |side| { + for (&ds, &refs, &sms, &positions, &outs, 0..) |*d, *ref, *sm, *pos, *out, i| { + d.* = f.draft(&driver, &host[i]); + d.dlogits.ptr += i * 0x100; + d.dlogits.len = ids.len * 2; + ref.* = d; + sm.* = if (i < 6) .{ .seed = 91 + i * 11, .temperature = 0.7, .top_p = 0.95, .top_k = 20 } else null; + pos.* = 100 + i * 31; + out.* = if (side == 0) &baseline[i] else &got[i]; + } + h.draw_batch.on = side == 1; + D.reset(); + calls = 0; + try ops.draftMany(flow, &refs, &nexts, &rows, &@as([8]usize, @splat(4)), &positions, &sms, &@as([8]f64, @splat(0)), &outs); + try t.expectEqual(@as(usize, 4), calls); + for (outs) |out| try t.expectEqual(@as(usize, 4), out.n); + if (side == 1) { + try t.expectEqual(@as(usize, 8), D.launches); + try t.expectEqual(@as(usize, 4), D.waits); + try t.expectEqual(@as(usize, 4), D.reads); + try t.expectEqual(@as(usize, 32), D.copies); + for (0..4) |step| { + try t.expectEqualSlices(usize, &.{ 1, 2 }, D.functions[step * 2 ..][0..2]); + try t.expectEqualSlices(u32, &.{ 8, 8 }, D.grids[step * 2 ..][0..2]); + for (0..8) |r| { + const i = step * 8 + r; + try t.expectEqual(ds[r].dlogits.ptr, D.copy_src[i]); + try t.expectEqual(h.draw_batch.scores.ptr + r * ids.len * 2, D.copy_dst[i]); + try t.expectEqual(ids.len * 2, D.copy_bytes[i]); + } + } + } + } + for (baseline, got) |old, new| { + try t.expectEqualSlices(u32, old.tokens[0..old.n], new.tokens[0..new.n]); + try t.expectEqualSlices(f64, old.probs[0..old.n], new.probs[0..new.n]); + } +} + +test "Flash Next batch draws: lone sampled pick joins both launches before one read, fallback keeps two waits" { + var driver = D.driver(); + defer cuda.download_stage.closeDriver(&driver); + var h = try f.head(&driver); + defer h.artifact.deinit(); + var host: [mtp.max_rows * draw.topk_max * 3]u16 align(4) = undefined; + var d = f.draft(&driver, &host); + const st: cuda.Stream = .{ .d = &driver, .handle = null }; + const sm: mtp.Sampling = .{ .seed = 73, .temperature = 0.7, .top_k = 2 }; + for (0..20) |pos| { + const expected = try mtp.drawPick(a, &.{ 0x3f80, 0, 0xbf80 }, h.ids, D.best[1], pos, sm); + for ([_]bool{ false, true }) |on| { + D.reset(); + const got = try @import("cuda_draft_draw.zig").single(&h, st, a, &d, pos, sm, on); + try t.expectEqualDeep(expected, got); + try t.expectEqual(@as(usize, if (on) 1 else 2), D.waits); + try t.expectEqual(@as(usize, if (on) 1 else 3), D.reads); + if (on) try joinedBeforeWait(true); + } + } +} diff --git a/zig/src/families/flashnext/cuda_mtp_nonfinite_test.zig b/zig/src/families/flashnext/cuda_mtp_nonfinite_test.zig index 4653ea3b216..211e5defebe 100644 --- a/zig/src/families/flashnext/cuda_mtp_nonfinite_test.zig +++ b/zig/src/families/flashnext/cuda_mtp_nonfinite_test.zig @@ -66,6 +66,7 @@ test "Flash Next nonfinite: main-model greedy sampled and masked rows fail befor const sampled: mtp.Sampling = .{ .seed = 7, .temperature = 1, .top_k = 2 }; for ([_]?mtp.Sampling{ null, sampled }) |sm| { Device.best = reduction(-std.math.inf(f32), std.math.nan(f32), std.math.maxInt(i32)); + Device.cols = &.{ -1, 1 }; var out = [_]u32{42}; try t.expectError(error.ProposalNonfinite, draw.draws(&h, st, gpa, &x, sm, &.{}, &out)); try t.expectEqual(@as(u32, 42), out[0]); @@ -94,4 +95,5 @@ test "Flash Next nonfinite: top-k rejects NaNs infinities and invalid columns be test { _ = @import("cuda_mtp_nonfinite_more_test.zig"); + _ = @import("cuda_draw_batch_test.zig"); } diff --git a/zig/src/families/flashnext/cuda_mtp_ops.zig b/zig/src/families/flashnext/cuda_mtp_ops.zig index b26beff01bd..7f10c6660dc 100644 --- a/zig/src/families/flashnext/cuda_mtp_ops.zig +++ b/zig/src/families/flashnext/cuda_mtp_ops.zig @@ -170,12 +170,12 @@ pub fn Ops(comptime Tri: type) type { /// The draft at `position` and its temperature-1 probability (Python Engine.sample_draft). pub fn pick(o: Self, d: *Draft, position: u64, sm: ?Sampling) !Pick { - const h = o.h; - const view_ = h.view(); - const n = view_.logical; - try h.best(o.stream(), d.dlogits.ptr, n, n, 1, d.best.ptr); - try download(o.stream(), std.mem.sliceAsBytes(d.best_host[0..4]), d.best.ptr); - return draw.pick(h, o.stream(), o.e.gpa, d, d.best_host[0..4].*, position, sm, false); + return @import("cuda_draft_draw.zig").single(o.h, o.stream(), o.e.gpa, d, position, sm, o.h.draw_batch.on and o.main == null); + } + + /// One shared verify group completes its reductions before drawing in stream order. + pub fn drawsMany(o: Self, scores: u64, ds: []const *Draft, sms: []const ?Sampling, masks: []const []const u32, outs: []const []u32) !void { + return @import("cuda_draw_batch.zig").drawsMany(o.h, o.stream(), o.e.gpa, scores, ds, sms, masks, outs); } /// Python decode.draft: absorb the kept rows, then chain up to `count` drafts under mtp.Stop, the first kept. @@ -447,13 +447,20 @@ pub fn draftMany(o: anytype, ds: []const *Draft, nexts: []const []const u32, row var step_nexts: [max_lanes][]const u32 = undefined; var step_rows: [max_lanes]u64 = undefined; while (n_act > 0 and j < max_chain) : (j += 1) { - // every active lane's best draft (fn_row_best on its own scores), then one download of all of them - for (act[0..n_act], 0..) |i, r| try h.best(o.stream(), ds[i].dlogits.ptr, h.ids.len, h.ids.len, 1, ds[0].best.ptr + r * 16); - try download(o.stream(), std.mem.sliceAsBytes(best_host[0 .. n_act * 4]), ds[0].best.ptr); + var ready: ?@import("cuda_draft_draw.zig").Ready = null; + if (h.draw_batch.on and !(if (@hasField(@TypeOf(o), "main")) o.main != null else false)) { + ready = try @import("cuda_draft_draw.zig").gather(h, o.stream(), ds, act[0..n_act], sms); + } else { + for (act[0..n_act], 0..) |i, r| try h.best(o.stream(), ds[i].dlogits.ptr, h.ids.len, h.ids.len, 1, ds[0].best.ptr + r * 16); + try download(o.stream(), std.mem.sliceAsBytes(best_host[0 .. n_act * 4]), ds[0].best.ptr); + } var next_act: usize = 0; var n_step: usize = 0; for (act[0..n_act], 0..) |i, r| { - const got = try draw.pick(h, o.stream(), o.e.gpa, ds[i], best_host[r * 4 ..][0..4].*, positions[i] + j, sms[i], true); + const got = if (ready) |*rd| + try rd.pick(h, o.stream(), o.e.gpa, ds[i], r, positions[i] + j, sms[i], true) + else + try draw.pick(h, o.stream(), o.e.gpa, ds[i], best_host[r * 4 ..][0..4].*, positions[i] + j, sms[i], true); const out = outs[i]; const t = stops[i].take(j, got.prob); if (!t.propose) continue; diff --git a/zig/src/families/glm/cuda_env_test.zig b/zig/src/families/glm/cuda_env_test.zig index 6f678d94dcb..cb457eda5a4 100644 --- a/zig/src/families/glm/cuda_env_test.zig +++ b/zig/src/families/glm/cuda_env_test.zig @@ -15,6 +15,7 @@ const switches = [_]Name{ .{ .name = "TF_GLM_PDL", .default = true }, .{ .name = "TF_GLM_PROMPT_STEPS", .default = true }, .{ .name = "TF_GLM_SHARED", .default = true }, + .{ .name = "TF_GLM_DSEL", .default = true }, }; const counts = [_][:0]const u8{"TF_GLM_DFLASH2_LOG"}; const reals = [_][:0]const u8{"TF_GLM_DRAFT_CONFIDENCE"}; diff --git a/zig/src/families/glm/cuda_forward.zig b/zig/src/families/glm/cuda_forward.zig index b99b82dad5e..e18dc98be0c 100644 --- a/zig/src/families/glm/cuda_forward.zig +++ b/zig/src/families/glm/cuda_forward.zig @@ -26,6 +26,7 @@ const exl3 = @import("cuda_exl3.zig"); const shared = @import("cuda_shared.zig"); const index_mod = @import("cuda_index.zig"); const l2pf_mod = @import("cuda_l2pf.zig"); +const pieces_mod = @import("cuda_forward_pieces.zig"); pub const prefill_rows = state.prefill_rows; pub const solo_rows = state.solo_rows; @@ -44,6 +45,7 @@ pub const Modules = struct { exl3: exl3.Kernels, // an EXL3 checkpoint's routed experts mm: mm_mod.Kernels, // glm_mm: the bf16 linears on tiled weights index: ?index_mod.Kernels, // TF_GLM_INDEX_CUDA: a prompt chunk's indexer scores and pools (glm_index) + dsel: bool, // TF_GLM_DSEL (default on): a decode window's DSA select on many CTAs (cuda_sparse.decodeSelect) tiled: bool = false, // eligible bf16 linears are tiled; KDA inputs with uneven strides retain their row-major path packs: ?*const mm_mod.Packed = null, // the linears packed to 4, 6 or 8 bits (TF_GLM_DENSE_BITS, _HEAD_BITS) copy_rows: cuda.Function, @@ -82,9 +84,11 @@ pub const Modules = struct { errdefer if (m.index) |*x| x.unload(); const mode = index_mod.Mode.read() catch return error.BadIndexSetting; if (mode != .off) m.index = index_mod.Kernels.load(d, k.glm_index, mode) catch |err| blk: { - std.log.warn("TF_GLM_INDEX_CUDA: the indexer kernels are not used ({t}); prompt chunks use tf_glm_scores", .{err}); + std.log.warn("glm: the indexer kernels are not used ({t}); prompt chunks use tf_glm_scores, as with TF_GLM_INDEX_CUDA=0", .{err}); break :blk null; }; + m.dsel = try @import("sys").environment.read(bool, "TF_GLM_DSEL", true); + if (!m.dsel) std.log.warn("TF_GLM_DSEL=0: a decode window's DSA select keeps one 1,024-thread CTA a row", .{}); m.tiled = false; m.packs = null; // `m` starts undefined: the field default does not apply return m; @@ -110,66 +114,10 @@ pub const Modules = struct { } }; -/// overlap.ROW_STEP and PIECES_MAX: piece boundaries on the BF16 prompt matmul's 128-row blocks, at most 16 pieces. -pub const row_step = 128; -pub const max_pieces = 16; - -/// overlap.ranges: [lo, hi) row pieces of a chunk of `rows`, about equal on row_step boundaries (fewer when short). -pub fn ranges(rows: usize, pieces: usize, out: *[max_pieces][2]usize) usize { - const per = (rows + pieces - 1) / pieces; - const size = (per + row_step - 1) / row_step * row_step; - var n: usize = 0; - var lo: usize = 0; - while (lo < rows) : (lo += size) { - out[n] = .{ lo, @min(rows, lo + size) }; - n += 1; - } - return n; -} - -/// A prompt chunk's pieced exchanges (overlap.Overlap): second stream and events; `count`: TF_GLM_OVERLAP_PIECES (3). -pub const Pieces = struct { - count: usize = 4, - side: cuda.Stream, - filled: [max_pieces]cuda.Event, - gathered: [max_pieces]cuda.Event, - glues: [max_pieces]cuda.Event, // split: a piece's own rows glued - shared: [max_pieces]cuda.Event, // split: every rank's glued rows of a piece in - owns_side: bool = true, // a paired step's second chunk (initTwin) runs on the first's side stream - - /// With `pair` (TF_GLM_PROMPT_PAIR) the side stream runs at the highest priority, ahead of the main stream's grids. - pub fn init(d: *const cuda.Driver, count: usize, pair: bool) !Pieces { - if (count == 0 or count > max_pieces) return error.BadPieces; - return make(d, count, if (pair) try cuda.Stream.initPriority(d, .highest) else try cuda.Stream.init(d, false), true); - } - - /// A paired step's second chunk on `of`'s side stream: every rank posts both chunks' exchanges in one order. - pub fn initTwin(d: *const cuda.Driver, of: *const Pieces) !Pieces { - return make(d, of.count, of.side, false); - } - - fn make(d: *const cuda.Driver, count: usize, side: cuda.Stream, owns_side: bool) !Pieces { - var p: Pieces = .{ .count = count, .side = side, .filled = undefined, .gathered = undefined, .glues = undefined, .shared = undefined, .owns_side = owns_side }; - for (&p.filled, &p.gathered, &p.glues, &p.shared) |*a, *b, *g, *s| { - a.* = try cuda.Event.init(d, false); - b.* = try cuda.Event.init(d, false); - g.* = try cuda.Event.init(d, false); - s.* = try cuda.Event.init(d, false); - } - return p; - } - - pub fn deinit(p: *Pieces) void { - for (&p.filled, &p.gathered, &p.glues, &p.shared) |*a, *b, *g, *s| { - a.deinit(); - b.deinit(); - g.deinit(); - s.deinit(); - } - if (p.owns_side) p.side.deinit(); - p.* = undefined; - } -}; +pub const row_step = pieces_mod.row_step; +pub const max_pieces = pieces_mod.max_pieces; +pub const ranges = pieces_mod.ranges; +pub const Pieces = pieces_mod.Pieces; /// How the ranks' partials meet: every rank in-process copying into the others' slots, or one rank over NCCL. pub const Exchange = union(enum) { @@ -215,7 +163,7 @@ pub const Forward = struct { } pub fn set(f: *const Forward) glue.Set { - return .{ .glue = &f.m.glue, .index = if (f.m.index) |*x| x else null, .mm = if (f.m.tiled) &f.m.mm else null, .packs = f.m.packs, .prompt = f.ranks[0].b.prefill, .linear = .{ .lane = &f.m.lane }, .copy_rows = f.m.copy_rows }; + return .{ .glue = &f.m.glue, .index = if (f.m.index) |*x| x else null, .mm = if (f.m.tiled) &f.m.mm else null, .packs = f.m.packs, .prompt = f.ranks[0].b.prefill, .linear = .{ .lane = &f.m.lane }, .copy_rows = f.m.copy_rows, .dsel = f.m.dsel }; } /// The layer sums' boundary (cuda_boundary.zig): every rank's fp32 partial into every gathered buffer. diff --git a/zig/src/families/glm/cuda_forward_pieces.zig b/zig/src/families/glm/cuda_forward_pieces.zig index ba803b1afbd..c713c513fb2 100644 --- a/zig/src/families/glm/cuda_forward_pieces.zig +++ b/zig/src/families/glm/cuda_forward_pieces.zig @@ -1,14 +1,75 @@ //! The existing pieced prompt exchanges, isolated so their diagnostic spans stay beside each stream operation. +const cuda = @import("cuda"); const relay = @import("cuda_relay.zig"); const taps = @import("cuda_taps.zig"); const fw = @import("cuda_forward.zig"); const prof = @import("cuda_prof.zig"); const Forward = fw.Forward; -const Pieces = fw.Pieces; const Site = fw.Forward.Site; const room = fw.Forward.room; const share = fw.Forward.share; +/// overlap.ROW_STEP and PIECES_MAX: piece boundaries on the BF16 prompt matmul's 128-row blocks, at most 16 pieces. +pub const row_step = 128; +pub const max_pieces = 16; + +/// overlap.ranges: [lo, hi) row pieces of a chunk of `rows`, about equal on row_step boundaries (fewer when short). +pub fn ranges(rows: usize, pieces: usize, out: *[max_pieces][2]usize) usize { + const per = (rows + pieces - 1) / pieces; + const size = (per + row_step - 1) / row_step * row_step; + var n: usize = 0; + var lo: usize = 0; + while (lo < rows) : (lo += size) { + out[n] = .{ lo, @min(rows, lo + size) }; + n += 1; + } + return n; +} + +/// A prompt chunk's pieced exchanges (overlap.Overlap): second stream and events; `count`: TF_GLM_OVERLAP_PIECES (3). +pub const Pieces = struct { + count: usize = 4, + side: cuda.Stream, + filled: [max_pieces]cuda.Event, + gathered: [max_pieces]cuda.Event, + glues: [max_pieces]cuda.Event, // split: a piece's own rows glued + shared: [max_pieces]cuda.Event, // split: every rank's glued rows of a piece in + owns_side: bool = true, // a paired step's second chunk (initTwin) runs on the first's side stream + + /// With `pair` (TF_GLM_PROMPT_PAIR) the side stream runs at the highest priority, ahead of the main stream's grids. + pub fn init(d: *const cuda.Driver, count: usize, pair: bool) !Pieces { + if (count == 0 or count > max_pieces) return error.BadPieces; + return make(d, count, if (pair) try cuda.Stream.initPriority(d, .highest) else try cuda.Stream.init(d, false), true); + } + + /// A paired step's second chunk on `of`'s side stream: every rank posts both chunks' exchanges in one order. + pub fn initTwin(d: *const cuda.Driver, of: *const Pieces) !Pieces { + return make(d, of.count, of.side, false); + } + + fn make(d: *const cuda.Driver, count: usize, side: cuda.Stream, owns_side: bool) !Pieces { + var p: Pieces = .{ .count = count, .side = side, .filled = undefined, .gathered = undefined, .glues = undefined, .shared = undefined, .owns_side = owns_side }; + for (&p.filled, &p.gathered, &p.glues, &p.shared) |*a, *b, *g, *s| { + a.* = try cuda.Event.init(d, false); + b.* = try cuda.Event.init(d, false); + g.* = try cuda.Event.init(d, false); + s.* = try cuda.Event.init(d, false); + } + return p; + } + + pub fn deinit(p: *Pieces) void { + for (&p.filled, &p.gathered, &p.glues, &p.shared) |*a, *b, *g, *s| { + a.deinit(); + b.deinit(); + g.deinit(); + s.deinit(); + } + if (p.owns_side) p.side.deinit(); + p.* = undefined; + } +}; + /// overlap.Overlap.partials: each piece filled on the main stream, exchanged on the second (gathered or split). pub fn exchangePieces(f: *const Forward, p: *const Pieces, j: usize, site: Site, cut: []const [2]usize) !void { defer prof.context(f.prof, j, null, if (site == .mixer) .mixer else .ffn); diff --git a/zig/src/families/glm/cuda_glue.zig b/zig/src/families/glm/cuda_glue.zig index ca135465ff4..777355de58f 100644 --- a/zig/src/families/glm/cuda_glue.zig +++ b/zig/src/families/glm/cuda_glue.zig @@ -6,7 +6,17 @@ const mm_mod = @import("cuda_mm.zig"); const index_mod = @import("cuda_index.zig"); /// What the forward's kernels launch from: our glue's, glm_mm's when tiled, qlinear's lane for FP8 kinds, copy_rows. -pub const Set = struct { glue: *const Kernels, index: ?*const index_mod.Kernels = null, mm: ?*const mm_mod.Kernels = null, packs: ?*const mm_mod.Packed = null, prompt: bool = false, linear: cuda.qlinear.Linear = .{}, copy_rows: ?cuda.Function = null }; +pub const Set = struct { + glue: *const Kernels, + index: ?*const index_mod.Kernels = null, + mm: ?*const mm_mod.Kernels = null, + packs: ?*const mm_mod.Packed = null, + prompt: bool = false, + linear: cuda.qlinear.Linear = .{}, + copy_rows: ?cuda.Function = null, + /// A decode window's DSA select on many CTAs (cuda_sparse.decodeSelect; TF_GLM_DSEL, default on). + dsel: bool = false, +}; /// A hidden-size norm's weight: bf16, or float32 (FP4-Local's) read as float32 by the _f32w kernels. pub const Norm = union(enum) { bf16: u64, f32: u64 }; @@ -45,6 +55,8 @@ pub const Kernels = struct { pool_keys: cuda.Function, select_rows: cuda.Function, select_rows_wide: cuda.Function, + dsel_scan: cuda.Function, // glm_index_decode.cuh: a decode window's rows marked on many CTAs + dsel_merge: cuda.Function, // and their picks, a CTA a row bmm_decode: cuda.Function, bmm_rows: cuda.Function, bmm_tile: cuda.Function, diff --git a/zig/src/families/glm/cuda_index.zig b/zig/src/families/glm/cuda_index.zig index 5c4ad55bb2a..4dd75d770f3 100644 --- a/zig/src/families/glm/cuda_index.zig +++ b/zig/src/families/glm/cuda_index.zig @@ -16,22 +16,22 @@ pub const pool_threads = 256; pub const rows_from = sparse.score_loop_from; pub const cap_max = 4096; -/// TF_GLM_INDEX_CUDA: unset or 0 (today's launches), 1 (both kernels), scores (only the scores, to bisect). +/// TF_GLM_INDEX_CUDA: unset, blank or 1 (both kernels), scores (only the scores, to bisect), 0 (neither). pub const Mode = enum { off, both, scores, pub fn parse(text: ?[]const u8) !Mode { - const t = text orelse return .off; - if (t.len == 0 or std.mem.eql(u8, t, "0")) return .off; - if (std.mem.eql(u8, t, "1")) return .both; + const t = text orelse return .both; + if (std.mem.trim(u8, t, " \t\r\n").len == 0 or std.mem.eql(u8, t, "1")) return .both; + if (std.mem.eql(u8, t, "0")) return .off; if (std.mem.eql(u8, t, "scores")) return .scores; return error.BadIndexMode; } pub fn read() !Mode { - const v = std.c.getenv("TF_GLM_INDEX_CUDA") orelse return .off; + const v = std.c.getenv("TF_GLM_INDEX_CUDA") orelse return .both; return parse(std.mem.span(v)); } }; @@ -96,13 +96,15 @@ fn cdiv(a: usize, b: usize) usize { return (a + b - 1) / b; } -test "GLM index: TF_GLM_INDEX_CUDA is off unless 1 or scores, and a typo is refused" { - try std.testing.expectEqual(Mode.off, try Mode.parse(null)); - try std.testing.expectEqual(Mode.off, try Mode.parse("")); - try std.testing.expectEqual(Mode.off, try Mode.parse("0")); +test "GLM index: TF_GLM_INDEX_CUDA is on unless 0, scores bisects, and a typo is refused" { + try std.testing.expectEqual(Mode.both, try Mode.parse(null)); + try std.testing.expectEqual(Mode.both, try Mode.parse("")); + try std.testing.expectEqual(Mode.both, try Mode.parse(" \t")); try std.testing.expectEqual(Mode.both, try Mode.parse("1")); + try std.testing.expectEqual(Mode.off, try Mode.parse("0")); try std.testing.expectEqual(Mode.scores, try Mode.parse("scores")); try std.testing.expectError(error.BadIndexMode, Mode.parse("on")); + try std.testing.expectError(error.BadIndexMode, Mode.parse("off")); } test "GLM index: the scores grid covers 8 rows a CTA and 16 pool blocks a CTA" { @@ -129,3 +131,51 @@ test "GLM index: only prompt-sized launches on aligned key caches take the kerne try std.testing.expect(!k.takes(512, 1024, 0x1000, 32760)); try std.testing.expect(!k.takes(512, topk - 1, 0x1000, 32768)); } + +/// A driver that records each launched function's handle, in order (selectTokens below, without a device). +const Recorded = struct { + var n: usize = 0; + var ids: [16]usize = undefined; + fn launch(f: cuda.abi.Function, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: cuda.abi.Stream, _: ?[*]?*anyopaque, _: ?[*]?*anyopaque) callconv(.c) c_int { + if (n < ids.len) ids[n] = @intFromPtr(f); + n += 1; + return 0; + } + fn function(out: *cuda.abi.Function, _: cuda.abi.Module, name: [*:0]const u8) callconv(.c) c_int { + out.* = @ptrFromInt(if (std.mem.eql(u8, std.mem.span(name), "tf_glm_dsa_tokens")) @as(usize, 41) else 40); + return 0; + } +}; + +test "GLM index: prompt chunks take the kernels; a decode row, an unaligned key cache and a small pool cap keep tf_glm_scores" { + const glue = @import("cuda_glue.zig"); + const latent = @import("cuda_latent.zig"); + var d: cuda.Driver = undefined; + d.api.cuLaunchKernel = Recorded.launch; + d.api.cuModuleGetFunction = Recorded.function; + var ks: glue.Kernels = undefined; // 20 tf_glm_scores, 21 tf_glm_select_rows, 22 its wide form + ks.scores = .{ .d = &d, .handle = @ptrFromInt(20) }; + ks.select_rows = .{ .d = &d, .handle = @ptrFromInt(21) }; + ks.select_rows_wide = .{ .d = &d, .handle = @ptrFromInt(22) }; + const ops: cuda.Module = .{ .d = &d, .handle = null }; // 40 tf_glm_add_i32, 41 tf_glm_dsa_tokens + const stream: cuda.Stream = .{ .d = &d, .handle = null }; + const s: sparse.Scratch = .{ .scores = 0x10000, .ls = 0, .li = 0, .pools = 0x20000, .at = 0x30000 }; + const table: latent.Table = .{ .pt = 0x4000, .ps = 32768, .page_rows = 512 }; + const Case = struct { rows: usize, pk: u64, cap: usize, want: []const usize }; + for ([_]Mode{ .both, .scores }) |mode| { + // 30 tf_glm_index_scores, 31 tf_glm_index_pools + const k: Kernels = .{ .module = undefined, .scores_fn = .{ .d = &d, .handle = @ptrFromInt(30) }, .pools_fn = .{ .d = &d, .handle = @ptrFromInt(31) }, .select = mode == .both }; + const set: glue.Set = .{ .glue = &ks, .index = &k }; + const prompt: []const usize = if (mode == .both) &.{ 30, 31, 41 } else &.{ 30, 21, 41 }; + for ([_]Case{ + .{ .rows = 512, .pk = 0x1000, .cap = 1 << 20, .want = prompt }, // a prompt chunk of 512 rows at 65,536 + .{ .rows = 1, .pk = 0x1000, .cap = 1 << 20, .want = &.{ 20, 22, 41 } }, // a decode row: the wide select + .{ .rows = 512, .pk = 0x1008, .cap = 1 << 20, .want = &.{ 20, 21, 41 } }, // keys off 16 bytes + .{ .rows = 512, .pk = 0x1000, .cap = 256, .want = &.{ 20, 21, 41 } }, // fewer than 512 pools + }) |c| { + Recorded.n = 0; + try sparse.selectTokens(set, ops, stream, 0x5000, 0x6000, 160, c.pk, table, 0x7000, 65536, c.rows, 32, 128, c.cap, s, 0x8000, 0x9000); + try std.testing.expectEqualSlices(usize, c.want, Recorded.ids[0..Recorded.n]); + } + } +} diff --git a/zig/src/families/glm/cuda_sparse.zig b/zig/src/families/glm/cuda_sparse.zig index 29521924a7a..218f53670a3 100644 --- a/zig/src/families/glm/cuda_sparse.zig +++ b/zig/src/families/glm/cuda_sparse.zig @@ -20,13 +20,59 @@ fn cdiv(a: usize, b: usize) usize { } /// At most wide_rows rows (one wave on 48 SMs) over wide_pools pools or more: 1,024 threads a row, the same bytes. -const wide_rows = 48; +pub const wide_rows = 48; const wide_pools = 4096; fn wideSelect(rows: usize, np: usize) bool { return rows <= wide_rows and np >= wide_pools; } +/// glm_index_decode.cuh's sizes: a scan CTA's pools and threads, a merge CTA's candidates and threads, the floor's aim. +pub const dsel_span = 4096; +pub const dsel_scan_threads = 256; +pub const dsel_cap = 4096; +pub const dsel_merge_threads = 1024; +/// The floor's aim, for speed only: every path picks tf_glm_select_rows' pools. +pub const dsel_target = 2048; + +/// The bytes of a decode select's gt and eq bit words for `rows` rows at `np` pools (Scratch.ls, its bits_rows). +pub fn bitsBytes(rows: usize, np: usize) usize { + return rows * 2 * cdiv(np, 32) * 4; +} + +/// tf_glm_dsel_scan's grid for `rows` rows from host_pos: the last row's pools (it sees the most) in spans. +pub fn dselScanCtas(host_pos: usize, rows: usize, np: usize) usize { + const last = @min(np, @max((host_pos + rows) / pool, topk_pools)); + // 0 when every row fits a merge CTA's candidates: the merge takes the rows whole and the scan marks nothing + return if (last <= dsel_cap) 0 else cdiv(last, dsel_span); +} + +/// A decode window's picks (the wide select's rows) on many CTAs: scores [rows][np] at `at` into pools [rows][512]. +pub fn decodeSelect( + set: glue.Set, + stream: cuda.Stream, + scores: u64, + pools: u64, + np: usize, + at: u64, + host_pos: usize, + rows: usize, + bits: u64, + /// 0, or [rows] int32 for each row's path (glm_index_decode.cuh; the checks count them). + path: u64, +) !void { + const words = cdiv(np, 32); + const g = dselScanCtas(host_pos, rows, np); + if (g > 0) { + var sa: cuda.Args = .{}; + inline for (.{ scores, @as(i64, @intCast(np)), at, @as(c_int, topk_pools), @as(c_int, dsel_target), bits, @as(i64, @intCast(words)) }) |v| sa.add(v); + try cuda.launch.launch(set.glue.dsel_scan, .{ .grid = .{ .x = @intCast(g), .y = @intCast(rows) }, .block = .{ .x = dsel_scan_threads } }, stream, &sa); + } + var ma: cuda.Args = .{}; + inline for (.{ scores, pools, @as(i64, @intCast(np)), at, @as(c_int, topk_pools), bits, @as(i64, @intCast(words)), path }) |v| ma.add(v); + try cuda.launch.launch(set.glue.dsel_merge, .{ .grid = .{ .x = @intCast(rows) }, .block = .{ .x = dsel_merge_threads } }, stream, &ma); +} + /// sparse.index_update: the window's LayerNormed index keys and gates into ik and ig at pos, completed pools into pk. pub fn indexUpdate(set: glue.Set, stream: cuda.Stream, k_raw: u64, k_stride: usize, gate: u64, ln_w: u64, ln_b: u64, ape: u64, ik: u64, ig: u64, pk: u64, t: latent.Table, pos: u64, rows: usize) !void { var a: cuda.Args = .{}; @@ -55,7 +101,15 @@ pub fn headScale(heads: usize) f32 { } /// The scratch of one selectTokens: scores fp32 [min(rows, 512)][np], and with np past select_list the list rows. -pub const Scratch = struct { scores: u64, ls: u64, li: u64, pools: u64, at: u64 }; +pub const Scratch = struct { + scores: u64, + ls: u64, + li: u64, + pools: u64, + at: u64, + /// The rows of decode select bit words (bitsBytes) `ls` also holds; 0: none, and the wide select runs. + bits_rows: usize = 0, +}; /// A prompt chunk's indexer rows split across the ranks (TF_GLM_INDEX_SPLIT): a block each, the picks all-gathered. pub const Split = struct { lib: *const cuda.nccl.Library, comm: cuda.nccl.Comm, rank: usize, world: usize }; @@ -107,9 +161,14 @@ pub fn selectTokensProfile(set: glue.Set, ops: cuda.Module, stream: cuda.Stream, stamp.end(); continue; }; + const wide = wideSelect(n, np_max); + if (wide and set.dsel and n <= s.bits_rows) { + try decodeSelect(set, stream, s.scores, s.pools + a * topk_pools * 8, np_max, at, host_pos + a, n, s.ls, 0); + stamp.end(); + continue; + } var sel: cuda.Args = .{}; inline for (.{ s.scores, s.pools + a * topk_pools * 8, @as(i64, @intCast(np_max)), at, @as(c_int, topk_pools) }) |v| sel.add(v); - const wide = wideSelect(n, np_max); try cuda.launch.launch(if (wide) set.glue.select_rows_wide else set.glue.select_rows, .{ .grid = .{ .x = @intCast(n) }, .block = .{ .x = if (wide) 1024 else 128 } }, stream, &sel); stamp.end(); } @@ -140,6 +199,17 @@ test "sparse.py's sizing rules" { try std.testing.expectEqual(@as(f32, @floatCast(1.0 / 5.656854249492381)), headScale(32)); } +test "GLM index: a decode select's scan covers the last row's pools in spans, and none when the merge takes rows whole" { + // 864K: the last row sees 216,064 pools of a 216,080 bucket + try std.testing.expectEqual(@as(usize, 53), dselScanCtas(864256 - 16, 16, 216080)); + try std.testing.expectEqual(@as(usize, 8), dselScanCtas(131072 - 1, 1, 65536)); // 32,768 visible of 65,536 + try std.testing.expectEqual(@as(usize, 0), dselScanCtas(4 * 4096 - 1, 1, 8192)); // 4,096 pools: one merge CTA + try std.testing.expectEqual(@as(usize, 2), dselScanCtas(4 * 4096 + 3, 1, 8192)); + try std.testing.expectEqual(@as(usize, 0), dselScanCtas(100, 1, 4096)); // a few visible: K pools + try std.testing.expect(dsel_span % (32 * (dsel_scan_threads / 32)) == 0); // whole words for every warp + try std.testing.expectEqual(@as(usize, 16 * 2 * 6753 * 4), bitsBytes(16, 216080)); +} + test "rank 0 splits a prompt chunk's indexer rows from TF_GLM_INDEX_SPLIT's position on, over two ranks or more" { try std.testing.expect(!splitAt(65536, 0, 3)); // 0: never try std.testing.expect(splitAt(65536, 65536, 3)); diff --git a/zig/src/families/glm/cuda_state.zig b/zig/src/families/glm/cuda_state.zig index eadbabf0e5e..5a5c8919a69 100644 --- a/zig/src/families/glm/cuda_state.zig +++ b/zig/src/families/glm/cuda_state.zig @@ -145,6 +145,27 @@ test "GLM TP3: existing scratch covers raw projections through the 127-row split } } +/// selectTokens' `ls` bytes in a Buffers and its decode select's rows of bit words (0 on a prompt's buffers). +fn selectLs(rows: usize, prefill: bool, seg: usize, np_max: usize) struct { bytes: usize, bits_rows: usize } { + const bits_rows: usize = if (prefill) 0 else @min(seg, sparse.wide_rows); + return .{ .bytes = @max(rows * sparse.select_list * 4, sparse.bitsBytes(bits_rows, np_max)), .bits_rows = bits_rows }; +} + +test "GLM buffers: a decode's ls holds its select's bit words for bits_rows rows, and a prompt's holds none" { + for ([_]usize{ 4096, 1048576 }) |capacity| { + const np_max = capacity / sparse.pool; + for ([_]usize{ 1, 8, 16, 48, 49, 64 }) |seg| { + for ([_]usize{ seg, prefill_rows }) |rows| { + const d = selectLs(rows, false, seg, np_max); + try std.testing.expectEqual(@as(usize, @min(seg, sparse.wide_rows)), d.bits_rows); + try std.testing.expect(d.bytes >= sparse.bitsBytes(d.bits_rows, np_max)); + try std.testing.expect(d.bytes >= rows * sparse.select_list * 4); + try std.testing.expectEqual(@as(usize, 0), selectLs(rows, true, seg, np_max).bits_rows); + } + } + } +} + /// Scratch for windows of up to `rows` rows (the Python family's Buffers): a prompt buffer (`prefill`) or a decode's. pub const Buffers = struct { arena: Arena, @@ -222,6 +243,7 @@ pub const Buffers = struct { const nch = latent.chunksFor(@min(capacity, dense_reach) + seg); const partial_rows = @max(nch * part_rows, latent.chunksFor(sparse.width) * seg); // dense calls, or one sparse const np_max = capacity / sparse.pool; + const sel = selectLs(rows, prefill, seg, np_max); var mm: usize = 4; // windows under rows_from rows keep their K slices apart (a prompt's tail chunk on the prefill buffers too) for (b16Shapes(w)) |sh_| mm = @max(mm, b16.partBytes(@min(rows, b16.rows_from - 1), sh_[0], sh_[1])); @@ -243,7 +265,7 @@ pub const Buffers = struct { partial_rows * HL * 4, 4, // dummy @min(seg, sparse.select_rows) * np_max * 4, - rows * sparse.select_list * 4, + sel.bytes, // ls: the list rows, and on a decode's buffers its select's bit words rows * sparse.select_list * 4, (if (prefill) rows + s.world else rows) * sparse.topk_pools * 8, // pools; a split's equal blocks end at most world - 1 rows past them 4, @@ -306,7 +328,7 @@ pub const Buffers = struct { .qi = p[30], .partials = .{ .po = p[31], .pm = p[32], .pl = p[33] }, .dummy = p[34], - .select = .{ .scores = p[35], .ls = p[36], .li = p[37], .pools = p[38], .at = p[39] }, + .select = .{ .scores = p[35], .ls = p[36], .li = p[37], .pools = p[38], .at = p[39], .bits_rows = sel.bits_rows }, .tokens = p[40], .counts = p[41], .mm_part = p[42], diff --git a/zig/src/families/nemotron/backend.zig b/zig/src/families/nemotron/backend.zig index 5c5f3360fc3..9cb12c4cf6d 100644 --- a/zig/src/families/nemotron/backend.zig +++ b/zig/src/families/nemotron/backend.zig @@ -152,6 +152,7 @@ pub const Metal = struct { .window_costs = self.costs.window[0..@min(self.costs.windows, max_window)], .mtp_step_ms = self.costs.head_ms, .hidden_rows = true, + .plain_share = true, .batch_rows = @intCast(self.o.batch_rows), .max_streams = @intCast(self.o.streams), .shared_costs = self.costs.shared[0..self.costs.shareds], diff --git a/zig/src/families/nemotron/cuda.zig b/zig/src/families/nemotron/cuda.zig index f10b6f19885..6221e18c247 100644 --- a/zig/src/families/nemotron/cuda.zig +++ b/zig/src/families/nemotron/cuda.zig @@ -26,6 +26,8 @@ pub const vision = @import("cuda_vision.zig"); pub const sites = @import("cuda_sites.zig"); pub const train_ops = @import("cuda_train_ops.zig"); pub const glue = @import("cuda_glue.zig"); +pub const torch_ops = @import("cuda_torch_ops.zig"); +pub const sampler = @import("cuda_sampler.zig"); pub const glue_ref = @import("glue_ref.zig"); pub const glue_math = @import("glue_math.zig"); pub const latent = @import("cuda_latent.zig"); @@ -39,6 +41,7 @@ pub const identity = @import("core").checkpoint_identity; test { _ = omni; _ = @import("cuda_bolt_lanes_test.zig"); + _ = @import("cuda_shared_draw.zig"); _ = @import("cuda_lanes.zig"); _ = @import("cuda_shared_grants_test.zig"); _ = vision; diff --git a/zig/src/families/nemotron/cuda_engine.zig b/zig/src/families/nemotron/cuda_engine.zig index 34de99beea9..336fbf1f949 100644 --- a/zig/src/families/nemotron/cuda_engine.zig +++ b/zig/src/families/nemotron/cuda_engine.zig @@ -59,6 +59,11 @@ pub const pin_sampled = pin_ids + state.max_rows; const window_words = pin_sampled + state.max_rows; // a window's words, as a shared window's stream lays its own out pub const pin_prompt = window_words; const pin_shared = pin_prompt + @max(segs.MAX * state.prefill_rows, state.pass_rows); +// a shared window's batched draw: a Rule a row, a position a row, then its tokens +const pin_draw = pin_shared + max_streams * window_words; +const draw_rules_words = state.max_rows * 8; +const draw_meta_words = state.max_rows; +const draw_tokens_words = state.max_rows; /// Graph ids of masked verify windows (launchGraph's ids: windows from 1, head levels from 1000). const masked_ids = 4000; @@ -90,6 +95,7 @@ pub const Engine = struct { done: [lookahead]cuda.Event = undefined, copied: cuda.Event = undefined, // the last window's uploads have read the pinned words sampled_ready: cuda.Event = undefined, + draw_at: [max_streams]u32 = @splat(0), // part k's first row in the last shared window's drawn-token slab pos: usize = 0, parity: usize = 0, prev_keep: usize = 0, @@ -210,7 +216,7 @@ pub const Engine = struct { errdefer if (!keep_owner) if (e.seg) |*s| s.deinit(); e.own = state.Seq.view(&e.b); e.bound = &e.own; - e.pinned = try cuda.HostBuffer.alloc(ctx.d, (pin_shared + max_streams * window_words) * 4); + e.pinned = try cuda.HostBuffer.alloc(ctx.d, (pin_draw + draw_rules_words + draw_meta_words + draw_tokens_words) * 4); errdefer if (!keep_owner) e.pinned.free(); e.history = try cuda.HostBuffer.allocMapped(ctx.d, (@as(usize, e.max_len) + state.max_rows) * 4); errdefer if (!keep_owner) e.history.free(); @@ -509,9 +515,25 @@ pub const Engine = struct { parts_f[k] = .{ .b = &views[k], .row0 = row0, .rows = p.rows, .sampled = e.sampling != null, .mask = p.mask, .slot = p.seq.slot, .untaught = p.seq.untaught }; row0 += p.rows; } + var sd: [max_streams]@import("cuda_shared_draw.zig").SharedDraw = undefined; + var draw_row: usize = 0; + for (parts, 0..) |p, k| { + sd[k] = .{ .sampling = p.seq.sampling, .pos = p.seq.pos, .rows = p.rows }; + e.draw_at[k] = @intCast(draw_row); + draw_row += p.rows; + } + var batch = if (parts.len > 1) @import("cuda_shared_draw.zig").batch(sd[0..parts.len], e.pinned, e.b.draw_rules, e.b.draw_meta, e.b.draw_tokens, pin_draw, pin_draw + draw_rules_words) else null; + if (batch) |b| try @import("cuda_shared_draw.zig").upload(b, e.ops()); try e.copied.record(e.stream); - try e.forward(null).windowSegs(parts_f[0..parts.len]); - for (parts, 0..) |p, k| try e.ops().download(std.mem.sliceAsBytes(host[k * window_words + pin_sampled ..][0..p.rows]), views[k].sampled); + var f = e.forward(null); + f.batch = if (batch) |*b| b else null; + try f.windowSegs(parts_f[0..parts.len]); + const slab = e.pinned.slice(u32)[pin_draw + draw_rules_words + draw_meta_words ..][0..draw_row]; + if (batch != null) { + try e.ops().download(std.mem.sliceAsBytes(slab), e.b.draw_tokens); + } else for (parts, 0..) |p, k| { + try e.ops().download(std.mem.sliceAsBytes(slab[e.draw_at[k]..][0..p.rows]), views[k].sampled); + } try e.sampled_ready.record(e.stream); for (parts) |p| { e.bind(p.seq); @@ -523,7 +545,7 @@ pub const Engine = struct { /// Part k's drawn ids from the last shared window (row r: the token at its position + r + 1). pub fn sharedTokens(e: *Engine, k: usize, rows: usize) ![]const u32 { try e.sampled_ready.synchronize(); - return e.pinned.slice(u32)[pin_shared + k * window_words + pin_sampled ..][0..rows]; + return e.pinned.slice(u32)[pin_draw + draw_rules_words + draw_meta_words + e.draw_at[k] ..][0..rows]; } /// The window's meta row as the kernels read it: position, buffer parity, previous keep, a spare word. diff --git a/zig/src/families/nemotron/cuda_forward.zig b/zig/src/families/nemotron/cuda_forward.zig index 0bf7a6cc629..928cdbaa1a0 100644 --- a/zig/src/families/nemotron/cuda_forward.zig +++ b/zig/src/families/nemotron/cuda_forward.zig @@ -44,6 +44,9 @@ pub const Marks = struct { } }; +/// A multi-stream window's batched draw: device slabs for rules, positions and tokens, its host words, its mode. +pub const Batch = struct { rules: u64, meta: u64, tokens: u64, host_rules: []const u8, host_meta: []const i32, sampled: bool }; + pub const Forward = struct { c: Config, w: *const weights.Weights, @@ -53,6 +56,7 @@ pub const Forward = struct { max_len: usize, nch: usize, sampled: bool, // the target draws by the bound sequence's rule (sample.cu); false: torch.argmax + batch: ?*const Batch = null, // a shared window's batched draw (null: a stream at a time) dump: ?*Dump = null, side: ?Side = null, // decode MoE layers run the shared expert here (null: one stream) marks: ?*Marks = null, // tf-cuda-test window-profile's events; null costs one check a class, no GPU work @@ -132,6 +136,37 @@ pub const Forward = struct { try f.windowSegs(&.{.{ .b = f.b, .row0 = 0, .rows = rows, .sampled = f.sampled, .slot = f.slot, .untaught = f.untaught }}); } + /// Every stream's rows drawn in one pass when all share a mode: the same rule, seed and position a row. + fn drawSegs(f: *const Forward, segs: []const Seg) !void { + const c = f.c; + const b = f.b; + if (segs.len == 1) return f.sample(b.logits, segs[0].rows, segs[0].b.meta, segs[0].b.sampled, segs[0].sampled, segs[0].b.rule); + const bat = f.batch orelse { + for (segs) |s| try f.sample(b.logits + s.row0 * @as(u64, c.vocab) * 2, s.rows, s.b.meta, s.b.sampled, s.sampled, s.b.rule); + return; + }; + var total: usize = 0; + var sampled: usize = 0; + for (segs) |s| { + total += s.rows; + sampled += @intFromBool(s.sampled); + } + // the batch was built from the same streams' modes (cuda_shared_draw.batch), its rules and positions uploaded + if (sampled != (if (bat.sampled) segs.len else 0)) return error.BadWindow; + if (bat.sampled) { + try f.ops.drawRows(b.logits, c.vocab, bat.rules, bat.meta, bat.tokens, total, null); + } else try f.ops.torch().argmax(b.logits, c.vocab, c.vocab, bat.tokens, total); + var g: kern.ScatterRows = std.mem.zeroes(kern.ScatterRows); + var row0: usize = 0; + for (segs, 0..) |s, k| { + g.tok[k] = s.b.sampled; + g.rows[k] = @intCast(s.rows); + g.row0[k] = @intCast(row0); + row0 += s.rows; + } + try f.ops.scatterRows(g, bat.tokens, 0, total); + } + /// Streams share matmuls, norms and experts but keep their mixer state; each row's latch alone picks its lessons. pub fn windowSegs(f: *const Forward, segs: []const Seg) !void { const routed = f.routedWindow(segs); @@ -239,7 +274,7 @@ pub const Forward = struct { try o.dense(b.y, b.xs, f.w.head, b.logits, rows); try f.mark(.head); for (segs) |s| if (s.mask.bits != 0) try o.grammarMask(b.logits + s.row0 * @as(u64, c.vocab) * 2, c.vocab, s.mask.bits, s.mask.words, s.rows); - for (segs) |s| try f.sample(b.logits + s.row0 * @as(u64, c.vocab) * 2, s.rows, s.b.meta, s.b.sampled, s.sampled, s.b.rule); + try f.drawSegs(segs); try f.mark(.sample); if (f.dump) |d| try d.tail(f.ops, b.logits, b.sampled, rows, c.vocab); } diff --git a/zig/src/families/nemotron/cuda_kernels.zig b/zig/src/families/nemotron/cuda_kernels.zig index bf1bc35e730..f984124dd97 100644 --- a/zig/src/families/nemotron/cuda_kernels.zig +++ b/zig/src/families/nemotron/cuda_kernels.zig @@ -42,6 +42,13 @@ pub const Snaps = extern struct { pub const max = 16; }; +/// A batched draft's rows: each part's `a` (wa bytes a row) and `b` (wb bytes a row), its start and row count. +pub const GatherRows = extern struct { a: [8]u64 = @splat(0), b: [8]u64 = @splat(0), rows: [8]c_int = @splat(0), row0: [8]c_int = @splat(0), wa: c_int = 0, wb: c_int = 0 }; +/// A span's last row: each part's source rows, moved to the destination rows in part order. +pub const LastRows = extern struct { a: [8]u64 = @splat(0), b: [8]u64 = @splat(0) }; +/// A level's rows: each part's token and probability destinations, its start and row count, the level's words. +pub const ScatterRows = extern struct { tok: [8]u64 = @splat(0), prob: [8]u64 = @splat(0), rows: [8]c_int = @splat(0), row0: [8]c_int = @splat(0), tok_at: c_int = 0, prob_at: c_int = 0 }; + pub const Kernels = struct { d: *const cuda.Driver, mods: [21]cuda.Module, @@ -64,6 +71,9 @@ pub const Kernels = struct { add_row: cuda.Function, add_bf16: cuda.Function, splice_rows: cuda.Function, // an image prompt's rows take the vision tower's features (Bolt) + gather_rows: cuda.Function, // a batched draft's rows from each part into the head's rows + gather_last: cuda.Function, // a batched draft's last rows moved down, in order + scatter_rows: cuda.Function, // a level's tokens and probabilities to each part's buffers draws: cuda.sample.Draws, // sample.cu: the keyed draws and logprob rows grammar_mask: cuda.Function, // structured output: disallowed tokens -inf before the draw torch: torch_ops.Functions, @@ -101,6 +111,9 @@ pub const Kernels = struct { k.add_row = try k.mods[7].function("tf_add_row"); k.add_bf16 = try k.mods[7].function("tf_add_bf16"); k.splice_rows = try k.mods[7].function("tf_splice_rows"); + k.gather_rows = try k.mods[7].function("tf_nemo_gather_rows"); + k.gather_last = try k.mods[7].function("tf_nemo_gather_last"); + k.scatter_rows = try k.mods[7].function("tf_nemo_scatter_rows"); k.torch = try torch_ops.Functions.resolve(k.mods[8..14]); k.draws = try cuda.sample.Draws.resolve(k.mods[14]); k.glue = try glue.Fns.resolve(k.mods[16..20]); @@ -239,6 +252,16 @@ pub const Ops = struct { return o.k.draws.draw(o.s, logits, vocab, rule, meta, offset, out, rows, ids, prob); } + /// sample.cu's rows draw: row r under rule[r] at position meta[r] + 1, one launch (or a row a launch). + pub fn drawRows(o: Ops, logits: u64, vocab: usize, rule: u64, meta: u64, out: u64, rows: usize, scratch: ?u64) !void { + return o.k.draws.drawRows(o.s, logits, vocab, rule, meta, out, rows, scratch); + } + + /// sample.cu's rows draw at an offset: row r under rule[r], columns mapped by `ids` (null: the whole head). + pub fn drawIdsRows(o: Ops, logits: u64, vocab: usize, rule: u64, meta: u64, offset: usize, out: u64, rows: usize, ids: ?u64, prob: ?u64) !void { + return o.k.draws.drawIdsRows(o.s, logits, vocab, rule, meta, offset, out, rows, ids, prob); + } + /// sample.cu: `rows` bf16 logits rows' disallowed tokens -inf, their bits `words` words a row at `bits`. pub fn grammarMask(o: Ops, logits: u64, vocab: usize, bits: u64, words: usize, rows: usize) !void { var a: cuda.Args = .{}; @@ -254,6 +277,34 @@ pub const Ops = struct { return o.k.draws.logprobRows(o.s, logits, vocab, picks, k, rank, out, rows); } + /// A batched draft's rows: each part's rows of `g`'s sources into dst_a and dst_b, one launch. + pub fn gatherRows(o: Ops, g: GatherRows, dst_a: u64, dst_b: u64, rows: usize) !void { + var a: cuda.Args = .{}; + a.add(g); + a.add(dst_a); + a.add(dst_b); + try o.go(o.k.gather_rows, .{ rows, 1, 1 }, 256, 0, &a); + } + + /// A batched draft's last rows moved to the destination rows, ascending, one block. + pub fn gatherLast(o: Ops, g: LastRows, dst_a: u64, dst_b: u64, wa: usize, wb: usize, n: usize) !void { + var a: cuda.Args = .{}; + a.add(g); + a.add(dst_a); + a.add(dst_b); + for ([_]usize{ wa, wb, n }) |v| a.add(@as(c_int, @intCast(v))); + try o.go(o.k.gather_last, .{ 1, 1, 1 }, 256, 0, &a); + } + + /// A level's tokens and probabilities to each part's buffers, one launch. + pub fn scatterRows(o: Ops, g: ScatterRows, tok: u64, prob: u64, rows: usize) !void { + var a: cuda.Args = .{}; + a.add(tok); + a.add(prob); + a.add(g); + try o.go(o.k.scatter_rows, .{ rows, 1, 1 }, 32, 0, &a); + } + /// Every projection format the kernels loaded (cuda/qlinear.zig). pub fn linear(o: Ops) cuda.qlinear.Linear { const m = if (o.k.modelopt) |*x| x else null; diff --git a/zig/src/families/nemotron/cuda_lanes.zig b/zig/src/families/nemotron/cuda_lanes.zig index 04e5220a322..2d89f8f2ccb 100644 --- a/zig/src/families/nemotron/cuda_lanes.zig +++ b/zig/src/families/nemotron/cuda_lanes.zig @@ -8,6 +8,7 @@ const engine = @import("cuda_engine.zig"); const Engine = engine.Engine; const reuse = @import("cuda_reuse.zig"); const mtp = @import("cuda_mtp.zig"); +const sampler = @import("cuda_sampler.zig"); const Head = mtp.Head; const state = @import("cuda_state.zig"); const prompt_rows = @import("cuda_prompt_rows.zig"); @@ -98,7 +99,6 @@ pub const Cuda = struct { .prompt_rows = true, } }; } - /// Structured output's bits for rows from `slot` (a forward's rows; a first token's: the last slot), device-read. pub fn putBits(self: *Cuda, slot: usize, masks: []const u32) !engine.Mask { const words = (self.e.c.vocab + 31) / 32; @@ -530,7 +530,7 @@ pub const Cuda = struct { } if (r.depth >= state.windowRows(self.e.c)) return error.BadDraftRequest; try self.e.ops().upload(self.e.b.sampled, std.mem.sliceAsBytes(follow)); - parts[batched] = .{ .k_cache = h.k_cache, .v_cache = h.v_cache, .table = self.e.b.table, .probs = h.probs, .ids = self.e.b.ids, .hidden = self.e.b.hidden, .sampled = self.e.b.sampled, .rule = if (self.e.sampling != null) self.e.b.rule else null, .pos = h.pos, .keep = follow.len, .depth = r.depth, .vocab = v }; + parts[batched] = .{ .k_cache = h.k_cache, .v_cache = h.v_cache, .table = self.e.b.table, .probs = h.probs, .ids = self.e.b.ids, .hidden = self.e.b.hidden, .sampled = self.e.b.sampled, .rule = if (self.e.sampling != null) self.e.b.rule else null, .rule_host = if (self.e.sampling) |x| sampler.rule(x) else null, .pos = h.pos, .keep = follow.len, .depth = r.depth, .vocab = v }; l.keep = follow.len; // as h.chain records h.keep: a reclaim begins this head again at these rows h.pos += follow.len; batched += 1; diff --git a/zig/src/families/nemotron/cuda_mtp.zig b/zig/src/families/nemotron/cuda_mtp.zig index fe85a1db40c..5c44b3993cd 100644 --- a/zig/src/families/nemotron/cuda_mtp.zig +++ b/zig/src/families/nemotron/cuda_mtp.zig @@ -8,6 +8,8 @@ const weights = @import("cuda_weights.zig"); const state = @import("cuda_state.zig"); const Engine = @import("cuda_engine.zig").Engine; const streams = @import("cuda_engine.zig").max_streams; +const kern = @import("cuda_kernels.zig"); +const glue = @import("cuda_glue.zig"); pub const max_chain = state.max_rows - 1; // drafts a window holds beside the pending token /// What a sequence keeps of the head between rounds: its caches and its drafts' confidences. @@ -17,6 +19,9 @@ const host_drafts = meta_words; // pinned layout: meta, drafts, confidences, the const host_probs = host_drafts + max_chain; const host_tokens = host_probs + max_chain; const host_metas = host_tokens + state.pass_rows; // a meta row a stream for `chains` +const host_rules = host_metas + streams * meta_words; // a Rule a stream +const host_pos = host_rules + streams * 8; +const host_words = host_pos + streams; /// The output rows a draft level reads: the draft vocabulary's (the draft head), or the target's whole head. pub const Vocab = @import("cuda_mtp_projection.zig").Vocab; @@ -31,6 +36,7 @@ pub const Part = struct { hidden: u64, sampled: u64, rule: ?u64, // null: greedy drafts + rule_host: ?sampler.Rule = null, // the same rule on the host, for a batched level's rules slab pos: usize, keep: usize, depth: usize, @@ -77,6 +83,10 @@ pub const Head = struct { atok: u64, topk: u64, invalid: u64, // the id lookup's error word: topk's columns are the table's, so it stays zero + rules: u64, // a batched level's rules, one a stream + pos_slab: u64, // its rows' positions, one a stream (pos + keep) + tok_rows: u64, // its tokens, one a row + prob_rows: u64, // its probabilities, one a row pos: usize = 0, keep: usize = 0, levels: usize = 0, @@ -119,23 +129,23 @@ pub const Head = struct { const kv: usize = @as(usize, e.max_len) * c.kv_heads * c.head_dim * 2; const n = if (e.w.draft_coverage != null) c.vocab else e.w.draft_count; const S: usize = streams; - const sizes = [_]usize{ kv, kv, meta_words * 4, state.max_rows * D * 2, state.max_rows * 4, max_chain * 4, D * 2, R * D * 2, R * 2 * D * 2, R * 2 * D / 64 * 4, R * D * 2, S * D * 2, S * D * 2, S * D * 2, S * D / 64 * 4, S * n * 2, n * 4, sampler.max_candidates * 4, sampler.max_candidates * 8, sampler.max_candidates * 8, 32, S * D * 2, S * meta_words * 4, R * 4, torch_ops.topkScratchBytes(1, n), 4 }; + const sizes = [_]usize{ kv, kv, meta_words * 4, state.max_rows * D * 2, state.max_rows * 4, max_chain * 4, D * 2, R * D * 2, R * 2 * D * 2, R * 2 * D / 64 * 4, R * D * 2, S * D * 2, S * D * 2, S * D * 2, S * D / 64 * 4, S * n * 2, S * n * 4, S * sampler.max_candidates * 4, S * sampler.max_candidates * 8, S * sampler.max_candidates * 8, 32, S * D * 2, S * meta_words * 4, R * 4, torch_ops.topkScratchBytes(S, n), 4, S * 32, S * 4, S * 4, S * 4 }; var total: usize = 0; for (sizes) |s| total += std.mem.alignForward(usize, s, 256); const h = try e.gpa.create(Head); errdefer e.gpa.destroy(h); - h.* = .{ .e = e, .buf = undefined, .pinned = undefined, .copied = undefined, .ready = undefined, .k_cache = 0, .v_cache = 0, .meta = 0, .hin = 0, .tok = 0, .probs = 0, .out = 0, .emb = 0, .cat = 0, .cxs = 0, .x = 0, .h1 = 0, .hn = 0, .row = 0, .rxs = 0, .logits = 0, .flog = 0, .vals = 0, .cols = 0, .cand = 0, .fp = 0, .outs = 0, .metas = 0, .atok = 0, .topk = 0, .invalid = 0 }; + h.* = .{ .e = e, .buf = undefined, .pinned = undefined, .copied = undefined, .ready = undefined, .k_cache = 0, .v_cache = 0, .meta = 0, .hin = 0, .tok = 0, .probs = 0, .out = 0, .emb = 0, .cat = 0, .cxs = 0, .x = 0, .h1 = 0, .hn = 0, .row = 0, .rxs = 0, .logits = 0, .flog = 0, .vals = 0, .cols = 0, .cand = 0, .fp = 0, .outs = 0, .metas = 0, .atok = 0, .topk = 0, .invalid = 0, .rules = 0, .pos_slab = 0, .tok_rows = 0, .prob_rows = 0 }; errdefer if (!h.cleanup()) @panic("MTP construction completion failed; keeping all parents until process exit"); h.buf = try cuda.DeviceBuffer.alloc(e.ctx.d, total); h.has_buf = true; - const fields = [_]*u64{ &h.k_cache, &h.v_cache, &h.meta, &h.hin, &h.tok, &h.probs, &h.out, &h.emb, &h.cat, &h.cxs, &h.x, &h.h1, &h.hn, &h.row, &h.rxs, &h.logits, &h.flog, &h.vals, &h.cols, &h.cand, &h.fp, &h.outs, &h.metas, &h.atok, &h.topk, &h.invalid }; + const fields = [_]*u64{ &h.k_cache, &h.v_cache, &h.meta, &h.hin, &h.tok, &h.probs, &h.out, &h.emb, &h.cat, &h.cxs, &h.x, &h.h1, &h.hn, &h.row, &h.rxs, &h.logits, &h.flog, &h.vals, &h.cols, &h.cand, &h.fp, &h.outs, &h.metas, &h.atok, &h.topk, &h.invalid, &h.rules, &h.pos_slab, &h.tok_rows, &h.prob_rows }; var at: usize = 0; for (fields, sizes) |f, s| { f.* = h.buf.ptr + at; at += std.mem.alignForward(usize, s, 256); } try h.buf.fill8(0, e.stream.handle); // on the engine's stream: the legacy one would race its first uploads - h.pinned = try cuda.HostBuffer.alloc(e.ctx.d, (host_metas + S * meta_words) * 4); + h.pinned = try cuda.HostBuffer.alloc(e.ctx.d, host_words * 4); h.has_pinned = true; h.copied = try cuda.Event.init(e.ctx.d, false); h.has_copied = true; @@ -241,7 +251,6 @@ pub const Head = struct { const o = f.ops; const t = f.glue; const D: u64 = c.hidden; - const qd: u64 = c.heads * c.head_dim; var rows: usize = 0; for (spans) |s| rows += s.rows; try f.embed(h.tok, h.emb, rows); @@ -249,13 +258,13 @@ pub const Head = struct { try o.dense(h.cat, h.cxs, m.eh_proj, h.x, rows); try t.addRmsnorm(h.x, null, m.attn_norm, h.x, b.y, b.xs, rows, c.hidden, c.eps); try o.dense(b.y, b.xs, m.attn.qkv, b.qkv, rows); - for (spans) |s| { - const r0: u64 = s.row0; - const qkv = b.qkv + r0 * c.qkvDim() * 2; - var at = f.ashape(); - at.pt = s.table; - try t.kvWrite(qkv, s.k_cache, s.v_cache, s.meta, s.rows, at); - try t.attention(qkv, s.k_cache, s.v_cache, s.meta, b.po + r0 * f.nch * qd * 4, b.pm + r0 * f.nch * c.heads * 4, b.pl + r0 * f.nch * c.heads * 4, b.att + r0 * qd * 2, b.axs + r0 * (qd / 64) * 4, s.rows, at); + var segs_buf: [glue.max_segs]glue.AttnSeg = undefined; + var at0: usize = 0; + while (at0 < spans.len) { + const take = @min(glue.max_segs, spans.len - at0); + for (spans[at0..][0..take], segs_buf[0..take]) |s, *sg| sg.* = .{ .kc = s.k_cache, .vc = s.v_cache, .meta = s.meta, .row0 = s.row0, .rows = s.rows, .pt = s.table }; + try t.attentionSegs(segs_buf[0..take], b.qkv, b.po, b.pm, b.pl, b.att, b.axs, f.ashape()); + at0 += take; } try o.dense(b.att, b.axs, m.attn.o, b.delta, rows); if (!tail) return; @@ -263,13 +272,14 @@ pub const Head = struct { const last = spans[0].row0 + spans[0].rows - 1; try t.addRmsnorm(h.x + last * D * 2, b.delta + last * D * 2, m.moe_norm, h.h1, b.y, b.xs, 1, c.hidden, c.eps); } else { - // span k's last row moves to row k: one norm launch on aligned rows, which a captured set needs + // span k's last row moves to row k: one ordered gather, which a captured set needs + var last: kern.LastRows = std.mem.zeroes(kern.LastRows); for (spans, 0..) |s, k| { - const last = s.row0 + s.rows - 1; - if (last == k) continue; - try o.copy(h.x + k * D * 2, h.x + last * D * 2, D * 2); - try o.copy(b.delta + k * D * 2, b.delta + last * D * 2, D * 2); + const at = s.row0 + s.rows - 1; + last.a[k] = h.x + at * D * 2; + last.b[k] = b.delta + at * D * 2; } + try o.gatherLast(last, h.x, b.delta, D * 2, D * 2, spans.len); try t.addRmsnorm(h.x, b.delta, m.moe_norm, h.h1, b.y, b.xs, spans.len, c.hidden, c.eps); } if (m.moe.latent != null) { @@ -378,6 +388,35 @@ pub const Head = struct { for (1..depth + 1) |j| try h.launch(j, v); } + /// Every live part's level j draw in one pass: the same draw per row, then one scatter to their buffers. + fn sampleRows(h: *Head, parts: []const Part, j: usize, v: Vocab) !void { + const e = h.e; + const live = parts.len; + const n = h.width(v); + const ids: ?u64 = if (v == .subset) e.w.draft_ids else null; + if (parts[0].rule != null) { + try e.ops().drawIdsRows(h.logits, n, h.rules, h.pos_slab, j - 1, h.tok_rows, live, ids, h.prob_rows); + } else { + const k = sampler.greedy_draft; + const count = sampler.count(k.k, n); + const t = e.ops().torch(); + try t.toF32(h.logits, h.flog, n * live); + try t.topk(h.flog, n, live, count, h.vals, h.cols, h.topk); + if (ids) |x| try t.lookup(x, n, h.cols, h.cand, live * count, h.invalid); + try e.forward(null).glue.keyed(h.vals, if (ids != null) h.cand else h.cols, h.meta, h.tok_rows, h.fp, h.fp, h.prob_rows, j - 1, live, count, k); + } + var g: kern.ScatterRows = std.mem.zeroes(kern.ScatterRows); + for (parts, 0..) |p, row| { + g.tok[row] = p.ids; + g.prob[row] = p.probs; + g.rows[row] = 1; + g.row0[row] = @intCast(row); + } + g.tok_at = @intCast(j); + g.prob_at = @intCast(j - 1); + try e.ops().scatterRows(g, h.tok_rows, h.prob_rows, live); + } + /// Several streams' draft requests level by level, a row a stream: drafts to their `ids`, confidences to `probs`. pub fn chains(h: *Head, parts: []Part) !void { const e = h.e; @@ -404,29 +443,62 @@ pub const Head = struct { for (0..max_chain + 1) |j| m[1 + j] = @intCast(p.pos + p.keep + j); } try o.upload(h.metas, std.mem.sliceAsBytes(host)); + const sampled = parts[0].rule != null; + var batched = e.k.triton == null and parts.len > 1; + for (parts) |p| batched = batched and p.vocab == parts[0].vocab and (p.rule != null) == sampled and (!sampled or p.rule_host != null); + if (batched and sampled) { + const rules = std.mem.sliceAsBytes(h.pinned.slice(u32)[host_rules..][0 .. parts.len * 8]); + for (parts, 0..) |p, k| @memcpy(rules[k * 32 ..][0..32], std.mem.asBytes(&p.rule_host.?)); + try o.upload(h.rules, rules); + const pos = h.pinned.slice(u32)[host_pos..][0..parts.len]; + for (parts, 0..) |p, k| pos[k] = @intCast(p.pos + p.keep); + try o.upload(h.pos_slab, std.mem.sliceAsBytes(pos)); + } try h.copied.record(e.stream); var spans: [streams]Span = undefined; var row0: usize = 0; + if (parts.len > 1) { + var g: kern.GatherRows = std.mem.zeroes(kern.GatherRows); + for (parts, 0..) |p, k| { + g.a[k] = p.hidden; + g.b[k] = p.sampled; + g.rows[k] = @intCast(p.keep); + g.row0[k] = @intCast(row0); + row0 += p.keep; + } + g.wa = @intCast(D * 2); + g.wb = 4; + try o.gatherRows(g, h.hin, h.tok, row0); + } else { + const p = parts[0]; + try o.copy(h.hin, p.hidden, p.keep * D * 2); + try o.copy(h.tok, p.sampled, p.keep * 4); + row0 = p.keep; + } + row0 = 0; for (parts, spans[0..parts.len]) |p, *s| { - try o.copy(h.hin + row0 * D * 2, p.hidden, p.keep * D * 2); - try o.copy(h.tok + row0 * 4, p.sampled, p.keep * 4); s.* = .{ .row0 = row0, .rows = p.keep, .meta = 0, .k_cache = p.k_cache, .v_cache = p.v_cache, .table = p.table, .vocab = p.vocab }; row0 += p.keep; } var live = parts.len; for (1..parts[0].depth + 1) |j| { while (parts[live - 1].depth < j) live -= 1; - if (j > 1) try o.copy(h.hin, h.outs, live * D * 2); + if (j > 1) { + try o.copy(h.hin, h.outs, live * D * 2); + if (batched) try o.copy(h.tok, h.tok_rows, live * 4); + } for (parts[0..live], spans[0..live], 0..) |p, *s, k| { s.meta = h.metas + k * meta_words * 4 + (j - 1) * 4; if (j == 1) continue; - try o.copy(h.tok + k * 4, p.ids + (j - 1) * 4, 4); + if (!batched) try o.copy(h.tok + k * 4, p.ids + (j - 1) * 4, 4); s.row0 = k; s.rows = 1; } const n = try h.forwardSpans(spans[0..live], true); try o.copy(h.outs, h.row, live * D * 2); - for (parts[0..live], 0..) |p, k| { + if (batched) { + try h.sampleRows(parts[0..live], j, parts[0].vocab); + } else for (parts[0..live], 0..) |p, k| { const meta = h.metas + k * meta_words * 4; try h.sample(h.logits + k * n * 2, p.rule, meta + 4, p.ids + j * 4, p.probs + (j - 1) * 4, j, p.vocab); } diff --git a/zig/src/families/nemotron/cuda_shared_draw.zig b/zig/src/families/nemotron/cuda_shared_draw.zig new file mode 100644 index 00000000000..56b8332d894 --- /dev/null +++ b/zig/src/families/nemotron/cuda_shared_draw.zig @@ -0,0 +1,41 @@ +//! A shared window's batched draw: its host rules and positions, when every stream shares a mode. +const std = @import("std"); +const cuda = @import("cuda"); +const forward = @import("cuda_forward.zig"); + +/// One stream of a shared window's draw: its sampling, position and rows. +pub const SharedDraw = struct { sampling: ?@import("lanes").Sampling, pos: usize, rows: usize }; + +/// A shared window's batched draw when every stream shares a mode; null when the modes are mixed. +pub fn batch(parts: []const SharedDraw, pinned: cuda.HostBuffer, rules: u64, meta: u64, tokens: u64, pin_rules: usize, pin_meta: usize) ?forward.Batch { + var sampled: usize = 0; + var total: usize = 0; + for (parts) |p| { + sampled += @intFromBool(cuda.sample.ruleFor(p.sampling) != null); + total += p.rows; + } + if (sampled != 0 and sampled != parts.len) return null; + var b: forward.Batch = .{ .rules = rules, .meta = meta, .tokens = tokens, .host_rules = &.{}, .host_meta = &.{}, .sampled = sampled != 0 }; + if (sampled == 0) return b; + const rb = std.mem.sliceAsBytes(pinned.slice(u32)[pin_rules..][0 .. total * 8]); + const hm = pinned.slice(i32)[pin_meta..][0..total]; + var at: usize = 0; + for (parts) |p| { + const r = cuda.sample.ruleFor(p.sampling).?; + for (0..p.rows) |r_| { + @memcpy(rb[(at + r_) * 32 ..][0..32], std.mem.asBytes(&r)); + hm[at + r_] = @intCast(p.pos + r_); + } + at += p.rows; + } + b.host_rules = rb; + b.host_meta = hm; + return b; +} + +/// A sampled batch's rules and positions to the device, with the window's other pinned words (before `copied`). +pub fn upload(b: forward.Batch, ops: anytype) !void { + if (!b.sampled) return; + try ops.upload(b.rules, b.host_rules); + try ops.upload(b.meta, std.mem.sliceAsBytes(b.host_meta)); +} diff --git a/zig/src/families/nemotron/cuda_sm89_test.zig b/zig/src/families/nemotron/cuda_sm89_test.zig index 1a4e1160efc..8799636e62d 100644 --- a/zig/src/families/nemotron/cuda_sm89_test.zig +++ b/zig/src/families/nemotron/cuda_sm89_test.zig @@ -193,7 +193,7 @@ test "modelopt host: real buffer and sibling allocations cover all dense partial defer sibling.deinit(); sibling.follow(&b); const bytes = b.arena.buf.ptr + b.arena.used - b.lane_part; - try t.expectEqual(@as(u64, if (latent == 12224) 24936960 else 21934080), bytes); + try t.expectEqual(@as(u64, if (latent == 12224) 24938368 else if (latent == 1024) 21935488 else 21934912), bytes); try t.expect(b.lane_part != sibling.lane_part); try t.expectEqual(bytes, sibling.arena.buf.ptr + sibling.arena.used - sibling.lane_part); const shapes = [_][2]usize{ .{ c.projDim(), c.hidden }, .{ c.hidden, c.inner() }, .{ c.qkvDim(), c.hidden }, .{ c.hidden, c.heads * c.head_dim }, .{ c.vocab, c.hidden }, .{ c.hidden, 2 * c.hidden }, .{ c.latent, c.hidden }, .{ c.hidden, c.latent } }; diff --git a/zig/src/families/nemotron/cuda_state.zig b/zig/src/families/nemotron/cuda_state.zig index f493e421e62..579fa224599 100644 --- a/zig/src/families/nemotron/cuda_state.zig +++ b/zig/src/families/nemotron/cuda_state.zig @@ -101,7 +101,7 @@ fn lanePartBytes(c: Config) usize { } return most; } -const scratch_count = 44; +const scratch_count = 47; /// Bytes of the shared expert's fixed plans (Buffers.shared): shared_words, or a latent MoE's plan for every row count. fn sharedBytes(c: Config) usize { @@ -147,7 +147,8 @@ fn scratchSizes(c: Config, nch: usize) [scratch_count]usize { ymoe, sharedBytes(c), R * kern.pocket_width * 4, R * c.latent * 2, R * c.latent * 2, act_rows * own * sw * 2, R * own * 4, job, ck8, - ck4, lanePartBytes(c), + ck4, lanePartBytes(c), W * 32, + W * 4, W * 4, }; } @@ -297,6 +298,9 @@ pub const Buffers = struct { job: u64, // rank 0's job to the other ranks: a header and the rows their shares read (cuda_worker.zig) ck8: u64, // the checkpoint's math: e4m3 rows an FP8 projection reads ck4: u64, // and a latent MoE's NVFP4 rows (cuda_latent_ck.zig) + draw_rules: u64, // a batched draw's rules, one a row (32 bytes each) + draw_meta: u64, // its rows' positions, one a row + draw_tokens: u64, // a batched draw's tokens, one a row /// Sizes every buffer for `max_len` cache rows and `nch` attention chunk partials a row; the own sequence's first. pub fn init(d: *const cuda.Driver, c: Config, max_len: usize, nch: usize, carve: ?*cuda.Carveout) !Buffers { @@ -343,11 +347,11 @@ pub const Buffers = struct { /// Every scratch field, in scratchSizes' order. fn scratchPtrs(b: *Buffers) [scratch_count]*u64 { return .{ - &b.logits, &b.p_meta, &b.p_ids, &b.p_hidden, &b.p_logits, &b.p_sampled, &b.emb, &b.h[0], &b.h[1], &b.y, - &b.xs, &b.delta, &b.proj, &b.p_xc, &b.sy, &b.g, &b.gxs, &b.qkv, &b.q, &b.att, - &b.axs, &b.po, &b.pm, &b.pl, &b.part, &b.pick, &b.wts, &b.plan.members, &b.plan.items, &b.plan.counts, - &b.plan.rank, &b.plan.hist, &b.act, &b.ymoe, &b.shared, &b.pocket, &b.lat, &b.comb, &b.sact, &b.sids, - &b.job, &b.ck8, &b.ck4, &b.lane_part, + &b.logits, &b.p_meta, &b.p_ids, &b.p_hidden, &b.p_logits, &b.p_sampled, &b.emb, &b.h[0], &b.h[1], &b.y, + &b.xs, &b.delta, &b.proj, &b.p_xc, &b.sy, &b.g, &b.gxs, &b.qkv, &b.q, &b.att, + &b.axs, &b.po, &b.pm, &b.pl, &b.part, &b.pick, &b.wts, &b.plan.members, &b.plan.items, &b.plan.counts, + &b.plan.rank, &b.plan.hist, &b.act, &b.ymoe, &b.shared, &b.pocket, &b.lat, &b.comb, &b.sact, &b.sids, + &b.job, &b.ck8, &b.ck4, &b.lane_part, &b.draw_rules, &b.draw_meta, &b.draw_tokens, }; } diff --git a/zig/src/families/nemotron/cuda_subset_batch_test.zig b/zig/src/families/nemotron/cuda_subset_batch_test.zig index ca131f480da..927e0fe336c 100644 --- a/zig/src/families/nemotron/cuda_subset_batch_test.zig +++ b/zig/src/families/nemotron/cuda_subset_batch_test.zig @@ -5,6 +5,11 @@ const lanes = @import("lanes"); const Engine = @import("cuda_engine.zig").Engine; const mtp = @import("cuda_mtp.zig"); const Head = mtp.Head; +const kern = @import("cuda_kernels.zig"); +const sampler = @import("cuda_sampler.zig"); +const shared_draw = @import("cuda_shared_draw.zig"); +const Config = @import("config.zig").Config; +const weights = @import("cuda_weights.zig"); const Backend = @import("cuda_lanes.zig").Cuda; const reuse = @import("cuda_reuse.zig"); const common = @import("cuda_subset_restore_test.zig"); @@ -65,6 +70,9 @@ const Frame = struct { } @memset(mem(u16, head.logits)[0..272], 0xffff); } + fn region(ptr: u64, len: usize) []u8 { + return @as([*]u8, @ptrFromInt(ptr))[0..len]; + } fn arg(comptime T: type, args: [*]?*anyopaque, at: usize) T { return @as(*const T, @ptrCast(@alignCast(args[at].?))).*; } @@ -76,9 +84,53 @@ const Frame = struct { const e = col % 2 + 2 * ((col % 16) / 8); return ((((tg * 8 + jj) * 4 + kt) * 32 + lane) * 4 + e); } - fn kernel(f: cuda.abi.Function, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: cuda.abi.Stream, params: ?[*]?*anyopaque, _: ?[*]?*anyopaque) callconv(.c) cuda.abi.Result { + fn kernel(f: cuda.abi.Function, gx: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: cuda.abi.Stream, params: ?[*]?*anyopaque, _: ?[*]?*anyopaque) callconv(.c) cuda.abi.Result { const args = params.?; - if (@intFromPtr(f) == 1) { + const handle = @intFromPtr(f); + if (handle == 4) { // gather rows + const g = arg(kern.GatherRows, args, 0); + const dst_a = arg(u64, args, 1); + const dst_b = arg(u64, args, 2); + for (0..gx) |r| { + var k: usize = 0; + while (k < 8 and !(r >= @as(usize, @intCast(g.row0[k])) and r < @as(usize, @intCast(g.row0[k])) + @as(usize, @intCast(g.rows[k])))) : (k += 1) {} + if (k == 8) continue; + const at = r - @as(usize, @intCast(g.row0[k])); + const wa: usize = @intCast(g.wa); + const wb: usize = @intCast(g.wb); + @memcpy(region(dst_a + r * wa, wa), region(g.a[k] + at * wa, wa)); + if (g.b[k] != 0) @memcpy(region(dst_b + r * wb, wb), region(g.b[k] + at * wb, wb)); + } + return 0; + } + if (handle == 5) { // gather last + const g = arg(kern.LastRows, args, 0); + const dst_a = arg(u64, args, 1); + const dst_b = arg(u64, args, 2); + const wa: usize = @intCast(arg(i32, args, 3)); + const wb: usize = @intCast(arg(i32, args, 4)); + const n: usize = @intCast(arg(i32, args, 5)); + for (0..n) |k| { + @memcpy(region(dst_a + k * wa, wa), region(g.a[k], wa)); + if (g.b[k] != 0) @memcpy(region(dst_b + k * wb, wb), region(g.b[k], wb)); + } + return 0; + } + if (handle == 6) { // scatter rows + const tok = arg(u64, args, 0); + const prob = arg(u64, args, 1); + const g = arg(kern.ScatterRows, args, 2); + for (0..gx) |r| { + var k: usize = 0; + while (k < 8 and !(r >= @as(usize, @intCast(g.row0[k])) and r < @as(usize, @intCast(g.row0[k])) + @as(usize, @intCast(g.rows[k])))) : (k += 1) {} + if (k == 8) continue; + const at = r - @as(usize, @intCast(g.row0[k])); + mem(u32, g.tok[k])[@as(usize, @intCast(g.tok_at)) + at] = mem(u32, tok)[r]; + mem(f32, g.prob[k])[@as(usize, @intCast(g.prob_at)) + at] = mem(f32, prob)[r]; + } + return 0; + } + if (handle == 1) { const x = mem(u16, arg(u64, args, 0)); const w = mem(u16, arg(u64, args, 1)); const out = mem(u16, arg(u64, args, 4)); @@ -115,7 +167,7 @@ const Frame = struct { pick = @intCast(c); }; const out = arg(u64, args, 5); - errors += @intFromBool(out != @intFromPtr(&buffers[slot].ids) + level * 4); + errors += @intFromBool(out != @intFromPtr(&buffers[slot].ids) + level * 4 and out != h.tok_rows + draws * 4); const ids = if (subset) mem(u32, arg(u64, args, 6)) else null; mem(u32, out)[0] = if (ids) |table| table[pick] else pick; const prob = arg(u64, args, if (subset) 7 else 6); @@ -134,14 +186,29 @@ const Frame = struct { const Scratch = struct { pinned: [5000]u32 align(16) = @splat(0), meta: [33]u32 = @splat(0), - metas: [66]u32 = @splat(0), - hin: [2 * D]u16 = @splat(0), - tok: [2]u32 = @splat(0), - row: [2 * D]u16 = @splat(0), - outs: [2 * D]u16 = @splat(0), + metas: [8 * 33]u32 = @splat(0), + hin: [8 * D]u16 = @splat(0), + tok: [8]u32 = @splat(0), + row: [8 * D]u16 = @splat(0), + outs: [8 * D]u16 = @splat(0), out: [D]u16 = @splat(0), - logits: [272]u16 = @splat(0xffff), - xs: [2]f32 = @splat(0), + logits: [8 * 128]u16 = @splat(0xffff), + rules: [8 * 8]u32 align(8) = @splat(0), + pos_slab: [8]u32 = @splat(0), + tok_rows: [8]u32 = @splat(0), + prob_rows: [8]f32 = @splat(0), + flog: [8 * 64]f32 = @splat(0), + vals: [8 * 28]f32 = @splat(0), + cols: [8 * 28]i64 = @splat(0), + cand: [8 * 28]i64 = @splat(0), + topk: [9000]u8 align(16) = @splat(0), + invalid: [1]u32 = @splat(0), + fp: [1]u32 = @splat(0), + probs: [8]f32 = @splat(0), + own_ids: [8][2]u32 = @splat(@splat(0)), // a part's tokens, a level each + own_probs: [8][2]f32 = @splat(@splat(0)), // a part's probabilities, a level each + atok: [8]u32 = @splat(0), + rxs: [8]f32 = @splat(0), fn head(s: *Scratch, e: *Engine, d: *cuda.Driver) Head { var h: Head = undefined; h.e = e; @@ -152,11 +219,11 @@ const Scratch = struct { h.absorb_graphs = @splat(null); h.first_graphs = @splat(@splat(null)); h.chain_graphs = @splat(@splat(null)); - inline for (.{ "meta", "metas", "hin", "tok", "row", "outs", "out", "logits" }) |field| @field(h, field) = @intFromPtr(&@field(s, field)); - h.rxs = @intFromPtr(&s.xs); + inline for (.{ "meta", "metas", "hin", "tok", "row", "outs", "out", "logits", "rules", "pos_slab", "tok_rows", "prob_rows", "flog", "vals", "cols", "cand", "topk", "invalid", "fp", "probs", "atok", "rxs" }) |field| @field(h, field) = @intFromPtr(&@field(s, field)); return h; } }; + fn request(s: *lanes.Stream, depth: u32) lanes.backend.DraftRequest { return .{ .stream = s, .follow = &.{}, .first = .{ .value = 1 }, .rows = null, .start = s.prompt_len, .position = s.prompt_len + 1, .depth = depth }; } @@ -196,6 +263,9 @@ test "restored head: 15 and 16 token transitions reach mixed shrinking real chai e.k.modelopt = .{ .lane = lane, .gemm = undefined, .experts = undefined, .pack = undefined }; e.k.draws.draw_fn = .{ .d = &d, .handle = @ptrFromInt(2) }; e.k.draws.draw_ids_fn = .{ .d = &d, .handle = @ptrFromInt(3) }; + e.k.gather_rows = .{ .d = &d, .handle = @ptrFromInt(4) }; + e.k.gather_last = .{ .d = &d, .handle = @ptrFromInt(5) }; + e.k.scatter_rows = .{ .d = &d, .handle = @ptrFromInt(6) }; e.b = undefined; e.b.lane_part = 0; e.w.draft_count = 64; @@ -305,3 +375,145 @@ test "restored head: 15 and 16 token transitions reach mixed shrinking real chai } for (Fake.used) |live| try t.expect(!live); } + +const Count = struct { + var draw: usize = 0; + var entries: [4]usize = @splat(0); + var levels: usize = 0; + fn reset() void { + draw = 0; + entries = @splat(0); + levels = 0; + } + fn kernel(f: cuda.abi.Function, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: cuda.abi.Stream, _: ?[*]?*anyopaque, _: ?[*]?*anyopaque) callconv(.c) cuda.abi.Result { + const h = @intFromPtr(f); + if (h >= 2 and h <= 13) draw += 1; + return 0; + } + fn network(_: *Head, _: []const mtp.Span, tail: bool) !void { + if (!tail) return; + entries[levels] = draw; + levels += 1; + } +}; + +test "batched draws: eight parts take 15 or fewer greedy draw-side launches a level and 2 sampled" { + var d = Fake.driver(); + d.api.cuLaunchKernel = Count.kernel; + const ctx: cuda.Context = .{ .d = &d, .handle = null, .device = 0 }; + cuda.copy_source.setCurrent(null); + const e = try t.allocator.create(Engine); + defer t.allocator.destroy(e); + Fake.e = e; + Fake.used = @splat(false); + e.* = undefined; + e.gpa = t.allocator; + e.ctx = &ctx; + e.stream = .{ .d = &d, .handle = null }; + defer e.stream.synchronize() catch unreachable; + e.c = std.mem.zeroes(Config); + e.c.hidden = D; + e.c.kv_heads = 1; + e.c.head_dim = 1; + e.c.layers = 1; + e.c.kinds[0] = .attention; + e.c.vocab = 128; + e.max_len = 64; + e.nch = 1; + e.sampling = null; + e.own = undefined; + e.own.untaught = false; + e.bound = &e.own; + e.side = undefined; + e.tp = null; + e.vision = null; + e.slot = 0; + var bufs: @import("cuda_state.zig").Buffers = undefined; + bufs.lane_part = 0; + bufs.ck8 = 0; + e.b = bufs; + e.k.d = &d; + e.k.triton = null; + e.k.ck = null; + e.k.ggml = null; + const f10: cuda.Function = .{ .d = &d, .handle = @ptrFromInt(10) }; + const f1: cuda.Function = .{ .d = &d, .handle = @ptrFromInt(1) }; + const lane: cuda.qmmf.Lane = .{ .mod = undefined, .fns = @splat(@splat(f1)), .f32_fns = @splat(@splat(f1)), .reduce = @splat(f1), .half = @splat(@splat(@splat(f1))), .half_below = 0, .clusters = false }; + e.k.modelopt = .{ .lane = lane, .gemm = undefined, .experts = undefined, .pack = undefined }; + e.k.torch = .{ .argmax = f10, .hist = f10, .digit = f10, .count = f10, .prefix = f10, .compact = f10, .to_f32 = f10, .lookup = f10, .strided = f10, .mamba_a = f10 }; + e.k.glue = undefined; + e.k.glue.keyed = .{ .d = &d, .handle = @ptrFromInt(11) }; + e.k.draws = undefined; + e.k.draws.draw_fn = .{ .d = &d, .handle = @ptrFromInt(2) }; + e.k.draws.draw_ids_fn = .{ .d = &d, .handle = @ptrFromInt(3) }; + e.k.draws.draw_ids_rows_fn = .{ .d = &d, .handle = @ptrFromInt(12) }; + e.k.gather_rows = .{ .d = &d, .handle = @ptrFromInt(20) }; + e.k.gather_last = .{ .d = &d, .handle = @ptrFromInt(21) }; + e.k.scatter_rows = .{ .d = &d, .handle = @ptrFromInt(13) }; + e.w = undefined; + e.w.draft_count = 64; + var ids: [64]u32 = undefined; + for (&ids, 0..) |*id, i| id.* = @intCast(i); + e.w.draft_ids = @intFromPtr(&ids); + e.w.draft_coverage = null; + var raw: [128 * D]u16 = @splat(0); + var dense: [128 * D]u16 = undefined; + cuda.qmmf.packBf16(&dense, &raw, 128, D); + e.w.head = .{ .bf16 = .{ .mode = .bf16, .codes = @intFromPtr(&dense), .scales = 0, .n = 128, .k = D, .npad = 128 } }; + e.w.draft_head = .{ .bf16 = .{ .mode = .bf16, .codes = @intFromPtr(&dense), .scales = 0, .n = 64, .k = D, .npad = 128 } }; + var scratch: Scratch = .{}; + var h = scratch.head(e, &d); + e.head = &h; + Head.test_network = Count.network; + defer Head.test_network = null; + var parts: [8]mtp.Part = undefined; + const rule = sampler.rule(.{ .seed = 1, .temperature = 1, .top_k = 1 }); + for (&parts, 0..) |*p, k| p.* = .{ .k_cache = @intFromPtr(&scratch.meta), .v_cache = @intFromPtr(&scratch.meta), .table = 0, .probs = @intFromPtr(&scratch.own_probs[k][0]), .ids = @intFromPtr(&scratch.own_ids[k][0]), .hidden = @intFromPtr(&scratch.hin), .sampled = @intFromPtr(&scratch.own_ids[k][0]), .rule = null, .pos = 0, .keep = 1, .depth = 2, .vocab = .subset, .rule_host = null }; + Count.reset(); + try h.chains(&parts); + try t.expectEqual(@as(usize, 2), Count.levels); + try t.expectEqual(@as(usize, 15), Count.entries[1] - Count.entries[0]); + try t.expectEqual(@as(usize, 15), Count.draw - Count.entries[1]); + for (&parts) |*p| { + p.rule = @intFromPtr(&scratch.rules); + p.rule_host = rule; + } + Count.reset(); + try h.chains(&parts); + try t.expectEqual(@as(usize, 2), Count.levels); + try t.expectEqual(@as(usize, 2), Count.entries[1] - Count.entries[0]); + try t.expectEqual(@as(usize, 2), Count.draw - Count.entries[1]); +} + +test "shared draw: a batch is refused when the modes differ and carries the rows' rules when they match" { + var words: [1024]u32 align(16) = @splat(0); + const pinned: cuda.HostBuffer = .{ .d = undefined, .bytes = std.mem.sliceAsBytes(&words) }; + const greedy = [_]shared_draw.SharedDraw{ .{ .sampling = null, .pos = 5, .rows = 1 }, .{ .sampling = null, .pos = 6, .rows = 1 } }; + try t.expect(!shared_draw.batch(&greedy, pinned, 100, 200, 300, 0, 64).?.sampled); + const s: @import("lanes").Sampling = .{ .seed = 7, .temperature = 1, .top_k = 1 }; + const sampled = [_]shared_draw.SharedDraw{ .{ .sampling = s, .pos = 5, .rows = 1 }, .{ .sampling = s, .pos = 6, .rows = 1 } }; + const b = shared_draw.batch(&sampled, pinned, 100, 200, 300, 0, 64).?; + try t.expect(b.sampled); + try t.expectEqual(@as(usize, 64), b.host_rules.len); + try t.expectEqual(@as(i32, 5), b.host_meta[0]); + try t.expectEqual(@as(i32, 6), b.host_meta[1]); + const mixed = [_]shared_draw.SharedDraw{ .{ .sampling = null, .pos = 5, .rows = 1 }, .{ .sampling = s, .pos = 6, .rows = 1 } }; + try t.expect(shared_draw.batch(&mixed, pinned, 100, 200, 300, 0, 64) == null); +} + +test "shared draw: a multi-row batch carries every row's rule and position" { + var words: [1024]u32 align(16) = @splat(0); + const pinned: cuda.HostBuffer = .{ .d = undefined, .bytes = std.mem.sliceAsBytes(&words) }; + const a: lanes.Sampling = .{ .seed = 11, .temperature = 1, .top_k = 5 }; + const b: lanes.Sampling = .{ .seed = 22, .temperature = 0.7, .top_k = 9 }; + const parts = [_]shared_draw.SharedDraw{ + .{ .sampling = a, .pos = 10, .rows = 1 }, + .{ .sampling = b, .pos = 20, .rows = 2 }, + .{ .sampling = a, .pos = 30, .rows = 1 }, + }; + const got = shared_draw.batch(&parts, pinned, 100, 200, 300, 0, 64).?; + try t.expectEqual(@as(usize, 4 * 8 * 4), got.host_rules.len); + const want = [_]sampler.Rule{ sampler.rule(a), sampler.rule(b), sampler.rule(b), sampler.rule(a) }; + for (want, 0..) |r, row| try t.expectEqualSlices(u8, std.mem.asBytes(&r), got.host_rules[row * 32 ..][0..32]); + try t.expectEqualSlices(i32, &.{ 10, 20, 21, 30 }, got.host_meta); +} diff --git a/zig/src/families/nemotron/cuda_vision.zig b/zig/src/families/nemotron/cuda_vision.zig index a7b00df8cac..abb7b8ba4a6 100644 --- a/zig/src/families/nemotron/cuda_vision.zig +++ b/zig/src/families/nemotron/cuda_vision.zig @@ -70,6 +70,7 @@ pub const Vision = struct { v.end(); if (images.len == 0) return; v.spans = try radio.plan(v.gpa, images, @intCast(from)); + errdefer v.end(); if (radio.rows.total(v.spans) > v.rows.limit) return error.ImageRows; if (v.encoder) |x| return x.encode(x.ctx, s, images, v.spans, &v.rows); try v.tower.encode(s, images, v.spans, &v.rows); diff --git a/zig/src/families/nemotron/cuda_vision_test.zig b/zig/src/families/nemotron/cuda_vision_test.zig index da23f0652d6..4ea8154ac60 100644 --- a/zig/src/families/nemotron/cuda_vision_test.zig +++ b/zig/src/families/nemotron/cuda_vision_test.zig @@ -1,5 +1,6 @@ -//! Actual Vision.begin reaches a no-CUDA tower shape sentinel after checking the production reservation. +//! Image setup lifetime through the real Vision methods and host-only encoders. const std = @import("std"); +const cuda = @import("cuda"); const vision = @import("cuda_vision.zig"); const radio = @import("radio"); const lanes = @import("lanes"); @@ -16,7 +17,7 @@ test "low independent image and video budgets reach the actual tower boundary" { const count = c[2] / 256; for (images[0..count], 0..) |*img, i| img.* = .{ .pixels = &.{}, .gh = 32, .gw = 32, .tokens = 256, .at = @intCast(1 + i * 300) }; try std.testing.expectError(error.RowShape, v.begin(undefined, images[0..count], 0)); - try std.testing.expectEqual(c[2], radio.rows.total(v.spans)); + try std.testing.expectEqual(@as(usize, 0), v.spans.len); } } @@ -24,3 +25,97 @@ test "reservation rejects overflow and keeps image-only budget" { try std.testing.expectError(error.BadVisionLimits, vision.reservation(.{ .image_tokens = 1, .video_tokens = std.math.maxInt(u32), .max_images = 1 }, true)); try std.testing.expectEqual(@as(u32, 256), try vision.reservation(.{ .image_tokens = 256, .video_tokens = 512, .max_images = 1 }, false)); } + +const request_images = [_]lanes.stream.Image{ + .{ .pixels = &.{}, .gh = 4, .gw = 4, .tokens = 4, .at = 1 }, + .{ .pixels = &.{}, .gh = 4, .gw = 4, .tokens = 4, .at = 7 }, +}; + +const Encode = struct { + calls: usize = 0, + rows: u32 = 0, + fail: bool = false, + + fn run(ctx: *anyopaque, _: cuda.Stream, _: []const lanes.stream.Image, spans: []const radio.Span, _: *const radio.Rows) anyerror!void { + const e: *Encode = @ptrCast(@alignCast(ctx)); + e.calls += 1; + e.rows = radio.rows.total(spans); + if (e.fail) return error.EncodeFailed; + } +}; + +fn fixture(gpa: std.mem.Allocator, encoder: *Encode, limit: u32) vision.Vision { + return .{ + .gpa = gpa, + .io = undefined, + .cfg = undefined, + .tower = undefined, + .rows = .{ .d = undefined, .buf = undefined, .hidden = 1, .limit = limit }, + .marks = undefined, + .limits = undefined, + .mark_ids = undefined, + .encoder = .{ .ctx = encoder, .encode = Encode.run }, + }; +} + +test "image rows refusal clears spans before a text pass" { + var encoder: Encode = .{}; + var v = fixture(std.testing.allocator, &encoder, 7); + defer v.end(); + try std.testing.expectError(error.ImageRows, v.begin(undefined, &request_images, 0)); + try std.testing.expectEqual(@as(usize, 0), encoder.calls); + try std.testing.expectEqual(@as(usize, 0), v.spans.len); + try v.splice(undefined, 0, 20, 0); +} + +test "image encoder failure clears spans before a text pass and retry" { + var encoder: Encode = .{ .fail = true }; + var v = fixture(std.testing.allocator, &encoder, 8); + defer v.end(); + for (1..4) |attempt| { + try std.testing.expectError(error.EncodeFailed, v.begin(undefined, &request_images, 0)); + try std.testing.expectEqual(attempt, encoder.calls); + try std.testing.expectEqual(@as(u32, 8), encoder.rows); + try std.testing.expectEqual(@as(usize, 0), v.spans.len); + try v.splice(undefined, 0, 20, 0); + } + encoder.fail = false; + try v.begin(undefined, &request_images, 0); + try std.testing.expectEqual(@as(usize, 4), encoder.calls); + try std.testing.expectEqual(@as(u32, 8), radio.rows.total(v.spans)); +} + +test "image success retains only the active prompt spans" { + var encoder: Encode = .{}; + var v = fixture(std.testing.allocator, &encoder, 8); + defer v.end(); + try v.begin(undefined, &request_images, 0); + try std.testing.expectEqual(@as(u32, 8), encoder.rows); + try std.testing.expectEqual(@as(u32, 8), radio.rows.total(v.spans)); + try v.begin(undefined, &request_images, 5); + try std.testing.expectEqual(@as(usize, 2), encoder.calls); + try std.testing.expectEqual(@as(u32, 4), encoder.rows); + try std.testing.expectEqualSlices(radio.Span, &.{.{ .at = 7, .n = 4, .row = 0, .image = 1 }}, v.spans); + try v.begin(undefined, &.{}, 0); + try std.testing.expectEqual(@as(usize, 2), encoder.calls); + try std.testing.expectEqual(@as(usize, 0), v.spans.len); + try v.splice(undefined, 0, 20, 0); +} + +fn allocationTrial(gpa: std.mem.Allocator) !void { + var encoder: Encode = .{}; + var v = fixture(gpa, &encoder, 8); + defer v.end(); + for (0..2) |_| { + v.begin(undefined, &request_images, 0) catch |err| { + try std.testing.expectEqual(@as(usize, 0), v.spans.len); + try v.splice(undefined, 0, 20, 0); + return err; + }; + try std.testing.expectEqual(@as(u32, 8), radio.rows.total(v.spans)); + } +} + +test "image planning allocation failure releases the prior prompt spans" { + try std.testing.checkAllAllocationFailures(std.testing.allocator, allocationTrial, .{}); +} diff --git a/zig/src/families/qwen3_5/cuda.zig b/zig/src/families/qwen3_5/cuda.zig index 69c8496b607..c8a3b424085 100644 --- a/zig/src/families/qwen3_5/cuda.zig +++ b/zig/src/families/qwen3_5/cuda.zig @@ -21,6 +21,7 @@ pub const joint_schema = @import("cuda_joint_schema"); pub const stage = @import("cuda_stage.zig"); test { + _ = @import("cuda_projection_many.zig"); _ = @import("cuda_attention.zig"); _ = @import("cuda_prompt.zig"); _ = @import("cuda_prompt_tail.zig"); diff --git a/zig/src/families/qwen3_5/cuda_projection_many.zig b/zig/src/families/qwen3_5/cuda_projection_many.zig index 76b40b20446..b9c2142c9f8 100644 --- a/zig/src/families/qwen3_5/cuda_projection_many.zig +++ b/zig/src/families/qwen3_5/cuda_projection_many.zig @@ -20,6 +20,15 @@ pub fn projectMany(e: *Engine, ls: []const Proj, x: u64, xs: u64, outs: []const for (ls, outs, many[0..ls.len]) |l, out, *m| m.* = .{ .q = l.a4, .out = out }; return e.affine.promptMany(e.stream, x, many[0..ls.len], rows); } + const paired = allow_fused_prompt and qwen38PairShape(ls, rows, prompt, e.affine.pdl, e.int8.on) and blk: { + for (outs, 0..) |out, i| for (outs[i + 1 ..]) |other| if (out == other) break :blk false; + break :blk true; + }; + if (paired) { + for (ls[0..2], outs[0..2], 0..) |l, out, i| try e.project(l, x, xs, out, rows, prompt, params, sums and i == 0); + const pair = [_]A.Out{ .{ .q = ls[2].a4, .out = outs[2] }, .{ .q = ls[3].a4, .out = outs[3] } }; + return e.affine.promptMany(e.stream, x, &pair, rows); + } const segmented = (e.affine.split != null or e.affine.pdl) and !(prompt and rows > 16) and !(e.affine.pdl and prompt and e.int8.on) and ls.len <= A.segs_max and for (ls) |l| { if (l != .a4 or l.inputs() != ls[0].inputs()) break false; } else true; @@ -47,6 +56,36 @@ fn qwen38PromptShape(ls: []const Proj, rows: usize) bool { return ls[0].outputs() == 10240 and ls[1].outputs() == 6144 and ls[2].outputs() == 48 and ls[3].outputs() == 48; } +/// Large BF16 prompt DeltaNet inputs on the GB10's existing many tile; qkv and z keep their own launches. +fn qwen38PairShape(ls: []const Proj, rows: usize, prompt: bool, pdl: bool, int8: bool) bool { + if (!prompt or !pdl or int8 or rows < 2048 or ls.len != 4) return false; + for (ls, [_]usize{ 10240, 6144, 48, 48 }) |l, n| { + if (l != .a4 or l.inputs() != 5120 or l.outputs() != n) return false; + } + return true; +} + +test "Qwen3.8 pair shape: only large BF16 GDN prompts on GB10 admit the a and b pair" { + const delta = [_]Proj{ affine(10240), affine(6144), affine(48), affine(48) }; + for ([_]usize{ 0, 16, 256, 2047, 2048, 4096 }) |rows| { + for ([_]bool{ false, true }) |prompt| for ([_]bool{ false, true }) |pdl| for ([_]bool{ false, true }) |int8| { + try std.testing.expectEqual(rows >= 2048 and prompt and pdl and !int8, qwen38PairShape(&delta, rows, prompt, pdl, int8)); + }; + } + for (0..delta.len) |i| { + var other = delta; + other[i].a4.k = 4096; + try std.testing.expect(!qwen38PairShape(&other, 2048, true, true, false)); + other = delta; + other[i].a4.n += 1; + try std.testing.expect(!qwen38PairShape(&other, 2048, true, true, false)); + other[i] = .{ .bf = .{ .w = 0, .n = delta[i].outputs(), .k = 5120 } }; + try std.testing.expect(!qwen38PairShape(&other, 2048, true, true, false)); + } + try std.testing.expect(!qwen38PairShape(delta[0..3], 2048, true, true, false)); + try std.testing.expect(!qwen38PairShape(&.{ delta[0], delta[1], delta[2], delta[3], delta[3] }, 2048, true, true, false)); +} + pub fn qwen38LargePromptShape(n: usize, k: usize, rows: usize) bool { if (rows < 2048 or k != 5120) return false; return switch (n) { diff --git a/zig/src/native/cuda.zig b/zig/src/native/cuda.zig index 9dc4041ada5..f7349cfb7f5 100644 --- a/zig/src/native/cuda.zig +++ b/zig/src/native/cuda.zig @@ -36,6 +36,7 @@ pub const chip = cuda_device.chip; pub const deviceName = cuda_device.deviceName; /// `capabilities --json`'s "p2p": NVML's GPUs and pairs on a host with two or more; null otherwise. pub const p2p = cuda.p2p_report.compact; +pub const kernelSupport = cuda_device.kernelSupport; const getenv = cuda_device.getenv; const setting = cuda_device.setting; const windows = @import("cuda_window.zig"); diff --git a/zig/src/native/cuda_device.zig b/zig/src/native/cuda_device.zig index 384ed1c8f47..58721ac2c8b 100644 --- a/zig/src/native/cuda_device.zig +++ b/zig/src/native/cuda_device.zig @@ -58,3 +58,20 @@ test "variables: device settings share raw parsing without opening the driver" { try std.testing.expectError(error.InvalidEnvironment, settings.parse("TF_CUDA_DEVICE", "one")); try std.testing.expectError(error.InvalidEnvironment, settings.parse("TF_CUDA_DEVICE", "-1")); } + +pub const KernelSupport = struct { kernels: ?bool, sms: []const u32 }; + +/// Build coverage of the detected GPU; no context, module or checkpoint is opened. +pub fn kernelSupport(_: Allocator) KernelSupport { + const unknown = KernelSupport{ .kernels = null, .sms = cuda.kernels.target_sms }; + const ordinal = @import("sys").environment.read(u32, "TF_CUDA_DEVICE", 0) catch return unknown; + var driver = cuda.Driver.open() catch return unknown; + defer driver.close(); + return kernelSupportOn(&driver, std.math.cast(c_int, ordinal) orelse return unknown); +} + +/// The same query on an already-open driver, without retaining a context. +pub fn kernelSupportOn(driver: *const cuda.Driver, ordinal: c_int) KernelSupport { + const capability = driver.capability(ordinal) catch return .{ .kernels = null, .sms = cuda.kernels.target_sms }; + return .{ .kernels = cuda.kernels.supports(capability), .sms = cuda.kernels.target_sms }; +} diff --git a/zig/src/native/cuda_vision_offer.zig b/zig/src/native/cuda_vision_offer.zig index 70dea6b4382..7a3e00ac534 100644 --- a/zig/src/native/cuda_vision_offer.zig +++ b/zig/src/native/cuda_vision_offer.zig @@ -156,6 +156,8 @@ test "a tower whose template writes its own markers gets no wrapper; other tower } test "actual offer prepares bounded video and plans mixed rows through the shared Vision owner" { + const Vision = nemotron.native.vision.Vision; + const Span = @typeInfo(@FieldType(Vision, "spans")).pointer.child; var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const a = arena.allocator(); @@ -178,6 +180,7 @@ test "actual offer prepares bounded video and plans mixed rows through the share const pixels: [64 * 64 * 3]u8 = @splat(1); for (indices, 0..) |_, i| try sink.take(sink.ctx, i, &pixels, 64, 64, 64 * 3); } + fn encode(_: *anyopaque, _: @FieldType(nemotron.Engine, "stream"), _: []const api.Image, _: []const Span, _: *const @FieldType(Vision, "rows")) anyerror!void {} }; var dummy: u8 = 0; const prepared = try held.video.?.prepare(held.ctx, a, .{ .frames = 30, .rate_num = 30, .rate_den = 1, .width = 64, .height = 64, .ctx = &dummy, .decode = Fake.decode }, 512, 256); @@ -191,13 +194,19 @@ test "actual offer prepares bounded video and plans mixed rows through the share .{ .pixels = group.pixels, .gh = group.gh, .gw = group.gw, .tokens = group.tokens, .at = 10 }, .{ .pixels = group.pixels, .gh = group.gh, .gw = group.gw, .tokens = group.tokens, .at = 400 }, }; - try std.testing.expectError(error.RowShape, v.begin(undefined, &images, 0)); + v.encoder = .{ .ctx = &dummy, .encode = Fake.encode }; + try v.begin(undefined, &images, 0); try std.testing.expectEqual(@as(usize, 2), v.spans.len); try std.testing.expectEqual(@as(u32, 256), v.spans[1].row); - try std.testing.expectError(error.RowShape, v.begin(undefined, &images, 300)); + try v.begin(undefined, &images, 300); try std.testing.expectEqual(@as(usize, 1), v.spans.len); try std.testing.expectEqual(@as(u32, 1), v.spans[0].image); try std.testing.expectEqual(@as(u32, 0), v.spans[0].row); + v.encoder = null; + for ([_]usize{ 0, 300 }) |from| { + try std.testing.expectError(error.RowShape, v.begin(undefined, &images, from)); + try std.testing.expectEqual(@as(usize, 0), v.spans.len); + } try std.testing.expect(offer(@as(?*nemotron.native.vision.Vision, null), null) == null); } diff --git a/zig/src/native/metal.zig b/zig/src/native/metal.zig index f096becd7dd..6db453f5376 100644 --- a/zig/src/native/metal.zig +++ b/zig/src/native/metal.zig @@ -556,3 +556,22 @@ test "Metal capabilities: fish_omni retains FP8 and includes its native NVFP4 ex }; try std.testing.expect(fp8 and nvfp4); } + +test "plain sharing: Nemotron without a head shares streams without widening its window" { + var b: nemotron.backend.Metal = undefined; + b.o = .{ .capacity = 4096, .streams = 4, .batch_rows = 32, .drafts = false }; + b.head = null; + b.costs = .{}; + const facts = b.facts(); + try std.testing.expect(facts.plain_share and facts.hidden_rows); + try std.testing.expectEqual(@as(u32, 1), facts.exact_width); + try std.testing.expect(!facts.mtp and !facts.speculate and !facts.allocate_shared_drafts); + var config = try lanes.Config.init(std.testing.allocator, facts, nemotron.backend.max_window, nemotron.backend.max_window - 1); + defer config.deinit(std.testing.allocator); + try std.testing.expect(config.family_streams and config.pipelined); + try std.testing.expectEqual(@as(u32, 4), config.batch_streams); + try std.testing.expectEqual(@as(u32, 1), config.family_width); + try std.testing.expectEqual(@as(u32, 0), config.max_copy); + try std.testing.expectEqual(@as(u32, 0), config.most_drafts); + try std.testing.expect(!config.family_mtp); +} diff --git a/zig/src/platform/environment.zig b/zig/src/platform/environment.zig index c73ab2066f4..da45b7281d1 100644 --- a/zig/src/platform/environment.zig +++ b/zig/src/platform/environment.zig @@ -12,6 +12,7 @@ pub const Rule = struct { forms: []const u8, trim: []const u8 = "", first_digit: bool = false, + blank_default: bool = true, /// A whole number's own bounds inside its kind's; a real kind applies `max` too when it is set. min: u64 = 0, max: u64 = std.math.maxInt(u64), @@ -30,6 +31,7 @@ pub fn isReal(kind: Kind) bool { } pub const rules = [_]Rule{ + .{ .name = "TF_FLASHNEXT_BATCH_DRAWS", .scope = .cuda, .kind = .flag, .blank_default = false, .forms = "0 or 1 (0 restores per-stream Flash Next row draws; default 1)" }, .{ .name = "TF_STARTUP_RECEIPT", .scope = .common, .kind = .flag, .forms = "0 or 1 (opt-in startup and first completion receipts)" }, .{ .name = "TENSORFOLD_VIDEO_TOKENS", .scope = .common, .kind = .u64, .forms = "a nonnegative whole video-token budget (default 16384; unsigned 64-bit count)" }, .{ .name = "TENSORFOLD_MAX_PDF_PAGES", .scope = .common, .kind = .positive, .forms = "a whole number from 1 to 4294967295 (capped by --vision-max-images)" }, @@ -80,6 +82,7 @@ pub const rules = [_]Rule{ .{ .name = "TF_GLM_PDL", .scope = .glm, .kind = .flag, .forms = "0 or 1" }, .{ .name = "TF_GLM_PROMPT_STEPS", .scope = .glm, .kind = .flag, .forms = "0 or 1" }, .{ .name = "TF_GLM_SHARED", .scope = .glm, .kind = .flag, .forms = "0 or 1" }, + .{ .name = "TF_GLM_DSEL", .scope = .glm, .kind = .flag, .forms = "0 or 1" }, .{ .name = "TF_GLM_DFLASH2_LOG", .scope = .glm, .kind = .u64, .forms = "a whole unsigned 64-bit round count (0 logs no drafts)" }, .{ .name = "TF_GLM_DRAFT_CONFIDENCE", .scope = .glm, .kind = .real, .max = 1, .forms = "a finite chain-chance cut from 0 to 1 (default 0.7)" }, // 2^31 - 32: GLM's slots, the window and its 32 verify rows (glm/cuda_native.zig's capacity), keep i32 positions @@ -208,10 +211,10 @@ pub fn registered(comptime name: []const u8) void { @compileError(name ++ " has no row in platform/environment.zig"); } -/// Null means unset, empty or whitespace-only (main's readers used their defaults then), never malformed. +/// Null means unset, or blank when the row preserves a legacy blank default, never malformed. pub fn parse(name: []const u8, raw: ?[]const u8) Error!?u64 { const r = rule(name); - if (std.mem.trim(u8, raw orelse return null, " \t\r\n").len == 0) return null; + if (std.mem.trim(u8, raw orelse return null, " \t\r\n").len == 0) return if (r.blank_default) null else error.InvalidEnvironment; const text = std.mem.trim(u8, raw.?, r.trim); if (r.first_digit and (text[0] < '0' or text[0] > '9')) return error.InvalidEnvironment; if (r.kind == .word) { diff --git a/zig/src/platform/environment_test.zig b/zig/src/platform/environment_test.zig index aab423a84b2..ee7e88fd763 100644 --- a/zig/src/platform/environment_test.zig +++ b/zig/src/platform/environment_test.zig @@ -36,6 +36,8 @@ test "environment: every strict reader refuses bad text before opening a model, const Case = struct { name: []const u8, raw: []const u8, n: u64 }; const valid = [_]Case{ + .{ .name = "TF_FLASHNEXT_BATCH_DRAWS", .raw = "0", .n = 0 }, + .{ .name = "TF_FLASHNEXT_BATCH_DRAWS", .raw = "1", .n = 1 }, .{ .name = "TENSORFOLD_VIDEO_TOKENS", .raw = "0", .n = 0 }, .{ .name = "TENSORFOLD_VIDEO_TOKENS", .raw = "18446744073709551615", .n = std.math.maxInt(u64) }, .{ .name = "TENSORFOLD_MAX_PDF_PAGES", .raw = "4294967295", .n = std.math.maxInt(u32) }, @@ -117,7 +119,9 @@ test "environment: valid forms remain raw numbers before existing consumer clamp try t.expect(why == null); } for (e.rules) |r| { - for ([_][]const u8{ "", " ", "\t \n" }) |raw| try t.expectEqual(@as(?u64, null), try e.parse(r.name, raw)); + for ([_][]const u8{ "", " ", "\t \n" }) |raw| { + if (r.blank_default) try t.expectEqual(@as(?u64, null), try e.parse(r.name, raw)) else try t.expectError(error.InvalidEnvironment, e.parse(r.name, raw)); + } // own scope tests: deepseek_v41/env_validate_test.zig, glm/cuda_env_test.zig, environment_flashnext_test.zig if (r.scope == .dsv41 or r.scope == .glm or r.scope == .flashnext) continue; var covered = false; diff --git a/zig/src/platform/memory_policy.zig b/zig/src/platform/memory_policy.zig index 4a23fd679a5..022d1bd6812 100644 --- a/zig/src/platform/memory_policy.zig +++ b/zig/src/platform/memory_policy.zig @@ -1,5 +1,6 @@ //! The shared reserve inside a Metal residency or preflight bound. pub const margin: u64 = 2 << 30; +pub const linux_pressure = @import("memory_pressure_linux.zig"); extern "c" fn proc_pid_rusage(pid: c_int, flavor: c_int, buffer: *anyopaque) c_int; extern "c" fn getpid() c_int; @@ -7,6 +8,7 @@ extern "c" fn sysctlbyname(name: [*:0]const u8, old: ?*anyopaque, old_len: ?*usi /// The kernel's memory pressure level (1 normal, 2 warning, 4 critical); null where the OS gives none. pub fn pressure() ?u32 { + if (@import("builtin").os.tag == .linux) return linux_pressure.pressure(); if (@import("builtin").os.tag != .macos) return null; var level: u32 = 0; var len: usize = @sizeOf(u32); diff --git a/zig/src/platform/memory_pressure_linux.zig b/zig/src/platform/memory_pressure_linux.zig new file mode 100644 index 00000000000..cd86b98274c --- /dev/null +++ b/zig/src/platform/memory_pressure_linux.zig @@ -0,0 +1,91 @@ +//! Bounded Linux pressure readings; a healthy reclaimable page cache is not itself memory pressure. +const std = @import("std"); +const builtin = @import("builtin"); + +pub const Reading = struct { + total: u64, + available: u64, + some_avg10: f64, + full_avg10: f64, + + /// Experimental PSI levels: 1 normal, 2 warning, 4 critical; the governor owns recovery timing. + pub fn level(r: Reading) u32 { + if (r.full_avg10 >= 10) return 4; + if (r.some_avg10 >= 10 or r.full_avg10 >= 1) return 2; + return 1; + } +}; + +fn avg10(line: []const u8) ?f64 { + var words = std.mem.tokenizeAny(u8, line, " \t\r"); + _ = words.next(); + var found: ?f64 = null; + while (words.next()) |word| { + if (!std.mem.startsWith(u8, word, "avg10=")) continue; + if (found != null) return null; + const n = std.fmt.parseFloat(f64, word[6..]) catch return null; + if (!std.math.isFinite(n) or n < 0 or n > 100) return null; + found = n; + } + return found; +} + +/// Read both PSI rows and both meminfo fields; incomplete, duplicate or malformed required data stays unknown. +pub fn parse(psi: []const u8, meminfo: []const u8) ?Reading { + var some: ?f64 = null; + var full: ?f64 = null; + var rows = std.mem.tokenizeScalar(u8, psi, '\n'); + while (rows.next()) |line| { + var words = std.mem.tokenizeAny(u8, line, " \t\r"); + const name = words.next() orelse continue; + const dst = if (std.mem.eql(u8, name, "some")) &some else if (std.mem.eql(u8, name, "full")) &full else continue; + if (dst.* != null) return null; + dst.* = avg10(line) orelse return null; + } + var total: ?u64 = null; + var available: ?u64 = null; + rows = std.mem.tokenizeScalar(u8, meminfo, '\n'); + while (rows.next()) |line| { + var words = std.mem.tokenizeAny(u8, line, ": \t\r"); + const name = words.next() orelse continue; + const dst = if (std.mem.eql(u8, name, "MemTotal")) &total else if (std.mem.eql(u8, name, "MemAvailable")) &available else continue; + if (dst.* != null) return null; + const kib = std.fmt.parseInt(u64, words.next() orelse return null, 10) catch return null; + if (!std.mem.eql(u8, words.next() orelse return null, "kB") or words.next() != null) return null; + dst.* = std.math.mul(u64, kib, 1024) catch return null; + } + const t = total orelse return null; + const a = available orelse return null; + if (t == 0 or a > t) return null; + return .{ .total = t, .available = a, .some_avg10 = some orelse return null, .full_avg10 = full orelse return null }; +} + +fn readFile(root: []const u8, name: []const u8, buf: []u8) ?[]const u8 { + var path: [std.Io.Dir.max_path_bytes]u8 = undefined; + const z = std.fmt.bufPrintSentinel(&path, "{s}/{s}", .{ root, name }, 0) catch return null; + const fd = std.c.open(z, .{ .ACCMODE = .RDONLY, .CLOEXEC = true }); + if (fd < 0) return null; + defer _ = std.c.close(fd); + var used: usize = 0; + while (used < buf.len) { + const n = std.c.read(fd, buf[used..].ptr, buf.len - used); + if (n < 0) return null; + if (n == 0) return buf[0..used]; + used += @intCast(n); + } + return null; +} + +/// The same production reader on a planted proc root; no allocation and no retained bytes between readings. +pub fn readAt(root: []const u8) ?Reading { + if (comptime builtin.os.tag == .windows) return null; + var psi: [1024]u8 = undefined; + var mem: [16384]u8 = undefined; + const p = readFile(root, "pressure/memory", &psi) orelse return null; + const m = readFile(root, "meminfo", &mem) orelse return null; + return parse(p, m); +} + +pub fn pressure() ?u32 { + return (readAt("/proc") orelse return null).level(); +} diff --git a/zig/src/server/anthropic.zig b/zig/src/server/anthropic.zig index 0b961556b6c..8f4408100ac 100644 --- a/zig/src/server/anthropic.zig +++ b/zig/src/server/anthropic.zig @@ -51,6 +51,7 @@ fn countTokens(srv: *Server, cx: *Cx, chat: Value, client_thinking: bool) errors const thinking = try fields.thinkingFields(cx, chat, srv.effort_levels); const on = thinking.enable orelse srv.config.enable_thinking; cx.clear_thinking = thinking.clear; + cx.named_effort = fields.namedEffort(thinking.effort, srv.effort_levels); // as the chat route sets it const tools = try tool_specs.active(cx, chat.get("tools"), chat.get("tool_choice")); const msgs = try messages_mod.normalizeWith(cx, chat.get("messages"), "system", srv.needs_user_after_tool, srv.media()); const explicit_off = client_thinking and !(thinking.enable orelse true); @@ -86,7 +87,7 @@ pub fn post(srv: *Server, conn: *Conn, a: Allocator) void { reply.init() catch return; var wire: Wire = .{ .reply = &reply }; const format_name = translate_mod.formatName(prepared[1]); - openai.runNamed(srv, a, wire.out(), .{ .conn = conn }, true, prepared[0], format_name, translate_mod.thinkingSent(prepared[1])); + openai.runNamed(srv, a, wire.out(), .{ .conn = conn }, true, prepared[0], format_name, translate_mod.thinkingSent(prepared[1]), false); if (wire.opened or wire.status == null or conn.broken) return; const payload = wire.payload; if (wire.status.? != 200) { diff --git a/zig/src/server/auth_scope.zig b/zig/src/server/auth_scope.zig index e279b7a8bd8..6a8264edc7a 100644 --- a/zig/src/server/auth_scope.zig +++ b/zig/src/server/auth_scope.zig @@ -56,8 +56,8 @@ fn validLabel(label: []const u8) bool { return true; } -const listing = [_][]const u8{ "/models", "/v1/models", "/v1/voices" }; -const reading = [_][]const u8{ "/memory", "/v1/memory", "/metrics", "/v1/metrics", "/v1/load", "/stats", "/dashboard", "/v1/benchmark/manifest" }; +const listing = [_][]const u8{ "/models", "/v1/models", "/v1/voices", "/api/tags", "/api/ps", "/api/version" }; +const reading = [_][]const u8{ "/memory", "/v1/memory", "/metrics", "/v1/metrics", "/v1/load", "/stats", "/dashboard", "/v1/benchmark/manifest", "/api/show" }; const inferring = [_][]const u8{ "/chat/completions", "/v1/chat/completions", "/completions", "/v1/completions", "/messages", "/v1/messages", "/messages/count_tokens", "/v1/messages/count_tokens", @@ -65,6 +65,7 @@ const inferring = [_][]const u8{ "/detokenize", "/v1/detokenize", "/v1/audio/speech", "/v1/embeddings", "/v1/images/generations", "/decisions", "/v1/decisions", "/systemone", "/v1/systemone", "/rerank", "/v1/rerank", "/v1/ocr", + "/api/chat", "/api/generate", "/api/embed", "/api/show", }; /// A gated request a key may make: the route as the dispatcher reads it, matched exactly, never by suffix. diff --git a/zig/src/server/chat.zig b/zig/src/server/chat.zig index 2b44473aea3..24fa9d58c84 100644 --- a/zig/src/server/chat.zig +++ b/zig/src/server/chat.zig @@ -58,6 +58,7 @@ pub const Sink = struct { call: *const fn (ctx: *anyopaque, delta: Value) error{Closed}!void, /// Called only after admission, with cancellation and mailbox draining already guarded. begin: ?*const fn (ctx: *anyopaque, prompt_len: usize) error{Closed}!void = null, + tokens: ?*const fn (ctx: *anyopaque, offset: usize, ids: []const u32) error{Closed}!void = null, }; pub const Reply = struct { @@ -81,6 +82,8 @@ pub const Reply = struct { logprobs: ?Value = null, /// The tokens and target rows ``logprobs`` are projected from, once the route's tool policy is final. probability_rows: ?@import("logprob_parts.zig").Capture = null, + /// For a token stream, each ``logprobs`` entry's raw token position, in the same shape; null otherwise. + logprob_positions: ?Value = null, /// ``choices[0].prompt_logprobs`` (vLLM's form) for a request that asked; null otherwise. prompt_logprobs: ?Value = null, loop_stop: ?u32 = null, // the loop period when --loop-guard-stop ended the reply in its reasoning @@ -159,7 +162,9 @@ pub fn prepare(srv: *Server, cx: *Cx, input: Input, gone: anytype) Failure!Prepa const thinking = input.prompt == null and (flag(f, "enable_thinking") orelse srv.config.enable_thinking); const instruct = input.prompt == null and !thinking and !input.own; // a client's chat with thinking off may take --instruct-sampling's set const reasoning = thinking and srv.info.capability(.reasoning) and (srv.text.vtable.format != .kimi or input.prompt == null); // the prompt renders `thinking`; the reply reads `reasoning` - const effort = srv.effortFor(if (f.get("reasoning_effort")) |e| (if (e == .string) e.string else null) else null); + const asked = if (f.get("reasoning_effort")) |e| (if (e == .string) e.string else null) else null; + const effort = srv.effortFor(asked); + cx.named_effort = if (input.prompt == null) fields_mod.namedEffort(asked, srv.effort_levels) else null; // a raw prompt has no template cx.clear_thinking = flag(f, "clear_thinking"); cx.template_fields = f; const rendered = try prompt_mod.prepare(srv, cx, input, thinking, effort); @@ -266,7 +271,7 @@ pub fn generate(srv: *Server, cx: *Cx, prepared: Prepared, sink: ?Sink, gone: an }; srv.release(preparing, null); // a background request waits only while a foreground one prepares preparing = false; - var gen: Generation = .{ .srv = srv, .a = a, .box = &box, .id = id, .asked = input.cancel, .reply_id = input.id, .seed = if (request.sampling) |v| v.seed else null, .sink = sink, .thinking = prepared.reasoning or (srv.text.vtable.format != .kimi and srv.info.capability(.reasoning) and reply_text.isChannel(srv.markers)), .chat = input.prompt == null, .stops = .{ .strings = stops_opt.strings }, .ignore_eos = stops_opt.ignore_eos, .max_tokens = request.max_tokens, .tools = input.tools, .token_ids = prepared.token_ids, .lp = if (request.logprobs != null) .{} else null, .loop_stop = request.loop_stop, .single = flag(input.fields, "tool_call_single") orelse false }; + var gen: Generation = .{ .srv = srv, .a = a, .box = &box, .id = id, .asked = input.cancel, .reply_id = input.id, .seed = if (request.sampling) |v| v.seed else null, .sink = sink, .thinking = prepared.reasoning or (srv.text.vtable.format != .kimi and srv.info.capability(.reasoning) and reply_text.isChannel(srv.markers)), .chat = input.prompt == null, .stops = .{ .strings = stops_opt.strings }, .ignore_eos = stops_opt.ignore_eos, .max_tokens = request.max_tokens, .tools = input.tools, .token_ids = prepared.token_ids, .lp = if (request.logprobs != null) .{ .positions = if (sink) |s| s.tokens != null else false } else null, .loop_stop = request.loop_stop, .single = flag(input.fields, "tool_call_single") orelse false }; defer srv.noteRequest(prepared.prompt_len, cached_tokens.within(box.cached, prepared.prompt_len), gen.collected.items.len, box.stats.drafted, box.stats.accepted, box.stats.rounds, received, gen.first_ns, gen.last_ns, box.stats.prefill_seconds, if (box.stats.prefill_seconds != null) box.stats.queued_seconds else null); errdefer if (!gen.engine_done) gen.cancel(); // the engine writes to the mailbox until it says finished const result: Failure!Reply = blk: { diff --git a/zig/src/server/chat_generation.zig b/zig/src/server/chat_generation.zig index bbce5e35334..137db952be5 100644 --- a/zig/src/server/chat_generation.zig +++ b/zig/src/server/chat_generation.zig @@ -30,6 +30,12 @@ fn rowsOf(a: Allocator, key: []const u8, entries: Value) Allocator.Error!Value { return .{ .object = o }; } +/// `d`'s logprobs: the `key` entries `settled` holds and, for a token stream, their raw token positions. +fn putRows(a: Allocator, d: Value, settled: Value, key: []const u8) Allocator.Error!void { + try d.object.put(a, "logprobs", try rowsOf(a, key, settled.get(key).?)); + if (settled.get("positions")) |at| try d.object.put(a, "logprob_positions", try rowsOf(a, key, at.get(key).?)); +} + pub const Generation = struct { srv: *Server, a: Allocator, @@ -106,6 +112,13 @@ pub const Generation = struct { if (g.first_ns == null) g.first_ns = arrived; g.last_ns = arrived; const sink = g.sink orelse return; + if (sink.tokens) |tokens| { + tokens(sink.ctx, g.collected.items.len - landed, chunk[0..landed]) catch { + g.cancel(); + return error.Cancelled; + }; + g.wrote_ns = nowNs(g.srv.io); + } if (g.streaming_done) return; var fresh: std.ArrayList(u32) = .empty; for (chunk[0..landed]) |t| { @@ -143,13 +156,13 @@ pub const Generation = struct { const thought_rows = if (rows) |r| r.get("reasoning_content") else null; if (thought.len > 0 or thought_rows != null) { const d: Value = if (thought.len > 0) try deltaOf(g.a, "reasoning_content", thought) else .{ .object = try json.newObject(g.a) }; - if (thought_rows) |t| try d.object.put(g.a, "logprobs", try rowsOf(g.a, "reasoning_content", t)); + if (thought_rows != null) try putRows(g.a, d, rows.?, "reasoning_content"); try g.emit(sink, d); } const prose_rows: []Value = if (rows) |r| r.get("content").?.array else &.{}; if (delta.len > 0 or prose_rows.len > 0) { const d: Value = if (prose_rows.len > 0) try deltaOf(g.a, "content", delta) else .{ .string = delta }; - if (prose_rows.len > 0) try d.object.put(g.a, "logprobs", try rowsOf(g.a, "content", .{ .array = prose_rows })); + if (prose_rows.len > 0) try putRows(g.a, d, rows.?, "content"); try g.emit(sink, d); } if (g.calls) |*c| { @@ -307,7 +320,8 @@ pub const Generation = struct { const decode_tokens = g.collected.items.len -| 1; const runtime = try json.newObject(a); try runtime.put(a, "enable_thinking", .{ .bool = thinking }); - try runtime.put(a, "reasoning_effort", if (!thinking) .{ .string = "none" } else if (effort) |e| .{ .string = e } else .null); + // the effort the template heard: with thinking off, only one the request named + try runtime.put(a, "reasoning_effort", if (!thinking) .{ .string = cx.named_effort orelse "none" } else if (effort) |e| .{ .string = e } else .null); try runtime.put(a, "engine", .{ .string = g.srv.info.name }); try runtime.put(a, "tokens_per_second", .{ .float = if (decode_s > 0) @as(f64, @floatFromInt(decode_tokens)) / decode_s else 0 }); try runtime.put(a, "seconds", .{ .float = @max(0, decode_s) }); // the reply's decode seconds, as tokens_per_second divides them @@ -369,7 +383,7 @@ pub const Generation = struct { .speculative = .{ .object = spec }, .thinking = thinking, .effort = effort, - .probability_rows = if (g.lp) |l| .{ .tokens = content_tokens, .rows = l.rows.items, .thinking = g.thinking, .stops = g.stops, .closer = close, .sent = l.sent } else null, + .probability_rows = if (g.lp) |l| .{ .tokens = content_tokens, .rows = l.rows.items, .thinking = g.thinking, .stops = g.stops, .closer = close, .sent = l.sent, .positions = l.positions } else null, .prompt_logprobs = if (m.prompt_rows) |r| try @import("logprobs.zig").promptValue(g.srv, a, r) else null, .loop_stop = stopped, }; diff --git a/zig/src/server/cli.zig b/zig/src/server/cli.zig index 4b802a8a507..e1fa9bff666 100644 --- a/zig/src/server/cli.zig +++ b/zig/src/server/cli.zig @@ -18,6 +18,8 @@ pub const Flag = struct { native: bool = false, /// The values it honours when only some of the choices. native_values: ?[]const []const u8 = null, + /// The value names a file or folder: a config file's relative one is read from that file's folder (cli_config.zig). + path: bool = false, }; const backend_values: []const []const u8 = if (builtin.os.tag == .macos) &.{ "auto", "mlx" } else if (served("--backend=rocm")) &.{ "auto", "rocm" } else &.{ "auto", "cuda" }; @@ -43,16 +45,17 @@ pub const flags = [_]Flag{ .{ .name = "--allowed-origin", .kind = .append, .native = true }, .{ .name = "--allowed-controls", .native = true }, .{ .name = "--port", .native = true }, - .{ .name = "--unix-socket", .native = true }, + .{ .name = "--config", .native = true }, // a TOML file of these flags, read first (cli_config.zig) + .{ .name = "--unix-socket", .path = true, .native = true }, .{ .name = "--name", .native = true }, - .{ .name = "--chat-template", .native = true }, - .{ .name = "--voices", .native = true }, + .{ .name = "--chat-template", .path = true, .native = true }, + .{ .name = "--voices", .path = true, .native = true }, .{ .name = "--default-voice", .native = true }, } ++ @import("drama_cfg.zig").flags ++ @import("admission_cli.zig").flags ++ @import("connection_cli.zig").flags ++ [_]Flag{ .{ .name = "--alias", .kind = .append, .native = true }, .{ .name = "--name-priority", .kind = .append, .native = true }, .{ .name = "--api-key", .kind = .append, .native = true }, - .{ .name = "--api-key-file", .native = true }, + .{ .name = "--api-key-file", .path = true, .native = true }, .{ .name = "--metrics-open", .kind = .store_true, .native = true }, .{ .name = "--dashboard", .kind = .store_true, .native = true }, .{ .name = "--vision", .kind = .store_true, .native = true }, @@ -66,7 +69,7 @@ pub const flags = [_]Flag{ .{ .name = "--context", .native = true }, .{ .name = "--profile", .choices = &.{"stable"}, .native = true }, .{ .name = "--max-frames", .native = true }, - .{ .name = "--speed-up", .native = !cuda_build }, + .{ .name = "--speed-up", .path = true, .native = !cuda_build }, .{ .name = "--max-tokens", .native = true }, .{ .name = "--temperature", .native = true }, .{ .name = "--prompt-seed", .kind = .store_true, .native = true }, @@ -100,21 +103,21 @@ pub const flags = [_]Flag{ .{ .name = "--idle-unload", .native = true }, .{ .name = "--compact-at", .native = true }, .{ .name = "--compact-keep", .native = true }, - .{ .name = "--compact-memory", .native = true }, + .{ .name = "--compact-memory", .path = true, .native = true }, .{ .name = "--slide", .kind = .store_true, .native = true }, .{ .name = "--slide-drift-gate", .kind = .store_true, .native = true }, - .{ .name = "--slide-graph", .native = true }, + .{ .name = "--slide-graph", .path = true, .native = true }, .{ .name = "--drafter", .native = true }, .{ .name = "--drafter-bits", .choices = &.{ "0", "4" }, .native = true }, .{ .name = "--rope-yarn", .native = cuda_build }, - .{ .name = "--record", .native = true }, + .{ .name = "--record", .path = true, .native = true }, .{ .name = "--kv-cache", .choices = &.{ "bf16", "fp8" }, .native = true }, .{ .name = "--prompt-precision", .choices = &.{ "bf16", "int8" }, .native = true }, .{ .name = "--mtp-drafts", .native = served("--mtp-drafts") }, .{ .name = "--mtp-confidence", .native = served("--mtp-confidence") }, .{ .name = "--lane-kernels", .choices = &.{ "auto", "on", "off" } }, .{ .name = "--prompt-cache-gib", .native = true }, - .{ .name = "--prompt-cache-disk", .native = true }, + .{ .name = "--prompt-cache-disk", .path = true, .native = true }, .{ .name = "--prompt-cache-over-cap", .kind = .store_true, .native = true }, .{ .name = "--checkpoint-slots", .native = served("--checkpoint-slots") }, .{ .name = "--spill-gib", .native = served("--spill-gib") }, @@ -127,7 +130,7 @@ pub const flags = [_]Flag{ .{ .name = "--mlx-cache-gib" }, .{ .name = "--ssd-experts", .native = builtin.os.tag == .macos }, .{ .name = "--ple-on-ssd", .kind = .store_true, .native = builtin.os.tag == .macos }, - .{ .name = "--fsr-route-trace", .native = builtin.os.tag == .macos }, + .{ .name = "--fsr-route-trace", .path = true, .native = builtin.os.tag == .macos }, .{ .name = "--no-update-check", .kind = .store_true, .native = true }, .{ .name = "--backend", .choices = &.{ "auto", "mlx", "cuda", "rocm" }, .native = true, .native_values = backend_values }, .{ .name = "--tp", .choices = &.{ "1", "2", "4", "8" }, .native = served("--tp") }, @@ -146,14 +149,14 @@ pub const flags = [_]Flag{ .{ .name = "--loops", .native = cuda_build }, // a looped model's recurrent passes (Dory: 1 to 4) // the native server's own: shared prompt states (a harness) kept on disk for later sessions and servers .{ .name = "--learn", .kind = .store_true, .native = true }, - .{ .name = "--learn-dir", .native = true }, + .{ .name = "--learn-dir", .path = true, .native = true }, .{ .name = "--learn-gib", .native = true }, .{ .name = "--learn-min-free-gib", .native = true }, .{ .name = "--learn-conversations", .kind = .store_true, .native = true }, .{ .name = "--learn-daily-gib", .native = true }, // the native server's own: drafts copied from a record of the token ids earlier requests read and wrote .{ .name = "--recall", .kind = .store_true, .native = true }, - .{ .name = "--recall-dir", .native = true }, + .{ .name = "--recall-dir", .path = true, .native = true }, .{ .name = "--recall-gib", .native = true }, .{ .name = "--recall-read-only", .kind = .store_true, .native = true }, // the native server's own: Cortheon's reasoning program and server-run web research for every chat request @@ -266,7 +269,7 @@ pub const Args = struct { /// A usage error's message (argparse's ``error:`` line); the caller exits 2. pub const Usage = struct { message: []const u8 = "" }; -fn find(name: []const u8) ?Flag { +pub fn find(name: []const u8) ?Flag { for (flags) |f| if (std.mem.eql(u8, f.name, name)) return f; return null; } @@ -304,15 +307,8 @@ pub fn parse(a: Allocator, argv: []const []const u8, u: *Usage) error{ Usage, Ou return fail(u, a, "argument {s}: expected one argument", .{name}); value = argv[i]; } - // --profile names its own refusals (apply); other flags keep the table's generic invalid-choice line - if (flag.choices.len > 0 and !std.mem.eql(u8, name, "--profile")) for (flag.choices) |c| { - if (std.mem.eql(u8, c, value.?)) break; - } else return fail(u, a, "argument {s}: invalid choice: '{s}'", .{ name, value.? }); } else if (eq != null) return fail(u, a, "argument {s}: ignored explicit argument '{s}'", .{ name, token[eq.? + 1 ..] }); - if (!flag.native) return fail(u, a, "{s} is not served by the native engine yet; the Python engine 0.6.6 serves it: python -m pip install git+https://github.com/ashhart/TensorFold.git@v0.6.6", .{name}); - if (flag.native_values) |allowed| if (value) |v| for (allowed) |x| { - if (std.mem.eql(u8, x, v)) break; - } else return fail(u, a, "{s} {s} is not served by the native engine; the Python engine 0.6.6 serves it: python -m pip install git+https://github.com/ashhart/TensorFold.git@v0.6.6", .{ name, v }); + if (std.mem.eql(u8, name, "--config")) return fail(u, a, "argument --config: serve reads it before its other flags; it cannot appear here", .{}); if (std.mem.eql(u8, name, "--prompt-cache-disk")) { if (disk_legacy) |old| return fail(u, a, "argument {s}: not allowed with {s}", .{ name, old }); disk_named = true; @@ -321,7 +317,7 @@ pub fn parse(a: Allocator, argv: []const []const u8, u: *Usage) error{ Usage, Ou disk_legacy = name; } if (std.mem.eql(u8, name, "--host") or std.mem.eql(u8, name, "--port")) tcp_flag = name; - try apply(a, &out, name, value, u, &repeated); + try one(a, &out, &repeated, flag, value, u); } if (out.unix_socket != null) if (builtin.os.tag == .windows) return fail(u, a, "argument --unix-socket: not served on Windows", .{}) else if (tcp_flag) |t| return fail(u, a, "argument --unix-socket: not allowed with {s}", .{t}); out.model = model orelse return fail(u, a, "the following arguments are required: model", .{}); @@ -332,19 +328,10 @@ pub fn parse(a: Allocator, argv: []const []const u8, u: *Usage) error{ Usage, Ou out.redraw.validate(out.silence) catch |err| return fail(u, a, "invalid redraw configuration: {s}", .{@errorName(err)}); if (out.vision_urls and !out.vision) return fail(u, a, "--vision-urls needs --vision", .{}); if (out.vision_pdf and !out.vision) return fail(u, a, "--vision-pdf needs --vision", .{}); - if (out.idle_unload < 0 or out.idle_unload > std.math.maxInt(i64) / std.time.ns_per_s) return fail(u, a, "argument --idle-unload: expected a seconds count from 0 (off) under {d}: '{d}'", .{ std.math.maxInt(i64) / std.time.ns_per_s, out.idle_unload }); + try @import("cli_late.zig").check(a, out, &repeated, u); out.alias = repeated.alias.items; out.name_priority = repeated.priorities.items; - for (out.name_priority) |entry| { - const eq = std.mem.indexOfScalar(u8, entry, '=') orelse - return fail(u, a, "argument --name-priority: takes ID=background, not '{s}'", .{entry}); - const id = std.mem.trim(u8, entry[0..eq], " \t"); - const word = std.mem.trim(u8, entry[eq + 1 ..], " \t"); - if (id.len == 0 or !std.ascii.eqlIgnoreCase(word, "background")) - return fail(u, a, "argument --name-priority: takes ID=background, not '{s}'", .{entry}); - } out.api_key = repeated.keys.items; - if (repeated.hosts.items.len > 64 or repeated.origins.items.len > 64) return fail(u, a, "at most 64 --allowed-host and 64 --allowed-origin entries are allowed", .{}); out.allowed_host = repeated.hosts.items; out.allowed_origin = repeated.origins.items; if (out.slide_drift_gate and !out.slide) return fail(u, a, "--slide-drift-gate needs --slide", .{}); @@ -354,6 +341,19 @@ pub fn parse(a: Allocator, argv: []const []const u8, u: *Usage) error{ Usage, Ou return out; } +/// One flag's own checks and its effect on `out`; a config file's entry is checked with it before the merge. +pub fn one(a: Allocator, out: *Args, repeated: *Repeated, flag: Flag, value: ?[]const u8, u: *Usage) error{ Usage, OutOfMemory }!void { + // --profile names its own refusals (apply); other flags keep the table's generic invalid-choice line + if (value) |v| if (flag.choices.len > 0 and !std.mem.eql(u8, flag.name, "--profile")) for (flag.choices) |c| { + if (std.mem.eql(u8, c, v)) break; + } else return fail(u, a, "argument {s}: invalid choice: '{s}'", .{ flag.name, v }); + if (!flag.native) return fail(u, a, "{s} is not served by the native engine yet; the Python engine 0.6.6 serves it: python -m pip install git+https://github.com/ashhart/TensorFold.git@v0.6.6", .{flag.name}); + if (flag.native_values) |allowed| if (value) |v| for (allowed) |x| { + if (std.mem.eql(u8, x, v)) break; + } else return fail(u, a, "{s} {s} is not served by the native engine; the Python engine 0.6.6 serves it: python -m pip install git+https://github.com/ashhart/TensorFold.git@v0.6.6", .{ flag.name, v }); + try apply(a, out, flag.name, value, u, repeated); +} + /// --spill-gib writes to the conversation store: beside --learn's shared prefixes only with --learn-conversations. fn spillWith(u: *Usage, a: Allocator, out: Args) error{ Usage, OutOfMemory }!void { if (spills(out) and out.learn and !out.learn_conversations) return fail(u, a, "--spill-gib writes evicted states to the conversation store, which --learn's shared prefixes do not use: use --prompt-cache-disk DIR without --learn-dir, add --learn-conversations, or serve without --learn", .{}); @@ -378,7 +378,7 @@ pub fn gib(u: *Usage, a: Allocator, name: []const u8, v: []const u8) error{ Usag return g; } -const Repeated = struct { alias: std.ArrayList([]const u8) = .empty, priorities: std.ArrayList([]const u8) = .empty, keys: std.ArrayList([]const u8) = .empty, hosts: std.ArrayList([]const u8) = .empty, origins: std.ArrayList([]const u8) = .empty }; +pub const Repeated = struct { alias: std.ArrayList([]const u8) = .empty, priorities: std.ArrayList([]const u8) = .empty, keys: std.ArrayList([]const u8) = .empty, hosts: std.ArrayList([]const u8) = .empty, origins: std.ArrayList([]const u8) = .empty }; fn apply(a: Allocator, out: *Args, name: []const u8, value: ?[]const u8, u: *Usage, repeated: *Repeated) error{ Usage, OutOfMemory }!void { const v = value orelse ""; diff --git a/zig/src/server/cli_capabilities.zig b/zig/src/server/cli_capabilities.zig index f4427f39f76..25cdb05edfc 100644 --- a/zig/src/server/cli_capabilities.zig +++ b/zig/src/server/cli_capabilities.zig @@ -7,6 +7,8 @@ const cli = @import("cli.zig"); pub const Engines = struct { version: []const u8, chip: ?[]const u8 = null, + kernels: ?bool = null, + kernel_sms: ?[]const u32 = null, optional_libraries: []const @import("sys").optional_libraries.Status = &.{}, backends: []const []const u8 = &.{}, /// model_type to the weight formats it reads, as gate entries name them; `decisions` lists the decision-only ones. @@ -59,6 +61,14 @@ pub fn capabilities(w: *std.Io.Writer, e: Engines) !void { .available = [_][]const u8{"stable"}, .registered_switches = api.profile.entries, }, .{}, w); + if (e.kernel_sms) |sms| { + try w.writeAll(", \"kernels\": "); + try std.json.Stringify.value(e.kernels, .{}, w); + try w.writeAll(", \"kernel_sms\": "); + try std.json.Stringify.value(sms, .{}, w); + } + try w.writeAll(", \"token_stream_versions\": "); + try std.json.Stringify.value(@import("token_stream.zig").versions, .{}, w); if (e.p2p) |p| try w.print(", \"p2p\": {s}", .{p}); try w.writeAll("}\n"); } diff --git a/zig/src/server/cli_config.zig b/zig/src/server/cli_config.zig new file mode 100644 index 00000000000..fc3316ab9cd --- /dev/null +++ b/zig/src/server/cli_config.zig @@ -0,0 +1,239 @@ +//! ``serve --config FILE.toml``: the file's keys become serve flags ahead of the command line's, which then win. +const std = @import("std"); +const cli = @import("cli.zig"); +const toml = @import("toml_flat.zig"); +const auth = @import("auth.zig"); +const platform = @import("sys"); +const file_meta = @import("file_meta.zig").meta; +const Allocator = std.mem.Allocator; + +const Error = error{ Usage, OutOfMemory }; + +/// The largest file read, in bytes. +pub const limit = 1 << 20; + +pub const Expanded = struct { + /// What ``cli.parse`` reads. + argv: []const []const u8, + /// The file, when one was read. + path: ?[]const u8 = null, + /// The settings it held. + options: usize = 0, + /// The line that sets ``api-key``, or 0: such a file must be unreadable by other users. + secret: u32 = 0, +}; + +/// ``--config`` on the command line: its file, its place (`width` tokens from `at`) and whether a model is named. +pub const Found = struct { path: []const u8, at: usize, width: usize, model: bool }; + +/// ``serve``'s arguments with ``--config FILE.toml`` replaced by the file's flags, ahead of the command line's. +pub fn expand(a: Allocator, argv: []const []const u8, u: *cli.Usage) Error!Expanded { + const found = try locate(a, argv, u) orelse return .{ .argv = argv }; + const path = found.path; + // opened once: the handle that is checked is the one that is read, and a link is not followed + const fd = auth.openKeys(try a.dupeSentinel(u8, path, 0)) catch |e| + return cli.fail(u, a, "argument --config: cannot open {s} ({s}); name an existing file, not a link", .{ path, @errorName(e) }); + defer _ = platform.c.close(fd); + const st = file_meta(fd, null) orelse return cli.fail(u, a, "argument --config: cannot read the mode of {s}", .{path}); + if (st.mode & platform.c.S.IFMT != platform.c.S.IFREG) return cli.fail(u, a, "argument --config: {s} is not a regular file", .{path}); + if (st.mode & 0o022 != 0) + return cli.fail(u, a, "argument --config: {s} can be written by other users (mode 0{o}): it chooses what is served; use chmod go-w", .{ path, st.mode & 0o7777 }); + const text = try a.alloc(u8, limit + 1); + var got: usize = 0; + while (got < text.len) { + const n = auth.readKeys(fd, text[got..]) catch |e| return cli.fail(u, a, "argument --config: cannot read {s} ({s})", .{ path, @errorName(e) }); + if (n == 0) break; + got += n; + } + if (got > limit) return cli.fail(u, a, "argument --config: {s} is over 1 MiB", .{path}); + const out = try merge(a, argv, found, text[0..got], u); + if (out.secret != 0 and st.mode & 0o044 != 0) + return cli.fail(u, a, "argument --config: {s} line {d}: api-key is set in a file other users can read (mode 0{o}); use chmod 600, or api-key-file", .{ path, out.secret, st.mode & 0o7777 }); + return out; +} + +/// One argument of ``serve`` as ``cli.parse`` consumes it: a positional (no name), or a flag with its value. +const Step = struct { at: usize, width: usize = 1, name: ?[]const u8 = null, value: ?[]const u8 = null, valueless: bool = false }; + +/// ``serve``'s arguments, one flag or positional a step; an unknown flag takes no value (parse refuses it later). +const Walk = struct { + argv: []const []const u8, + i: usize = 0, + + fn next(w: *Walk) ?Step { + if (w.i >= w.argv.len) return null; + const at = w.i; + const token = w.argv[at]; + w.i += 1; + if (!std.mem.startsWith(u8, token, "--")) return .{ .at = at }; + const eq = std.mem.indexOfScalar(u8, token, '='); + const name = token[0 .. eq orelse token.len]; + const flag = cli.find(name) orelse return .{ .at = at, .name = name }; + if (flag.kind == .store_true) return .{ .at = at, .name = name }; + if (eq) |e| return .{ .at = at, .name = name, .value = token[e + 1 ..] }; + const disk = std.mem.eql(u8, name, "--prompt-cache-disk"); // parse refuses a flag as this one's directory + if (w.i >= w.argv.len or (disk and std.mem.startsWith(u8, w.argv[w.i], "--"))) return .{ .at = at, .name = name, .valueless = true }; + w.i += 1; + return .{ .at = at, .width = 2, .name = name, .value = w.argv[at + 1] }; + } +}; + +/// Where ``--config`` is, walking the arguments as ``cli.parse`` consumes them; null without one. +pub fn locate(a: Allocator, argv: []const []const u8, u: *cli.Usage) Error!?Found { + var found: ?Found = null; + var model = false; + var valueless: ?[]const u8 = null; // the first flag left without its value: removing --config must not repair it + var walk: Walk = .{ .argv = argv }; + while (walk.next()) |step| { + const name = step.name orelse { + model = true; + continue; + }; + if (step.valueless and valueless == null) valueless = name; + const value = step.value orelse continue; + if (!std.mem.eql(u8, name, "--config")) continue; + if (found != null) return cli.fail(u, a, "argument --config: given twice; a command reads one config file", .{}); + if (!std.ascii.endsWithIgnoreCase(value, ".toml")) + return cli.fail(u, a, "argument --config: expected a .toml file: '{s}'", .{value}); + found = .{ .path = value, .at = step.at, .width = step.width, .model = false }; + } + if (found == null) return null; + if (valueless) |name| return cli.fail(u, a, "argument {s}: expected one argument", .{name}); + found.?.model = model; + return found; +} + +/// The command line names `flag`, so a repeatable flag's list in the file gives way to it. +fn given(argv: []const []const u8, flag: cli.Flag) bool { + var walk: Walk = .{ .argv = argv }; + while (walk.next()) |step| if (step.name) |name| if (std.mem.eql(u8, name, flag.name)) return true; + return false; +} + +/// The file's text checked against the flag table and merged with the command line; it reads no file. +pub fn merge(a: Allocator, argv: []const []const u8, found: Found, text: []const u8, u: *cli.Usage) Error!Expanded { + var problem: toml.Problem = .{}; + const entries = toml.parse(a, text, &problem) catch |e| switch (e) { + error.OutOfMemory => |x| return x, + error.Invalid => return cli.fail(u, a, "argument --config: {s} line {d}: {s}", .{ found.path, problem.line, problem.message }), + }; + var out: std.ArrayList([]const u8) = .empty; + var seen: std.ArrayList([]const u8) = .empty; + var model: ?[]const u8 = null; + var secret: u32 = 0; + const base = std.fs.path.dirname(found.path); // the file's folder: where its relative paths start + for (entries) |entry| { + var scratch: cli.Args = .{}; // one entry's values, read as parse reads them, so its checks see the whole list + var repeated: cli.Repeated = .{}; + const at: Where = .{ .a = a, .u = u, .path = found.path, .line = entry.line, .scratch = &scratch, .repeated = &repeated }; + const key = try a.dupe(u8, entry.key); + std.mem.replaceScalar(u8, key, '_', '-'); + if (std.mem.eql(u8, key, "model")) { + if (entry.value != .scalar or entry.value.scalar != .string) return at.fail("model takes a string", .{}); + model = try anchored(a, base, entry.value.scalar.string); + if (std.mem.startsWith(u8, model.?, "--")) return at.fail("model cannot start with --, which parse reads as a flag: write a folder as ./{s}", .{model.?}); + continue; + } + if (std.mem.eql(u8, key, "config")) return at.fail("a config file cannot name another config file", .{}); + const flag = cli.find(try std.fmt.allocPrint(a, "--{s}", .{key})) orelse return at.fail("unknown key '{s}'", .{entry.key}); + if (!flag.native) return at.fail("{s} is not served by this build", .{flag.name}); + for (seen.items) |name| if (std.mem.eql(u8, name, flag.name)) return at.fail("{s} is set twice ('{s}' and its other spelling)", .{ flag.name, entry.key }); + try seen.append(a, flag.name); + if (std.mem.eql(u8, flag.name, "--api-key")) secret = entry.line; + const start = out.items.len; + switch (flag.kind) { + .store_true => { + if (entry.value != .scalar or entry.value.scalar != .boolean) return at.fail("{s} is a switch: use true or false", .{flag.name}); + if (try positive(a, flag)) |name| return at.fail("{s} has the switch {s}: write {s} = {s}", .{ flag.name, name, name[2..], if (entry.value.scalar.boolean) "false" else "true" }); + const on = if (entry.value.scalar.boolean) flag else try negative(a, flag) orelse continue; + try at.check(on, null); + try out.append(a, on.name); + }, + .value => switch (entry.value) { + .array => return at.fail("{s} takes one value, not a list", .{flag.name}), + .scalar => |s| try out.append(a, try at.valued(flag, base, s) orelse return at.fail("{s} takes a value, not true or false", .{flag.name})), + }, + .append => switch (entry.value) { + .array => |list| for (list) |item| try out.append(a, (try at.valued(flag, base, .{ .string = item })).?), + .scalar => |s| try out.append(a, try at.valued(flag, base, s) orelse return at.fail("{s} takes values, not true or false", .{flag.name})), + }, + } + // a repeatable flag the command line names replaces the file's list, so an old key or host does not stay + if (flag.kind == .append and given(argv, flag)) out.shrinkRetainingCapacity(start); + } + var merged: std.ArrayList([]const u8) = .empty; + if (!found.model) if (model) |m| try merged.append(a, m); + try merged.appendSlice(a, out.items); + try merged.appendSlice(a, argv[0..found.at]); + try merged.appendSlice(a, argv[found.at + found.width ..]); + return .{ .argv = merged.items, .path = found.path, .options = entries.len, .secret = secret }; +} + +/// The line ``serve`` adds under a usage error when a file was read, so a flag nobody typed has a source. +pub fn note(a: Allocator, e: Expanded) error{OutOfMemory}!?[]const u8 { + const path = e.path orelse return null; + return try std.fmt.allocPrint(a, "--config {s} supplied {d} option{s}, read before the command line's", .{ path, e.options, if (e.options == 1) "" else "s" }); +} + +/// A file's line, for its refusals. +const Where = struct { + a: Allocator, + u: *cli.Usage, + path: []const u8, + line: u32, + scratch: *cli.Args, + repeated: *cli.Repeated, + + fn fail(w: Where, comptime fmt: []const u8, args: anytype) Error { + return cli.fail(w.u, w.a, "argument --config: {s} line {d}: " ++ fmt, .{ w.path, w.line } ++ args); + } + + /// The flag's own check of this value, as on the command line, so its refusal names the file's line. + fn check(w: Where, flag: cli.Flag, value: ?[]const u8) Error!void { + const checked = if (cli.one(w.a, w.scratch, w.repeated, flag, value, w.u)) |_| @import("cli_late.zig").check(w.a, w.scratch.*, w.repeated, w.u) else |e| e; + checked catch |e| switch (e) { + error.OutOfMemory => |x| return x, + error.Usage => return w.fail("{s}", .{w.u.message}), + }; + } + + /// ``--name=text`` for a string or a number, placed and checked; null for a boolean. + fn valued(w: Where, flag: cli.Flag, base: ?[]const u8, s: toml.Scalar) Error!?[]const u8 { + var text = switch (s) { + .string, .integer, .float => |t| t, // a folder can be named 123 + .boolean => return null, + }; + if (std.mem.eql(u8, flag.name, "--drafter")) text = try anchored(w.a, base, text) else if (flag.path and text.len > 0) { + if (text[0] == '~') return w.fail("{s}: no shell expands ~ in a config file; write the whole path", .{flag.name}); + if (base) |b| if (!std.fs.path.isAbsolute(text)) { + text = try std.fs.path.join(w.a, &.{ b, text }); + }; + } + try w.check(flag, text); + return try std.fmt.allocPrint(w.a, "{s}={s}", .{ flag.name, text }); // one token: a value that starts with - stays one + } +}; + +/// The served ``--no-x`` that undoes the switch ``--x``; null without one. +fn negative(a: Allocator, flag: cli.Flag) error{OutOfMemory}!?cli.Flag { + return served(try std.fmt.allocPrint(a, "--no-{s}", .{flag.name[2..]})); +} + +/// The served ``--x`` that ``--no-x`` undoes, which is then the one key for the pair; null for any other flag. +fn positive(a: Allocator, flag: cli.Flag) error{OutOfMemory}!?[]const u8 { + if (!std.mem.startsWith(u8, flag.name, "--no-")) return null; + return if (served(try std.fmt.allocPrint(a, "--{s}", .{flag.name["--no-".len..]}))) |f| f.name else null; +} + +fn served(name: []const u8) ?cli.Flag { + const other = cli.find(name) orelse return null; + return if (other.kind == .store_true and other.native) other else null; +} + +/// A model or drafter that starts with ./ or ../ is a folder beside the file; any other text is left as written. +fn anchored(a: Allocator, base: ?[]const u8, text: []const u8) error{OutOfMemory}![]const u8 { + const b = base orelse return text; + if (!std.mem.startsWith(u8, text, "./") and !std.mem.startsWith(u8, text, "../")) return text; + const joined = try std.fs.path.join(a, &.{ b, if (text[1] == '/') text[2..] else text }); + return if (std.mem.startsWith(u8, joined, "--")) try std.fs.path.join(a, &.{ ".", joined }) else joined; // not a flag +} diff --git a/zig/src/server/cli_config_test.zig b/zig/src/server/cli_config_test.zig new file mode 100644 index 00000000000..2e1fd850f90 --- /dev/null +++ b/zig/src/server/cli_config_test.zig @@ -0,0 +1,335 @@ +//! cli_config.zig: where ``--config`` is found, what a file's keys become, and that the command line wins. +const std = @import("std"); +const cli = @import("cli.zig"); +const config = @import("cli_config.zig"); +const t = std.testing; + +const Fixture = struct { + arena: std.heap.ArenaAllocator = .init(t.allocator), + u: cli.Usage = .{}, + + fn deinit(f: *Fixture) void { + f.arena.deinit(); + } + + /// The merged arguments for `text` as ``f.toml``, given before `rest` on a command line. + fn merged(f: *Fixture, text: []const u8, rest: []const []const u8) ![]const []const u8 { + const a = f.arena.allocator(); + var argv: std.ArrayList([]const u8) = .empty; + try argv.appendSlice(a, &.{ "--config", "f.toml" }); + try argv.appendSlice(a, rest); + const found = (try config.locate(a, argv.items, &f.u)).?; + const out = config.merge(a, argv.items, found, text, &f.u) catch |e| { + if (e == error.Usage) std.debug.print("refused: {s}\n", .{f.u.message}); + return e; + }; + return out.argv; + } + + fn tokens(f: *Fixture, text: []const u8, want: []const []const u8) !void { + const got = try f.merged(text, &.{}); + errdefer std.debug.print("file: {s}\n", .{text}); + try t.expectEqual(want.len, got.len); + for (want, got) |w, g| try t.expectEqualStrings(w, g); + } + + /// `text` is refused with exactly `message` after the ``argument --config: f.toml line N: `` prefix. + fn refused(f: *Fixture, text: []const u8, line: u32, message: []const u8) !void { + const a = f.arena.allocator(); + const argv: []const []const u8 = &.{ "--config", "f.toml" }; + const found = (try config.locate(a, argv, &f.u)).?; + try t.expectError(error.Usage, config.merge(a, argv, found, text, &f.u)); + try t.expectEqualStrings(try std.fmt.allocPrint(a, "argument --config: f.toml line {d}: {s}", .{ line, message }), f.u.message); + } + + fn locateFails(f: *Fixture, argv: []const []const u8, message: []const u8) !void { + try t.expectError(error.Usage, config.locate(f.arena.allocator(), argv, &f.u)); + try t.expectEqualStrings(message, f.u.message); + } +}; + +test "serve --config: locate finds the flag as parse consumes arguments" { + var f: Fixture = .{}; + defer f.deinit(); + const a = f.arena.allocator(); + try t.expect(try config.locate(a, &.{ "m", "--port", "1" }, &f.u) == null); + const spaced = (try config.locate(a, &.{ "m", "--port", "1", "--config", "a.toml", "--dashboard" }, &f.u)).?; + try t.expectEqualDeep(config.Found{ .path = "a.toml", .at = 3, .width = 2, .model = true }, spaced); + const joined = (try config.locate(a, &.{ "--config=dir/a.TOML", "m" }, &f.u)).?; + try t.expectEqualDeep(config.Found{ .path = "dir/a.TOML", .at = 0, .width = 1, .model = true }, joined); + try t.expect(!(try config.locate(a, &.{ "--config", "a.toml", "--port", "1" }, &f.u)).?.model); + // another flag's value is neither --config nor the model + try t.expect(try config.locate(a, &.{ "m", "--name", "--config" }, &f.u) == null); + try t.expect(!(try config.locate(a, &.{ "--name", "served", "--config", "a.toml" }, &f.u)).?.model); + try t.expect(try config.locate(a, &.{ "m", "--name=--config", "a.toml" }, &f.u) == null); + // without --config nothing is refused here: parse reports it, as before + try t.expect(try config.locate(a, &.{ "m", "--port" }, &f.u) == null); + try t.expect(try config.locate(a, &.{ "m", "--bogus", "--config" }, &f.u) == null); + try f.locateFails(&.{ "--config", "a.toml", "--config=b.toml" }, "argument --config: given twice; a command reads one config file"); + // a trailing --config has no file to read: parse reports it, in its usual words + try t.expect(try config.locate(a, &.{ "m", "--config" }, &f.u) == null); + try t.expectError(error.Usage, cli.parse(a, &.{ "m", "--config" }, &f.u)); + try t.expectEqualStrings("argument --config: expected one argument", f.u.message); + try f.locateFails(&.{ "--config", "a.yaml" }, "argument --config: expected a .toml file: 'a.yaml'"); + try f.locateFails(&.{"--config="}, "argument --config: expected a .toml file: ''"); + try f.locateFails(&.{ "--config", "toml" }, "argument --config: expected a .toml file: 'toml'"); + // removing --config must not repair a flag left without its value + try f.locateFails(&.{ "m", "--prompt-cache-disk", "--config", "a.toml", "cache" }, "argument --prompt-cache-disk: expected one argument"); + try f.locateFails(&.{ "m", "--config", "a.toml", "--port" }, "argument --port: expected one argument"); +} + +test "serve --config: each kind of flag takes its values and refuses the rest by line" { + var f: Fixture = .{}; + defer f.deinit(); + try f.tokens("", &.{}); + try f.tokens("host = \"0.0.0.0\"\nport = 9000\ntemperature = 0.5\n", &.{ "--host=0.0.0.0", "--port=9000", "--temperature=0.5" }); + try f.tokens("max_tokens = 1_024\ntop-k = +40\nparallel = \"auto\"\n", &.{ "--max-tokens=1024", "--top-k=40", "--parallel=auto" }); + try f.tokens("chat-template = \"-x\"\nname = \"\"\n", &.{ "--chat-template=-x", "--name=" }); + try f.tokens("alias = \"a\"\n", &.{"--alias=a"}); + try f.tokens("alias = [\"a\", \"b\"]\napi_key = []\n", &.{ "--alias=a", "--alias=b" }); + try f.tokens("dashboard = true\nmetrics-open = false\n", &.{"--dashboard"}); + try f.tokens("thinking = false\n", &.{"--no-thinking"}); + // a pair of switches has one key, the positive one + try f.refused("no-thinking = false\n", 1, "--no-thinking has the switch --thinking: write thinking = true"); + try f.refused("port = 1\nno_thinking = true\n", 2, "--no-thinking has the switch --thinking: write thinking = false"); + try f.tokens("thinking = true\nno_drafts = true\n", &.{ "--thinking", "--no-drafts" }); + try f.tokens("no-drafts = false\n", &.{}); + try f.refused("port = 1\nprot = 2\n", 2, "unknown key 'prot'"); + try f.refused("\"--port\" = 2\n", 1, "unknown key '--port'"); + try f.refused("config = \"other.toml\"\n", 1, "a config file cannot name another config file"); + try f.refused("port = true\n", 1, "--port takes a value, not true or false"); + try f.refused("port = [\"1\", \"2\"]\n", 1, "--port takes one value, not a list"); + try f.refused("alias = true\n", 1, "--alias takes values, not true or false"); + try f.refused("# aliases\nalias = [\"a\",\n false]\n", 3, "an array holds strings only: quote each item"); + try f.refused("alias = [1]\n", 1, "an array holds strings only: quote each item"); + try f.refused("dashboard = \"yes\"\n", 1, "--dashboard is a switch: use true or false"); + try f.refused("dashboard = 1\n", 1, "--dashboard is a switch: use true or false"); + try f.refused("dashboard = [\"true\"]\n", 1, "--dashboard is a switch: use true or false"); + try f.refused("max-tokens = 1\nmax_tokens = 2\n", 2, "--max-tokens is set twice ('max_tokens' and its other spelling)"); + try f.refused("model = 7\n", 1, "model takes a string"); + try f.refused("model = [\"m\"]\n", 1, "model takes a string"); + try f.refused("model = \"--name\"\n", 1, "model cannot start with --, which parse reads as a flag: write a folder as ./--name"); + try f.tokens("model = \"-m\"\n", &.{"-m"}); + try f.refused("port = 1\n[serve]\n", 2, "tables are not read: every key is a top-level setting"); + // a flag this build does not serve is refused even where its value would emit nothing + try t.expect(!cli.find("--vision-offload").?.native and !cli.find("--policy").?.native); + try f.refused("vision-offload = false\n", 1, "--vision-offload is not served by this build"); + try f.refused("port = 1\npolicy = []\n", 2, "--policy is not served by this build"); + try f.refused("lane-kernels = \"auto\"\n", 1, "--lane-kernels is not served by this build"); +} + +test "serve --config: the file's model yields to the command line's, and its flags come first" { + var f: Fixture = .{}; + defer f.deinit(); + const text = "port = 1\nmodel = \"file/model\"\nalias = [\"a\"]\n"; + const alone = try f.merged(text, &.{ "--port", "2" }); + try t.expectEqual(@as(usize, 5), alone.len); + for ([_][]const u8{ "file/model", "--port=1", "--alias=a", "--port", "2" }, alone) |w, g| try t.expectEqualStrings(w, g); + const named = try f.merged(text, &.{ "cli/model", "--alias", "z" }); + for ([_][]const u8{ "--port=1", "cli/model", "--alias", "z" }, named) |w, g| try t.expectEqualStrings(w, g); + try t.expectEqual(@as(usize, 4), named.len); // --alias on the command line replaces the file's list + // --config between other arguments leaves them in order + const a = f.arena.allocator(); + const argv: []const []const u8 = &.{ "m", "--dashboard", "--config=f.toml", "--port", "3" }; + const out = try config.merge(a, argv, (try config.locate(a, argv, &f.u)).?, "port = 1\n", &f.u); + for ([_][]const u8{ "--port=1", "m", "--dashboard", "--port", "3" }, out.argv) |w, g| try t.expectEqualStrings(w, g); + try t.expectEqualStrings("f.toml", out.path.?); + try t.expectEqual(@as(usize, 1), out.options); +} + +test "serve --config: a relative path in the file starts at the file's folder" { + var f: Fixture = .{}; + defer f.deinit(); + const a = f.arena.allocator(); + const text = + \\model = "./weights/m" + \\chat-template = "t.jinja" + \\api-key-file = "../keys" + \\learn-dir = "/abs/learn" + \\drafter = "./drafter" + \\name = "plain/name" + \\kv-cache = "bf16" + ; + const sep = std.fs.path.sep_str; + const argv: []const []const u8 = &.{ "--config", "conf" ++ sep ++ "f.toml" }; + const out = try config.merge(a, argv, (try config.locate(a, argv, &f.u)).?, text, &f.u); + const want = [_][]const u8{ "conf" ++ sep ++ "weights/m", "--chat-template=conf" ++ sep ++ "t.jinja", "--api-key-file=conf" ++ sep ++ "../keys", "--learn-dir=/abs/learn", "--drafter=conf" ++ sep ++ "drafter", "--name=plain/name", "--kv-cache=bf16" }; + try t.expectEqual(want.len, out.argv.len); + for (want, out.argv) |w, g| try t.expectEqualStrings(w, g); + // a repo id, or a folder named without ./, is left as written: the hub resolves it as it does a typed model + try f.tokens("model = \"org/Model\"\ndrafter = \"org/Drafter\"\n", &.{ "org/Model", "--drafter=org/Drafter" }); + const rel = try config.merge(a, argv, (try config.locate(a, argv, &f.u)).?, "model = \"org/Model\"\ndrafter = \"../d\"\n", &f.u); + for ([_][]const u8{ "org/Model", "--drafter=conf" ++ sep ++ "../d" }, rel.argv) |w, g| try t.expectEqualStrings(w, g); + // a number names a folder too, and a folder that starts with -- does not turn the model into a flag + const odd: []const []const u8 = &.{"--config=--conf" ++ sep ++ "f.toml"}; + const dashed = try config.merge(a, odd, (try config.locate(a, odd, &f.u)).?, "model = \"./weights\"\ncompact-memory = 123\n", &f.u); + for ([_][]const u8{ "." ++ sep ++ "--conf" ++ sep ++ "weights", "--compact-memory=--conf" ++ sep ++ "123" }, dashed.argv) |w, g| try t.expectEqualStrings(w, g); + // a file in the working directory has no folder to add + try f.tokens("model = \"./m\"\nchat-template = \"t.jinja\"\n", &.{ "./m", "--chat-template=t.jinja" }); +} + +test "serve --config: a file parses as its flags typed by hand, and the command line wins" { + var f: Fixture = .{}; + defer f.deinit(); + const a = f.arena.allocator(); + const text = + \\model = "org/Model" + \\host = "0.0.0.0" + \\port = 9000 + \\context = 131072 + \\temperature = 0.6 + \\thinking = false + \\dashboard = true + \\alias = ["a", "b"] + \\compact-at = "auto" + \\prompt_cache_gib = 2.5 + ; + const typed: []const []const u8 = &.{ "org/Model", "--host", "0.0.0.0", "--port", "9000", "--context", "131072", "--temperature", "0.6", "--no-thinking", "--dashboard", "--alias", "a", "--alias", "b", "--compact-at", "auto", "--prompt-cache-gib", "2.5" }; + const from_file = try cli.parse(a, try f.merged(text, &.{}), &f.u); + const by_hand = try cli.parse(a, typed, &f.u); + try t.expectEqualDeep(by_hand, from_file); + try t.expectEqualDeep(try cli.request(a, "d", "t", by_hand), try cli.request(a, "d", "t", from_file)); + try t.expectEqual(@as(u16, 9000), from_file.port); + try t.expect(!from_file.thinking and from_file.dashboard and from_file.compact_auto); + + const over = try cli.parse(a, try f.merged(text, &.{ "other/model", "--port", "9001", "--thinking", "--alias", "z", "--compact-at", "0.5", "--temperature=0" }), &f.u); + try t.expectEqualStrings("other/model", over.model); + try t.expectEqual(@as(u16, 9001), over.port); + try t.expect(over.thinking); + try t.expectEqual(@as(?f64, 0), over.temperature); + try t.expect(!over.compact_auto); + try t.expectEqual(@as(?f64, 0.5), over.compact_fraction); + try t.expectEqual(@as(usize, 1), over.alias.len); // a repeatable flag on the command line replaces the file's list + try t.expectEqualStrings("z", over.alias[0]); + // so a key, a host or an origin the file names does not stay in force beside the command line's + const keys = try cli.parse(a, try f.merged("api-key = [\"old\", \"older\"]\nallowed-host = \"a.example\"\nalias = \"kept\"\n", &.{ "m", "--api-key=new", "--allowed-host", "b.example" }), &f.u); + try t.expectEqual(@as(usize, 1), keys.api_key.len); + try t.expectEqualStrings("new", keys.api_key[0]); + try t.expectEqual(@as(usize, 1), keys.allowed_host.len); + try t.expectEqualStrings("b.example", keys.allowed_host[0]); + try t.expectEqualStrings("kept", keys.alias[0]); // a list the command line does not name stays the file's + try t.expectEqualStrings("0.0.0.0", over.host); // what the command line does not name stays the file's + try t.expect(over.dashboard); + + // flags that refuse each other do so across the file and the command line + if (@import("builtin").os.tag != .windows) { + try t.expectError(error.Usage, cli.parse(a, try f.merged("unix-socket = \"/tmp/s.sock\"\n", &.{ "m", "--port", "1" }), &f.u)); + try t.expectEqualStrings("argument --unix-socket: not allowed with --port", f.u.message); + } + // a value the flag refuses is refused in the flag's own words, with the file's line + try f.refused("model = \"m\"\n\nport = 99999\n", 3, "argument --port: invalid port: '99999'"); + try f.refused("backend = \"vulkan\"\n", 1, "argument --backend: invalid choice: 'vulkan'"); + try f.refused("port = 1\ntemperature = \"warm\"\n", 2, "argument --temperature: invalid float value: 'warm'"); + try f.refused("alias = [\"a\"]\nallowed-host = [\"ok.example\",\n \"bad host:1\"]\n", 2, "argument --allowed-host: expected a hostname or bracketed IP without a port: 'bad host:1'"); + try f.refused("compact-at = 1.5\n", 1, "argument --compact-at: expected auto or a fraction in (0, 1]: '1.5'"); + // checks that parse runs once every flag is read name the line too + try f.refused("port = 1\nidle-unload = -1\n", 2, "argument --idle-unload: expected a seconds count from 0 (off) under 9223372036: '-1'"); + try f.refused("name-priority = [\"a=background\", \"broken\"]\n", 1, "argument --name-priority: takes ID=background, not 'broken'"); + { + var hosts: std.ArrayList(u8) = .empty; + try hosts.appendSlice(a, "allowed-host = [\n"); + for (0..65) |n| try hosts.print(a, " \"h{d}.example\",\n", .{n}); + try hosts.appendSlice(a, "]\n"); + try f.refused(hosts.items, 1, "at most 64 --allowed-host and 64 --allowed-origin entries are allowed"); + const argv: []const []const u8 = &.{ "--config", "f.toml", "--name-priority", "x=background" }; + try t.expectError(error.Usage, config.merge(a, argv, (try config.locate(a, argv, &f.u)).?, "name-priority = [\"broken\"]\n", &f.u)); + try t.expectEqualStrings("argument --config: f.toml line 1: argument --name-priority: takes ID=background, not 'broken'", f.u.message); + } + // a replaced list is still checked, so a bad entry does not hide behind the command line + { + const argv: []const []const u8 = &.{ "--config", "f.toml", "--allowed-host", "b.example" }; + try t.expectError(error.Usage, config.merge(a, argv, (try config.locate(a, argv, &f.u)).?, "allowed-host = \"bad host:1\"\n", &f.u)); + try t.expectEqualStrings("argument --config: f.toml line 1: argument --allowed-host: expected a hostname or bracketed IP without a port: 'bad host:1'", f.u.message); + } + // no shell expands ~ in the file: a path flag refuses it, where the hub expands a model's or drafter's ~/ + try f.refused("port = 1\nrecall-dir = \"~/recall\"\n", 2, "--recall-dir: no shell expands ~ in a config file; write the whole path"); + try f.tokens("model = \"~/models/m\"\ndrafter = \"~/d\"\n", &.{ "~/models/m", "--drafter=~/d" }); + try t.expectError(error.Usage, cli.parse(a, try f.merged("port = 1\n", &.{}), &f.u)); + try t.expectEqualStrings("the following arguments are required: model", f.u.message); +} + +test "serve --config: expand reads the file, passes other commands through and names what it cannot read" { + var f: Fixture = .{}; + defer f.deinit(); + const a = f.arena.allocator(); + const plain: []const []const u8 = &.{ "m", "--port", "1" }; + const same = try config.expand(a, plain, &f.u); + try t.expect(same.argv.ptr == plain.ptr and same.argv.len == plain.len and same.path == null); + try t.expect(try config.note(a, same) == null); + + var tmp = t.tmpDir(.{}); + defer tmp.cleanup(); + const dir = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}", .{tmp.sub_path}); + try tmp.dir.writeFile(t.io, .{ .sub_path = "serve.toml", .data = "model = \"org/Model\"\nport = 9000\n" }); + const path = try std.fs.path.join(a, &.{ dir, "serve.toml" }); + const read = try config.expand(a, &.{ "--config", path, "--dashboard" }, &f.u); + try t.expectEqual(@as(usize, 3), read.argv.len); + for ([_][]const u8{ "org/Model", "--port=9000", "--dashboard" }, read.argv) |w, g| try t.expectEqualStrings(w, g); + try t.expectEqualStrings(try std.fmt.allocPrint(a, "--config {s} supplied 2 options, read before the command line's", .{path}), (try config.note(a, read)).?); + try t.expectEqualStrings("--config x.toml supplied 1 option, read before the command line's", (try config.note(a, .{ .argv = &.{}, .path = "x.toml", .options = 1 })).?); + + // a file that other users can write is refused before it is read; a folder is not a file + if (@import("builtin").os.tag != .windows) { + const c = @import("sys").c; + const pathz = try a.dupeSentinel(u8, path, 0); + for ([_]u32{ 0o664, 0o646, 0o666 }) |mode| { + try t.expectEqual(@as(c_int, 0), c.fchmodat(std.posix.AT.FDCWD, pathz, @intCast(mode), 0)); + try t.expectError(error.Usage, config.expand(a, &.{ "--config", path }, &f.u)); + try t.expectEqualStrings(try std.fmt.allocPrint(a, "argument --config: {s} can be written by other users (mode 0{o}): it chooses what is served; use chmod go-w", .{ path, mode }), f.u.message); + } + for ([_]u32{ 0o600, 0o644, 0o640 }) |mode| { + try t.expectEqual(@as(c_int, 0), c.fchmodat(std.posix.AT.FDCWD, pathz, @intCast(mode), 0)); + try t.expectEqual(@as(usize, 2), (try config.expand(a, &.{ "--config", path }, &f.u)).options); + } + // a file that sets api-key is refused while other users can read it; any other file may be world-readable + try tmp.dir.writeFile(t.io, .{ .sub_path = "key.toml", .data = "model = \"m\"\n\napi-key = \"k\"\n" }); + const key = try std.fs.path.join(a, &.{ dir, "key.toml" }); + const keyz = try a.dupeSentinel(u8, key, 0); + for ([_]u32{ 0o644, 0o640, 0o604 }) |mode| { + try t.expectEqual(@as(c_int, 0), c.fchmodat(std.posix.AT.FDCWD, keyz, @intCast(mode), 0)); + try t.expectError(error.Usage, config.expand(a, &.{ "--config", key }, &f.u)); + try t.expectEqualStrings(try std.fmt.allocPrint(a, "argument --config: {s} line 3: api-key is set in a file other users can read (mode 0{o}); use chmod 600, or api-key-file", .{ key, mode }), f.u.message); + } + try t.expectEqual(@as(c_int, 0), c.fchmodat(std.posix.AT.FDCWD, keyz, 0o600, 0)); + try t.expectEqual(@as(u32, 3), (try config.expand(a, &.{ "--config", key }, &f.u)).secret); + // a link is not followed: the file that is checked is the file that is read + try tmp.dir.symLink(t.io, "serve.toml", "link.toml", .{}); + const link = try std.fs.path.join(a, &.{ dir, "link.toml" }); + try t.expectError(error.Usage, config.expand(a, &.{ "--config", link }, &f.u)); + try t.expectEqualStrings(try std.fmt.allocPrint(a, "argument --config: cannot open {s} (SymLinkLoop); name an existing file, not a link", .{link}), f.u.message); + try tmp.dir.createDir(t.io, "folder.toml", .default_dir); + const folder = try std.fs.path.join(a, &.{ dir, "folder.toml" }); + try t.expectError(error.Usage, config.expand(a, &.{ "--config", folder }, &f.u)); + try t.expectEqualStrings(try std.fmt.allocPrint(a, "argument --config: {s} is not a regular file", .{folder}), f.u.message); + } + + const missing = try std.fs.path.join(a, &.{ dir, "none.toml" }); + try t.expectError(error.Usage, config.expand(a, &.{ "m", "--config", missing }, &f.u)); + const absent = if (@import("builtin").os.tag == .windows) "OpenFailed" else "FileNotFound"; + try t.expectEqualStrings(try std.fmt.allocPrint(a, "argument --config: cannot open {s} ({s}); name an existing file, not a link", .{ missing, absent }), f.u.message); + + // exactly the limit is read; one byte more, and far more, get the size message + const filler = try a.alloc(u8, 3 * config.limit); + @memset(filler, '#'); + for ([_]usize{ config.limit, config.limit + 1, 3 * config.limit }) |size| { + try tmp.dir.writeFile(t.io, .{ .sub_path = "big.toml", .data = filler[0..size] }); + const big = try std.fs.path.join(a, &.{ dir, "big.toml" }); + if (size == config.limit) { + try t.expectEqual(@as(usize, 0), (try config.expand(a, &.{ "m", "--config", big }, &f.u)).options); + } else { + try t.expectError(error.Usage, config.expand(a, &.{ "m", "--config", big }, &f.u)); + try t.expectEqualStrings(try std.fmt.allocPrint(a, "argument --config: {s} is over 1 MiB", .{big}), f.u.message); + } + } +} + +test "serve --config: parse refuses the flag itself and capabilities lists it" { + var f: Fixture = .{}; + defer f.deinit(); + const a = f.arena.allocator(); + try t.expectError(error.Usage, cli.parse(a, &.{ "m", "--config", "f.toml" }, &f.u)); + try t.expectEqualStrings("argument --config: serve reads it before its other flags; it cannot appear here", f.u.message); + var out: std.Io.Writer.Allocating = .init(a); + try cli.capabilities(&out.writer, .{ .version = "test" }); + try t.expect(std.mem.indexOf(u8, out.written(), "\"--config\": {}") != null); +} diff --git a/zig/src/server/cli_late.zig b/zig/src/server/cli_late.zig new file mode 100644 index 00000000000..1797b8ffb44 --- /dev/null +++ b/zig/src/server/cli_late.zig @@ -0,0 +1,17 @@ +//! Serve flag checks of one flag's own values that run once every flag is read; a config file runs them on its own. +const std = @import("std"); +const cli = @import("cli.zig"); + +/// The idle unload's range, each --name-priority entry's form and the host and origin list sizes. +pub fn check(a: std.mem.Allocator, out: cli.Args, repeated: *const cli.Repeated, u: *cli.Usage) error{ Usage, OutOfMemory }!void { + if (out.idle_unload < 0 or out.idle_unload > std.math.maxInt(i64) / std.time.ns_per_s) return cli.fail(u, a, "argument --idle-unload: expected a seconds count from 0 (off) under {d}: '{d}'", .{ std.math.maxInt(i64) / std.time.ns_per_s, out.idle_unload }); + for (repeated.priorities.items) |entry| { + const eq = std.mem.indexOfScalar(u8, entry, '=') orelse + return cli.fail(u, a, "argument --name-priority: takes ID=background, not '{s}'", .{entry}); + const id = std.mem.trim(u8, entry[0..eq], " \t"); + const word = std.mem.trim(u8, entry[eq + 1 ..], " \t"); + if (id.len == 0 or !std.ascii.eqlIgnoreCase(word, "background")) + return cli.fail(u, a, "argument --name-priority: takes ID=background, not '{s}'", .{entry}); + } + if (repeated.hosts.items.len > 64 or repeated.origins.items.len > 64) return cli.fail(u, a, "at most 64 --allowed-host and 64 --allowed-origin entries are allowed", .{}); +} diff --git a/zig/src/server/engines.zig b/zig/src/server/engines.zig index 528a00b8be1..3cd4ff1d693 100644 --- a/zig/src/server/engines.zig +++ b/zig/src/server/engines.zig @@ -28,7 +28,13 @@ pub const std_options: std.Options = @import("std_options.zig").of(native); /// What ``capabilities --json`` reports: this release, the chip here, and what the built-in backend serves. pub fn capabilities(a: Allocator) cli.Engines { - return .{ .version = @import("build_options").version, .chip = if (native.families.len > 0) native.chip(a) else null, .backends = native.backends, .families = native.families }; + var caps = cli.Engines{ .version = @import("build_options").version, .chip = if (native.families.len > 0) native.chip(a) else null, .backends = native.backends, .families = native.families }; + if (@hasDecl(native, "kernelSupport")) { + const support = native.kernelSupport(a); + caps.kernels = support.kernels; + caps.kernel_sms = support.sms; + } + return caps; } /// ``capabilities --json``'s NVML P2P summary when the backend has one (CUDA, two or more GPUs); else null. diff --git a/zig/src/server/errors.zig b/zig/src/server/errors.zig index 2622f5d6586..ff1a7ca2e9c 100644 --- a/zig/src/server/errors.zig +++ b/zig/src/server/errors.zig @@ -32,8 +32,12 @@ pub const Cx = struct { param: ?[]const u8 = null, /// The request's ``chat_template_kwargs.clear_thinking``, over the server's (GLM-5.3 templates only). clear_thinking: ?bool = null, + /// The effort the request itself named (no server default): a thinking-off prompt renders only this one. + named_effort: ?[]const u8 = null, /// The request controls a native prompt renderer must retain in every prefix probe. template_fields: @import("json").Value = .null, + /// Set by a route that has already planned the same body (its first plan writes the request log). + skip_request_log: bool = false, pub fn fail(cx: *Cx, kind: Kind, comptime fmt: []const u8, args: anytype) Refused { cx.kind = kind; diff --git a/zig/src/server/fields.zig b/zig/src/server/fields.zig index df765944fe6..aad8720a231 100644 --- a/zig/src/server/fields.zig +++ b/zig/src/server/fields.zig @@ -243,6 +243,12 @@ fn order(name: []const u8) ?usize { return null; } +/// The effort a request itself names, on the template's levels; null for none or `none` (never --reasoning-effort). +pub fn namedEffort(request: ?[]const u8, levels: []const []const u8) ?[]const u8 { + const e = request orelse return null; + return if (std.mem.eql(u8, e, "none")) null else coerceEffort(e, levels); +} + /// The nearest level the template names, ties going higher; xhigh and none stay. pub fn coerceEffort(effort: []const u8, levels: []const []const u8) []const u8 { if (levels.len == 0) { diff --git a/zig/src/server/fixtures/thinking/README.md b/zig/src/server/fixtures/thinking/README.md index 443128dfcb4..3ea764c854f 100644 --- a/zig/src/server/fixtures/thinking/README.md +++ b/zig/src/server/fixtures/thinking/README.md @@ -2,7 +2,9 @@ These are unmodified checkpoint assets supplied for the GLM-5.3-Flash-NVFP4 revision `da920bb0b9f4` (nvidia/GLM-5.3-Flash-NVFP4, MIT) and LiquidAI/LFM2.5-24B-A2B-MLX-4bit at revision -`667408d494bde191c2cb9dd4f4549827816b9275` (LFM Open License v1.0); `THIRD_PARTY_NOTICES.md` records both. +`667408d494bde191c2cb9dd4f4549827816b9275` (LFM Open License v1.0), and the Qwen3.8 files from +TensorFold/Qwen3.8-27B-MLX-4bit at revision `70ae7fac63274ff2eac54152031433374cb80f2f` (Qwen/Qwen3.8-27B's template, +Apache-2.0); `THIRD_PARTY_NOTICES.md` records all three. They exercise the native template loader, renderer and thinking-off request path. The test vocabulary is deliberately small. Its marker IDs are fixture IDs, @@ -15,3 +17,5 @@ included, and these tests do not qualify model output on a device. | `glm53.jinja` | `34d5ee66b12fa6446cdae131c352b8f68cd85369e0e6fda115583805fada3891` | | `lfm2-tokenizer_config.json` | `11f1de897317b489dd09199284528382eeb17f566398b16e2039bb2266d26b09` | | `lfm2.jinja` | `aadd425edb1d42fe9288e5de3624c21c1c03099129b9cfea5978f1bc67222c0a` | +| `qwen38-tokenizer_config.json` | `792fa3f0cb88b111e54ef3134c873531008c4df471d108da17903426e308aa7b` | +| `qwen38.jinja` | `c3cf9e34abf4f9e36c2d72165aa9c132d3e2a725b6c2586aaa3a8af9d7a81041` | diff --git a/zig/src/server/fixtures/thinking/qwen38-tokenizer_config.json b/zig/src/server/fixtures/thinking/qwen38-tokenizer_config.json new file mode 100644 index 00000000000..1d134cd298b --- /dev/null +++ b/zig/src/server/fixtures/thinking/qwen38-tokenizer_config.json @@ -0,0 +1,33 @@ +{ + "add_prefix_space": false, + "audio_bos_token": "<|audio_start|>", + "audio_eos_token": "<|audio_end|>", + "audio_token": "<|audio_pad|>", + "backend": "tokenizers", + "bos_token": null, + "clean_up_tokenization_spaces": false, + "eos_token": "<|im_end|>", + "errors": "replace", + "image_token": "<|image_pad|>", + "is_local": true, + "local_files_only": false, + "model_max_length": 262144, + "model_specific_special_tokens": { + "audio_bos_token": "<|audio_start|>", + "audio_eos_token": "<|audio_end|>", + "audio_token": "<|audio_pad|>", + "image_token": "<|image_pad|>", + "video_token": "<|video_pad|>", + "vision_bos_token": "<|vision_start|>", + "vision_eos_token": "<|vision_end|>" + }, + "pad_token": "<|endoftext|>", + "pretokenize_regex": "(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?[\\p{L}\\p{M}]+|\\p{N}| ?[^\\s\\p{L}\\p{M}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+", + "processor_class": "Qwen3VLProcessor", + "split_special_tokens": false, + "tokenizer_class": "Qwen2Tokenizer", + "unk_token": null, + "video_token": "<|video_pad|>", + "vision_bos_token": "<|vision_start|>", + "vision_eos_token": "<|vision_end|>" +} diff --git a/zig/src/server/fixtures/thinking/qwen38.jinja b/zig/src/server/fixtures/thinking/qwen38.jinja new file mode 100644 index 00000000000..c0c686f9c38 --- /dev/null +++ b/zig/src/server/fixtures/thinking/qwen38.jinja @@ -0,0 +1,170 @@ +{%- set image_count = namespace(value=0) %} +{%- set video_count = namespace(value=0) %} +{%- macro render_content(content, do_vision_count, is_system_content=false) %} + {%- if content is string %} + {{- content }} + {%- elif content is iterable and content is not mapping %} + {%- for item in content %} + {%- if 'image' in item or 'image_url' in item or item.type == 'image' %} + {%- if is_system_content %} + {{- raise_exception('System message cannot contain images.') }} + {%- endif %} + {%- if do_vision_count %} + {%- set image_count.value = image_count.value + 1 %} + {%- endif %} + {%- if add_vision_id %} + {{- 'Picture ' ~ image_count.value ~ ': ' }} + {%- endif %} + {{- '<|vision_start|><|image_pad|><|vision_end|>' }} + {%- elif 'video' in item or item.type == 'video' %} + {%- if is_system_content %} + {{- raise_exception('System message cannot contain videos.') }} + {%- endif %} + {%- if do_vision_count %} + {%- set video_count.value = video_count.value + 1 %} + {%- endif %} + {%- if add_vision_id %} + {{- 'Video ' ~ video_count.value ~ ': ' }} + {%- endif %} + {{- '<|vision_start|><|video_pad|><|vision_end|>' }} + {%- elif 'text' in item %} + {{- item.text }} + {%- else %} + {{- raise_exception('Unexpected item type in content.') }} + {%- endif %} + {%- endfor %} + {%- elif content is none or content is undefined %} + {{- '' }} + {%- else %} + {{- raise_exception('Unexpected content type.') }} + {%- endif %} +{%- endmacro %} +{%- if not messages %} + {{- raise_exception('No messages provided.') }} +{%- endif %} +{%- set reasoning_instructions = '' %} +{%- if enable_thinking is undefined or enable_thinking is true %} + {%- set resolved_reasoning_effort = reasoning_effort|default('xhigh') %} + {%- if resolved_reasoning_effort not in ('xhigh', 'medium', 'low') %} + {{- raise_exception('Unexpected reasoning effort ' ~ reasoning_effort ~ '. Supported types are xhigh (default), medium, and low.') }} + {%- endif %} + {%- if resolved_reasoning_effort == 'xhigh' %} + {%- set reasoning_instructions = 'Reasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.' %} + {%- elif resolved_reasoning_effort == 'low' %} + {%- set reasoning_instructions = 'Reasoning effort is set to low. Keep your thinking brief and focused, moving directly to the conclusion without unnecessary elaboration.' %} + {%- endif %} +{%- endif %} +{%- if tools and tools is iterable and tools is not mapping %} + {{- '<|im_start|>system\n' }} + {%- if reasoning_instructions %} + {{- reasoning_instructions + '\n\n' }} + {%- endif %} + {{- "# Tools\n\nYou have access to the following functions:\n\n" }} + {%- for tool in tools %} + {{- "\n" }} + {{- tool | tojson }} + {%- endfor %} + {{- "\n" }} + {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n\n\n\nvalue_1\n\n\nThis is the value for the second parameter\nthat can span\nmultiple lines\n\n\n\n\n\nReminder:\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n' }} + {%- if messages[0].role == 'system' %} + {%- set content = render_content(messages[0].content, false, true)|trim %} + {%- if content %} + {{- '\n\n' + content }} + {%- endif %} + {%- endif %} + {{- '<|im_end|>\n' }} +{%- else %} + {%- if messages[0].role == 'system' %} + {%- set content = render_content(messages[0].content, false, true)|trim %} + {%- if content %} + {{- '<|im_start|>system\n' + (reasoning_instructions + '\n\n' if reasoning_instructions else '') + content + '<|im_end|>\n' }} + {%- elif reasoning_instructions %} + {{- '<|im_start|>system\n' + reasoning_instructions + '<|im_end|>\n' }} + {%- endif %} + {%- elif reasoning_instructions %} + {{- '<|im_start|>system\n' + reasoning_instructions + '<|im_end|>\n' }} + {%- endif %} +{%- endif %} +{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %} +{%- for message in messages[::-1] %} + {%- set index = (messages|length - 1) - loop.index0 %} + {%- if ns.multi_step_tool and message.role == "user" %} + {%- set content = render_content(message.content, false)|trim %} + {%- if not(content.startswith('') and content.endswith('')) %} + {%- set ns.multi_step_tool = false %} + {%- set ns.last_query_index = index %} + {%- endif %} + {%- endif %} +{%- endfor %} +{%- if ns.multi_step_tool %} + {{- raise_exception('No user query found in messages.') }} +{%- endif %} +{%- for message in messages %} + {%- set content = render_content(message.content, true)|trim %} + {%- if message.role == "system" %} + {%- if not loop.first %} + {{- raise_exception('System message must be at the beginning.') }} + {%- endif %} + {%- elif message.role == "user" %} + {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }} + {%- elif message.role == "assistant" %} + {%- set reasoning_content = '' %} + {%- if message.reasoning_content is string %} + {%- set reasoning_content = message.reasoning_content %} + {%- endif %} + {%- set reasoning_content = reasoning_content|trim %} + {%- if preserve_thinking is undefined or preserve_thinking is true or loop.index0 > ns.last_query_index %} + {{- '<|im_start|>' + message.role + '\n\n' + reasoning_content + '\n\n\n' + content }} + {%- else %} + {{- '<|im_start|>' + message.role + '\n' + content }} + {%- endif %} + {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %} + {%- for tool_call in message.tool_calls %} + {%- if tool_call.function is defined %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {%- if loop.first %} + {%- if content|trim %} + {{- '\n\n\n\n' }} + {%- else %} + {{- '\n\n' }} + {%- endif %} + {%- else %} + {{- '\n\n\n' }} + {%- endif %} + {%- if tool_call.arguments is defined and tool_call.arguments != '' %} + {%- for args_name, args_value in tool_call.arguments|items %} + {{- '\n' }} + {%- set args_value = args_value | string if args_value is string else args_value | tojson | safe %} + {{- args_value }} + {{- '\n\n' }} + {%- endfor %} + {%- endif %} + {{- '\n' }} + {%- endfor %} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- elif message.role == "tool" %} + {%- if loop.previtem and loop.previtem.role != "tool" %} + {{- '<|im_start|>user' }} + {%- endif %} + {{- '\n\n' }} + {{- content }} + {{- '\n' }} + {%- if not loop.last and loop.nextitem.role != "tool" %} + {{- '<|im_end|>\n' }} + {%- elif loop.last %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- else %} + {{- raise_exception('Unexpected message role.') }} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|im_start|>assistant\n' }} + {%- if enable_thinking is defined and enable_thinking is false %} + {{- '\n\n\n\n' }} + {%- else %} + {{- '\n' }} + {%- endif %} +{%- endif %} \ No newline at end of file diff --git a/zig/src/server/input_types.zig b/zig/src/server/input_types.zig new file mode 100644 index 00000000000..794cc21e0a3 --- /dev/null +++ b/zig/src/server/input_types.zig @@ -0,0 +1,46 @@ +//! What a served model takes as input, decided once at startup: /v1/models' input_types and the refusals read it. +const std = @import("std"); +const api = @import("engine_api"); +const json = @import("json"); + +/// Images with --vision; videos when the model offers them and this server can decode them (libtfvideo loads). +pub const Inputs = struct { + image: bool = false, + video: bool = false, + + pub fn of(vision: ?api.Vision, video_decoder: bool) Inputs { + const v = vision orelse return .{}; + return .{ .image = true, .video = v.video != null and video_decoder }; + } + + /// `["text"]`, then "image" and "video" when taken, in that order. + pub fn value(i: Inputs, a: std.mem.Allocator) std.mem.Allocator.Error!json.Value { + const out = try a.alloc(json.Value, 1 + @as(usize, @intFromBool(i.image)) + @intFromBool(i.video)); + out[0] = .{ .string = "text" }; + if (i.image) out[1] = .{ .string = "image" }; + if (i.video) out[out.len - 1] = .{ .string = "video" }; + return .{ .array = out }; + } +}; + +/// At startup: whether libtfvideo loads for `vision`'s videos, by the loader each video uses, which keeps its answer. +pub fn decodes(vision: ?api.Vision) bool { + const v = vision orelse return false; + if (v.video == null) return false; + const quiet = @import("sys").optional_libraries.atBoundary(); // the line below says it once, with what follows + defer quiet.deinit(); + if (api.tfvideo.version() != null) return true; + const message = @import("sys").optional_libraries.spec(.video).message; + @import("log.zig").line("--vision: {s}; video_url parts are refused and /v1/models lists no video", .{message}); + return false; +} + +/// The media a request may carry: the template's vision and PDF, and the image and video inputs /v1/models publishes. +pub fn media(srv: anytype) @import("messages.zig").Media { + var result = @import("messages.zig").Media.ofVision(srv.info.vision, srv.config.vision_pdf); + const taken = Inputs.of(srv.info.vision, srv.video_decoder); + result.images = taken.image; + result.videos = taken.video; + result.native_deepseek = srv.text.native_deepseek; + return result; +} diff --git a/zig/src/server/logprob_parts.zig b/zig/src/server/logprob_parts.zig index 52d3de2997a..4aa8feaa3b7 100644 --- a/zig/src/server/logprob_parts.zig +++ b/zig/src/server/logprob_parts.zig @@ -17,7 +17,10 @@ const Error = error{ Failed, OutOfMemory }; pub const Sent = struct { content: usize = 0, reasoning: usize = 0 }; /// A finished reply's tokens and rows, projected once its text and calls are final; `closer` ends a call EOS cut. -pub const Capture = struct { tokens: []const u32, rows: []const api.LogprobRow, thinking: bool, stops: rt.Stops, closer: []const u8 = "", sent: Sent = .{} }; +pub const Capture = struct { tokens: []const u32, rows: []const api.LogprobRow, thinking: bool, stops: rt.Stops, closer: []const u8 = "", sent: Sent = .{}, positions: bool = false }; + +/// What a projection lists: the entries, or each entry's raw token position (a token stream's anchor). +pub const Form = enum { entries, positions }; const Channel = enum { content, reasoning, tool, dropped }; /// Visible bytes of one channel; an open range may still grow while the reply streams. @@ -49,47 +52,53 @@ pub const Live = struct { rows: std.ArrayList(api.LogprobRow) = .empty, // copied with each round's tokens spelled: Spelled = .{}, sent: Sent = .{}, + positions: bool = false, // a token stream: settled entries also name their raw token positions pub fn add(l: *Live, srv: *Server, a: A, tokens: []const u32) Error!void { return l.spelled.add(srv, a, tokens); } - /// ``{content, reasoning_content}`` entries the streamed text now settles; null when there are none. + /// ``{content, reasoning_content}`` entries the text now settles, and a token stream's ``positions``; null if none. pub fn settle(l: *Live, srv: *Server, a: A, tokens: []const u32, thinking: bool, stops: rt.Stops, content: []const u8, reasoning: []const u8) Error!?V { const visible = stops.visible(l.spelled.raw.items, false); const ranges = try layout(srv, a, visible, tokens, thinking, false, .{ .content = content, .reasoning = reasoning }); - const prose = try fresh(srv, a, &l.spelled, tokens, l.rows.items, ranges, .content, &l.sent.content); - const thought = try fresh(srv, a, &l.spelled, tokens, l.rows.items, ranges, .reasoning, &l.sent.reasoning); + const prose = try fresh(a, &l.spelled, ranges, .content, &l.sent.content); + const thought = try fresh(a, &l.spelled, ranges, .reasoning, &l.sent.reasoning); if (prose.len == 0 and thought.len == 0) return null; const out = try json.newObject(a); - try out.put(a, "content", .{ .array = prose }); - if (thought.len > 0) try out.put(a, "reasoning_content", .{ .array = thought }); + try out.put(a, "content", .{ .array = try values(srv, a, &l.spelled, tokens, l.rows.items, prose, .entries) }); + if (thought.len > 0) try out.put(a, "reasoning_content", .{ .array = try values(srv, a, &l.spelled, tokens, l.rows.items, thought, .entries) }); + if (l.positions) { + const at = try json.newObject(a); + try at.put(a, "content", .{ .array = try values(srv, a, &l.spelled, tokens, l.rows.items, prose, .positions) }); + if (thought.len > 0) try at.put(a, "reasoning_content", .{ .array = try values(srv, a, &l.spelled, tokens, l.rows.items, thought, .positions) }); + try out.put(a, "positions", .{ .object = at }); + } return .{ .object = out }; } }; -/// The newly settled entries of one channel past `sent`, which grows by their count. -fn fresh(srv: *Server, a: A, s: *const Spelled, tokens: []const u32, rows: []const api.LogprobRow, ranges: []const Range, channel: Channel, sent: *usize) Error![]V { +/// The newly settled pieces of one channel past `sent`, which grows by their count. +fn fresh(a: A, s: *const Spelled, ranges: []const Range, channel: Channel, sent: *usize) Error![]const Piece { const all = try pieces(a, s, ranges, channel, 0); var end = sent.*; while (end < all.len and all[end].settled) end += 1; if (end <= sent.*) return &.{}; - const out = try values(srv, a, s, tokens, rows, all[sent.*..end]); - sent.* = end; - return out; + defer sent.* = end; + return all[sent.*..end]; } /// ``choices[0].logprobs``: prose in ``content``, ``reasoning_content``, and one ``{index, content}`` group a call. -pub fn project(srv: *Server, cx: *Cx, c: Capture, content: []const u8, reasoning: ?[]const u8, tools: []const V, calls: ?[]V) errors.Refused!V { +pub fn project(srv: *Server, cx: *Cx, c: Capture, content: []const u8, reasoning: ?[]const u8, tools: []const V, calls: ?[]V, form: Form) errors.Refused!V { const a = cx.a; if (c.rows.len < c.tokens.len) return cx.other("the engine gave fewer logprob rows than reply tokens"); - return whole(srv, a, c, .{ .content = content, .reasoning = reasoning, .tools = tools, .calls = if (calls) |list| list.len else null }) catch |e| switch (e) { + return whole(srv, a, c, .{ .content = content, .reasoning = reasoning, .tools = tools, .calls = if (calls) |list| list.len else null }, form) catch |e| switch (e) { error.OutOfMemory => error.OutOfMemory, error.Failed => cx.other("the logprob rows are out of step with the reply's tokens, or a token has no exact bytes"), }; } -fn whole(srv: *Server, a: A, c: Capture, shown: Shown) Error!V { +fn whole(srv: *Server, a: A, c: Capture, shown: Shown, form: Form) Error!V { var s: Spelled = .{}; try s.add(srv, a, c.tokens); const visible = c.stops.visible(s.raw.items, false); @@ -97,14 +106,14 @@ fn whole(srv: *Server, a: A, c: Capture, shown: Shown) Error!V { const text = if (c.closer.len > 0) try std.mem.concat(a, u8, &.{ visible, c.closer }) else visible; const ranges = try layout(srv, a, text, c.tokens, c.thinking, true, shown); const out = try json.newObject(a); - try out.put(a, "content", .{ .array = try values(srv, a, &s, c.tokens, c.rows, try pieces(a, &s, ranges, .content, 0)) }); - if (shown.reasoning != null or c.thinking) try out.put(a, "reasoning_content", .{ .array = try values(srv, a, &s, c.tokens, c.rows, try pieces(a, &s, ranges, .reasoning, 0)) }); + try out.put(a, "content", .{ .array = try values(srv, a, &s, c.tokens, c.rows, try pieces(a, &s, ranges, .content, 0), form) }); + if (shown.reasoning != null or c.thinking) try out.put(a, "reasoning_content", .{ .array = try values(srv, a, &s, c.tokens, c.rows, try pieces(a, &s, ranges, .reasoning, 0), form) }); const count = shown.calls orelse return .{ .object = out }; const groups = try a.alloc(V, count); for (groups, 0..) |*slot, i| { const o = try json.newObject(a); try o.put(a, "index", try json.intValue(a, i)); - try o.put(a, "content", .{ .array = try values(srv, a, &s, c.tokens, c.rows, try pieces(a, &s, ranges, .tool, i)) }); + try o.put(a, "content", .{ .array = try values(srv, a, &s, c.tokens, c.rows, try pieces(a, &s, ranges, .tool, i), form) }); slot.* = .{ .object = o }; } try out.put(a, "tool_calls", .{ .array = groups }); @@ -128,9 +137,23 @@ pub fn rest(a: A, rows: V, sent: Sent) A.Error!?V { return if (left) .{ .object = out } else null; } -fn values(srv: *Server, a: A, s: *const Spelled, tokens: []const u32, rows: []const api.LogprobRow, list: []const Piece) Error![]V { +/// The last chunk's delta: entries no chunk carried yet, with a token stream's positions; null when none are left. +pub fn restDelta(a: A, reply: *const @import("chat.zig").Reply) A.Error!?V { + const sent = (reply.probability_rows orelse return null).sent; + const left = (try rest(a, reply.logprobs orelse return null, sent)) orelse return null; + const out = try json.newObject(a); + try out.put(a, "logprobs", left); + if (reply.logprob_positions) |at| if (try rest(a, at, sent)) |p| try out.put(a, "logprob_positions", p); + return .{ .object = out }; +} + +fn values(srv: *Server, a: A, s: *const Spelled, tokens: []const u32, rows: []const api.LogprobRow, list: []const Piece, form: Form) Error![]V { const out = try a.alloc(V, list.len); for (list, out) |p, *slot| { + if (form == .positions) { + slot.* = try json.intValue(a, p.token); + continue; + } const cropped = p.lo != s.from(p.token) or p.hi != s.ends.items[p.token]; slot.* = try lp.rowValue(srv, a, tokens[p.token], rows[p.token], s.raw.items[p.lo..p.hi], cropped); } diff --git a/zig/src/server/logprob_parts_test.zig b/zig/src/server/logprob_parts_test.zig index 454f0936beb..9062f849626 100644 --- a/zig/src/server/logprob_parts_test.zig +++ b/zig/src/server/logprob_parts_test.zig @@ -184,7 +184,7 @@ test "logprob combinations: a call past parallel_tool_calls false is dropped, no const parsed = try @import("tool_parse.zig").parse(a, reply, tools, 1); try std.testing.expectEqualStrings("ab", parsed.content); var cx: errors.Cx = .{ .a = a }; - const lp = try @import("logprob_parts.zig").project(srv, &cx, .{ .tokens = ids, .rows = rows, .thinking = false, .stops = .{ .strings = &.{} } }, parsed.content, null, tools, parsed.calls); + const lp = try @import("logprob_parts.zig").project(srv, &cx, .{ .tokens = ids, .rows = rows, .thinking = false, .stops = .{ .strings = &.{} } }, parsed.content, null, tools, parsed.calls, .entries); const prose = lp.get("content").?.array; try std.testing.expectEqualStrings("ab", try spell(a, lp.get("content").?)); try std.testing.expectEqual(-@as(f64, @floatFromInt(reply.len)), prose[1].get("logprob").?.float); diff --git a/zig/src/server/logprobs.zig b/zig/src/server/logprobs.zig index f647e0e1c08..5a364aed405 100644 --- a/zig/src/server/logprobs.zig +++ b/zig/src/server/logprobs.zig @@ -92,7 +92,9 @@ pub fn offered(srv: *Server, a: Allocator) Allocator.Error!bool { /// ``reply.logprobs`` from its captured rows, once the route's tool policy has settled its content and calls. pub fn project(srv: *Server, cx: *Cx, reply: *@import("chat.zig").Reply, tools: []const Value, calls: ?[]Value) errors.Refused!void { const captured = reply.probability_rows orelse return; - reply.logprobs = try @import("logprob_parts.zig").project(srv, cx, captured, reply.content, reply.reasoning, tools, calls); + const parts = @import("logprob_parts.zig"); + reply.logprobs = try parts.project(srv, cx, captured, reply.content, reply.reasoning, tools, calls, .entries); + if (captured.positions) reply.logprob_positions = try parts.project(srv, cx, captured, reply.content, reply.reasoning, tools, calls, .positions); } /// One token's entry; a token the reply shows only part of keeps its row but shows those `bytes` and its ``token_id``. diff --git a/zig/src/server/main.zig b/zig/src/server/main.zig index c6d4f8081a7..4f3c5296f51 100644 --- a/zig/src/server/main.zig +++ b/zig/src/server/main.zig @@ -2,6 +2,7 @@ const std = @import("std"); const json = @import("json"); const cli = @import("cli.zig"); +const cli_config = @import("cli_config.zig"); const log = @import("log.zig"); const hub = @import("hub.zig"); const engines = @import("engines.zig"); @@ -18,7 +19,7 @@ const checkpoint_cli = @import("checkpoint_cli"); const pdf_worker = @import("pdf_worker.zig"); const web_cli = @import("web_cli.zig"); -const usage_line = "usage: tensorfold serve [-h] [--host HOST] [--port PORT] [--unix-socket PATH] [--name NAME] [--chat-template FILE]" ++ +const usage_line = "usage: tensorfold serve [-h] [--config FILE.toml] [--host HOST] [--port PORT] [--unix-socket PATH] [--name NAME] [--chat-template FILE]" ++ " [--alias ALIAS] [--allowed-host NAME] [--allowed-origin ORIGIN] [--api-key API_KEY] [--api-key-file API_KEY_FILE] [--metrics-open] [--dashboard]" ++ " [--max-inflight N] [--max-inflight-per-key N] [--requests-per-second N] [--request-burst N]" ++ " [--max-connections N] [--max-connections-per-address N] [--trusted-proxy ADDRESS]" ++ @@ -103,13 +104,22 @@ pub fn main(init: std.process.Init) !u8 { } const started = std.Io.Clock.awake.now(io).toNanoseconds(); var u: cli.Usage = .{}; - var args = cli.parse(a, argv[2..], &u) catch |e| switch (e) { + const expanded = cli_config.expand(a, argv[2..], &u) catch |e| switch (e) { error.Usage => { std.debug.print("{s}tensorfold serve: error: {s}\n", .{ usage_line, u.message }); return 2; }, else => |x| return x, }; + var args = cli.parse(a, expanded.argv, &u) catch |e| switch (e) { + error.Usage => { + std.debug.print("{s}tensorfold serve: error: {s}\n", .{ usage_line, u.message }); + if (try cli_config.note(a, expanded)) |n| std.debug.print("tensorfold serve: {s}\n", .{n}); + return 2; + }, + else => |x| return x, + }; + if (expanded.path) |path| log.line("config: {s} ({d} options)", .{ path, expanded.options }); if (try engines.environment(a, args)) |why| return fail(why); const receipt = @import("core").startup_receipt; receipt.enable(io, entry, try @import("sys").environment.read(bool, "TF_STARTUP_RECEIPT", false)); diff --git a/zig/src/server/models_idle_audit_test.zig b/zig/src/server/models_idle_audit_test.zig index 64a55d8b41d..28c280d1545 100644 --- a/zig/src/server/models_idle_audit_test.zig +++ b/zig/src/server/models_idle_audit_test.zig @@ -43,6 +43,7 @@ test "capability audit: model discovery waits for an idle reload and reads the p srv.thinking_switch = false; srv.effort_levels = &.{}; srv.think_close = &.{}; + srv.video_decoder = false; // discovery reads it for input_types (#3004) // Discovery reads the template for effort use; this one names none. var text_vtable: @TypeOf(srv.text.vtable.*) = undefined; text_vtable.template_source = struct { diff --git a/zig/src/server/models_input_types_test.zig b/zig/src/server/models_input_types_test.zig new file mode 100644 index 00000000000..2e39c9a92d0 --- /dev/null +++ b/zig/src/server/models_input_types_test.zig @@ -0,0 +1,135 @@ +//! /v1/models' input_types (#3004) through the route, and a video_url part to a server that takes no video: a 400. +const std = @import("std"); +const api = @import("engine_api"); +const json = @import("json"); +const Server = @import("server.zig").Server; +const Conn = @import("http_conn.zig").Conn; +const Cx = @import("errors.zig").Cx; +const messages = @import("messages.zig"); +const images = @import("images.zig"); +const t = std.testing; + +const Wire = struct { + out: std.Io.Writer.Allocating, + fn write(ctx: *anyopaque, bytes: []const u8) error{Closed}!void { + const self: *Wire = @ptrCast(@alignCast(ctx)); + self.out.writer.writeAll(bytes) catch return error.Closed; + } +}; + +fn noImage(_: *anyopaque, _: std.mem.Allocator, _: []const u8, _: u32) anyerror!api.PreparedImage { + return error.Unused; +} + +fn noVideo(_: *anyopaque, _: std.mem.Allocator, _: api.VideoSource, _: u32, _: u32) anyerror!api.PreparedVideo { + return error.Unused; +} + +var dummy: u8 = 0; + +/// An image offer, and with `video` the video offer a checkpoint with a video token makes. +fn offer(video: bool) api.Vision { + var v: api.Vision = .{ .ctx = &dummy, .prepare = noImage, .image_token = 9, .image_tokens = 64, .max_images = 4 }; + if (video) v.video = .{ .prepare = noVideo, .video_token = 8, .group_open = 6, .group_close = 7, .video_tokens = 64, .max_videos = 2, .max_frames = 256 }; + return v; +} + +var text_vtable: @import("model_text.zig").Text.VTable = undefined; + +fn noTemplate(_: *anyopaque) []const u8 { + return ""; +} + +/// A server with only discovery's and media's fields set: no engine, model or tokenizer. +fn server(vision: ?api.Vision, video_decoder: bool) Server { + var srv: Server = undefined; + srv.io = t.io; + srv.info = .{ .vision = vision }; + srv.config = .{ .served_name = "model", .model_ids = &.{ "model", "alias" } }; + srv.idle_manager = null; + srv.thinking_switch = false; + srv.effort_levels = &.{}; + srv.think_close = &.{}; + srv.video_decoder = video_decoder; + text_vtable.template_source = noTemplate; + srv.text = .{ .ctx = undefined, .vtable = &text_vtable }; + return srv; +} + +/// GET /v1/models' `data`, as a client reads it. +fn listed(a: std.mem.Allocator, srv: *Server) ![]json.Value { + var wire: Wire = .{ .out = .init(a) }; + var conn: Conn = .{ .fd = -1, .peer = "", .buf = &.{}, .gpa = a, .version = "HTTP/1.1", .method = "GET", .write_hooks = .{ .ctx = &wire, .write = Wire.write } }; + try @import("status_routes.zig").models(srv, &conn, a); + const bytes = wire.out.written(); + const split = std.mem.indexOf(u8, bytes, "\r\n\r\n").? + 4; + return (try json.parse(a, bytes[split..])).ok.get("data").?.array; +} + +test "model discovery input types: text only, image, and image and video, last in every entry" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const Case = struct { vision: ?api.Vision, decoder: bool, want: []const []const u8 }; + const cases = [_]Case{ + .{ .vision = null, .decoder = true, .want = &.{"text"} }, + .{ .vision = offer(false), .decoder = true, .want = &.{ "text", "image" } }, + .{ .vision = offer(true), .decoder = true, .want = &.{ "text", "image", "video" } }, + // the checkpoint offers video but libtfvideo does not load here: no video, as the refusal below says + .{ .vision = offer(true), .decoder = false, .want = &.{ "text", "image" } }, + }; + // every key before it is main's, in main's order (context_window 0 adds no length keys) + const keys = [_][]const u8{ "id", "object", "created", "owned_by", "capabilities", "input_types" }; + for (cases) |c| { + var srv = server(c.vision, c.decoder); + for (try listed(a, &srv)) |model| { + try t.expectEqual(keys.len, model.object.count()); + for (keys, model.object.keys()) |want, got| try t.expectEqualStrings(want, got); + const types = model.get("input_types").?.array; + try t.expectEqual(c.want.len, types.len); + for (c.want, types) |want, got| try t.expectEqualStrings(want, got.string); + } + } +} + +test "model discovery input types: a video_url part to a model that takes no video is a named 400" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const body = (try json.parse(a, + \\[{"role": "user", "content": [{"type": "video_url", "video_url": {"url": "data:video/mp4;base64,YQ=="}}, {"type": "text", "text": "x"}]}] + )).ok; + // an image model, and a video checkpoint on a server without libtfvideo (main lets the second through to a 500) + for ([_]Server{ server(offer(false), true), server(offer(true), false) }) |srv_value| { + var srv = srv_value; + for (try listed(a, &srv)) |model| for (model.get("input_types").?.array) |ty| try t.expect(!std.mem.eql(u8, ty.string, "video")); + var cx: Cx = .{ .a = a }; + try t.expectError(error.Refused, messages.normalizeWith(&cx, body, "system", false, srv.media())); + try t.expectEqual(@as(u16, 400), cx.status()); + try t.expectEqualStrings("content parts must be text or image_url; audio and video inputs are unsupported", cx.message); + } + // the same request where video is listed passes normalization + var srv = server(offer(true), true); + var cx: Cx = .{ .a = a }; + _ = try messages.normalizeWith(&cx, body, "system", false, srv.media()); +} + +test "model discovery input types: a video the decoder library cannot open is a 400 that names it, not a 500" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + // this host's libtfvideo would decode the bytes instead (CI hosts have none): ask the loader the video uses + const sys = @import("sys"); + const quiet = sys.optional_libraries.atBoundary(); + const loads = api.tfvideo.version() != null; + quiet.deinit(); + if (loads) return error.SkipZigTest; + const body = (try json.parse(a, + \\[{"role": "user", "content": [{"type": "video_url", "video_url": {"url": "data:video/mp4;base64,YQ=="}}]}] + )).ok; + var cx: Cx = .{ .a = a }; + try t.expectError(error.Refused, images.expand(offer(true), null, images.MarkText.text(), &cx, body, &[_]u32{8}, 0)); + try t.expectEqual(@as(u16, 400), cx.status()); + try t.expect(std.mem.startsWith(u8, cx.message, "video 1: this server takes no video input: ")); + try t.expect(std.mem.indexOf(u8, cx.message, sys.optional_libraries.spec(.video).names[0]) != null); +} diff --git a/zig/src/server/ollama.zig b/zig/src/server/ollama.zig new file mode 100644 index 00000000000..2e36678eb1d --- /dev/null +++ b/zig/src/server/ollama.zig @@ -0,0 +1,359 @@ +//! Ollama's HTTP API on the native server: chat, generate, embeddings and discovery, translated onto the OpenAI seam. +const std = @import("std"); +const json = @import("json"); +const openai = @import("openai.zig"); +const embeddings = @import("embeddings.zig"); +const http_body = @import("http_body.zig"); +const routes = @import("routes.zig"); +const sse = @import("sse.zig"); +const Server = @import("server.zig").Server; +const Conn = @import("http_conn.zig").Conn; +const Cx = @import("errors.zig").Cx; +const errors = @import("errors.zig"); +const Value = json.Value; +const Allocator = std.mem.Allocator; + +const mapped = [_][]const u8{ "temperature", "top_k", "top_p", "min_p", "stop", "seed", "presence_penalty", "frequency_penalty" }; + +/// Translate Ollama's `options` and `think` onto the chat request the engine already reads. +pub fn options(a: Allocator, window: u32, raw: Value, out: *json.Object, cx: *Cx) errors.Refused!void { + _ = a; + if (raw.get("options")) |opts| { + if (opts != .object) return cx.refuse("options must be an object"); + var it = opts.object.iterator(); + while (it.next()) |entry| { + const key = entry.key_ptr.*; + if (std.mem.eql(u8, key, "num_ctx")) { + const v = entry.value_ptr.*; + if (v == .int) if ((std.fmt.parseInt(i64, v.int, 10) catch 0) > @as(i64, @intCast(window))) + return cx.refuse("num_ctx is above this model's context window"); + continue; + } + var known = std.mem.eql(u8, key, "num_predict"); + for (mapped) |name| known = known or std.mem.eql(u8, key, name); + if (!known) return cx.refuse(std.fmt.allocPrint(cx.a, "option {s} is not supported by this engine", .{key}) catch return error.OutOfMemory); + } + for (mapped) |key| if (opts.get(key)) |v| try out.put(cx.a, key, v); + if (opts.get("num_predict")) |v| try out.put(cx.a, "max_tokens", v); + } + if (raw.get("think")) |think| { + if (think != .bool) return cx.refuse("think must be a boolean"); + const kwargs = try json.newObject(cx.a); + try kwargs.put(cx.a, "enable_thinking", think); + try out.put(cx.a, "chat_template_kwargs", .{ .object = kwargs }); + } +} + +/// `/api/chat` and `/api/generate` body as a chat request with `return_token_ids` on. +pub fn chatBody(a: Allocator, model: []const u8, window: u32, raw: Value, cx: *Cx) errors.Refused!Value { + if (raw != .object) return cx.refuse("request body must be an object"); + const out = try json.newObject(a); + try out.put(a, "model", .{ .string = model }); + if (raw.get("messages")) |messages| { + if (messages != .array) return cx.refuse("messages must be an array"); + try out.put(a, "messages", messages); + } else if (raw.get("prompt")) |prompt| { + if (prompt != .string) return cx.refuse("prompt must be a string"); + const list = try a.alloc(Value, 1); + const message = try json.newObject(a); + try message.put(a, "role", .{ .string = "user" }); + try message.put(a, "content", prompt); + list[0] = .{ .object = message }; + try out.put(a, "messages", .{ .array = list }); + } else return cx.refuse("a chat request needs messages; a generate request needs a prompt"); + if (raw.get("system")) |system| { + if (system != .string) return cx.refuse("system must be a string"); + const messages = out.get("messages").?.array; + const list = try a.alloc(Value, messages.len + 1); + const first = try json.newObject(a); + try first.put(a, "role", .{ .string = "system" }); + try first.put(a, "content", system); + list[0] = .{ .object = first }; + @memcpy(list[1..], messages); + try out.put(a, "messages", .{ .array = list }); + } + if (raw.get("format")) |format| switch (format) { + .string => |name| { + if (!std.mem.eql(u8, name, "json")) return cx.refuse("format must be \"json\" or a JSON schema object"); + const rf = try json.newObject(a); + try rf.put(a, "type", .{ .string = "json_object" }); + try out.put(a, "response_format", .{ .object = rf }); + }, + .object => { + const rf = try json.newObject(a); + try rf.put(a, "type", .{ .string = "json_schema" }); + const js = try json.newObject(a); + try js.put(a, "schema", format); + try rf.put(a, "json_schema", .{ .object = js }); + try out.put(a, "response_format", .{ .object = rf }); + }, + else => return cx.refuse("format must be \"json\" or a JSON schema object"), + }; + if (raw.get("tools")) |tools| { + if (tools != .array) return cx.refuse("tools must be an array"); + try out.put(a, "tools", tools); + if (raw.get("tool_choice")) |choice| try out.put(a, "tool_choice", choice); + } else if (raw.get("tool_choice") != null) return cx.refuse("tool_choice needs tools"); + if (raw.get("images") != null) return cx.refuse("images are not supported by this engine"); + if (raw.get("stream")) |stream| { + if (stream != .bool) return cx.refuse("stream must be true, false or absent"); + try out.put(a, "stream", stream); + } + try out.put(a, "return_token_ids", .{ .bool = true }); + try options(a, window, raw, out, cx); + return .{ .object = out }; +} + +/// The NDJSON sink: one JSON object per line, no SSE framing. +const Wire = struct { + conn: *Conn, + a: Allocator, + model: []const u8, + created: i64, + generated: std.ArrayList(u8) = .empty, + last: ?Value = null, + streaming: bool = false, + generate: bool = false, + finished: bool = false, + + fn out(w: *Wire) openai.Out { + return .{ .ctx = w, .vt = &.{ .open = open, .event = event, .reply = reply } }; + } + fn open(_: *anyopaque, _: usize) error{Closed}!void {} + fn line(w: *Wire, value: Value) error{Closed}!void { + const text = json.stringify(w.a, value, .{ .compact = true }) catch return error.Closed; + w.conn.writeAll(text) catch return error.Closed; + w.conn.writeAll("\n") catch return error.Closed; + } + fn base(w: *Wire, a: Allocator) !*json.Object { + const o = try json.newObject(a); + try o.put(a, "model", .{ .string = w.model }); + try o.put(a, "created_at", .{ .string = try rfc3339(a, w.created) }); + return o; + } + fn finish(w: *Wire, value: Value) !void { + w.last = value; + } + fn putContent(w: *Wire, o: *json.Object, text: []const u8) !void { + if (w.generate) { + try o.put(w.a, "response", .{ .string = text }); + return; + } + const m = try json.newObject(w.a); + try m.put(w.a, "role", .{ .string = "assistant" }); + try m.put(w.a, "content", .{ .string = text }); + try o.put(w.a, "message", .{ .object = m }); + } + fn event(ctx: *anyopaque, payload: ?Value) error{Closed}!void { + const w: *Wire = @ptrCast(@alignCast(ctx)); + const p = payload orelse { + w.doneLine() catch return error.Closed; + return; + }; + // A stream that opened and then failed ends with an error line, never a success line. + if (p == .object) if (p.get("error")) |e| { + const message: []const u8 = if (e == .object) + (e.strField("message") orelse "the request failed") + else if (e == .string) + e.string + else + "the request failed"; + const o = json.newObject(w.a) catch return error.Closed; + o.put(w.a, "error", .{ .string = message }) catch return error.Closed; + w.line(.{ .object = o }) catch return error.Closed; + w.finished = true; + return; + }; + w.finish(p) catch return error.Closed; + if (p != .object) return; + const choices = p.get("choices") orelse return; + if (choices != .array or choices.array.len == 0) return; + const delta = choices.array[0].get("delta") orelse choices.array[0].get("text") orelse return; + const text = if (delta == .string) delta.string else delta.strField("content") orelse return; + if (text.len == 0) return; + w.generated.appendSlice(w.a, text) catch return error.Closed; + const o = w.base(w.a) catch return error.Closed; + w.putContent(o, text) catch return error.Closed; + o.put(w.a, "done", .{ .bool = false }) catch return error.Closed; + w.line(.{ .object = o }) catch return error.Closed; + } + fn reply(ctx: *anyopaque, status: u16, payload: Value) void { + const w: *Wire = @ptrCast(@alignCast(ctx)); + if (status != 200) { + const o = json.newObject(w.a) catch return; + const message = if (payload == .object) + (if (payload.get("error")) |e| (if (e == .object) e.strField("message") else e.str()) else payload.strField("message")) orelse "the request failed" + else + "the request failed"; + o.put(w.a, "error", .{ .string = message }) catch return; + w.line(.{ .object = o }) catch return; + w.finished = true; + return; + } + w.finish(payload) catch {}; + if (payload == .object) if (payload.get("choices")) |choices| { + if (choices == .array and choices.array.len > 0) { + const first = choices.array[0]; + const text = if (first.get("message")) |m| m.strField("content") orelse "" else first.strField("text") orelse ""; + w.generated.clearRetainingCapacity(); + w.generated.appendSlice(w.a, text) catch {}; + } + }; + w.doneLine() catch {}; + } + fn doneLine(w: *Wire) !void { + if (w.finished) return; + w.finished = true; + const o = try w.base(w.a); + try w.putContent(o, if (w.streaming) "" else w.generated.items); + const last = w.last; + if (last) |value| if (value == .object) { + if (value.get("tensorfold")) |t| if (t == .object) { + if (t.get("prefill_seconds")) |v| try o.put(w.a, "prompt_eval_duration", try duration(w.a, v)); + if (t.get("seconds")) |v| try o.put(w.a, "eval_duration", try duration(w.a, v)); + if (t.get("token_ids")) |ids| if (ids == .array) { + try o.put(w.a, "eval_count", try json.intValue(w.a, ids.array.len)); + try o.put(w.a, "token_ids", ids); + }; + }; + if (value.get("usage")) |u| if (u == .object) { + if (u.get("prompt_tokens")) |v| try o.put(w.a, "prompt_eval_count", v); + }; + const choices = value.get("choices") orelse Value.null; + if (choices == .array and choices.array.len > 0) if (choices.array[0].get("finish_reason")) |reason| + try o.put(w.a, "done_reason", reason); + }; + if (o.get("done_reason") == null) try o.put(w.a, "done_reason", .{ .string = "stop" }); + try o.put(w.a, "done", .{ .bool = true }); + try w.line(.{ .object = o }); + } +}; + +/// RFC 3339 UTC time from Unix seconds, as Ollama's `created_at` field. +fn rfc3339(a: Allocator, secs: i64) ![]const u8 { + const es = std.time.epoch.EpochSeconds{ .secs = if (secs < 0) 0 else @intCast(secs) }; + const yd = es.getEpochDay().calculateYearDay(); + const md = yd.calculateMonthDay(); + const ds = es.getDaySeconds(); + return std.fmt.allocPrint(a, "{d:0>4}-{d:0>2}-{d:0>2}T{d:0>2}:{d:0>2}:{d:0>2}Z", .{ + yd.year, md.month.numeric(), @as(u8, md.day_index) + 1, + ds.getHoursIntoDay(), ds.getMinutesIntoHour(), ds.getSecondsIntoMinute(), + }); +} + +fn duration(a: Allocator, seconds: Value) !Value { + const value: f64 = switch (seconds) { + .float => |f| f, + .int => std.fmt.parseFloat(f64, seconds.int) catch 0, + else => 0, + }; + return json.intValue(a, @as(i64, @intFromFloat(@max(0, value) * 1e9))); +} + +pub fn chat(srv: *Server, conn: *Conn, a: Allocator) void { + serve(srv, conn, a, false); +} + +pub fn generate(srv: *Server, conn: *Conn, a: Allocator) void { + serve(srv, conn, a, true); +} + +fn serve(srv: *Server, conn: *Conn, a: Allocator, is_generate: bool) void { + var cx: Cx = .{ .a = a }; + const raw = http_body.readJson(conn, &cx) catch { + const err = openai.errorBody(a, &cx, "messages") catch return; + return routes.sendValue(conn, a, cx.status(), openai.wrapError(a, err) catch return); + }; + const translated = chatBody(a, srv.config.served_name, @intCast(srv.info.context_window), raw, &cx) catch { + const err = openai.errorBody(a, &cx, "messages") catch return; + return routes.sendValue(conn, a, cx.status(), openai.wrapError(a, err) catch return); + }; + // A refusal must keep its status: plan before the 200 head goes out. + var pre: Cx = .{ .a = a }; + _ = openai.plan(srv, &pre, true, translated, null, true) catch { + const err = openai.errorBody(a, &pre, "messages") catch return; + return routes.sendValue(conn, a, pre.status(), openai.wrapError(a, err) catch return); + }; + const streaming = if (raw.get("stream")) |v| v.truthy() else false; + var wire: Wire = .{ + .conn = conn, + .a = a, + .model = srv.config.served_name, + .created = std.Io.Clock.real.now(srv.io).toSeconds(), + .streaming = streaming, + .generate = is_generate, + }; + conn.startResponse(200, null) catch return; + conn.addHeader("Content-Type", "application/x-ndjson") catch return; + conn.addHeader("Connection", "close") catch return; + conn.finish("") catch return; + openai.runNamed(srv, a, wire.out(), .{ .conn = conn }, true, translated, null, true, true); +} + +pub fn embed(srv: *Server, conn: *Conn, a: Allocator) void { + var cx: Cx = .{ .a = a }; + const raw = http_body.readJson(conn, &cx) catch { + const err = openai.errorBody(a, &cx, "input") catch return; + return routes.sendValue(conn, a, cx.status(), openai.wrapError(a, err) catch return); + }; + const Gone = struct { + c: *Conn, + pub fn check(g: @This()) bool { + return g.c.peerGone(); + } + }; + const value = embeddings.reply(srv, &cx, raw, Gone{ .c = conn }) catch { + const err = openai.errorBody(a, &cx, "input") catch return; + return routes.sendValue(conn, a, cx.status(), openai.wrapError(a, err) catch return); + }; + const out = json.newObject(a) catch return; + out.put(a, "model", .{ .string = srv.config.served_name }) catch return; + const source = if (value == .object) value.get("data") else null; + const rows: []const Value = if (source != null and source.? == .array) source.?.array else &.{}; + const list = a.alloc(Value, rows.len) catch return; + for (rows, list) |item, *slot| slot.* = if (item == .object) item.get("embedding") orelse Value{ .array = &.{} } else .{ .array = &.{} }; + out.put(a, "embeddings", .{ .array = list }) catch return; + if (value == .object) if (value.get("usage")) |u| if (u == .object) if (u.get("prompt_tokens")) |v| + out.put(a, "prompt_eval_count", v) catch return; + return routes.sendValue(conn, a, 200, .{ .object = out }); +} + +pub fn tags(srv: *Server, conn: *Conn, a: Allocator) void { + const list = a.alloc(Value, srv.config.model_ids.len) catch return; + for (srv.config.model_ids, list) |id, *slot| { + const model = json.newObject(a) catch return; + model.put(a, "name", .{ .string = id }) catch return; + model.put(a, "model", .{ .string = id }) catch return; + slot.* = .{ .object = model }; + } + const o = json.newObject(a) catch return; + o.put(a, "models", .{ .array = list }) catch return; + routes.sendValue(conn, a, 200, .{ .object = o }); +} + +pub fn show(srv: *Server, conn: *Conn, a: Allocator) void { + _ = http_body.read(conn, a, http_body.limit) catch {}; + const o = json.newObject(a) catch return; + o.put(a, "modelfile", .{ .string = "" }) catch return; + o.put(a, "parameters", .{ .string = "" }) catch return; + o.put(a, "template", .{ .string = srv.text.templateSource() }) catch return; + o.put(a, "details", .{ .object = json.newObject(a) catch return }) catch return; + routes.sendValue(conn, a, 200, .{ .object = o }); +} + +pub fn ps(srv: *Server, conn: *Conn, a: Allocator) void { + const o = json.newObject(a) catch return; + const list = a.alloc(Value, 1) catch return; + const model = json.newObject(a) catch return; + model.put(a, "name", .{ .string = srv.config.served_name }) catch return; + model.put(a, "model", .{ .string = srv.config.served_name }) catch return; + list[0] = .{ .object = model }; + o.put(a, "models", .{ .array = list }) catch return; + routes.sendValue(conn, a, 200, .{ .object = o }); +} + +pub fn version(srv: *const Server, conn: *Conn, a: Allocator) void { + const o = json.newObject(a) catch return; + o.put(a, "version", .{ .string = srv.config.identity.version }) catch return; + routes.sendValue(conn, a, 200, .{ .object = o }); +} diff --git a/zig/src/server/ollama_e2e_test.zig b/zig/src/server/ollama_e2e_test.zig new file mode 100644 index 00000000000..b951139d487 --- /dev/null +++ b/zig/src/server/ollama_e2e_test.zig @@ -0,0 +1,463 @@ +//! Ollama routes over a real loopback socket with the CPU fake engine: replies end, NDJSON is whole, tokens agree. +const std = @import("std"); +const api = @import("engine_api"); +const json = @import("json"); +const server = @import("server.zig"); +const auth = @import("auth.zig"); +const listener = @import("listener.zig"); +const model_text = @import("model_text.zig"); +const ByteText = @import("embedding_protocol_test.zig").ByteText; +const Text = struct { + const table = blk: { + var base = ByteText.model().vtable.*; + base.render = render; + base.decode = decode; + break :blk base; + }; + fn model() model_text.Text { + return .{ .ctx = undefined, .vtable = &table }; + } + fn render(_: *anyopaque, a: Allocator, _: json.Value, _: model_text.RenderOptions, _: *[]const u8) model_text.Error!model_text.Rendered { + return .{ .text = try a.dupe(u8, "prompt") }; + } + fn decode(_: *anyopaque, a: Allocator, ids: []const u32) ![]u8 { + const out = try a.alloc(u8, ids.len); + for (out, ids) |*byte, id| byte.* = @intCast(id); + return out; + } +}; +const KeyFile = @import("auth_scope_test.zig").KeyFile; +const posix = @import("sys").posix; +const t = std.testing; +const Allocator = std.mem.Allocator; + +const Engine = struct { + embed: bool = false, + fail_after_tokens: bool = false, + fn engine(e: *Engine) api.Engine { + return .{ .ctx = e, .vtable = &.{ .info = info, .submit = submit, .cancel = cancel, .status = status, .memory = memory } }; + } + fn cast(ptr: *anyopaque) *Engine { + return @ptrCast(@alignCast(ptr)); + } + fn info(ptr: *anyopaque) api.Info { + const e = cast(ptr); + if (e.embed) return .{ + .context_window = 4096, + .name = "fake-model", + .text_generation = false, + .embeddings = .{ .dimensions = 2, .vocabulary = 256, .max_batch_tokens = 128 }, + }; + return .{ .context_window = 4096, .name = "fake-model" }; + } + fn submit(ptr: *anyopaque, id: api.Id, request: *const api.Request, sink: api.Sink) api.SubmitError!void { + const e = cast(ptr); + if (e.embed) { + if (request.embedding) |batch| { + for (batch.output) |*v| v.* = 0.5; + } + sink.event(sink.ctx, id, &.{ .finished = .{ .reason = .length } }); + return; + } + sink.event(sink.ctx, id, &.{ .prefilled = 0 }); + sink.event(sink.ctx, id, &.{ .tokens = &.{ 2, 7, 1 } }); + if (e.fail_after_tokens) return error.Closed; + sink.event(sink.ctx, id, &.{ .finished = .{ .reason = .stop } }); + } + fn cancel(_: *anyopaque, _: api.Id) void {} + fn status(_: *anyopaque, out: *api.Status, _: []u32) void { + out.* = .{}; + } + fn memory(_: *anyopaque, _: bool) ?api.Memory { + return null; + } +}; + +const Harness = struct { + srv: *server.Server = undefined, + listener: listener.Listener = undefined, + accept: std.Thread = undefined, + stop: std.atomic.Value(bool) = .init(false), + log_path: ?[]const u8 = null, + + fn start(h: *Harness, engine: *Engine, keys: ?*auth.Store) !void { + h.srv = try server.Server.init(t.allocator, t.io, engine.engine(), Text.model(), .{ + .served_name = "fake-model", + .model_ids = &.{"fake-model"}, + .request_log = h.log_path, + .enable_thinking = false, + .use_drafts = false, + .keep_warm_s = 0, + }, keys); + errdefer h.srv.deinit(); + h.listener = try listener.Listener.open(.{ .ip4 = .loopback(0) }); + errdefer h.listener.close(); + h.accept = try std.Thread.spawn(.{}, server.Server.serve, .{ h.srv, h.listener, &h.stop }); + } + fn deinit(h: *Harness) void { + h.stop.store(true, .release); + h.accept.join(); + var waited: usize = 0; + while (h.srv.open_connections.load(.acquire) > 0) : (waited += 1) { + if (waited == 30000) @panic("ollama fixture did not quiesce"); + std.Io.sleep(t.io, .fromMilliseconds(1), .awake) catch {}; + } + h.listener.close(); + h.srv.deinit(); + } + fn exchange(h: *Harness, a: Allocator, raw: []const u8) ![]const u8 { + const address: std.Io.net.IpAddress = .{ .ip4 = .loopback(h.listener.port()) }; + var storage: std.Io.Threaded.PosixAddress = undefined; + const len = std.Io.Threaded.addressToPosix(&address, &storage); + const rc = posix.system.socket(posix.AF.INET, posix.SOCK.STREAM, 0); + if (posix.errno(rc) != .SUCCESS) return error.Socket; + const fd: posix.socket_t = @intCast(rc); + defer _ = posix.system.close(fd); + if (posix.errno(posix.system.connect(fd, &storage.any, len)) != .SUCCESS) return error.Connect; + var sent: usize = 0; + while (sent < raw.len) { + const n = posix.system.write(fd, raw[sent..].ptr, raw.len - sent); + if (posix.errno(n) != .SUCCESS or n == 0) return error.Write; + sent += @intCast(n); + } + var out: std.ArrayList(u8) = .empty; + var buffer: [4096]u8 = undefined; + while (true) { + var fds = [_]posix.pollfd{.{ .fd = fd, .events = posix.POLL.IN, .revents = 0 }}; + if (try posix.poll(&fds, 30000) == 0) return error.Timeout; + const n = posix.system.read(fd, &buffer, buffer.len); + if (posix.errno(n) != .SUCCESS) return error.Read; + if (n == 0) return out.items; + try out.appendSlice(a, buffer[0..@intCast(n)]); + } + } + fn ask(h: *Harness, a: Allocator, path: []const u8, key: ?[]const u8, body: []const u8) ![]const u8 { + const auth_header = if (key) |k| try std.fmt.allocPrint(a, "Authorization: Bearer {s}\r\n", .{k}) else ""; + const raw = try std.fmt.allocPrint(a, "POST {s} HTTP/1.1\r\nHost: localhost\r\n{s}Content-Type: application/json\r\nContent-Length: {d}\r\nConnection: close\r\n\r\n{s}", .{ path, auth_header, body.len, body }); + return h.exchange(a, raw); + } + + fn get(h: *Harness, a: Allocator, path: []const u8, key: ?[]const u8) ![]const u8 { + const auth_header = if (key) |k| try std.fmt.allocPrint(a, "Authorization: Bearer {s}\r\n", .{k}) else ""; + const raw = try std.fmt.allocPrint(a, "GET {s} HTTP/1.1\r\nHost: localhost\r\n{s}Connection: close\r\n\r\n", .{ path, auth_header }); + return h.exchange(a, raw); + } +}; + +fn bodyOf(reply: []const u8) []const u8 { + const at = std.mem.indexOf(u8, reply, "\r\n\r\n") orelse return ""; + return reply[at + 4 ..]; +} + +fn statusIs(reply: []const u8, code: u16) bool { + var buf: [32]u8 = undefined; + const want = std.fmt.bufPrint(&buf, "HTTP/1.1 {d} ", .{code}) catch return false; + return std.mem.startsWith(u8, reply, want); +} + +fn lines(a: Allocator, body: []const u8) ![]json.Value { + var out: std.ArrayList(json.Value) = .empty; + var it = std.mem.splitScalar(u8, body, '\n'); + while (it.next()) |line| { + if (line.len == 0) continue; + const parsed = json.parse(a, line) catch return error.BadNdjson; + if (parsed != .ok) return error.BadNdjson; + try out.append(a, parsed.ok); + } + return out.items; +} + +const chat_body = "{\"model\":\"fake-model\",\"messages\":[{\"role\":\"user\",\"content\":\"H\"}],\"stream\":false,\"options\":{\"temperature\":0,\"num_predict\":8,\"seed\":1234}}"; +const generate_body = "{\"model\":\"fake-model\",\"prompt\":\"H\",\"stream\":false,\"options\":{\"temperature\":0,\"num_predict\":8,\"seed\":1234}}"; + +test "ollama HTTP: non-stream chat and generate replies end with one complete done line" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var engine: Engine = .{}; + var h: Harness = .{}; + try h.start(&engine, null); + defer h.deinit(); + for ([_][]const u8{ "/api/chat", "/api/generate" }) |path| { + const body = if (std.mem.eql(u8, path, "/api/chat")) chat_body else generate_body; + const reply = try h.ask(a, path, null, body); + try t.expect(statusIs(reply, 200)); + const rows = try lines(a, bodyOf(reply)); + try t.expectEqual(@as(usize, 1), rows.len); // the socket closed: no hang, one final line + const row = rows[0]; + try t.expect(row.get("done").?.bool); + for ([_][]const u8{ "done_reason", "prompt_eval_count", "eval_count", "prompt_eval_duration", "eval_duration" }) |key| + try t.expect(row.get(key) != null); + } +} + +test "ollama HTTP: a streaming chat sends false deltas then one done line" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var engine: Engine = .{}; + var h: Harness = .{}; + try h.start(&engine, null); + defer h.deinit(); + const raw = "{\"model\":\"fake-model\",\"messages\":[{\"role\":\"user\",\"content\":\"H\"}],\"stream\":true,\"options\":{\"temperature\":0}}"; + const reply = try h.ask(a, "/api/chat", null, raw); + try t.expect(statusIs(reply, 200)); + const rows = try lines(a, bodyOf(reply)); + try t.expect(rows.len >= 2); + var done: usize = 0; + for (rows, 0..) |row, i| { + if (row.get("done").?.bool) { + done += 1; + try t.expectEqual(rows.len - 1, i); + try t.expect(row.get("done_reason") != null); + } else try t.expect(row.get("message") != null); + } + try t.expectEqual(@as(usize, 1), done); +} + +test "ollama HTTP: seeded chat and completions return the same token ids" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var engine: Engine = .{}; + var h: Harness = .{}; + try h.start(&engine, null); + defer h.deinit(); + const ollama = try h.ask(a, "/api/chat", null, chat_body); + try t.expect(statusIs(ollama, 200)); + const rows = try lines(a, bodyOf(ollama)); + const ollama_ids = rows[0].get("token_ids").?.array; + const openai_body = "{\"model\":\"fake-model\",\"messages\":[{\"role\":\"user\",\"content\":\"H\"}],\"max_tokens\":8,\"temperature\":0,\"seed\":1234,\"return_token_ids\":true}"; + const openai = try h.ask(a, "/v1/chat/completions", null, openai_body); + try t.expect(statusIs(openai, 200)); + const parsed = json.parse(a, bodyOf(openai)) catch return error.BadJson; + const openai_ids = parsed.ok.get("tensorfold").?.get("token_ids").?.array; + try t.expectEqual(ollama_ids.len, openai_ids.len); + for (ollama_ids, openai_ids) |x, y| try t.expectEqualStrings(x.int, y.int); +} + +test "ollama HTTP: show answers over POST, tags has no empty fields, a read key gets tags but not chat" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var keys_file = try KeyFile.init("monitor[read]: read-secret\nops: ops-secret\n"); + defer keys_file.deinit(); + var keys: auth.Store = undefined; + var problem: []const u8 = ""; + keys = try auth.Store.init(t.allocator, &.{}, "", keys_file.path, false, &problem); + defer keys.deinit(); + var engine: Engine = .{}; + var h: Harness = .{}; + try h.start(&engine, &keys); + defer h.deinit(); + + try t.expect(statusIs(try h.ask(a, "/api/show", "ops-secret", "{\"model\":\"fake-model\"}"), 200)); + try t.expect(statusIs(try h.ask(a, "/api/chat", "read-secret", chat_body), 403)); + const tags = try h.get(a, "/api/tags", "read-secret"); + try t.expect(statusIs(tags, 200)); + const parsed = json.parse(a, bodyOf(tags)) catch return error.BadJson; + const models = parsed.ok.get("models").?.array; + try t.expect(models.len > 0); + try t.expect(models[0].get("modified_at") == null); + try t.expect(models[0].get("size") == null); +} + +fn openaiWhole(a: Allocator, h: *Harness, body: []const u8) ![]const u8 { + const reply = try h.ask(a, "/v1/chat/completions", null, body); + const parsed = json.parse(a, bodyOf(reply)) catch return error.BadJson; + const choices = parsed.ok.get("choices").?.array; + if (choices.len == 0) return error.BadJson; + if (choices[0].get("message")) |m| return m.strField("content") orelse ""; + return choices[0].strField("text") orelse ""; +} + +fn rfc3339Shape(text: []const u8) bool { + return text.len == 20 and text[4] == '-' and text[7] == '-' and text[10] == 'T' and + text[13] == ':' and text[16] == ':' and text[19] == 'Z'; +} + +test "ollama HTTP: non-stream content, generate response, streamed join and created_at match" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var engine: Engine = .{}; + var h: Harness = .{}; + try h.start(&engine, null); + defer h.deinit(); + + const openai_body = "{\"model\":\"fake-model\",\"messages\":[{\"role\":\"user\",\"content\":\"H\"}],\"max_tokens\":8,\"temperature\":0,\"seed\":1234,\"return_token_ids\":true}"; + const whole = try openaiWhole(a, &h, openai_body); + try t.expect(whole.len > 0); + + const chat = try h.ask(a, "/api/chat", null, chat_body); + try t.expect(statusIs(chat, 200)); + const rows = try lines(a, bodyOf(chat)); + const content = rows[0].get("message").?.strField("content") orelse ""; + try t.expectEqualStrings(whole, content); + try t.expect(rfc3339Shape(rows[0].strField("created_at") orelse "")); + + const generated = try h.ask(a, "/api/generate", null, generate_body); + try t.expect(statusIs(generated, 200)); + const generated_rows = try lines(a, bodyOf(generated)); + try t.expectEqualStrings(whole, generated_rows[0].strField("response") orelse ""); + try t.expect(generated_rows[0].get("message") == null); + + const stream_raw = "{\"model\":\"fake-model\",\"messages\":[{\"role\":\"user\",\"content\":\"H\"}],\"stream\":true,\"options\":{\"temperature\":0,\"num_predict\":8,\"seed\":1234}}"; + const stream = try h.ask(a, "/api/chat", null, stream_raw); + const stream_rows = try lines(a, bodyOf(stream)); + var joined: std.ArrayList(u8) = .empty; + for (stream_rows) |row| { + const message = row.get("message") orelse continue; + try joined.appendSlice(a, message.strField("content") orelse ""); + } + try t.expectEqualStrings(whole, joined.items); // the final done line adds no text + const final = stream_rows[stream_rows.len - 1]; + const final_text: []const u8 = final.get("message").?.strField("content") orelse "x"; + try t.expect(final_text.len == 0); +} + +test "ollama HTTP: an invalid value and an unknown option keep their status and name the cause" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var engine: Engine = .{}; + var h: Harness = .{}; + try h.start(&engine, null); + defer h.deinit(); + + const hot = try h.ask(a, "/api/chat", null, "{\"model\":\"fake-model\",\"messages\":[{\"role\":\"user\",\"content\":\"H\"}],\"options\":{\"temperature\":\"hot\"}}"); + try t.expect(!statusIs(hot, 200)); + try t.expect(std.mem.indexOf(u8, bodyOf(hot), "error") != null); + + const unknown = try h.ask(a, "/api/chat", null, "{\"model\":\"fake-model\",\"messages\":[{\"role\":\"user\",\"content\":\"H\"}],\"options\":{\"num_gpu\":1}}"); + try t.expect(!statusIs(unknown, 200)); + try t.expect(std.mem.indexOf(u8, bodyOf(unknown), "num_gpu") != null); +} + +test "ollama HTTP: two requests on one kept-alive connection both answer" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var engine: Engine = .{}; + var h: Harness = .{}; + try h.start(&engine, null); + defer h.deinit(); + const show_body = "{\"model\":\"fake-model\"}"; + const raw = try std.fmt.allocPrint( + a, + "POST /api/show HTTP/1.1\r\nHost: localhost\r\nContent-Type: application/json\r\nContent-Length: {d}\r\n\r\n{s}GET /api/version HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n", + .{ show_body.len, show_body }, + ); + const reply = try h.exchange(a, raw); + try t.expectEqual(@as(usize, 2), std.mem.count(u8, reply, "HTTP/1.1 200")); + try t.expect(std.mem.indexOf(u8, reply, "501") == null); +} + +test "ollama HTTP: embed answers in Ollama's shape with an embedding fake" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var engine: Engine = .{ .embed = true }; + var h: Harness = .{}; + try h.start(&engine, null); + defer h.deinit(); + const reply = try h.ask(a, "/api/embed", null, "{\"model\":\"fake-model\",\"input\":\"hello\"}"); + try t.expect(statusIs(reply, 200)); + const parsed = json.parse(a, bodyOf(reply)) catch return error.BadJson; + const embeddings = parsed.ok.get("embeddings").?.array; + try t.expectEqual(@as(usize, 1), embeddings.len); + try t.expectEqual(@as(usize, 2), embeddings[0].array.len); + try t.expect(parsed.ok.get("object") == null); +} + +test "ollama HTTP: a stream that fails after its tokens ends with an error line, not a success line" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var engine: Engine = .{ .fail_after_tokens = true }; + var h: Harness = .{}; + try h.start(&engine, null); + defer h.deinit(); + const raw = "{\"model\":\"fake-model\",\"messages\":[{\"role\":\"user\",\"content\":\"H\"}],\"stream\":true}"; + const reply = try h.ask(a, "/api/chat", null, raw); + try t.expect(statusIs(reply, 200)); + const rows = try lines(a, bodyOf(reply)); + try t.expect(rows.len >= 1); + var saw_error = false; + for (rows, 0..) |row, i| { + if (row.get("done")) |done| try t.expect(!done.bool); + if (row.get("error") != null) { + saw_error = true; + try t.expectEqual(rows.len - 1, i); + } + } + try t.expect(saw_error); +} + +test "ollama HTTP: format, tools and images are mapped or refused by name" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var engine: Engine = .{}; + var h: Harness = .{}; + try h.start(&engine, null); + defer h.deinit(); + const prefix = "{\"model\":\"fake-model\",\"messages\":[{\"role\":\"user\",\"content\":\"H\"}]"; + const json_format = try std.fmt.allocPrint(a, "{s},\"format\":\"json\"}}", .{prefix}); + try t.expect(statusIs(try h.ask(a, "/api/chat", null, json_format), 200)); + const schema = try std.fmt.allocPrint(a, "{s},\"format\":{{\"type\":\"object\",\"properties\":{{}}}}}}", .{prefix}); + try t.expect(statusIs(try h.ask(a, "/api/chat", null, schema), 200)); + const tools = try std.fmt.allocPrint(a, "{s},\"tools\":[{{\"type\":\"function\",\"function\":{{\"name\":\"lookup\",\"description\":\"d\",\"parameters\":{{\"type\":\"object\",\"properties\":{{}}}}}}}}]}}", .{prefix}); + try t.expect(statusIs(try h.ask(a, "/api/chat", null, tools), 200)); + const refused = [_]struct { name: []const u8, field: []const u8 }{ + .{ .name = "format", .field = "\"format\":\"xml\"" }, + .{ .name = "tools", .field = "\"tools\":{}" }, + .{ .name = "images", .field = "\"images\":[\"AQ==\"]" }, + }; + for (refused) |r| { + const bad = try std.fmt.allocPrint(a, "{s},{s}}}", .{ prefix, r.field }); + const reply = try h.ask(a, "/api/chat", null, bad); + try t.expect(statusIs(reply, 400)); + try t.expect(std.mem.indexOf(u8, bodyOf(reply), r.name) != null); + } +} + +test "ollama HTTP: stream takes only true, false or nothing" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var engine: Engine = .{}; + var h: Harness = .{}; + try h.start(&engine, null); + defer h.deinit(); + const prefix = "{\"model\":\"fake-model\",\"messages\":[{\"role\":\"user\",\"content\":\"H\"}]"; + for ([_][]const u8{ "\"stream\":\"yes\"", "\"stream\":1", "\"stream\":null" }) |value| { + const raw = try std.fmt.allocPrint(a, "{s},{s}}}", .{ prefix, value }); + const reply = try h.ask(a, "/api/chat", null, raw); + try t.expect(statusIs(reply, 400)); + try t.expect(std.mem.indexOf(u8, bodyOf(reply), "stream") != null); + } + const absent = try std.fmt.allocPrint(a, "{s}}}", .{prefix}); + try t.expect(statusIs(try h.ask(a, "/api/chat", null, absent), 200)); +} + +test "ollama HTTP: one request writes one request-log line" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = t.tmpDir(.{}); + defer tmp.cleanup(); + const path = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}/requests.jsonl", .{tmp.sub_path}); + var engine: Engine = .{}; + var h: Harness = .{ .log_path = path }; + try h.start(&engine, null); + defer h.deinit(); + try t.expect(statusIs(try h.ask(a, "/api/chat", null, chat_body), 200)); + const text = try std.Io.Dir.cwd().readFileAlloc(t.io, path, a, .limited(1 << 16)); + var count: usize = 0; + var it = std.mem.splitScalar(u8, text, '\n'); + while (it.next()) |line| if (line.len > 0) { + count += 1; + }; + try t.expectEqual(@as(usize, 1), count); +} diff --git a/zig/src/server/ollama_test.zig b/zig/src/server/ollama_test.zig new file mode 100644 index 00000000000..604ff582f37 --- /dev/null +++ b/zig/src/server/ollama_test.zig @@ -0,0 +1,89 @@ +//! Ollama translation host tests: options, refusals, body shapes and NDJSON framing. +const std = @import("std"); +const json = @import("json"); +const ollama = @import("ollama.zig"); +const errors = @import("errors.zig"); +const t = std.testing; + +fn body(a: std.mem.Allocator, text: []const u8) json.Value { + return (json.parse(a, text) catch unreachable).ok; +} + +test "ollama options map onto the chat request and think becomes a template kwarg" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var cx: errors.Cx = .{ .a = a }; + const raw = body(a, + \\{"model":"m","messages":[{"role":"user","content":"H"}],"think":true,"options":{"temperature":0.3,"top_k":20,"top_p":0.9,"min_p":0.1,"num_predict":7,"seed":4,"presence_penalty":0.2,"frequency_penalty":0.3}} + ); + const chat = try ollama.chatBody(a, "local-model", 4096, raw, &cx); + try t.expectEqualStrings("local-model", chat.get("model").?.string); + try t.expect(chat.get("return_token_ids").?.bool); + try t.expectApproxEqAbs(@as(f64, 0.3), chat.get("temperature").?.float, 1e-9); + try t.expectEqualStrings("7", chat.get("max_tokens").?.int); + try t.expect(chat.get("chat_template_kwargs").?.get("enable_thinking").?.bool); +} + +test "ollama refuses unsupported options by name and a num_ctx past the window" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var cx: errors.Cx = .{ .a = a }; + for ([_][]const u8{ "mirostat", "repeat_penalty", "tfs_z", "num_ctx" }) |option| { + cx.message = ""; + const text = std.fmt.allocPrint(a, "{{\"prompt\":\"H\",\"options\":{{\"{s}\":{s}}}}}", .{ option, if (std.mem.eql(u8, option, "num_ctx")) "8192" else "1" }) catch unreachable; + try t.expectError(error.Refused, ollama.chatBody(a, "local-model", 4096, body(a, text), &cx)); + if (std.mem.eql(u8, option, "num_ctx")) + try t.expect(std.mem.indexOf(u8, cx.message, "context window") != null) + else + try t.expect(std.mem.indexOf(u8, cx.message, option) != null); + } +} + +test "ollama generate prompt and system become chat messages" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var cx: errors.Cx = .{ .a = a }; + const raw = body(a, "{\"prompt\":\"H\",\"system\":\"rules\"}"); + const chat = try ollama.chatBody(a, "local-model", 4096, raw, &cx); + const messages = chat.get("messages").?.array; + try t.expectEqual(@as(usize, 2), messages.len); + try t.expectEqualStrings("system", messages[0].get("role").?.string); + try t.expectEqualStrings("rules", messages[0].get("content").?.string); + try t.expectEqualStrings("user", messages[1].get("role").?.string); + try t.expectEqualStrings("H", messages[1].get("content").?.string); +} + +test "ollama stops and seed pass through unchanged" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var cx: errors.Cx = .{ .a = a }; + const raw = body(a, "{\"prompt\":\"H\",\"options\":{\"stop\":[\"END\"],\"seed\":9,\"top_k\":40}}"); + const chat = try ollama.chatBody(a, "local-model", 4096, raw, &cx); + try t.expectEqual(@as(usize, 1), chat.get("stop").?.array.len); + try t.expectEqualStrings("9", chat.get("seed").?.int); + try t.expectEqualStrings("40", chat.get("top_k").?.int); +} + +test "ollama maps json format and tools, and refuses unknown fields by name" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var cx: errors.Cx = .{ .a = a }; + const mapped = body(a, + \\{"prompt":"H","format":"json","tools":[{"type":"function","function":{"name":"lookup"}}],"tool_choice":"auto","stream":false} + ); + const chat = try ollama.chatBody(a, "local-model", 4096, mapped, &cx); + try t.expectEqualStrings("json_object", chat.get("response_format").?.get("type").?.string); + try t.expectEqual(@as(usize, 1), chat.get("tools").?.array.len); + try t.expect(chat.get("stream").?.bool == false); + for ([_][]const u8{ "format", "tools", "images", "stream" }) |field| { + cx.message = ""; + const raw = body(a, try std.fmt.allocPrint(a, "{{\"prompt\":\"H\",\"{s}\":{s}}}", .{ field, if (std.mem.eql(u8, field, "format")) "\"xml\"" else if (std.mem.eql(u8, field, "tools")) "{}" else if (std.mem.eql(u8, field, "images")) "[]" else "\"yes\"" })); + try t.expectError(error.Refused, ollama.chatBody(a, "local-model", 4096, raw, &cx)); + try t.expect(std.mem.indexOf(u8, cx.message, field) != null); + } +} diff --git a/zig/src/server/openai.zig b/zig/src/server/openai.zig index 9f9075dde57..51546486d78 100644 --- a/zig/src/server/openai.zig +++ b/zig/src/server/openai.zig @@ -10,6 +10,7 @@ const messages = @import("messages.zig"); const tool_specs = @import("tool_specs.zig"); const tool_parse = @import("tool_parse.zig"); const tool_stream = @import("tool_stream.zig"); +const token_stream = @import("token_stream.zig"); const ids = @import("ids.zig"); const log = @import("log.zig"); const request_log = @import("request_log.zig"); @@ -116,6 +117,7 @@ pub fn replyModel(srv: *const Server, body: Value) []const u8 { pub const Plan = struct { input: chat.Input, stream: bool, + token_stream: bool, separate_usage: bool, policy: tool_stream.Policy, named: []const u8, @@ -133,7 +135,7 @@ pub fn plan(srv: *Server, cx: *Cx, is_chat: bool, raw: Value, format: ?[]const u const asked = if (is_chat) json.truthyField(body, "logprobs") else body.field("logprobs") != null; const exact_bytes = asked and try @import("logprobs.zig").offered(srv, cx.a); const logprobs = if (is_chat) try fields.probabilityOptions(cx, body, exact_bytes) else try fields.legacyLogprobs(cx, body, exact_bytes); - if (srv.config.request_log) |path| request_log.append(cx.a, path, body); + if (!cx.skip_request_log) if (srv.config.request_log) |path| request_log.append(cx.a, path, body); var input: chat.Input = .{ .fields = undefined, .format = format }; if (is_chat) { input.messages = try messages.normalizeWith(cx, body.get("messages"), "system", srv.needs_user_after_tool, srv.media()); @@ -176,6 +178,7 @@ pub fn plan(srv: *Server, cx: *Cx, is_chat: bool, raw: Value, format: ?[]const u return .{ .input = input, .stream = streamed, + .token_stream = try token_stream.requested(cx, body, streamed, srv.config.cortheon and is_chat), .separate_usage = options != null and options.? == .object and json.truthyField(options.?, "include_usage"), .policy = policy, .named = replyModel(srv, body), @@ -227,14 +230,14 @@ fn promptText(srv: *Server, cx: *Cx, p: Value) errors.Refused![]const u8 { /// The chat or completion reply to ``raw`` (already decoded), written to ``out``. pub fn run(srv: *Server, a: Allocator, out: Out, gone: Gone, is_chat: bool, raw: Value) void { - runNamed(srv, a, out, gone, is_chat, raw, null, true); + runNamed(srv, a, out, gone, is_chat, raw, null, true, false); } /// ``run`` for a route whose client named the grammar field (Responses' text.format, Messages' output_config.format). -pub fn runNamed(srv: *Server, a: Allocator, out: Out, gone: Gone, is_chat: bool, raw: Value, format: ?[]const u8, client_thinking: bool) void { +pub fn runNamed(srv: *Server, a: Allocator, out: Out, gone: Gone, is_chat: bool, raw: Value, format: ?[]const u8, client_thinking: bool, skip_request_log: bool) void { const field: []const u8 = if (is_chat) "messages" else "prompt"; const id = ids.make(a, if (is_chat) "chatcmpl-" else "cmpl-", 32) catch return; - var cx: Cx = .{ .a = a }; + var cx: Cx = .{ .a = a, .skip_request_log = skip_request_log }; var p = plan(srv, &cx, is_chat, raw, format, client_thinking) catch |e| { if (e == error.OutOfMemory) cx.message = "out of memory"; logRefused(id, cx.message); @@ -268,6 +271,7 @@ const Run = struct { plan: Plan, id: []const u8, created: i64, + token_cursor: token_stream.Cursor = .{}, streamed_prose: bool = false, prose_sent: std.ArrayList(u8) = .empty, // the content a tool stream sent text_offset: usize = 0, // characters a completion stream's logprob rows have covered @@ -299,6 +303,7 @@ const Run = struct { const list = try a.alloc(Value, 1); list[0] = .{ .object = choice }; try o.put(a, "choices", .{ .array = list }); + if (r.plan.token_stream) try token_stream.anchor(a, o, r.token_cursor, delta); return .{ .object = o }; } @@ -523,7 +528,7 @@ const Run = struct { defer if (!handed) r.srv.release(prepared.preparing, prepared.request); var sink_state: StreamSink = .{ .run = r, .tools = tools, .prompt_len = prepared.prompt_len }; handed = true; - const sink: chat.Sink = .{ .ctx = &sink_state, .call = StreamSink.call, .begin = StreamSink.begin }; + const sink: chat.Sink = .{ .ctx = &sink_state, .call = StreamSink.call, .begin = StreamSink.begin, .tokens = if (r.plan.token_stream) token_stream.sinkTokens(StreamSink) else null }; var live = gone; live.out = r.out; live.opened = &sink_state.opened; @@ -570,11 +575,7 @@ const Run = struct { } @import("logprobs.zig").project(r.srv, &cx, &reply, r.plan.input.tools, calls) catch |e| return r.streamFailed(if (e == error.Refused) cx.message else "out of memory"); // the entries no chunk carried yet, once the stop and tool policies are final - if (reply.logprobs) |rows| if (@import("logprob_parts.zig").rest(a, rows, reply.probability_rows.?.sent) catch return) |left| { - const delta = json.newObject(a) catch return; - delta.put(a, "logprobs", left) catch return; - r.emit(r.chunk(.{ .object = delta }, null) catch return) catch return; - }; + if (@import("logprob_parts.zig").restDelta(a, &reply) catch return) |delta| r.emit(r.chunk(delta, null) catch return) catch return; const last = r.chunk(.{ .string = "" }, if (reply.finish_reason.len > 0) reply.finish_reason else "length") catch return; if (compaction) |s| compact.stamp(&cx, &reply, s) catch return; r.extras(last.object, &reply) catch return; diff --git a/zig/src/server/prompt.zig b/zig/src/server/prompt.zig index 593ef2af7a3..d68f8fd4b56 100644 --- a/zig/src/server/prompt.zig +++ b/zig/src/server/prompt.zig @@ -41,7 +41,7 @@ pub fn renderRequest(srv: *Server, cx: *Cx, messages: Value, tools: []const Valu .tools = if (tools.len > 0) Value{ .array = @constCast(tools) } else null, .add_generation_prompt = generation, .enable_thinking = thinking, - .reasoning_effort = if (thinking) effort else null, + .reasoning_effort = if (thinking) effort else cx.named_effort, // off: only an effort the request named .clear_thinking = cx.clear_thinking, .tool_choice = cx.template_fields.get("tool_choice"), .response_format = cx.template_fields.get("response_format"), @@ -122,7 +122,7 @@ fn generationPrompt(srv: *Server, cx: *Cx, thinking: bool) errors.Refused![]cons /// Earlier replies' decoded rows: from each turn's generation prompt end through its closing stop token. pub fn replySpans(srv: *Server, cx: *Cx, prompt: []const u32) errors.Refused![]const [2]u32 { if (srv.eos.len == 0) return &.{}; - var probe: Cx = .{ .a = cx.a, .clear_thinking = cx.clear_thinking, .template_fields = cx.template_fields }; // a template that refuses the probe leaves the request without spans, not failed + var probe: Cx = .{ .a = cx.a, .clear_thinking = cx.clear_thinking, .named_effort = cx.named_effort, .template_fields = cx.template_fields }; // a template that refuses the probe leaves the request without spans, not failed const openers = [2][]const u32{ generationPrompt(srv, &probe, false) catch &.{}, generationPrompt(srv, &probe, true) catch &.{} }; var spans: std.ArrayList([2]u32) = .empty; var i: usize = 0; @@ -175,7 +175,7 @@ fn continuedLen(srv: *Server, cx: *Cx, messages: Value, tools: []const Value, th reply.put(cx.a, "role", .{ .string = "assistant" }) catch return history_len; reply.put(cx.a, "content", .{ .string = "\u{2063}probe" }) catch return history_len; list[messages.array.len] = .{ .object = reply }; - var scratch: Cx = .{ .a = cx.a, .clear_thinking = cx.clear_thinking, .template_fields = cx.template_fields }; + var scratch: Cx = .{ .a = cx.a, .clear_thinking = cx.clear_thinking, .named_effort = cx.named_effort, .template_fields = cx.template_fields }; const probe = renderIds(srv, &scratch, .{ .array = list }, tools, thinking, effort, false) catch return history_len; const i = std.mem.indexOfDiff(u32, history, probe) orelse return history_len; return if (i > 0 and i < history_len) i else history_len; @@ -214,7 +214,7 @@ pub fn rewindLen(srv: *Server, cx: *Cx, messages: Value, real_count: usize, tool const user = json.copyObject(cx.a, messages.array[user_index].object) catch return 0; user.put(cx.a, "content", .{ .string = "\u{2063}probe" }) catch return 0; list[user_index] = .{ .object = user }; - var scratch: Cx = .{ .a = cx.a, .clear_thinking = cx.clear_thinking, .template_fields = cx.template_fields }; + var scratch: Cx = .{ .a = cx.a, .clear_thinking = cx.clear_thinking, .named_effort = cx.named_effort, .template_fields = cx.template_fields }; const probe = renderIds(srv, &scratch, .{ .array = list }, tools, thinking, effort, true) catch return 0; const i = std.mem.indexOfDiff(u32, prompt, probe) orelse return 0; return if (i < prompt.len) i else 0; @@ -233,7 +233,7 @@ pub fn systemPrefixLen(srv: *Server, cx: *Cx, messages: Value, tools: []const Va user.put(cx.a, "role", .{ .string = "user" }) catch return 0; user.put(cx.a, "content", .{ .string = "\u{2063}probe" }) catch return 0; probe[first_user] = .{ .object = user }; - var scratch: Cx = .{ .a = cx.a, .clear_thinking = cx.clear_thinking, .template_fields = cx.template_fields }; + var scratch: Cx = .{ .a = cx.a, .clear_thinking = cx.clear_thinking, .named_effort = cx.named_effort, .template_fields = cx.template_fields }; const other = renderIds(srv, &scratch, .{ .array = probe }, tools, thinking, effort, true) catch return 0; var shared: usize = 0; while (shared < @min(prompt_ids.len, other.len) and prompt_ids[shared] == other[shared]) shared += 1; diff --git a/zig/src/server/reply_incremental_test.zig b/zig/src/server/reply_incremental_test.zig new file mode 100644 index 00000000000..253fb7e34cc --- /dev/null +++ b/zig/src/server/reply_incremental_test.zig @@ -0,0 +1,60 @@ +//! Incremental reply text: a character split across tokens is held whole, and each decode reads only the new window. +const std = @import("std"); +const reply_text = @import("reply_text.zig"); + +/// A byte tokenizer whose decode, like model_text's, spells a trailing partial UTF-8 sequence as U+FFFD. +const Bytes = struct { + pieces: []const []const u8, + longest: usize = 0, + fn decode(t: *Bytes, a: std.mem.Allocator, tokens: []const u32) ![]u8 { + t.longest = @max(t.longest, tokens.len); + var out: std.ArrayList(u8) = .empty; + for (tokens) |id| try out.appendSlice(a, t.pieces[id]); + var cut = out.items.len; + while (cut > 0 and out.items[cut - 1] & 0xc0 == 0x80) cut -= 1; + if (cut > 0 and out.items[cut - 1] >= 0xc0) { + const need = std.unicode.utf8ByteSequenceLength(out.items[cut - 1]) catch 1; + if (out.items.len - (cut - 1) < need) { + out.shrinkRetainingCapacity(cut - 1); + try out.appendSlice(a, "\u{fffd}"); + } + } + return out.items; + } +}; + +test "incremental reply text: a character split across tokens streams only once it is whole" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var t: Bytes = .{ .pieces = &.{ "a", "\xe2\x82", "\xac", "b" } }; + var inc: reply_text.Incremental = .{}; + try std.testing.expectEqualStrings("a", try inc.extend(a, &t, Bytes.decode, &.{0})); + try std.testing.expect(!inc.pending()); + try std.testing.expectEqualStrings("a", try inc.extend(a, &t, Bytes.decode, &.{1})); + try std.testing.expect(inc.pending()); + try std.testing.expectEqualStrings("a\u{20ac}", try inc.extend(a, &t, Bytes.decode, &.{2})); + try std.testing.expect(!inc.pending()); + const all = try inc.extend(a, &t, Bytes.decode, &.{3}); + try std.testing.expectEqualStrings(try t.decode(a, &.{ 0, 1, 2, 3 }), all); +} + +test "incremental reply text: a long reply decodes the previous chunk and the new tokens, never the whole reply" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var t: Bytes = .{ .pieces = &.{ "x", "\xc3", "\xa9" } }; + var inc: reply_text.Incremental = .{}; + var want: std.ArrayList(u8) = .empty; + for (0..300) |i| { + if (i % 50 == 49) { + _ = try inc.extend(a, &t, Bytes.decode, &.{ 1, 2 }); // one character in two tokens, in one chunk + try want.appendSlice(a, "\u{e9}"); + } else { + _ = try inc.extend(a, &t, Bytes.decode, &.{0}); + try want.append(a, 'x'); + } + } + try std.testing.expectEqualStrings(want.items, inc.text.items); + try std.testing.expect(t.longest <= 4); +} diff --git a/zig/src/server/responses.zig b/zig/src/server/responses.zig index f462b73ea64..bb59cde8971 100644 --- a/zig/src/server/responses.zig +++ b/zig/src/server/responses.zig @@ -119,7 +119,7 @@ pub fn turn(srv: *Server, a: Allocator, conn: *Conn, cx: *Cx, body: Value, t: tr var out: Wire = .{ .reply = &reply }; cancel_ids.alias = base.get("id").?.string; // the cancel route takes the response's id too defer cancel_ids.alias = null; - openai.runNamed(srv, a, out.out(), .{ .conn = conn }, true, t.chat, t.format, true); + openai.runNamed(srv, a, out.out(), .{ .conn = conn }, true, t.chat, t.format, true, false); if (out.opened or conn.broken) return .{ .streamed = reply.final }; const status = out.status orelse return .{ .streamed = null }; if (status != 200) return .{ .refused = .{ .status = status, .payload = out.payload } }; diff --git a/zig/src/server/root.zig b/zig/src/server/root.zig index c2aa073eba9..c1e175bb0bd 100644 --- a/zig/src/server/root.zig +++ b/zig/src/server/root.zig @@ -57,6 +57,7 @@ test { _ = @import("std_options.zig"); _ = @import("fields.zig"); _ = @import("reply_text.zig"); + _ = @import("reply_incremental_test.zig"); _ = @import("tool_parse.zig"); _ = @import("tool_lfm2.zig"); _ = @import("tool_lfm2_stream_test.zig"); @@ -78,6 +79,8 @@ test { _ = @import("cli_test.zig"); _ = @import("cli_profile_test.zig"); _ = @import("compact_at_cli_test.zig"); + _ = @import("toml_flat_test.zig"); + _ = @import("cli_config_test.zig"); _ = @import("unix_socket_cli_test.zig"); _ = @import("effort_cli_audit_test.zig"); _ = @import("live.zig"); @@ -85,6 +88,7 @@ test { _ = @import("hub.zig"); _ = @import("chunk_plan.zig"); _ = @import("status_routes.zig"); + _ = @import("models_input_types_test.zig"); _ = @import("speech.zig"); _ = @import("images_generations.zig"); _ = @import("drama_cfg.zig"); @@ -162,6 +166,7 @@ test { _ = @import("cancel_ids.zig"); _ = @import("cancel_route_test.zig"); _ = @import("hf_eos_http_test.zig"); + _ = @import("token_stream_test.zig"); _ = @import("reply_gpu_seconds_test.zig"); _ = @import("spark_wire.zig"); _ = @import("spark_wire_test.zig"); @@ -303,4 +308,5 @@ test { _ = @import("ocr/run_test.zig"); _ = @import("ocr/size_test.zig"); _ = @import("ocr/prompt_ids_test.zig"); + _ = @import("ollama_e2e_test.zig"); } diff --git a/zig/src/server/routes.zig b/zig/src/server/routes.zig index 0bfed401eeb..381d5767c82 100644 --- a/zig/src/server/routes.zig +++ b/zig/src/server/routes.zig @@ -13,6 +13,7 @@ const cancel_ids = @import("cancel_ids.zig"); const openai = @import("openai.zig"); const responses = @import("responses.zig"); const anthropic = @import("anthropic.zig"); +const ollama = @import("ollama.zig"); const tokens = @import("tokens.zig"); const decisions = @import("decisions.zig"); const systemone = @import("systemone.zig"); @@ -106,6 +107,10 @@ fn get(srv: *Server, conn: *Conn, a: Allocator) void { if (std.mem.eql(u8, route, recall.path)) return recall.get(srv, conn, a); if (std.mem.eql(u8, route, "/v1/benchmark/manifest")) return status.manifestRoute(srv, conn, a) catch {}; if (route.len == 0 or std.mem.eql(u8, route, "/health")) return status.health(srv, conn, a) catch {}; + if (std.mem.eql(u8, route, "/api/tags")) return ollama.tags(srv, conn, a); + if (std.mem.eql(u8, route, "/api/show")) return ollama.show(srv, conn, a); + if (std.mem.eql(u8, route, "/api/ps")) return ollama.ps(srv, conn, a); + if (std.mem.eql(u8, route, "/api/version")) return ollama.version(srv, conn, a); if (std.mem.endsWith(u8, route, "/models")) return status.models(srv, conn, a) catch {}; unknown(conn, a); } @@ -134,19 +139,27 @@ fn post(srv: *Server, conn: *Conn, a: Allocator) void { const is_chat = std.mem.endsWith(u8, route, "/chat/completions"); const is_rerank = std.mem.eql(u8, route, "/v1/rerank") or std.mem.eql(u8, route, "/rerank"); const is_ocr = std.mem.eql(u8, route, "/v1/ocr"); - if (!is_ocr and !is_rerank and !is_embedding and !is_speech and !is_images and !is_slide and imprint_op == null and !is_anthropic and !is_responses and !is_decisions and !is_systemone and !is_chat and !std.mem.endsWith(u8, route, "/completions")) { + const is_ollama_chat = std.mem.eql(u8, route, "/api/chat"); + const is_ollama_generate = std.mem.eql(u8, route, "/api/generate"); + const is_ollama_embed = std.mem.eql(u8, route, "/api/embed"); + const is_ollama_show = std.mem.eql(u8, route, "/api/show"); + if (!is_ocr and !is_rerank and !is_embedding and !is_speech and !is_images and !is_slide and imprint_op == null and !is_anthropic and !is_responses and !is_decisions and !is_systemone and !is_chat and !is_ollama_chat and !is_ollama_generate and !is_ollama_embed and !is_ollama_show and !std.mem.endsWith(u8, route, "/completions")) { discardBody(conn, a); return unknown(conn, a); } - const group: api.load_ledger.RouteGroup = if (is_chat) .chat_completions else if (is_responses) .responses else if (is_anthropic) .messages else if (is_embedding) .embeddings else if (is_speech) .speech else if (std.mem.endsWith(u8, route, "/completions")) .completions else .other; - const is_text = is_ocr or is_speech or is_anthropic or is_responses or is_decisions or is_systemone or is_chat or std.mem.endsWith(u8, route, "/completions"); - const kind: request_gate.RouteKind = .{ .text = is_text, .embedding = is_embedding, .rerank = is_rerank, .systemone = is_systemone }; + const group: api.load_ledger.RouteGroup = if (is_chat or is_ollama_chat or is_ollama_generate) .chat_completions else if (is_responses) .responses else if (is_anthropic) .messages else if (is_embedding or is_ollama_embed) .embeddings else if (is_speech) .speech else if (std.mem.endsWith(u8, route, "/completions")) .completions else .other; + const is_text = is_ocr or is_speech or is_anthropic or is_responses or is_decisions or is_systemone or is_chat or is_ollama_chat or is_ollama_generate or std.mem.endsWith(u8, route, "/completions"); + const kind: request_gate.RouteKind = .{ .text = is_text, .embedding = is_embedding or is_ollama_embed, .rerank = is_rerank, .systemone = is_systemone }; var entered = request_gate.enter(srv, a, conn.key_digest, group, kind); defer entered.held.release(); if (entered.refusal) |refusal| return refuse(conn, a, is_anthropic, refusal); if (std.mem.eql(u8, route, "/v1/audio/speech")) return speech.post(srv, conn, a) catch {}; if (is_images) return images.post(srv, conn, a) catch {}; if (is_embedding) return embeddings.post(srv, conn, a); + if (is_ollama_chat) return ollama.chat(srv, conn, a); + if (is_ollama_generate) return ollama.generate(srv, conn, a); + if (is_ollama_embed) return ollama.embed(srv, conn, a); + if (is_ollama_show) return ollama.show(srv, conn, a); if (is_slide) return slide.learn(srv, conn, a); if (imprint_op) |op| return imprint.post(srv, conn, a, op); if (is_rerank) return @import("rerank.zig").post(srv, conn, a); diff --git a/zig/src/server/server.zig b/zig/src/server/server.zig index 63b27fed778..b6f936967ae 100644 --- a/zig/src/server/server.zig +++ b/zig/src/server/server.zig @@ -149,6 +149,7 @@ pub const Server = struct { chunks: chunk_plan.Plan = .{}, effort_levels: []const []const u8 = &.{}, thinking_switch: bool = false, + video_decoder: bool = false, // libtfvideo loaded in `init`: with the video offer it decides video input (#3004) eos: []const u32 = &.{}, think_close: []const u32 = &.{}, think_close_end: ?u32 = null, @@ -191,9 +192,7 @@ pub const Server = struct { /// Reads what the template and tokenizer decide once: late system role, think markers, efforts, the forced close. pub fn media(srv: *const Server) @import("messages.zig").Media { - var result = @import("messages.zig").Media.ofVision(srv.info.vision, srv.config.vision_pdf); - result.native_deepseek = srv.text.native_deepseek; - return result; + return @import("input_types.zig").media(srv); } pub fn init(gpa: Allocator, io: std.Io, engine: api.Engine, text: model_text.Text, config: Config, keys: ?*auth.Store) !*Server { @@ -208,6 +207,7 @@ pub const Server = struct { log.line("--vision: marker token {d} is not an added token in this tokenizer; image and video input cannot be served safely", .{id}); return error.InvalidVisionMarkers; }; + srv.video_decoder = @import("input_types.zig").decodes(srv.info.vision); // no decoder: video parts are a 400, never a 500 const engine_voices = if (srv.info.speech) |sp| sp.voices else &.{}; if (engine_voices.len > 0) { // the server's own copy: an idle unload frees the engine's names while /v1/voices still lists them diff --git a/zig/src/server/slide.zig b/zig/src/server/slide.zig index f8642e3bae6..e38d788b4da 100644 --- a/zig/src/server/slide.zig +++ b/zig/src/server/slide.zig @@ -104,6 +104,7 @@ pub fn learn(srv: *Server, conn: *Conn, a: Allocator) void { defer out.stop(); out.start(srv.io, 5000) catch |e| return out.fail(&cx, e); const gone = &out; + const reserved = @import("slide_reserved.zig").Reserved.init(srv, &cx, recall) catch |e| return out.fail(&cx, e); const facts = found.facts(srv, &cx, text, source, gone) catch |e| return out.fail(&cx, e); if (facts.len == 0) { out.event("failed", .{ .message = "no facts found in the text: nothing was learned" }); @@ -133,7 +134,7 @@ pub fn learn(srv: *Server, conn: *Conn, a: Allocator) void { // a chat fact not about the user ("The Quillon bridge is 1,312 metres long.") learns as a document's does const document = !std.mem.eql(u8, source, "chat") or !wording.firstPerson(fact); const gave = if (document or correcting) &.{} else giveWay(srv, a, &cx, fact, id, gone); - var plan = (teach.lesson(srv, &cx, &srv.teacher, &.{fact}, &kept, document, facts, supplied, gone) catch |e| { + var plan = (teach.withRecall(srv, &cx, &srv.teacher, &.{fact}, &kept, document, facts, supplied, reserved, gone) catch |e| { missed(srv, &out, id, words(&cx, e)); putBack(srv, a, gave, id); continue; diff --git a/zig/src/server/slide_lesson.zig b/zig/src/server/slide_lesson.zig index e5a81535d66..6ffb1d6620c 100644 --- a/zig/src/server/slide_lesson.zig +++ b/zig/src/server/slide_lesson.zig @@ -105,9 +105,14 @@ pub fn routed(srv: *Server, cx: *Cx, c: Check) !struct { prompt: api.Example, ke /// One lesson for the facts `told` (kept[f]: fact f had enough clean answers), or null; `siblings`: all facts told. pub fn lesson(srv: *Server, cx: *Cx, teacher: *Teacher, told: []const []const u8, kept: []bool, document: bool, siblings: []const []const u8, supplied: []const []const u8, gone: anytype) !?Plan { + return withRecall(srv, cx, teacher, told, kept, document, siblings, supplied, .{}, gone); +} + +/// A request's held-out recall prompts are reserved before any examples are written. +pub fn withRecall(srv: *Server, cx: *Cx, teacher: *Teacher, told: []const []const u8, kept: []bool, document: bool, siblings: []const []const u8, supplied: []const []const u8, reserved: @import("slide_reserved.zig").Reserved, gone: anytype) !?Plan { const a = cx.a; const end = try turnEnd(srv, cx, teacher); - var parts: Parts = .{ .thinks = try thinks(srv, cx, teacher), .document = document, .siblings = siblings }; + var parts: Parts = .{ .thinks = try thinks(srv, cx, teacher), .document = document, .siblings = siblings, .reserved = reserved }; var count: u32 = 0; const language = try languageOf(srv, cx, told[0], gone); for (told, kept, 0..) |fact, *k, f| { @@ -199,7 +204,7 @@ pub fn lesson(srv: *Server, cx: *Cx, teacher: *Teacher, told: []const []const u8 .unasked = parts.unasked.items, .steps = steps, }; - return .{ .questions = parts.all.items, .full = full, .facts = told, .held = parts.held.items, .probes = parts.probes.items, .checks = checks.items, .thinks = parts.thinks, .document = document, .stale = .{ .keep = stale_keep.items, .bank = stale_bank.items } }; + return .{ .questions = parts.all.items, .full = try reserved.clean(a, full), .facts = told, .held = parts.held.items, .probes = parts.probes.items, .checks = checks.items, .thinks = parts.thinks, .document = document, .stale = .{ .keep = stale_keep.items, .bank = stale_bank.items } }; } pub const Parts = @import("slide_lesson_parts.zig").Parts; @@ -243,6 +248,7 @@ fn keepNear(srv: *Server, cx: *Cx, parts: *Parts, fact: []const u8, nears: []con pub fn run(j: *const @This(), i: usize) !void { var jcx: Cx = .{ .a = j.a }; const n = j.nears[i]; + if (try j.parts.reserved.question(j.srv, &jcx, n.q)) return; if (untold.protected(n.q)) return; // only ever checked, never trained if (n.judge and try slide_take.answered(j.srv, &jcx, j.fact, n.q, j.parts.document, j.gone)) return; if (n.siblings and try siblingAnswers(j.srv, &jcx, j.parts.siblings, j.fact, n.q, j.parts.document, j.gone)) { @@ -298,7 +304,7 @@ pub fn factLesson(srv: *Server, cx: *Cx, parts: *Parts, fact: []const u8, f: usi const written = try wording.questions(a, asked.content, probes); const qs = try supplied_questions.ahead(a, supplied, written); if (supplied.len > 0) log.line("slide: {d} questions supplied with \"{s}\"", .{ supplied.len, fact }); - var got: Got = .{ .entity = try aboutEntity(srv, cx, fact, gone), .siblings = parts.siblings }; + var got: Got = .{ .entity = try aboutEntity(srv, cx, fact, gone), .siblings = parts.siblings, .reserved = parts.reserved }; var phrase: []const u8 = ""; if (got.entity) { const said = try askBase(srv, cx, null, try std.fmt.allocPrint(a, prompts.fact_subject_prompt, .{fact}), 16, gone); @@ -373,7 +379,10 @@ pub fn factLesson(srv: *Server, cx: *Cx, parts: *Parts, fact: []const u8, f: usi try parts.own.appendSlice(a, told.items); log.line("slide: {d} questions kept for: {s} ({s})", .{ refs.items.len, fact, try std.mem.join(a, " | ", told.items) }); if (qs.len < min_probes) log.line("slide: the questions came back as: {s}", .{asked.content}); - if (pairs.items.len < min_probes) return false; + if (pairs.items.len < min_probes) { + if (got.reserved_dropped) return cx.refuse(@import("slide_reserved.zig").refusal); + return false; + } try parts.all.appendSlice(a, refs.items); // the two most typical wordings held out, so a vague one ("Which dog do I have?") never decides recall const n = pairs.items.len; @@ -457,6 +466,7 @@ fn routerData(srv: *Server, cx: *Cx, parts: *Parts, fact: []const u8, f: usize, const wordings = try wording.questions(a, more.content, count); if (wordings.len == 0) log.line("slide: no more wordings came back: {s}", .{more.content}); for (wordings) |q| { + if (try parts.reserved.question(srv, cx, q)) continue; if ((try seen.getOrPut(a, q)).found_existing) continue; const personal = !parts.document and (!wording.firstPerson(q) or wording.someoneElse(fact, q)); const why: ?[]const u8 = if (personal or !units.sameScript(fact, q)) "is not the user asking about themselves" else if (wording.gives(fact, asked_all, answered_all, q)) "gives the fact away" else if (!try judged(srv, cx, fact, q, parts.document, gone)) "is not answered by the fact" else if (try siblingAnswers(srv, cx, parts.siblings, fact, q, parts.document, gone)) "is another fact's" else null; diff --git a/zig/src/server/slide_lesson_parts.zig b/zig/src/server/slide_lesson_parts.zig index c5aafd7e955..8d2443f5ac0 100644 --- a/zig/src/server/slide_lesson_parts.zig +++ b/zig/src/server/slide_lesson_parts.zig @@ -6,6 +6,7 @@ const Check = @import("slide_lesson.zig").Check; /// The facts' examples as a lesson gathers them. pub const Parts = struct { + reserved: @import("slide_reserved.zig").Reserved = .{}, train: std.ArrayList(api.Example) = .empty, all: std.ArrayList(Held) = .empty, // every cold lesson question, including the training questions held_ex: std.ArrayList(api.Example) = .empty, diff --git a/zig/src/server/slide_metrics.zig b/zig/src/server/slide_metrics.zig index 37169db5ce4..b941a4a9afb 100644 --- a/zig/src/server/slide_metrics.zig +++ b/zig/src/server/slide_metrics.zig @@ -12,6 +12,7 @@ const schema = @import("slide_metrics_types.zig"); const panel = @import("slide_panel.zig"); const graph = @import("slide_graph.zig"); const chat = @import("chat.zig"); +const reserved = @import("slide_reserved.zig"); const Allocator = std.mem.Allocator; pub const Report = schema.Report; const Output = schema.Output; @@ -72,10 +73,7 @@ fn baseline(srv: *Server, cx: *Cx, qs: []const Query, gone: anytype, r: *Report) /// All example roles are checked: an externally supplied wording is never credited if the plan reads it. pub fn contaminated(srv: *Server, cx: *Cx, plan: teach.Plan, question: []const u8) !bool { const head = (try asks.promptOnly(srv, cx, cx.a, null, question)).ids; - inline for (.{ "train", "think", "held", "near", "keep", "asked", "unasked", "kept" }) |role| { - for (@field(plan.full, role)) |ex| if (std.mem.indexOf(u32, ex.ids, head) != null) return true; - } - return false; + return reserved.contaminated(plan.full, head); } /// Three greedy passes, before committing a candidate; this function never trains or changes a lesson's rows. diff --git a/zig/src/server/slide_metrics_test.zig b/zig/src/server/slide_metrics_test.zig index 3751c8219c8..3ae7b3af86d 100644 --- a/zig/src/server/slide_metrics_test.zig +++ b/zig/src/server/slide_metrics_test.zig @@ -20,6 +20,9 @@ const Model = struct { drift: bool = false, cumulative: bool = false, miss_recall: bool = false, + writer: enum { normal, replace, reserved_only } = .normal, + writer_lists: usize = 0, + read_reserved: bool = false, fn engine(m: *@This()) api.Engine { var e = m.inner.engine(); e.ctx = m; @@ -38,6 +41,12 @@ const Model = struct { } fn learn(ctx: *anyopaque, req: *const api.LearnRequest, sink: api.LearnSink) api.LearnError!void { const m: *@This() = @ptrCast(@alignCast(ctx)); + const head = "user:What colour do I like?|A:"; + var ids: [head.len]u32 = undefined; + for (head, &ids) |b, *v| v.* = b; + inline for (.{ "train", "think", "held", "near", "keep", "asked", "unasked", "kept" }) |role| { + for (@field(req.*, role)) |ex| m.read_reserved = m.read_reserved or std.mem.indexOf(u32, ex.ids, &ids) != null; + } const e = m.inner.engine(); return e.vtable.learn.?(e.ctx, req, sink); } @@ -48,6 +57,14 @@ const Model = struct { for (req.prompt[0..n], bytes[0..n]) |v, *b| b.* = @intCast(v); const prompt = bytes[0..n]; var answer: ?[]const u8 = null; + const only_reserved = m.writer == .reserved_only and std.mem.indexOf(u8, prompt, "Write ") != null and std.mem.indexOf(u8, prompt, "questions") != null; + if (only_reserved or (m.writer == .replace and std.mem.indexOf(u8, prompt, "different short questions that it answers") != null)) { + m.writer_lists += 1; + answer = if (m.writer == .reserved_only) "1. What colour do I like?\n" else if (m.writer_lists == 1) + writer_first + else + "1. What colour would I choose?\n" ++ writer_rest; + } inline for (.{ panel.unrelated[0..], panel.controls[0..], panel.neighbours[0..] }) |qs| { for (qs) |q| if (std.mem.indexOf(u8, prompt, q) != null) { answer = "The reference response stays fixed."; @@ -63,7 +80,7 @@ const Model = struct { if (std.mem.indexOf(u8, prompt, "External colour recall?") != null) answer = if (m.inner.live[0] and !m.miss_recall and !req.untaught) "blue" else "unknown"; if (std.mem.indexOf(u8, prompt, "External fruit recall?") != null) answer = if (m.inner.live[1] and !req.untaught) "apples" else "unknown"; if (answer) |text| { - var ids: [128]u32 = undefined; + var ids: [8192]u32 = undefined; for (text, ids[0..text.len]) |b, *v| v.* = b; sink.event(sink.ctx, id, &.{ .tokens = ids[0..text.len] }); sink.event(sink.ctx, id, &.{ .finished = .{ .reason = .stop } }); @@ -291,3 +308,96 @@ test "Slide metrics: receipt decoding preserves saved values defaults and exact try t.expectError(error.InvalidMetricReceipt, store.decode(schema.Report, a, (try json.parse(a, text)).ok)); try t.expectError(error.InvalidMetricReceipt, store.decode(schema.Baseline, a, (try json.parse(a, "{}")).ok)); } + +const writer_first = "1. What colour do I like?\n" ++ writer_rest; +const writer_rest = "2. Which colour do I like?\n3. What is my favourite colour?\n" ++ + "4. Tell me the colour I like.\n5. Which colour is my favourite?\n6. What colour did I say I like?\n" ++ + "7. Do you know what colour I like?\n8. What colour do I enjoy?\n9. Name the colour I like.\n" ++ + "10. Which colour do I love?\n11. What kind of colour do I like?\n12. What colour am I fond of?\n"; + +fn reservedRoute(m: *Model, normalized: bool, gate: bool) !void { + var text: fixture.Text = .{}; + var rendered = text.text(); + var vtable = rendered.vtable.*; + if (normalized) { + vtable.encode_masked = normalizedEncode; + rendered.vtable = &vtable; + } + const srv = try Server.init(t.allocator, t.io, m.engine(), rendered, .{ + .served_name = "m", + .model_ids = &.{"m"}, + .enable_thinking = false, + .use_drafts = false, + .slide_drift_gate = gate, + }, null); + defer srv.deinit(); + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const q = if (normalized) "WHAT colour do I like?!" else "What colour do I like?"; + const body = try std.fmt.allocPrint(a, "{{\"text\":\"I like blue.\",\"recall\":[{{\"fact\":\"I like blue.\",\"question\":\"{s}\",\"answer\":\"blue\"}}]}}", .{q}); + const wire = try fixture.learnWire(a, srv, body); + try t.expect(std.mem.indexOf(u8, wire, "data: [DONE]") != null); + if (m.writer == .reserved_only) { + try t.expect(std.mem.indexOf(u8, wire, "the plan could not avoid the supplied recall wordings") != null); + try t.expect(!m.inner.live[0] and !m.read_reserved); + try t.expectEqual(@as(usize, 4), m.writer_lists); + return; + } + try t.expect(m.inner.live[0]); + try t.expectEqual(!gate, m.read_reserved); + if (gate) { + try t.expect(m.writer_lists >= 2); + const facts = try srv.slide.snapshot(a); + const r = try store.decode(schema.Report, a, facts[0].evaluation.?); + try t.expect(r.complete); + try t.expectEqual(@as(?[]const u8, null), r.refused); + } +} + +fn normalizedEncode(ctx: *anyopaque, a: std.mem.Allocator, bytes: []const u8, _: []const @import("model_text.zig").Span, _: *[]const u8) @import("model_text.zig").Error![]u32 { + const canonical = try std.mem.replaceOwned(u8, a, bytes, "WHAT colour do I like?!", "What colour do I like?"); + const text: *fixture.Text = @ptrCast(@alignCast(ctx)); + const base = text.text(); + return base.vtable.encode(ctx, a, canonical, false); +} + +test "Slide metrics: reserved writer question is replaced before the complete gate and every learner role" { + var m: Model = .{ .writer = .replace }; + defer m.inner.deinit(); + try reservedRoute(&m, false, true); +} + +test "Slide metrics: tokenizer-equivalent recall casing spacing and punctuation stay held out" { + var m: Model = .{ .writer = .replace }; + defer m.inner.deinit(); + try reservedRoute(&m, true, true); +} + +test "Slide metrics: a writer limited to reserved wordings refuses by name without training" { + var m: Model = .{ .writer = .reserved_only }; + defer m.inner.deinit(); + try reservedRoute(&m, false, true); +} + +test "Slide metrics: gate off still trains a supplied recall wording as before" { + var m: Model = .{ .writer = .replace }; + defer m.inner.deinit(); + try reservedRoute(&m, false, false); +} + +test "Slide metrics: empty recall plan fingerprint" { + var m: Model = .{}; + defer m.inner.deinit(); + var text: fixture.Text = .{}; + const srv = try server(&m, &text, true, null); + defer srv.deinit(); + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + var cx: Cx = .{ .a = arena.allocator() }; + const p = try plan(srv, &cx); + const bytes = try std.json.Stringify.valueAlloc(cx.a, .{ p.full, p.questions, p.held, p.probes, p.checks }, .{}); + var digest: [32]u8 = undefined; + std.crypto.hash.sha2.Sha256.hash(bytes, &digest, .{}); + std.debug.print("EMPTY_RECALL_PLAN {s} bytes={d}\n", .{ std.fmt.bytesToHex(digest, .lower), bytes.len }); +} diff --git a/zig/src/server/slide_reserved.zig b/zig/src/server/slide_reserved.zig new file mode 100644 index 00000000000..89c1906039e --- /dev/null +++ b/zig/src/server/slide_reserved.zig @@ -0,0 +1,76 @@ +//! Supplied recall prompts stay outside every lesson role under the drift gate. +const std = @import("std"); +const api = @import("engine_api"); +const asks = @import("slide_ask.zig"); +const input = @import("slide_recall_input.zig"); +const Server = @import("server.zig").Server; +const Cx = @import("errors.zig").Cx; +const roles = .{ "train", "think", "held", "near", "keep", "asked", "unasked", "kept" }; + +/// The gate compares the rendered token sequence, including the tokenizer's own normalization. +pub fn contains(ids: []const u32, head: []const u32) bool { + return std.mem.indexOf(u32, ids, head) != null; +} + +pub fn contaminated(full: api.LearnRequest, head: []const u32) bool { + inline for (roles) |role| { + for (@field(full, role)) |ex| if (contains(ex.ids, head)) return true; + } + return false; +} + +pub const Reserved = struct { + heads: []const []const u32 = &.{}, + + pub fn init(srv: *Server, cx: *Cx, recall: []const input.Item) !Reserved { + if (!srv.config.slide_drift_gate or recall.len == 0) return .{}; + const heads = try cx.a.alloc([]const u32, recall.len); + for (recall, heads) |r, *head| head.* = (try asks.promptOnly(srv, cx, cx.a, null, r.question)).ids; + return .{ .heads = heads }; + } + + pub fn reads(r: Reserved, ids: []const u32) bool { + for (r.heads) |head| if (contains(ids, head)) return true; + return false; + } + + pub fn question(r: Reserved, srv: *Server, cx: *Cx, q: []const u8) !bool { + if (r.heads.len == 0) return false; + return r.reads((try asks.promptOnly(srv, cx, cx.a, null, q)).ids); + } + + /// Also cover router, keep and contextual examples, using the gate's complete-role scan. + pub fn clean(r: Reserved, a: std.mem.Allocator, full: api.LearnRequest) !api.LearnRequest { + if (r.heads.len == 0) return full; + var out = full; + inline for (roles) |role| { + var xs: std.ArrayList(api.Example) = .empty; + for (@field(full, role)) |ex| if (!r.reads(ex.ids)) try xs.append(a, ex); + @field(out, role) = try xs.toOwnedSlice(a); + } + return out; + } +}; + +pub const refusal = "the plan could not avoid the supplied recall wordings"; + +test "Slide metrics: reserved cleaning covers exactly the gate's example roles" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const head = &[_]u32{ 1, 2, 3 }; + const reserved: Reserved = .{ .heads = &.{head} }; + const clean: api.Example = .{ .ids = &.{ 1, 3, 2 }, .start = 1, .decide = 0 }; + const dirty: api.Example = .{ .ids = &.{ 9, 1, 2, 3, 8 }, .start = 1, .decide = 0 }; + inline for (roles) |role| { + var full: api.LearnRequest = .{}; + @field(full, role) = &.{ clean, dirty }; + try std.testing.expect(contaminated(full, head)); + const filtered = try reserved.clean(a, full); + try std.testing.expect(!contaminated(filtered, head)); + try std.testing.expectEqual(@as(usize, 1), @field(filtered, role).len); + try std.testing.expectEqualSlices(u32, clean.ids, @field(filtered, role)[0].ids); + const unchanged = try (Reserved{}).clean(a, full); + try std.testing.expect(@field(unchanged, role).ptr == @field(full, role).ptr); + } +} diff --git a/zig/src/server/slide_take.zig b/zig/src/server/slide_take.zig index ad6c010997e..6a4528c3492 100644 --- a/zig/src/server/slide_take.zig +++ b/zig/src/server/slide_take.zig @@ -25,6 +25,8 @@ const bare_words = 12; // a bare answer's words at most, kept whole when the mod /// A fact's questions kept so far: their examples, answers and (for the first few) subjects. pub const Got = struct { + reserved: @import("slide_reserved.zig").Reserved = .{}, + reserved_dropped: bool = false, entity: bool = false, // the fact is about someone or something in particular: its questions key on that subject words: []const []const u8 = &.{}, // the words its questions name that subject by (from the fact itself) named: []const []const u8 = &.{}, // of those, its proper names, which a question must say when it has any @@ -45,6 +47,10 @@ pub fn take(srv: *Server, cx: *Cx, got: *Got, fact: []const u8, f: usize, qs: [] const a = cx.a; var fresh: std.ArrayList([]const u8) = .empty; next: for (qs) |q| { + if (try got.reserved.question(srv, cx, q)) { + got.reserved_dropped = true; + continue; + } for (got.refs.items) |r| if (std.mem.eql(u8, r.question, q)) continue :next; for (fresh.items) |x| if (std.mem.eql(u8, x, q)) continue :next; try fresh.append(a, q); diff --git a/zig/src/server/status_routes.zig b/zig/src/server/status_routes.zig index 460a38c7a6b..8e26bef30a0 100644 --- a/zig/src/server/status_routes.zig +++ b/zig/src/server/status_routes.zig @@ -12,6 +12,7 @@ const Metrics = @import("metrics.zig").Metrics; const stats_snapshot = @import("stats_snapshot.zig"); const Value = json.Value; const Allocator = std.mem.Allocator; +const Inputs = @import("input_types.zig").Inputs; /// With keys on, health names nothing about the model. pub fn health(srv: *Server, conn: *Conn, a: Allocator) !void { @@ -83,7 +84,7 @@ pub fn models(srv: *Server, conn: *Conn, a: Allocator) !void { const data = try a.alloc(Value, srv.config.model_ids.len); const reasoning = try modelReasoning(a, srv); for (srv.config.model_ids, data) |id, *slot| { - slot.* = try modelValue(a, id, info, created, reasoning); + slot.* = try modelValue(a, id, info, created, reasoning, .of(info.vision, srv.video_decoder)); } const o = try json.newObject(a); try o.put(a, "object", .{ .string = "list" }); @@ -101,7 +102,7 @@ fn modelReasoning(a: Allocator, srv: *const Server) Allocator.Error!?Value { } /// Discovery extensions report the loaded engine's prompt-plus-reply limit; zero leaves it unspecified. -fn modelValue(a: Allocator, id: []const u8, info: api.Info, created: i64, reasoning: ?Value) Allocator.Error!Value { +fn modelValue(a: Allocator, id: []const u8, info: api.Info, created: i64, reasoning: ?Value, inputs: Inputs) Allocator.Error!Value { const m = try json.newObject(a); try m.put(a, "id", .{ .string = id }); try m.put(a, "object", .{ .string = "model" }); @@ -117,6 +118,7 @@ fn modelValue(a: Allocator, id: []const u8, info: api.Info, created: i64, reason try m.put(a, "max_model_len", try json.intValue(a, window)); } if (info.capability(.reasoning)) if (reasoning) |r| try m.put(a, "reasoning", r); + try m.put(a, "input_types", try inputs.value(a)); // last: the keys before it keep their order and bytes (#3004) return .{ .object = m }; } @@ -275,7 +277,7 @@ test "model discovery reports fitted engine context equally for its served name defer arena.deinit(); const info: api.Info = .{ .context_window = 8192, .context_fitted = true }; for ([_][]const u8{ "served-model", "model-alias" }) |id| { - const value = try modelValue(arena.allocator(), id, info, 123, null); + const value = try modelValue(arena.allocator(), id, info, 123, null, .{}); try std.testing.expectEqualStrings(id, value.get("id").?.string); try std.testing.expectEqual(@as(i64, 8192), value.get("context_length").?.int64().?); try std.testing.expectEqual(value.get("context_length").?.int64(), value.get("max_model_len").?.int64()); @@ -286,10 +288,10 @@ test "model discovery reports fitted engine context equally for its served name test "model discovery omits an unspecified context and preserves the full u32 limit" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); - const unlimited = try modelValue(arena.allocator(), "model", .{}, 0, null); + const unlimited = try modelValue(arena.allocator(), "model", .{}, 0, null, .{}); try std.testing.expect(unlimited.get("context_length") == null); try std.testing.expect(unlimited.get("max_model_len") == null); - const bounded = try modelValue(arena.allocator(), "model", .{ .context_window = std.math.maxInt(u32) }, 0, null); + const bounded = try modelValue(arena.allocator(), "model", .{ .context_window = std.math.maxInt(u32) }, 0, null, .{}); try std.testing.expectEqual(@as(i64, std.math.maxInt(u32)), bounded.get("max_model_len").?.int64().?); } @@ -297,9 +299,9 @@ test "model discovery adds reasoning to an entry only when the model has it" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const a = arena.allocator(); - const plain = try modelValue(a, "model", .{}, 0, null); + const plain = try modelValue(a, "model", .{}, 0, null, .{}); try std.testing.expect(plain.get("reasoning") == null); - const thinking = try modelValue(a, "model", .{}, 0, try reasoningValue(a, true, true, null, &.{"low"})); + const thinking = try modelValue(a, "model", .{}, 0, try reasoningValue(a, true, true, null, &.{"low"}), .{}); try std.testing.expect(thinking.get("reasoning").?.get("default_enabled").?.bool); } @@ -337,10 +339,10 @@ test "model discovery respects the loaded engine's reasoning refusal despite tem const a = arena.allocator(); const template = try reasoningValue(a, true, true, "low", &.{ "low", "high" }); for ([_][]const u8{ "ocr", "scorer", "alias" }) |id| { - const loaded = try modelValue(a, id, .{ .reasoning = false }, 0, template); + const loaded = try modelValue(a, id, .{ .reasoning = false }, 0, template, .{}); try std.testing.expect(loaded.get("reasoning") == null); } - const text = try modelValue(a, "text", .{ .reasoning = true }, 0, template); + const text = try modelValue(a, "text", .{ .reasoning = true }, 0, template, .{}); try std.testing.expect(text.get("reasoning").?.get("default_enabled").?.bool); } @@ -349,7 +351,7 @@ test "Nemotron window: model discovery reports the real fallback" { defer arena.deinit(); var info: api.Info = .{}; info.reported_context_window = @import("nemotron_limits").reported(0, @import("nemotron_limits").positions(0)); - const value = try modelValue(arena.allocator(), "model", info, 0, null); + const value = try modelValue(arena.allocator(), "model", info, 0, null, .{}); try std.testing.expect(value.get("context_length") != null); try std.testing.expectEqual(@as(i64, 262193), value.get("context_length").?.int64().?); try std.testing.expectEqual(value.get("context_length").?.int64(), value.get("max_model_len").?.int64()); @@ -419,7 +421,7 @@ test "model discovery exposes engine capability booleans for every served name" const a = arena.allocator(); const info: api.Info = .{ .structures = true, .greedy_only = true, .logprobs = false, .penalties = false }; for ([_][]const u8{ "primary", "alias" }) |id| { - const entry = try modelValue(a, id, info, 0, null); + const entry = try modelValue(a, id, info, 0, null, .{}); const flags = entry.get("capabilities") orelse return error.TestExpectedCapabilities; try std.testing.expect(flags.get("structures").?.bool); try std.testing.expect(flags.get("greedy_only").?.bool); @@ -439,7 +441,7 @@ test "model discovery capability and logprob admission use one loaded flag" { const body = (try json.parse(a, "{\"logprobs\":true}")).ok; for ([_]bool{ false, true }) |supported| { const info: api.Info = .{ .logprobs = supported }; - const entry = try modelValue(a, "model", info, 0, null); + const entry = try modelValue(a, "model", info, 0, null, .{}); const published = entry.get("capabilities").?.get("logprobs").?.bool; var cx: @import("errors.zig").Cx = .{ .a = a }; const got = @import("fields.zig").probabilityOptions(&cx, body, info.capability(.logprobs)); @@ -456,10 +458,10 @@ test "model discovery publishes the thinking facts last in its one capabilities var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const a = arena.allocator(); - const entry_keys = [_][]const u8{ "id", "object", "created", "owned_by", "capabilities", "context_length", "max_model_len" }; + const entry_keys = [_][]const u8{ "id", "object", "created", "owned_by", "capabilities", "context_length", "max_model_len", "input_types" }; for ([_][2]bool{ .{ false, false }, .{ true, false }, .{ false, true }, .{ true, true } }) |facts| { const info: api.Info = .{ .context_window = 8, .thinking_switch = facts[0], .thinking_applicable = facts[1] }; - const entry = try modelValue(a, "model", info, 0, null); + const entry = try modelValue(a, "model", info, 0, null, .{}); try std.testing.expectEqual(entry_keys.len, entry.object.count()); for (entry_keys, entry.object.keys()) |want, got| try std.testing.expectEqualStrings(want, got); const flags = entry.get("capabilities").?.object; diff --git a/zig/src/server/structure_field_test.zig b/zig/src/server/structure_field_test.zig index 5a788b7b1e1..a478d3c32a8 100644 --- a/zig/src/server/structure_field_test.zig +++ b/zig/src/server/structure_field_test.zig @@ -336,7 +336,7 @@ test "structure field: the Responses translation hands the engine text.format" { const r = try responses_translate.translate(&cx, body, History{}); var conn: Conn = .{ .fd = -1, .peer = "", .buf = &.{}, .gpa = g }; var wire: Wire = .{}; - openai.runNamed(srv, g, wire.out(), .{ .conn = &conn }, true, r.chat, r.format, true); + openai.runNamed(srv, g, wire.out(), .{ .conn = &conn }, true, r.chat, r.format, true, false); try std.testing.expectEqual(@as(u16, 200), wire.status); try std.testing.expectEqualStrings("text.format", rec.field()); try std.testing.expectEqualStrings("json", rec.kind); diff --git a/zig/src/server/thinking_request_test.zig b/zig/src/server/thinking_request_test.zig index b5b139f1c05..62e8ac93aed 100644 --- a/zig/src/server/thinking_request_test.zig +++ b/zig/src/server/thinking_request_test.zig @@ -293,7 +293,8 @@ fn checkpoint(source: []const u8, config: []const u8, kind: []const u8, expected } } -fn checkpointReply(srv: *Server, a: Allocator, script: *Script, extra: []const u8, ids: []const u32) !void { +/// One chat request with `extra` fields through `openai.run`, answered by the script: the whole JSON reply. +fn post(srv: *Server, a: Allocator, script: *Script, extra: []const u8) !json.Value { const body = (try json.parse(a, try std.fmt.allocPrint(a, "{{\"model\":\"m\",\"messages\":[{{\"role\":\"user\",\"content\":\"H\"}}],\"max_tokens\":2,\"return_token_ids\":true{s}}}", .{extra}))).ok; var conn: Conn = .{ .fd = -1, .peer = "", .buf = &.{}, .gpa = a }; var response: Reply = .{ .a = a }; @@ -301,8 +302,12 @@ fn checkpointReply(srv: *Server, a: Allocator, script: *Script, extra: []const u openai.run(srv, a, response.out(), .{ .conn = &conn }, true, body); try std.testing.expectEqual(@as(?u16, 200), response.status); try std.testing.expect(script.seen); + return response.whole.?; +} + +fn checkpointReply(srv: *Server, a: Allocator, script: *Script, extra: []const u8, ids: []const u32) !void { + const whole = try post(srv, a, script, extra); try std.testing.expectEqualSlices(u32, ids, script.prompt[0..script.count]); - const whole = response.whole.?; const message = whole.get("choices").?.array[0].get("message").?; const is_closed = ids[ids.len - 1] == 301; try std.testing.expectEqualStrings(if (is_closed) "K" else "", message.strField("content").?); @@ -321,3 +326,79 @@ test "thinking request: checkpoint GLM 5.3 off closes its generation prefix and test "thinking request: checkpoint LFM2 off closes its generation prefix and preserves main ids" { try checkpoint(@embedFile("fixtures/thinking/lfm2.jinja"), @embedFile("fixtures/thinking/lfm2-tokenizer_config.json"), "lfm2_moe", "<|startoftext|><|im_start|>user\nH<|im_end|>\n<|im_start|>assistant\n"); } + +/// GLM 5.3's template with thinking off, served: the prompt carries `word` from `effort`, which the reply reports. +fn effortOff(server_effort: ?[]const u8, extra: []const u8, effort: ?[]const u8, word: []const u8) !void { + const t = std.testing; + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const config = @embedFile("fixtures/thinking/glm53-tokenizer_config.json"); + var f = try @import("thinking_family_fixture.zig").init(t.allocator, t.io, @embedFile("fixtures/thinking/glm53.jinja"), config, "glm5_next"); + defer f.deinit(); + var problem: []const u8 = ""; + const hf = try HfText.load(t.allocator, t.io, f.path, null, a, &problem); + defer hf.deinit(); + const text = hf.text(); + const messages = (try json.parse(a, "[{\"role\":\"user\",\"content\":\"H\"}]")).ok; + const raw = try text.render(a, messages, .{ .enable_thinking = false, .reasoning_effort = effort }, &problem); + try t.expect(std.mem.indexOf(u8, raw.text, word) != null); + const ids = try std.mem.concat(a, u32, &.{ try raw.encode(text, a, &problem), &.{301} }); + var script: Script = .{}; + const srv = try Server.init(t.allocator, t.io, script.engine(), text, .{ + .served_name = "m", + .model_ids = &.{ "m", "alias" }, + .use_drafts = false, + .reasoning_effort = server_effort, + }, null); + defer srv.deinit(); + const whole = try post(srv, a, &script, extra); + try t.expectEqualSlices(u32, ids, script.prompt[0..script.count]); + try t.expectEqualStrings(effort orelse "none", whole.get("tensorfold").?.strField("reasoning_effort").?); +} + +test "thinking request: GLM 5.3 off renders a named effort, and main's Max when none is named" { + try effortOff(null, off ++ ",\"reasoning_effort\":\"high\"", "high", "Reasoning Effort: High"); + try effortOff(null, ",\"thinking\":false,\"reasoning_effort\":\"low\"", "low", "Reasoning Effort: Low"); + try effortOff(null, off, null, "Reasoning Effort: Max"); + try effortOff(null, ",\"reasoning_effort\":\"none\"", null, "Reasoning Effort: Max"); +} + +test "thinking request: --reasoning-effort never reaches a thinking-off prompt, which keeps main's bytes" { + // effortOff's expected prompt is the template's render with no effort and thinking off: main's ids + try effortOff("high", off, null, "Reasoning Effort: Max"); + try effortOff("high", ",\"thinking\":false", null, "Reasoning Effort: Max"); + try effortOff("high", off ++ ",\"reasoning_effort\":\"low\"", "low", "Reasoning Effort: Low"); // the request's own +} + +test "thinking request: Qwen3.8 off takes a named effort, which its template reads only while thinking" { + const t = std.testing; + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const config = @embedFile("fixtures/thinking/qwen38-tokenizer_config.json"); + var f = try @import("thinking_family_fixture.zig").init(t.allocator, t.io, @embedFile("fixtures/thinking/qwen38.jinja"), config, "qwen3_5"); + defer f.deinit(); + var problem: []const u8 = ""; + const hf = try HfText.load(t.allocator, t.io, f.path, null, a, &problem); + defer hf.deinit(); + const text = hf.text(); + const messages = (try json.parse(a, "[{\"role\":\"user\",\"content\":\"H\"}]")).ok; + const heard = try text.render(a, messages, .{ .enable_thinking = false, .reasoning_effort = "xhigh" }, &problem); + try t.expectEqualStrings((try text.render(a, messages, .{ .enable_thinking = false }, &problem)).text, heard.text); + var script: Script = .{}; + const srv = try Server.init(t.allocator, t.io, script.engine(), text, .{ .served_name = "m", .model_ids = &.{ "m", "alias" }, .use_drafts = false }, null); + defer srv.deinit(); + const whole = try post(srv, a, &script, off ++ ",\"reasoning_effort\":\"high\""); // heard as xhigh on Qwen3.8's levels + try t.expectEqualSlices(u32, try heard.encode(text, a, &problem), script.prompt[0..script.count]); + try t.expectEqualStrings("xhigh", whole.get("tensorfold").?.strField("reasoning_effort").?); +} + +test "thinking request: a named effort is the request's own, with no fallback, so Kimi's off prompt keeps none" { + const fields = @import("fields.zig"); + const levels = [_][]const u8{ "low", "high", "max" }; + try std.testing.expect(fields.namedEffort(null, &levels) == null); // effortFor would give Kimi "max" + try std.testing.expect(fields.namedEffort("none", &levels) == null); + try std.testing.expectEqualStrings("high", fields.namedEffort("high", &levels).?); + try std.testing.expectEqualStrings("high", fields.namedEffort("medium", &levels).?); // on GLM-5.3's levels +} diff --git a/zig/src/server/token_stream.zig b/zig/src/server/token_stream.zig new file mode 100644 index 00000000000..19cd7aa914a --- /dev/null +++ b/zig/src/server/token_stream.zig @@ -0,0 +1,63 @@ +const std = @import("std"); +const json = @import("json"); +const errors = @import("errors.zig"); +const Allocator = std.mem.Allocator; +const Value = json.Value; + +pub const versions = [_]u32{1}; +pub const Cursor = struct { count: usize = 0, last: ?u32 = null }; + +pub fn requested(cx: *errors.Cx, body: Value, streaming: bool, cortheon: bool) errors.Refused!bool { + const options = body.get("stream_options") orelse return false; + const version = options.get("tensorfold_token_stream_version") orelse return false; + if (version != .int or version.int64() != 1) + return cx.refuse("stream_options.tensorfold_token_stream_version must be the integer 1"); + if (!streaming or body.get("stream").? != .bool) return cx.refuse("tensorfold token streams require stream: true"); + if (cortheon) return cx.refuse("tensorfold token stream version 1 does not support Cortheon's multi-round replies"); + return true; +} + +/// The chat sink's token callback for a stream sink type whose `run` is the reply it streams. +pub fn sinkTokens(comptime S: type) *const fn (*anyopaque, usize, []const u32) error{Closed}!void { + return &struct { + fn call(ctx: *anyopaque, offset: usize, ids: []const u32) error{Closed}!void { + const s: *S = @ptrCast(@alignCast(ctx)); + return emit(s.run, offset, ids); + } + }.call; +} + +pub fn emit(r: anytype, offset: usize, ids: []const u32) error{Closed}!void { + if (ids.len == 0 or offset != r.token_cursor.count) return error.Closed; + const value = payload(r.a, r.id, r.plan.named, offset, ids) catch return error.Closed; + try r.out.vt.event(r.out.ctx, value); + r.token_cursor = .{ .count = offset + ids.len, .last = ids[ids.len - 1] }; +} + +fn payload(a: Allocator, id: []const u8, model: []const u8, offset: usize, ids: []const u32) Allocator.Error!Value { + const out = try json.newObject(a); + try out.put(a, "object", .{ .string = "tensorfold.token.chunk" }); + try out.put(a, "version", .{ .int = "1" }); + try out.put(a, "id", .{ .string = id }); + try out.put(a, "model", .{ .string = model }); + try out.put(a, "offset", try json.intValue(a, offset)); + try out.put(a, "token_ids", try tokenIds(a, ids)); + return .{ .object = out }; +} + +pub fn tokenIds(a: Allocator, ids: []const u32) Allocator.Error!Value { + const values = try a.alloc(Value, ids.len); + for (values, ids) |*value, id| value.* = try json.intValue(a, id); + return .{ .array = values }; +} + +pub fn anchor(a: Allocator, out: *json.Object, cursor: Cursor, delta: ?Value) Allocator.Error!void { + const value = try json.newObject(a); + try value.put(a, "version", .{ .int = "1" }); + try value.put(a, "token_count", try json.intValue(a, cursor.count)); + try value.put(a, "token_id", if (cursor.last) |id| try json.intValue(a, id) else .null); + // each logprob entry's raw token position, in the shape of the chunk's logprobs + if (delta) |d| if (d == .object) if (d.object.fetchOrderedRemove("logprob_positions")) |at| + try value.put(a, "logprob_positions", at.value); + try out.put(a, "tensorfold_stream", .{ .object = value }); +} diff --git a/zig/src/server/token_stream_test.zig b/zig/src/server/token_stream_test.zig new file mode 100644 index 00000000000..83219f173f4 --- /dev/null +++ b/zig/src/server/token_stream_test.zig @@ -0,0 +1,505 @@ +const std = @import("std"); +const api = @import("engine_api"); +const json = @import("json"); +const openai = @import("openai.zig"); +const preflight = @import("stream_preflight_test.zig"); +const Server = @import("server.zig").Server; +const Conn = @import("http_conn.zig").Conn; +const Allocator = std.mem.Allocator; +const Value = json.Value; + +const Script = struct { + ids: []const u32, + stride: usize = 1, + submits: usize = 0, + cancels: usize = 0, + await_cancel: bool = false, + logprobs: bool = false, + active: ?struct { id: api.Id, sink: api.Sink } = null, + + fn engine(s: *Script) api.Engine { + return .{ .ctx = s, .vtable = &.{ .info = info, .submit = submit, .cancel = cancel, .status = status, .memory = memory } }; + } + + fn info(ctx: *anyopaque) api.Info { + const s: *Script = @ptrCast(@alignCast(ctx)); + return .{ .context_window = 4096, .logprobs = s.logprobs }; + } + + fn submit(ctx: *anyopaque, id: api.Id, request_: *const api.Request, sink: api.Sink) api.SubmitError!void { + const s: *Script = @ptrCast(@alignCast(ctx)); + s.submits += 1; + s.active = .{ .id = id, .sink = sink }; + sink.event(sink.ctx, id, &.{ .prefilled = 0 }); + var at: usize = 0; + while (at < s.ids.len) : (at += s.stride) { + const batch = s.ids[at..@min(at + s.stride, s.ids.len)]; + if (request_.logprobs) |count| { + var rows: [128]api.LogprobRow = undefined; + for (batch, rows[0..batch.len], at..) |token, *row, i| { + row.* = .{ .token = token, .logprob = -@as(f32, @floatFromInt(i + 1)) / 4, .count = count }; + for (0..count) |j| { + row.ids[j] = if (j == 0) token else 'z'; + row.logprobs[j] = row.logprob - @as(f32, @floatFromInt(j)); + } + } + sink.event(sink.ctx, id, &.{ .logprobs = rows[0..batch.len] }); + } + sink.event(sink.ctx, id, &.{ .tokens = batch }); + } + if (!s.await_cancel) sink.event(sink.ctx, id, &.{ .finished = .{ .reason = .length } }); + } + + fn cancel(ctx: *anyopaque, _: api.Id) void { + const s: *Script = @ptrCast(@alignCast(ctx)); + s.cancels += 1; + if (s.await_cancel) if (s.active) |active| { + active.sink.event(active.sink.ctx, active.id, &.{ .finished = .{ .reason = .cancelled } }); + s.active = null; + }; + } + + fn status(_: *anyopaque, out: *api.Status, _: []u32) void { + out.* = .{}; + } + + fn memory(_: *anyopaque, _: bool) ?api.Memory { + return null; + } +}; + +const Captured = struct { + a: Allocator, + events: std.ArrayList(Value) = .empty, + whole: ?Value = null, + status: ?u16 = null, + opened: bool = false, + done: bool = false, + fail_raw: bool = false, + failed_raw: bool = false, + + fn out(c: *Captured) openai.Out { + return .{ .ctx = c, .vt = &.{ .open = open, .event = event, .reply = reply } }; + } + + fn open(ctx: *anyopaque, _: usize) error{Closed}!void { + const c: *Captured = @ptrCast(@alignCast(ctx)); + c.opened = true; + } + + fn event(ctx: *anyopaque, payload: ?Value) error{Closed}!void { + const c: *Captured = @ptrCast(@alignCast(ctx)); + const v = payload orelse { + c.done = true; + return; + }; + if (c.fail_raw) { + if (isRaw(v)) { + c.failed_raw = true; + return error.Closed; + } + if (v.get("choices")) |choices| if (choices.array.len > 0) { + const choice = choices.array[0]; + const delta = choice.get("delta") orelse choice; + if (delta.strField("content")) |piece| if (piece.len > 0) return error.Closed; + }; + } + c.events.append(c.a, v) catch return error.Closed; + } + + fn reply(ctx: *anyopaque, status_code: u16, value: Value) void { + const c: *Captured = @ptrCast(@alignCast(ctx)); + c.status = status_code; + c.whole = value; + } +}; + +fn isRaw(v: Value) bool { + return std.mem.eql(u8, v.strField("object") orelse "", "tensorfold.token.chunk"); +} + +fn run(srv: *Server, a: Allocator, body: Value, is_chat: bool, fail_raw: bool) Captured { + var conn: Conn = .{ .fd = -1, .peer = "", .buf = &.{}, .gpa = a }; + var captured: Captured = .{ .a = a, .fail_raw = fail_raw }; + openai.run(srv, a, captured.out(), .{ .conn = &conn }, is_chat, body); + return captured; +} + +fn request(a: Allocator, enabled: bool, is_chat: bool) !Value { + const body = (try json.parse(a, if (is_chat) + "{\"model\":\"m\",\"messages\":[{\"role\":\"user\",\"content\":\"x\"}],\"stream\":true,\"max_tokens\":512,\"return_token_ids\":true}" + else + "{\"model\":\"m\",\"prompt\":[1],\"stream\":true,\"max_tokens\":512,\"return_token_ids\":true}")).ok; + if (enabled) try body.object.put(a, "stream_options", (try json.parse(a, "{\"tensorfold_token_stream_version\":1}")).ok); + return body; +} + +fn rawIds(a: Allocator, captured: Captured) ![]u32 { + var ids: std.ArrayList(u32) = .empty; + for (captured.events.items) |event| { + if (isRaw(event)) { + try std.testing.expectEqual(@as(i64, 1), event.get("version").?.int64().?); + try std.testing.expectEqual(@as(i64, @intCast(ids.items.len)), event.get("offset").?.int64().?); + for (event.get("token_ids").?.array) |v| try ids.append(a, @intCast(v.int64().?)); + } else if (event.get("choices") != null) { + const anchor = event.get("tensorfold_stream") orelse return error.MissingTokenAnchor; + try std.testing.expectEqual(@as(i64, 1), anchor.get("version").?.int64().?); + try std.testing.expectEqual(@as(i64, @intCast(ids.items.len)), anchor.get("token_count").?.int64().?); + const last = anchor.get("token_id").?; + if (ids.items.len == 0) try std.testing.expect(last == .null) else try std.testing.expectEqual(@as(i64, ids.items[ids.items.len - 1]), last.int64().?); + } + } + return ids.items; +} + +test "token stream: committed token ids arrive with contiguous offsets and semantic anchors" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var text: preflight.TestText = .{}; + var script: Script = .{ .ids = &.{ 'O', 'K', 0, 'X' }, .stride = 3 }; + const srv = try Server.init(std.testing.allocator, std.testing.io, script.engine(), text.text(), .{ + .served_name = "m", + .model_ids = &.{"m"}, + .enable_thinking = false, + }, null); + defer srv.deinit(); + srv.eos = &.{0}; + for ([_]bool{ false, true }) |is_chat| { + const captured = run(srv, a, try request(a, true, is_chat), is_chat, false); + try std.testing.expect(captured.opened and captured.done); + try std.testing.expectEqualSlices(u32, &.{ 'O', 'K', 0 }, try rawIds(a, captured)); + } +} + +fn final(captured: Captured) !Value { + for (captured.events.items) |event| if (event.get("tensorfold") != null) return event; + return error.MissingFinalReply; +} + +fn checkFinal(a: Allocator, captured: Captured, expected: []const u32) !void { + try std.testing.expect(captured.opened and captured.done and captured.whole == null); + try std.testing.expectEqualSlices(u32, expected, try rawIds(a, captured)); + const reply = try final(captured); + const runtime = reply.get("tensorfold").?; + const returned = runtime.get("token_ids").?.array; + try std.testing.expectEqual(expected.len, returned.len); + for (expected, returned) |id, value| try std.testing.expectEqual(@as(i64, id), value.int64().?); + const sha = @import("tokens.zig").tokenSha256(expected); + try std.testing.expectEqualStrings(&sha, runtime.strField("token_sha256").?); + for (captured.events.items) |event| if (event.get("usage")) |usage| { + try std.testing.expectEqual(@as(i64, @intCast(expected.len)), usage.get("completion_tokens").?.int64().?); + return; + }; + return error.MissingUsage; +} + +fn content(a: Allocator, captured: Captured, field: []const u8) ![]const u8 { + var out: std.ArrayList(u8) = .empty; + for (captured.events.items) |event| { + const choices = event.get("choices") orelse continue; + if (choices.array.len == 0) continue; + const choice = choices.array[0]; + const delta = choice.get("delta") orelse choice; + if (delta.strField(field)) |value| try out.appendSlice(a, value); + } + return out.items; +} + +fn normalized(a: Allocator, captured: Captured) ![]const u8 { + var out: std.ArrayList(Value) = .empty; + for (captured.events.items) |event| { + if (isRaw(event)) continue; + const copy = (try json.parse(a, try json.stringify(a, event, .{}))).ok; + for ([_][]const u8{ "id", "created", "tensorfold_stream" }) |key| _ = copy.object.fetchOrderedRemove(key); + if (copy.get("tensorfold")) |runtime| { + for ([_][]const u8{ "tokens_per_second", "seconds", "time_to_first_token" }) |key| + _ = runtime.object.fetchOrderedRemove(key); + } + try out.append(a, copy); + } + return json.stringify(a, .{ .array = out.items }, .{}); +} + +const Text = @import("model_text.zig").Text; +const end_thinking: u32 = 300; +const end_reply: u32 = 301; + +fn exactText(base: *preflight.TestText, table: *Text.VTable) Text { + var text = base.text(); + table.* = text.vtable.*; + table.decode = exactDecode; + table.token_bytes = exactBytes; + table.token_id = exactId; + text.vtable = table; + return text; +} + +fn exactBytes(_: *anyopaque, a: Allocator, id: u32) Allocator.Error!?[]u8 { + if (id == end_thinking) return try a.dupe(u8, ""); + if (id == end_reply) return try a.dupe(u8, ""); + return try a.dupe(u8, &.{@intCast(id)}); +} + +fn exactId(_: *anyopaque, text: []const u8) ?u32 { + return if (std.mem.eql(u8, text, "")) end_thinking else null; +} + +fn exactDecode(ctx: *anyopaque, a: Allocator, ids: []const u32) Allocator.Error![]u8 { + var raw: std.ArrayList(u8) = .empty; + for (ids) |id| try raw.appendSlice(a, (try exactBytes(ctx, a, id)).?); + var out: std.ArrayList(u8) = .empty; + try @import("tokenizer").unicode.appendLossy(&out, a, raw.items); + return out.items; +} + +test "token stream: UTF-8 tokens precede complete text and logprob entries name their raw positions" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var text: preflight.TestText = .{}; + var table: Text.VTable = undefined; + const ids = [_]u32{ 'r', end_thinking, '\n', 'A', 0xf0, 0x9f, 0x98, 0x80, 'A', end_reply }; + var script: Script = .{ .ids = &ids, .logprobs = true }; + const srv = try Server.init(std.testing.allocator, std.testing.io, script.engine(), exactText(&text, &table), .{ + .served_name = "m", + .model_ids = &.{"m"}, + .enable_thinking = true, + }, null); + defer srv.deinit(); + srv.eos = &.{end_reply}; + const body = try request(a, true, true); + try body.object.put(a, "logprobs", .{ .bool = true }); + try body.object.put(a, "top_logprobs", .{ .int = "2" }); + const captured = run(srv, a, body, true, false); + try checkFinal(a, captured, &ids); + try std.testing.expectEqualStrings("r", try content(a, captured, "reasoning_content")); + try std.testing.expectEqualStrings("A😀A", try content(a, captured, "content")); + var emoji_count: usize = 0; + for (captured.events.items) |event| { + const choices = event.get("choices") orelse continue; + if (choices.array.len == 0) continue; + const delta = choices.array[0].get("delta").?; + if (delta.strField("content")) |piece| { + try std.testing.expect(std.unicode.utf8ValidateSlice(piece)); + if (std.mem.eql(u8, piece, "😀")) { + emoji_count += 1; + try std.testing.expectEqual(@as(i64, 8), event.get("tensorfold_stream").?.get("token_count").?.int64().?); + } + } + } + try std.testing.expectEqual(@as(usize, 1), emoji_count); + const seen = try positions(a, captured); + try std.testing.expectEqualSlices(usize, &.{ 3, 4, 5, 6, 7, 8 }, seen.content); + try std.testing.expectEqualSlices(usize, &.{0}, seen.reasoning); +} + +/// Each streamed logprob entry's position by channel, in stream order, after checking it against the entry's row. +fn positions(a: Allocator, captured: Captured) !struct { content: []usize, reasoning: []usize, tools: []usize } { + var lists = [_]std.ArrayList(usize){ .empty, .empty, .empty }; + for (captured.events.items) |event| { + const choices = event.get("choices") orelse continue; + if (choices.array.len == 0) continue; + const choice = choices.array[0]; + try std.testing.expect(choice.get("delta").?.get("logprob_positions") == null); + const lp = choice.get("logprobs") orelse continue; + if (lp == .null) continue; + const at = event.get("tensorfold_stream").?.get("logprob_positions").?; + for ([_][]const u8{ "content", "reasoning_content" }, lists[0..2]) |key, *list| + if (lp.get(key)) |rows| try matchRows(a, rows, at.get(key).?, list); + if (lp.get("tool_calls")) |groups| for (groups.array, at.get("tool_calls").?.array) |group, places| + try matchRows(a, group.get("content").?, places.get("content").?, &lists[2]); + } + return .{ .content = lists[0].items, .reasoning = lists[1].items, .tools = lists[2].items }; +} + +/// The script's row for position `i` has logprob -(i + 1) / 4, so each entry names the row it came from. +fn matchRows(a: Allocator, rows: Value, places: Value, list: *std.ArrayList(usize)) !void { + try std.testing.expectEqual(rows.array.len, places.array.len); + for (rows.array, places.array) |row, place| { + const i: usize = @intCast(place.int64().?); + try std.testing.expectEqual(-@as(f64, @floatFromInt(i + 1)) / 4, row.get("logprob").?.float); + try list.append(a, i); + } +} + +test "token stream: a call's logprob entries name their positions in the last chunk" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var text: preflight.TestText = .{}; + var table: Text.VTable = undefined; + const reply = "ok \n{\"name\":\"lookup\",\"arguments\":{\"q\":\"a\"}}\n"; + const ids = try a.alloc(u32, reply.len); + for (ids, reply) |*id, byte| id.* = byte; + var script: Script = .{ .ids = ids, .stride = 4, .logprobs = true }; + const srv = try Server.init(std.testing.allocator, std.testing.io, script.engine(), exactText(&text, &table), .{ + .served_name = "m", + .model_ids = &.{"m"}, + }, null); + defer srv.deinit(); + var got: [2]Captured = undefined; + for (&got, 0..) |*capture, enabled| { + const body = try request(a, enabled == 1, true); + try body.object.put(a, "logprobs", .{ .bool = true }); + try body.object.put(a, "tools", (try json.parse( + a, + "[{\"type\":\"function\",\"function\":{\"name\":\"lookup\",\"parameters\":{\"type\":\"object\",\"properties\":{\"q\":{\"type\":\"string\"}},\"required\":[\"q\"]}}}]", + )).ok); + capture.* = run(srv, a, body, true, false); + } + try checkFinal(a, got[1], ids); + try std.testing.expectEqualStrings("tool_calls", (try final(got[1])).get("choices").?.array[0].strField("finish_reason").?); + for (got[0].events.items) |event| try std.testing.expect(!isRaw(event) and event.get("tensorfold_stream") == null); + try std.testing.expectEqualStrings(try normalized(a, got[0]), try normalized(a, got[1])); + const seen = try positions(a, got[1]); + // the call's entries cover its envelope, after the prose entries and in token order + try std.testing.expect(seen.tools.len > 0); + try std.testing.expect(seen.content.len == 0 or seen.content[seen.content.len - 1] < seen.tools[0]); + for (seen.tools[1..], seen.tools[0 .. seen.tools.len - 1]) |next, prev| try std.testing.expect(next >= prev); + try std.testing.expectEqual(@as(u32, '<'), ids[seen.tools[0]]); +} + +test "token stream: empty completion and length or stop cuts agree with final usage and hashes" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var text: preflight.TestText = .{}; + const cases = [_]struct { ids: []const u32, expected: []const u32, limit: []const u8, stop: ?[]const u8, visible: []const u8 }{ + .{ .ids = &.{}, .expected = &.{}, .limit = "8", .stop = null, .visible = "" }, + .{ .ids = &.{ 'A', 'B', 'C', 'D' }, .expected = &.{ 'A', 'B' }, .limit = "2", .stop = null, .visible = "AB" }, + .{ .ids = &.{ 'A', 'E', 'N', 'D', 'X' }, .expected = &.{ 'A', 'E', 'N', 'D' }, .limit = "8", .stop = "END", .visible = "A" }, + }; + for (cases) |case| for ([_]bool{ false, true }) |separate| { + var script: Script = .{ .ids = case.ids, .stride = 8 }; + const srv = try Server.init(std.testing.allocator, std.testing.io, script.engine(), text.text(), .{ + .served_name = "m", + .model_ids = &.{"m"}, + .enable_thinking = false, + }, null); + defer srv.deinit(); + const body = try request(a, true, true); + try body.object.put(a, "max_tokens", .{ .int = case.limit }); + if (case.stop) |stop| try body.object.put(a, "stop", .{ .string = stop }); + try body.get("stream_options").?.object.put(a, "include_usage", .{ .bool = separate }); + const captured = run(srv, a, body, true, false); + try checkFinal(a, captured, case.expected); + try std.testing.expectEqualStrings(case.visible, try content(a, captured, "content")); + }; +} + +test "token stream: reasoning and tools keep ordinary deltas including the final flush" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var text: preflight.TestText = .{}; + const cases = [_]struct { reply: []const u8, thinking: bool, tools: bool, content_: []const u8, reasoning: []const u8 }{ + .{ .reply = "plananswer", .thinking = true, .tools = false, .content_ = "answer", .reasoning = "plan" }, + .{ .reply = "answer", .thinking = false, .tools = true, .content_ = "", .reasoning = "" }, + }; + for (cases) |case| for ([_]usize{ 1, 128 }) |stride| { + const expected = try preflight.TestText.encode(&text, a, case.reply, false); + var script: Script = .{ .ids = expected, .stride = stride }; + const srv = try Server.init(std.testing.allocator, std.testing.io, script.engine(), text.text(), .{ + .served_name = "m", + .model_ids = &.{"m"}, + .enable_thinking = case.thinking, + }, null); + defer srv.deinit(); + var got: [2]Captured = undefined; + for (&got, 0..) |*capture, enabled| { + const body = try request(a, enabled == 1, true); + if (case.tools) try body.object.put(a, "tools", (try json.parse( + a, + "[{\"type\":\"function\",\"function\":{\"name\":\"lookup\",\"parameters\":{\"type\":\"object\",\"properties\":{\"q\":{\"type\":\"string\"}},\"required\":[\"q\"]}}}]", + )).ok); + capture.* = run(srv, a, body, true, false); + } + try checkFinal(a, got[1], expected); + try std.testing.expectEqualStrings(case.content_, try content(a, got[1], "content")); + try std.testing.expectEqualStrings(case.reasoning, try content(a, got[1], "reasoning_content")); + for (got[0].events.items) |event| try std.testing.expect(!isRaw(event) and event.get("tensorfold_stream") == null); + try std.testing.expectEqualStrings(try normalized(a, got[0]), try normalized(a, got[1])); + if (case.tools) { + var arguments: std.ArrayList(u8) = .empty; + for (got[1].events.items) |event| { + const choices = event.get("choices") orelse continue; + if (choices.array.len == 0) continue; + const delta = choices.array[0].get("delta").?; + if (delta.get("tool_calls")) |calls| for (calls.array) |call| { + if (call.get("function")) |function| if (function.strField("arguments")) |piece| + try arguments.appendSlice(a, piece); + }; + } + const args = (try json.parse(a, arguments.items)).ok; + try std.testing.expectEqualStrings("a", args.strField("q").?); + try std.testing.expectEqualStrings("tool_calls", (try final(got[1])).get("choices").?.array[0].strField("finish_reason").?); + } + }; +} + +test "token stream: unsupported versions and nonstreaming or Cortheon chat refuse before submission" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var text: preflight.TestText = .{}; + var script: Script = .{ .ids = &.{'A'} }; + const srv = try Server.init(std.testing.allocator, std.testing.io, script.engine(), text.text(), .{ + .served_name = "m", + .model_ids = &.{"m"}, + .enable_thinking = false, + }, null); + defer srv.deinit(); + for ([_][]const u8{ "0", "2", "true", "\"1\"", "1.0", "null" }) |version| { + const body = try request(a, true, true); + try body.get("stream_options").?.object.put(a, "tensorfold_token_stream_version", (try json.parse(a, version)).ok); + const captured = run(srv, a, body, true, false); + try std.testing.expectEqual(@as(?u16, 400), captured.status); + try std.testing.expect(!captured.opened); + } + for ([_][]const u8{ "false", "1", "\"true\"", "null" }) |stream| { + const body = try request(a, true, true); + try body.object.put(a, "stream", (try json.parse(a, stream)).ok); + try std.testing.expectEqual(@as(?u16, 400), run(srv, a, body, true, false).status); + } + srv.config.cortheon = true; + try std.testing.expectEqual(@as(?u16, 400), run(srv, a, try request(a, true, true), true, false).status); + try std.testing.expectEqual(@as(usize, 0), script.submits); +} + +test "token stream: failed raw writes cancel and drain before the next request" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var text: preflight.TestText = .{}; + var script: Script = .{ .ids = &.{ 'A', 'B' }, .await_cancel = true }; + const srv = try Server.init(std.testing.allocator, std.testing.io, script.engine(), text.text(), .{ + .served_name = "m", + .model_ids = &.{"m"}, + .enable_thinking = false, + }, null); + defer srv.deinit(); + const cancelled = run(srv, a, try request(a, true, true), true, true); + try std.testing.expect(cancelled.opened and !cancelled.done and cancelled.whole == null and cancelled.failed_raw); + try std.testing.expectEqual(@as(usize, 1), script.cancels); + try std.testing.expectEqual(@as(i64, 0), srv.preparing.load(.acquire)); + script.await_cancel = false; + const recovered = run(srv, a, try request(a, true, true), true, false); + try checkFinal(a, recovered, &.{ 'A', 'B' }); + try std.testing.expectEqual(@as(usize, 2), script.submits); + try std.testing.expectEqual(@as(i64, 0), srv.preparing.load(.acquire)); +} + +test "token stream: capabilities advertise the implemented wire version" { + var out: std.Io.Writer.Allocating = .init(std.testing.allocator); + defer out.deinit(); + try @import("cli_capabilities.zig").capabilities(&out.writer, .{ .version = "test" }); + const parsed = try std.json.parseFromSlice(std.json.Value, std.testing.allocator, out.written(), .{}); + defer parsed.deinit(); + try std.testing.expect(parsed.value.object.get("token_stream_versions") != null); + try std.testing.expect(parsed.value.object.get("token_stream_versions").? == .array); + const versions = parsed.value.object.get("token_stream_versions").?.array.items; + try std.testing.expectEqual(@as(usize, 1), versions.len); + try std.testing.expectEqual(@as(i64, 1), versions[0].integer); +} diff --git a/zig/src/server/tokens.zig b/zig/src/server/tokens.zig index 5c1a5f0a4ab..2ab839c6971 100644 --- a/zig/src/server/tokens.zig +++ b/zig/src/server/tokens.zig @@ -38,6 +38,7 @@ fn tokenize(srv: *Server, cx: *Cx, body: Value) errors.Refused!Value { const thinking = try fields.thinkingFields(cx, body, srv.effort_levels); const on = thinking.enable orelse srv.config.enable_thinking; cx.clear_thinking = thinking.clear; + cx.named_effort = fields.namedEffort(thinking.effort, srv.effort_levels); cx.template_fields = body; ids = prompt.renderIds(srv, cx, msgs, tools, on, srv.effortFor(thinking.effort), generation) catch |e| switch (e) { error.Refused => return cx.other(cx.message), diff --git a/zig/src/server/toml_flat.zig b/zig/src/server/toml_flat.zig new file mode 100644 index 00000000000..d1f32580e68 --- /dev/null +++ b/zig/src/server/toml_flat.zig @@ -0,0 +1,235 @@ +//! A strict subset of TOML 1.0 for flat settings files: top-level ``key = value`` lines, the rest refused by line. +const std = @import("std"); +const Allocator = std.mem.Allocator; + +/// A number keeps its text, ready to be a flag's value: no ``_``, and no leading ``+`` on an integer. +pub const Scalar = union(enum) { string: []const u8, integer: []const u8, float: []const u8, boolean: bool }; +pub const Value = union(enum) { scalar: Scalar, array: []const []const u8 }; +pub const Entry = struct { key: []const u8, line: u32, value: Value }; + +/// Why a text was refused and on which line (1-based). +pub const Problem = struct { line: u32 = 0, message: []const u8 = "" }; + +pub const Error = error{ Invalid, OutOfMemory }; + +/// Top-level ``key = value`` lines in file order; every text this accepts is valid TOML 1.0 with the same meaning. +pub fn parse(a: Allocator, text: []const u8, problem: *Problem) Error![]const Entry { + var r: Reader = .{ .a = a, .text = text, .problem = problem }; + if (std.mem.startsWith(u8, text, "\xef\xbb\xbf")) return r.fail("a byte order mark is not TOML 1.0: save the file without one"); + if (!std.unicode.utf8ValidateSlice(text)) { + var lines = std.mem.splitScalar(u8, text, '\n'); // a line feed is never inside a multi-byte sequence + while (lines.next()) |l| : (r.line += 1) if (!std.unicode.utf8ValidateSlice(l)) break; + return r.fail("invalid UTF-8"); + } + var out: std.ArrayList(Entry) = .empty; + while (true) { + r.blanks(); + if (r.done()) break; + if (try r.lineEnd()) continue; + if (r.peek() == '#') { + try r.comment(); + continue; + } + if (r.peek() == '[') return r.fail("tables are not read: every key is a top-level setting"); + const line = r.line; + const key = try r.key(); + for (out.items) |e| if (std.mem.eql(u8, e.key, key)) return r.fail("key defined twice"); + r.blanks(); + if (r.peek() == '.') return r.fail("dotted keys are not read: every key is a top-level setting"); + if (r.peek() != '=') return r.fail("expected '=' after the key"); + r.at += 1; + r.blanks(); + const value = try r.value(); + r.blanks(); + if (r.peek() == '#') try r.comment(); + if (!r.done() and !try r.lineEnd()) return r.fail("unexpected text after the value"); + try out.append(a, .{ .key = key, .line = line, .value = value }); + } + return out.items; +} + +const Reader = struct { + a: Allocator, + text: []const u8, + problem: *Problem, + at: usize = 0, + line: u32 = 1, + + fn fail(r: *Reader, message: []const u8) Error { + r.problem.* = .{ .line = r.line, .message = message }; + return error.Invalid; + } + + fn done(r: *const Reader) bool { + return r.at >= r.text.len; + } + + /// The byte at the cursor, or 0 at the end of the text (a NUL in the text is refused wherever it can occur). + fn peek(r: *const Reader) u8 { + return if (r.at < r.text.len) r.text[r.at] else 0; + } + + fn blanks(r: *Reader) void { + while (r.peek() == ' ' or r.peek() == '\t') r.at += 1; + } + + /// Consumes a line end (LF or CRLF) at the cursor; a CR alone is refused. + fn lineEnd(r: *Reader) Error!bool { + if (r.peek() == '\r') { + if (r.at + 1 >= r.text.len or r.text[r.at + 1] != '\n') return r.fail("a carriage return without a line feed"); + r.at += 1; + } + if (r.peek() != '\n' or r.done()) return false; + r.at += 1; + r.line += 1; + return true; + } + + fn control(c: u8) bool { + return (c < 0x20 and c != '\t') or c == 0x7f; + } + + /// From ``#`` to the line end, which stays unread. + fn comment(r: *Reader) Error!void { + while (!r.done() and r.peek() != '\n' and !(r.peek() == '\r' and r.at + 1 < r.text.len and r.text[r.at + 1] == '\n')) : (r.at += 1) + if (control(r.peek())) return r.fail("a control character in a comment"); + } + + fn key(r: *Reader) Error![]const u8 { + if (r.peek() == '"' or r.peek() == '\'') return r.string(); + const start = r.at; + while (std.ascii.isAlphanumeric(r.peek()) or r.peek() == '_' or r.peek() == '-') r.at += 1; + if (r.at == start) return r.fail("expected a key"); + return r.text[start..r.at]; + } + + fn value(r: *Reader) Error!Value { + if (r.peek() == '{') return r.fail("inline tables are not read"); + if (r.peek() != '[') return .{ .scalar = try r.scalar() }; + r.at += 1; + var items: std.ArrayList([]const u8) = .empty; + while (true) { + try r.gap(); + if (r.done()) return r.fail("unterminated array"); + if (r.peek() == ']') break; + if (r.peek() == '[' or r.peek() == '{') return r.fail("nested arrays and inline tables are not read"); + if (r.peek() != '"' and r.peek() != '\'') return r.fail("an array holds strings only: quote each item"); + try items.append(r.a, try r.string()); + try r.gap(); + if (r.peek() == ',') r.at += 1 else if (r.peek() != ']') return r.fail(if (r.done()) "unterminated array" else "expected ',' or ']' in the array"); + } + r.at += 1; + return .{ .array = items.items }; + } + + /// Blanks, line ends and comments between an array's items. + fn gap(r: *Reader) Error!void { + while (true) { + r.blanks(); + if (r.peek() == '#') try r.comment() else if (!try r.lineEnd()) return; + } + } + + fn scalar(r: *Reader) Error!Scalar { + if (r.peek() == '"' or r.peek() == '\'') return .{ .string = try r.string() }; + const start = r.at; + while (!r.done() and std.mem.indexOfScalar(u8, " \t\r\n,]#", r.peek()) == null) r.at += 1; + const token = r.text[start..r.at]; + if (token.len == 0) return r.fail("expected a value"); + if (std.mem.eql(u8, token, "true")) return .{ .boolean = true }; + if (std.mem.eql(u8, token, "false")) return .{ .boolean = false }; + const kind = number(token) orelse + return r.fail("not a string, a decimal number, true or false (dates, times and 0x, 0o and 0b integers are not read)"); + const body = if (kind == .integer and token[0] == '+') token[1..] else token; + const clean = try r.a.alloc(u8, body.len - std.mem.count(u8, body, "_")); + var n: usize = 0; + for (body) |c| if (c != '_') { + clean[n] = c; + n += 1; + }; + return if (kind == .integer) .{ .integer = clean } else .{ .float = clean }; + } + + /// A basic (``"``) or literal (``'``) string on one line, decoded. + fn string(r: *Reader) Error![]const u8 { + const quote = r.peek(); + if (std.mem.startsWith(u8, r.text[r.at..], if (quote == '"') "\"\"\"" else "'''")) return r.fail("multi-line strings are not read"); + r.at += 1; + var out: std.ArrayList(u8) = .empty; + while (true) : (r.at += 1) { + if (r.done() or r.peek() == '\n' or r.peek() == '\r') return r.fail("unterminated string"); + const c = r.peek(); + if (c == quote) break; + if (control(c)) return r.fail("a control character in a string: write it as an escape"); + if (c != '\\' or quote == '\'') { + try out.append(r.a, c); + continue; + } + r.at += 1; + const simple: ?u8 = switch (r.peek()) { + 'b' => 0x08, + 't' => '\t', + 'n' => '\n', + 'f' => 0x0c, + 'r' => '\r', + '"' => '"', + '\\' => '\\', + else => null, + }; + if (simple) |s| { + try out.append(r.a, s); + continue; + } + const width: usize = switch (r.peek()) { + 'u' => 4, + 'U' => 8, + else => return r.fail("unknown escape in a string (TOML has \\b \\t \\n \\f \\r \\\" \\\\ \\uXXXX \\UXXXXXXXX)"), + }; + if (r.at + width >= r.text.len) return r.fail("unterminated string"); + const hex = r.text[r.at + 1 .. r.at + 1 + width]; + for (hex) |h| if (!std.ascii.isHex(h)) return r.fail(bad_escape); + const code = std.fmt.parseInt(u21, hex, 16) catch return r.fail(bad_escape); + var buf: [4]u8 = undefined; + const len = std.unicode.utf8Encode(code, &buf) catch return r.fail(bad_escape); + try out.appendSlice(r.a, buf[0..len]); + r.at += width; + } + r.at += 1; + return out.items; + } +}; + +const bad_escape = "a \\u or \\U escape needs 4 or 8 hexadecimal digits of a Unicode scalar value"; + +const Number = enum { integer, float }; + +/// TOML 1.0's decimal integer or float, or null: a sign, digits with ``_`` only between two, fraction, exponent. +fn number(token: []const u8) ?Number { + var s = token; + if (s.len > 0 and (s[0] == '+' or s[0] == '-')) s = s[1..]; + if (std.mem.eql(u8, s, "inf") or std.mem.eql(u8, s, "nan")) return .float; + const whole_end = std.mem.indexOfAny(u8, s, ".eE") orelse s.len; + const whole = s[0..whole_end]; + if (!digits(whole) or (whole.len > 1 and whole[0] == '0')) return null; + var rest = s[whole_end..]; + if (rest.len == 0) return .integer; + if (rest[0] == '.') { + const frac_end = std.mem.indexOfAny(u8, rest, "eE") orelse rest.len; + if (!digits(rest[1..frac_end])) return null; + rest = rest[frac_end..]; + if (rest.len == 0) return .float; + } + rest = rest[1..]; // past the e + if (rest.len > 0 and (rest[0] == '+' or rest[0] == '-')) rest = rest[1..]; + return if (digits(rest)) .float else null; +} + +/// One or more digits, with single underscores only between two digits. +fn digits(s: []const u8) bool { + if (s.len == 0) return false; + for (s, 0..) |c, i| { + if (std.ascii.isDigit(c)) continue; + if (c != '_' or i == 0 or i + 1 == s.len or !std.ascii.isDigit(s[i - 1]) or !std.ascii.isDigit(s[i + 1])) return false; + } + return true; +} diff --git a/zig/src/server/toml_flat_test.zig b/zig/src/server/toml_flat_test.zig new file mode 100644 index 00000000000..1578d8643fc --- /dev/null +++ b/zig/src/server/toml_flat_test.zig @@ -0,0 +1,175 @@ +//! toml_flat.zig: what the flat TOML reader accepts, how it decodes it, and each refusal with its line. +const std = @import("std"); +const toml = @import("toml_flat.zig"); +const t = std.testing; + +fn read(a: std.mem.Allocator, text: []const u8) ![]const toml.Entry { + var problem: toml.Problem = .{}; + return toml.parse(a, text, &problem) catch |e| { + std.debug.print("refused at line {d}: {s}\n", .{ problem.line, problem.message }); + return e; + }; +} + +/// `text` is refused on `line` with a message that holds `needle`. +fn refused(a: std.mem.Allocator, text: []const u8, line: u32, needle: []const u8) !void { + var problem: toml.Problem = .{}; + try t.expectError(error.Invalid, toml.parse(a, text, &problem)); + errdefer std.debug.print("text: {s}\nline {d}: {s}\n", .{ text, problem.line, problem.message }); + try t.expectEqual(line, problem.line); + try t.expect(std.mem.indexOf(u8, problem.message, needle) != null); +} + +test "flat TOML: scalars, comments and line ends decode in file order" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const entries = try read(a, + \\# a launch + \\model = "org/Model" # trailing comment + \\ + \\port=8080 + \\ temperature = 0.6 + \\thinking = false + \\dashboard = true + \\path = 'C:\raw\n' + \\"quoted key" = "a # not a comment" + \\'lit-key' = "" + ); + try t.expectEqual(@as(usize, 8), entries.len); + try t.expectEqualStrings("model", entries[0].key); + try t.expectEqual(@as(u32, 2), entries[0].line); + try t.expectEqualStrings("org/Model", entries[0].value.scalar.string); + try t.expectEqualStrings("8080", entries[1].value.scalar.integer); + try t.expectEqual(@as(u32, 4), entries[1].line); + try t.expectEqualStrings("0.6", entries[2].value.scalar.float); + try t.expect(!entries[3].value.scalar.boolean); + try t.expect(entries[4].value.scalar.boolean); + try t.expectEqualStrings("C:\\raw\\n", entries[5].value.scalar.string); + try t.expectEqualStrings("quoted key", entries[6].key); + try t.expectEqualStrings("a # not a comment", entries[6].value.scalar.string); + try t.expectEqualStrings("lit-key", entries[7].key); + try t.expectEqualStrings("", entries[7].value.scalar.string); + try t.expectEqual(@as(usize, 0), (try read(a, "")).len); + try t.expectEqual(@as(usize, 0), (try read(a, " # only a comment")).len); + const crlf = try read(a, "a = 1\r\nb = [\r\n \"2\",\r\n]\r\n# end\r\n"); + try t.expectEqual(@as(usize, 2), crlf.len); + try t.expectEqual(@as(u32, 2), crlf[1].line); + try t.expectEqualStrings("2", crlf[1].value.array[0]); +} + +test "flat TOML: every escape of a basic string decodes" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const entries = try read(a, "s = \"\\b\\t\\n\\f\\r\\\"\\\\ \\u00e9 \\U0001F600 tab\traw \xc3\xa9\"\n"); + try t.expectEqualStrings("\x08\t\n\x0c\r\"\\ \xc3\xa9 \xf0\x9f\x98\x80 tab\traw \xc3\xa9", entries[0].value.scalar.string); +} + +test "flat TOML: numbers keep their text without underscores or an integer's plus" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const Case = struct { text: []const u8, want: []const u8, float: bool = false }; + for ([_]Case{ + .{ .text = "0", .want = "0" }, + .{ .text = "-0", .want = "-0" }, + .{ .text = "1_000", .want = "1000" }, + .{ .text = "+7", .want = "7" }, + .{ .text = "-17", .want = "-17" }, + .{ .text = "-0.5", .want = "-0.5", .float = true }, + .{ .text = "+1.0", .want = "+1.0", .float = true }, + .{ .text = "6.02e+23", .want = "6.02e+23", .float = true }, + .{ .text = "1e3", .want = "1e3", .float = true }, + .{ .text = "1E-03", .want = "1E-03", .float = true }, + .{ .text = "9_224.617_445e1_0", .want = "9224.617445e10", .float = true }, + .{ .text = "inf", .want = "inf", .float = true }, + .{ .text = "-nan", .want = "-nan", .float = true }, + }) |c| { + const entries = try read(a, try std.fmt.allocPrint(a, "n = {s}\n", .{c.text})); + const got = entries[0].value.scalar; + try t.expectEqualStrings(c.want, if (c.float) got.float else got.integer); + } +} + +test "flat TOML: arrays take strings on one line or several, with comments and a trailing comma" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const entries = try read(a, + \\empty = [] + \\one = ["a", 'b', "c, d]"] + \\many = [ # the aliases + \\ "x", + \\ + \\ "y", # second + \\] + \\after = 1 + ); + try t.expectEqual(@as(usize, 0), entries[0].value.array.len); + const one = entries[1].value.array; + try t.expectEqual(@as(usize, 3), one.len); + try t.expectEqualStrings("a", one[0]); + try t.expectEqualStrings("b", one[1]); + try t.expectEqualStrings("c, d]", one[2]); + try t.expectEqual(@as(usize, 2), entries[2].value.array.len); + try t.expectEqualStrings("y", entries[2].value.array[1]); + try t.expectEqual(@as(u32, 3), entries[2].line); + try t.expectEqual(@as(u32, 8), entries[3].line); +} + +test "flat TOML: what the subset leaves out is refused by line and by name" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + try refused(a, "a = 1\n[server]\nb = 2\n", 2, "tables are not read"); + try refused(a, "[[servers]]\n", 1, "tables are not read"); + try refused(a, "a.b = 1\n", 1, "dotted keys"); + try refused(a, "\"a\" . b = 1\n", 1, "dotted keys"); + try refused(a, "a = { b = 1 }\n", 1, "inline tables"); + try refused(a, "a = [[1], [2]]\n", 1, "nested arrays"); + try refused(a, "a = [\n { b = 1 },\n]\n", 2, "nested arrays and inline tables"); + try refused(a, "a = \"\"\"\nx\n\"\"\"\n", 1, "multi-line strings"); + try refused(a, "a = '''x'''\n", 1, "multi-line strings"); + for ([_][]const u8{ "0x10", "0o7", "0b1", "1979-05-27", "07:32:00", "1979-05-27T07:32:00Z", "01", "-01", "1__0", "1.", ".5", "1_", "_1", "1e", "1.5e", "1.e5", "1.2.3", "+", "Inf", "NaN", "True", "yes", "bare" }) |token| + try refused(a, try std.fmt.allocPrint(a, "ok = 1\nn = {s}\n", .{token}), 2, "not a string, a decimal number, true or false"); +} + +test "flat TOML: malformed text is refused by line" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + try refused(a, "a = 1\nb = 2\na = 3\n", 3, "key defined twice"); + for ([_][]const u8{ "\"a\"", "'a'", "\"\\u0061\"" }) |spelling| // one key under each quoted spelling + try refused(a, try std.fmt.allocPrint(a, "a = 1\n{s} = 2\n", .{spelling}), 2, "key defined twice"); + try refused(a, "a = \"open\nb = 1\n", 1, "unterminated string"); + try refused(a, "a = 'open", 1, "unterminated string"); + try refused(a, "a = [\"1\", \"2\"\nb = 3\n", 2, "expected ',' or ']'"); + try refused(a, "a = [\"1\",\n \"2\",\n", 3, "unterminated array"); + try refused(a, "a = [\"1\" \"2\"]\n", 1, "expected ',' or ']'"); + for ([_][]const u8{ "[,]", "[1]", "[\"a\", 2.5]", "[true]", "[\"a\",\n\n bare]" }) |list| // an array holds strings only + try refused(a, try std.fmt.allocPrint(a, "a = {s}\n", .{list}), if (std.mem.indexOfScalar(u8, list, '\n') != null) 3 else 1, "an array holds strings only"); + try refused(a, "a = 1 2\n", 1, "unexpected text after the value"); + try refused(a, "a = \"x\" y\n", 1, "unexpected text after the value"); + try refused(a, "\n\na 1\n", 3, "expected '='"); + try refused(a, "a\n", 1, "expected '='"); + try refused(a, "a =\n", 1, "expected a value"); + try refused(a, "a = # nothing\n", 1, "expected a value"); + try refused(a, "= 1\n", 1, "expected a key"); + try refused(a, "a b = 1\n", 1, "expected '='"); + try refused(a, "a = \"\\q\"\n", 1, "unknown escape"); + try refused(a, "a = \"\\uD800\"\n", 1, "Unicode scalar value"); + try refused(a, "a = \"\\u12\"\n", 1, "Unicode scalar value"); + try refused(a, "a = \"\\u+123\"\n", 1, "Unicode scalar value"); + try refused(a, "a = \"\\U00110000\"\n", 1, "Unicode scalar value"); + try refused(a, "a = \"\\u00e", 1, "unterminated string"); + try refused(a, "a = \"bell\x07\"\n", 1, "control character in a string"); + try refused(a, "a = 'del\x7f'\n", 1, "control character in a string"); + try refused(a, "a = 1 # bell\x07\n", 1, "control character in a comment"); + try refused(a, "a = 1\r# x\n", 1, "carriage return without a line feed"); + try refused(a, "a = 1\n# x\ry\n", 2, "control character in a comment"); + try refused(a, "a = \x00\n", 1, "not a string, a decimal number, true or false"); + try refused(a, "\xef\xbb\xbfa = 1\n", 1, "byte order mark"); + try refused(a, "a = 1\nb = 2\nc = \"\xff\"\n", 3, "invalid UTF-8"); + try refused(a, "a = \"\xc3\"", 1, "invalid UTF-8"); +} diff --git a/zig/src/server/videos.zig b/zig/src/server/videos.zig index 0dffe24cec7..711ce6b0d13 100644 --- a/zig/src/server/videos.zig +++ b/zig/src/server/videos.zig @@ -82,8 +82,9 @@ pub fn prepare( b: *Budget, ) errors.Refused!api.PreparedVideo { const bytes = try bytesOf(cx, fetch, url, b); + // without libtfvideo this server takes no video: the request's refusal (400), as a model without video gets (#3004) var d: Decoder = .{ .v = api.tfvideo.Video.open(bytes) catch |e| return switch (e) { - error.NoLibrary => cx.fail(.server, "{s}", .{@import("sys").optional_libraries.spec(.video).message}), + error.NoLibrary => cx.refuse(try std.fmt.allocPrint(cx.a, "video {d}: this server takes no video input: {s}", .{ i + 1, @import("sys").optional_libraries.spec(.video).message })), error.NoStream => cx.refuse(try std.fmt.allocPrint(cx.a, "video {d}: the video has no video stream", .{i + 1})), error.OutOfMemory => error.OutOfMemory, else => cx.refuse(try std.fmt.allocPrint( diff --git a/zig/src/server/warm.zig b/zig/src/server/warm.zig index fdd7a543618..6f63b9ae365 100644 --- a/zig/src/server/warm.zig +++ b/zig/src/server/warm.zig @@ -42,6 +42,8 @@ fn start(srv: *Server, input: chat.Input, message: Value, thinking: bool, effort const a = p.arena.allocator(); const clear = input.fields.get("clear_thinking"); var cx: errors.Cx = .{ .a = a, .clear_thinking = if (clear != null and clear.? == .bool) clear.?.bool else null }; + const asked = input.fields.get("reasoning_effort"); + cx.named_effort = @import("fields.zig").namedEffort(if (asked != null and asked.? == .string) asked.?.string else null, srv.effort_levels); const warm_prompt = try shared(srv, &cx, input, message, thinking, effort); var prompt = warm_prompt.ids; // an image conversation's pass holds its images as its turns did (data URLs only: no URL is fetched twice) diff --git a/zig/tests/cuda/contract_flashnext_topk.zig b/zig/tests/cuda/contract_flashnext_topk.zig index 2c1064cb65a..a6490d455d5 100644 --- a/zig/tests/cuda/contract_flashnext_topk.zig +++ b/zig/tests/cuda/contract_flashnext_topk.zig @@ -17,7 +17,7 @@ fn noSums(_: c.Shape) usize { /// rows = score rows, n = the columns ranked (V), k = the candidates kept (K). pub fn spec() c.Spec { - return .{ .name = "cuda flashnext fn_row_topk (a row's top_k candidates for sampled draws)", .accum = .none, .depth = noSums, .out = .raw, .nan = .{ .stated = "bf16 bits as drawRow orders them (-0 as +0, NaN above +Inf); ties to the lowest columns; the values above the K-th, then the ties, each in column order" }, .tiles = .{ .{}, .{ .size = 1024, .step = 1, .min = 1 }, .{ .size = k_max, .step = 1, .min = 1 } }, .served = &.{ .{ .rows = 1, .n = vocab, .k = 20 }, .{ .rows = 9, .n = vocab, .k = k_max }, .{ .rows = 17, .n = vocab, .k = 1 } } }; + return .{ .name = "cuda flashnext fn_row_topk (a row's top_k candidates for sampled draws)", .accum = .none, .depth = noSums, .out = .raw, .nan = .{ .stated = "NaN of either sign or +Inf sets column 0 to -1; other bf16 bits as drawRow orders them (-0 as +0); ties to the lowest columns; the values above the K-th, then the ties, each in column order" }, .tiles = .{ .{}, .{ .size = 1024, .step = 1, .min = 1 }, .{ .size = k_max, .step = 1, .min = 1 } }, .served = &.{ .{ .rows = 1, .n = vocab, .k = 20 }, .{ .rows = 9, .n = vocab, .k = k_max }, .{ .rows = 17, .n = vocab, .k = 1 }, .{ .rows = 8, .n = 79591, .k = 20 }, .{ .rows = 64, .n = vocab, .k = 20 } } }; } /// drawRow's order as an unsigned key: larger value, larger key; -0 as +0. @@ -112,6 +112,10 @@ pub const TopK = struct { at += 1; need -= 1; }; + for (x) |v| if ((v & 0x7fff) > 0x7f80 or v == 0x7f80) { + cols[row * k] = -1; + break; + }; } return std.mem.concat(a, u8, &.{ std.mem.sliceAsBytes(vals), std.mem.sliceAsBytes(cols) }); } diff --git a/zig/tests/cuda/contract_glm_dsel.zig b/zig/tests/cuda/contract_glm_dsel.zig new file mode 100644 index 00000000000..a93cd2abba4 --- /dev/null +++ b/zig/tests/cuda/contract_glm_dsel.zig @@ -0,0 +1,70 @@ +//! GLM's decode select on many CTAs under the contract on CUDA: scan and merge, bit-equal to tf_glm_select_rows. +const core = @import("core"); +const glm = @import("glm_cuda"); +const rig_ = @import("contract_rig.zig"); +const select = @import("contract_glm_select.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; +const sparse = glm.sparse; + +/// The wide select's rows and buckets, where cuda_sparse launches the decode select instead, and a 1M window's bucket. +pub fn spec() c.Spec { + const k = sparse.topk_pools; + var s = select.spec(); + s.name = "cuda glm decode select tf_glm_dsel_scan tf_glm_dsel_merge"; + s.served = &[_]c.Shape{ .{ .rows = 1, .n = 4096, .k = k }, .{ .rows = 4, .n = 65536, .k = k }, .{ .rows = 48, .n = 131072, .k = k }, .{ .rows = 8, .n = 260096, .k = k } }; + return s; +} + +/// Each row's K pools through cuda_sparse.decodeSelect; scores, host rule and baseline are the wide select's. +pub const Dsel = struct { + base: select.Select, + fns: glm.glue.Kernels, + rig: *rig_.Rig = undefined, // the base's, set by kernel() once this value sits at its final address + bits: u64 = 0, + short: bool = false, // the control: past two spans, the select is told its bucket is one span short + + pub fn deinit(self: *Dsel) void { + self.base.deinit(); + } + + pub fn kernel(self: *Dsel) g.Kernel { + self.rig = &self.base.rig; + var s = spec(); + if (self.short) s.name = "control: GLM decode select reads its bucket one span short"; + return .{ .spec = s, .ctx = self, .vt = &vt, .control = if (self.short) .shapes else null }; + } + + const vt = g.hooks(Dsel); + + pub fn prepare(self: *Dsel, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (!try self.base.prepare(shape, fill, seed)) return false; + self.bits = try self.base.rig.scratch(sparse.bitsBytes(shape.rows, shape.n)); + return true; + } + + pub fn run(self: *Dsel) !void { + const b = &self.base; + const set: glm.glue.Set = .{ .glue = &self.fns, .dsel = true }; + const n = if (self.short and b.shape.n > 2 * sparse.dsel_span) b.shape.n - sparse.dsel_span else b.shape.n; + try sparse.decodeSelect(set, b.rig.s, b.in, b.out, n, b.pos, b.at, b.shape.rows, self.bits, 0); + try b.rig.s.synchronize(); + } + + pub fn replaced(self: *Dsel) ![]const u8 { + return self.base.replaced(); + } + + pub fn count(self: *Dsel) usize { + return self.base.count(); + } + + pub fn reference(self: *Dsel, want: []f64, mag: []f64) !void { + return self.base.reference(want, mag); + } + + pub fn check(self: *Dsel, gate: g.Gate) !?[]const u8 { + return self.base.check(gate); + } +}; diff --git a/zig/tests/cuda/contract_glm_index.zig b/zig/tests/cuda/contract_glm_index.zig index 4ee444259f0..57f5b2d992a 100644 --- a/zig/tests/cuda/contract_glm_index.zig +++ b/zig/tests/cuda/contract_glm_index.zig @@ -7,6 +7,7 @@ const check = @import("check.zig"); const rig_ = @import("contract_rig.zig"); const pages = @import("contract_glm_pages.zig"); const select = @import("contract_glm_select.zig"); +const dsel = @import("contract_glm_dsel.zig"); const contract = core.contract; const c = contract.spec; @@ -329,22 +330,28 @@ pub const Tokens = struct { } }; -/// The index scores and the decode select, registered together so the runner keeps one entry for GLM's index. +/// The index scores and the decode selects (and the decode select's control), one runner entry for GLM's index. pub const Index = struct { scores: Scores, select: select.Select, + dsel: dsel.Dsel, + dsel_short: dsel.Dsel, pub fn init(gpu: check.Gpu, s: cuda.Stream, fns: glm.glue.Kernels) Index { - return .{ .scores = .{ .rig = .{ .gpu = gpu, .s = s }, .f = fns.scores }, .select = .{ .rig = .{ .gpu = gpu, .s = s }, .wide = fns.select_rows_wide, .narrow = fns.select_rows } }; + return .{ .scores = .{ .rig = .{ .gpu = gpu, .s = s }, .f = fns.scores }, .select = .{ .rig = .{ .gpu = gpu, .s = s }, .wide = fns.select_rows_wide, .narrow = fns.select_rows }, .dsel = .{ .base = .{ .rig = .{ .gpu = gpu, .s = s }, .wide = fns.select_rows_wide, .narrow = fns.select_rows }, .fns = fns }, .dsel_short = .{ .base = .{ .rig = .{ .gpu = gpu, .s = s }, .wide = fns.select_rows_wide, .narrow = fns.select_rows }, .fns = fns, .short = true } }; } /// After init's value sits at its final address: each kernel's context points into it. pub fn append(self: *Index, a: std.mem.Allocator, kernels: *std.ArrayList(g.Kernel)) !void { try kernels.append(a, self.scores.kernel()); try kernels.append(a, self.select.kernel()); + try kernels.append(a, self.dsel.kernel()); + try kernels.append(a, self.dsel_short.kernel()); } pub fn deinit(self: *Index) void { + self.dsel_short.deinit(); + self.dsel.deinit(); self.select.deinit(); self.scores.deinit(); } diff --git a/zig/tests/cuda/contract_qmm_prefill_many.zig b/zig/tests/cuda/contract_qmm_prefill_many.zig index 986fed5e783..1cebb2b77b3 100644 --- a/zig/tests/cuda/contract_qmm_prefill_many.zig +++ b/zig/tests/cuda/contract_qmm_prefill_many.zig @@ -19,6 +19,8 @@ const served = [_]c.Shape{ .{ .rows = 129, .n = 10240, .k = 5120 }, .{ .rows = 257, .n = 17408, .k = 5120 }, .{ .rows = 33, .n = 65, .k = 512 }, + .{ .rows = 2048, .n = 48, .k = 5120 }, + .{ .rows = 4096, .n = 48, .k = 5120 }, }; const rule = "every output byte equals separate qmm_prefill launches on the same BF16 input and affine-4 weights"; @@ -147,6 +149,7 @@ pub fn bench(gpu: gpu_check.Gpu) !void { fn widths(shape: c.Shape) []const usize { if (shape.k == 512 and shape.n == 65) return &.{ 65, 129 }; return switch (shape.n) { + 48 => &.{ 48, 48 }, 12288 => &.{ 12288, 1024, 1024 }, 10240 => &.{ 10240, 6144, 48, 48 }, 17408 => &.{ 17408, 17408 }, diff --git a/zig/tests/cuda/contract_qmm_prefill_tile22.zig b/zig/tests/cuda/contract_qmm_prefill_tile22.zig index fe3d4e1fa5d..32e4d795d77 100644 --- a/zig/tests/cuda/contract_qmm_prefill_tile22.zig +++ b/zig/tests/cuda/contract_qmm_prefill_tile22.zig @@ -14,6 +14,8 @@ fn noSums(_: c.Shape) usize { } const served = [_]c.Shape{ + .{ .rows = 2048, .n = 48, .k = 5120 }, + .{ .rows = 4096, .n = 48, .k = 5120 }, .{ .rows = 2048, .n = 12288, .k = 5120 }, .{ .rows = 2048, .n = 10240, .k = 5120 }, .{ .rows = 2048, .n = 17408, .k = 5120 }, diff --git a/zig/tests/cuda/contract_row_best_ref.zig b/zig/tests/cuda/contract_row_best_ref.zig index c9739c26692..367969935f4 100644 --- a/zig/tests/cuda/contract_row_best_ref.zig +++ b/zig/tests/cuda/contract_row_best_ref.zig @@ -10,9 +10,10 @@ fn depth(shape: c.Shape) usize { const served = blk: { const widths = [_]usize{ 31, 1, 32, 33, 1023, 1024, 1025, 79_591, 248_320 }; - var shapes: [widths.len + 1]c.Shape = undefined; + var shapes: [widths.len + 2]c.Shape = undefined; for (widths, 0..) |k, i| shapes[i] = .{ .rows = 12, .n = 4, .k = k }; shapes[widths.len] = .{ .rows = 33, .n = 4, .k = 1025 }; + shapes[widths.len + 1] = .{ .rows = 64, .n = 4, .k = 248_320 }; break :blk shapes; }; diff --git a/zig/tests/cuda/glm_index_check.zig b/zig/tests/cuda/glm_index_check.zig index 48dd2d0ad25..db1e4738738 100644 --- a/zig/tests/cuda/glm_index_check.zig +++ b/zig/tests/cuda/glm_index_check.zig @@ -166,8 +166,142 @@ pub fn run(gpu: check.Gpu) !void { } std.debug.print("glm_index_pools paths: whole row {d}, candidates {d}, whole row after the candidates missed {d}\n", .{ paths[0], paths[1], paths[2] }); try check.expect(paths[0] > 0 and paths[1] > 0 and paths[2] > 0, "glm-index-check: the whole-row, candidate and retry paths must all occur", .{}); + fails += try decode(gpu, s, ops, &ks, rand); + std.debug.print("decode select paths: whole row {d}, candidates {d}, whole row after the candidates missed {d}, ties at the floor {d}\n", .{ dpaths[0], dpaths[1], dpaths[2], dpaths[3] }); + try check.expect(dpaths[0] > 0 and dpaths[1] > 0 and dpaths[2] > 0 and dpaths[3] > 0, "glm-index-check: the decode select's four paths must all occur", .{}); try check.expect(fails == 0, "glm-index-check: {d} buffers differ", .{fails}); - check.pass("glm-index-check: scores, pools and token lists byte-equal at {d} cases, tied scores through both selects", .{cases.len}); + check.pass("glm-index-check: scores, pools and token lists byte-equal at {d} cases, tied scores through both selects; the decode select at {d} windows", .{ cases.len, dcases.len }); +} + +/// A decode window at long buckets: its first position, rows, and the sequence's pool capacity (pk_rows - 2). +const DCase = struct { pos: usize, rows: usize, cap: usize }; +const dcases = [_]DCase{ + .{ .pos = 4 * 4096 - 1, .rows = 1, .cap = 8192 }, // 4,096 pools: the merge takes the row whole + .{ .pos = 4 * 4096 + 3, .rows = 2, .cap = 8192 }, // the first row whole, the second past the merge's candidates + .{ .pos = 131072 - 1, .rows = 1, .cap = 216080 }, + .{ .pos = 131072 - 4, .rows = 4, .cap = 216080 }, + .{ .pos = 204800 - 16, .rows = 16, .cap = 216080 }, + .{ .pos = 864256 - 1, .rows = 1, .cap = 216080 }, + .{ .pos = 864256 - 16, .rows = 16, .cap = 216080 }, // the production context: a bucket clipped to the capacity +}; + +/// How many rows took each path of the decode select (whole row, candidates, whole row after them, ties at the floor). +var dpaths = [4]usize{ 0, 0, 0, 0 }; + +/// The decode select (cuda_sparse.decodeSelect) against tf_glm_select_rows byte for byte: planted, then selectTokens. +fn decode(gpu: check.Gpu, s: cuda.Stream, ops: cuda.Module, ks: *const glm.glue.Kernels, rand: std.Random) !usize { + const gpa = gpu.gpa; + const old: glm.glue.Set = .{ .glue = ks }; + const new: glm.glue.Set = .{ .glue = ks, .dsel = true }; + const special = [_]f32{ std.math.nan(f32), -std.math.nan(f32), 0.0, -0.0, std.math.inf(f32), -std.math.inf(f32) }; + var fails: usize = 0; + for (dcases) |c| { + const np = sp.poolBucket(c.pos, c.rows, c.cap); + var bufs: Bufs = .empty; + defer { + for (bufs.items) |*b| b.free(); + bufs.deinit(gpa); + } + const p0: i32 = @intCast(c.pos); + const dpos = try fromHost(gpu, &bufs, std.mem.asBytes(&p0)); + const scores = try zeros(gpu, &bufs, c.rows * np * 4); + const pa = try zeros(gpu, &bufs, c.rows * sp.topk_pools * 8); + const pb = try zeros(gpu, &bufs, c.rows * sp.topk_pools * 8); + const bits = try zeros(gpu, &bufs, sp.bitsBytes(c.rows, np)); + const path = try zeros(gpu, &bufs, c.rows * 4); + const host = try gpa.alloc(f32, c.rows * np); + defer gpa.free(host); + for (0..6) |kind| { + for (0..c.rows) |r| { + const vis = (c.pos + r + 1) / 4; + const limit = @min(np, @max(vis, sp.topk_pools)); + const row = host[r * np ..][0..np]; + for (row, 0..) |*x, i| { + // past the limit: no select may read + x.* = if (i >= limit) 1e9 else if (i >= vis) -std.math.inf(f32) else switch (kind) { + 0 => rand.floatNorm(f32), + // the top level crowds the floor + 1 => @as(f32, @floatFromInt(rand.uintLessThan(u32, 16))) * 0.25, + 2 => 0.0, // every visible pool tied + 3 => if (rand.uintLessThan(u32, 8) == 0) special[rand.uintLessThan(usize, special.len)] else rand.floatNorm(f32), + 4 => rand.floatNorm(f32), + else => if (i % 3 == 0) 1.0 else if (i % 997 == 0) 2.0 + rand.float(f32) else rand.floatNorm(f32) * 0.1, + }; + } + if (kind == 4) { // every sampled run high: the floor overshoots and the candidates fall short of K + for (0..4096) |q| { + const j = (q / 8) * limit / 512 / 8 * 8 + q % 8; + if (j < vis) row[j] = 100.0 + @as(f32, @floatFromInt(q)); + } + } + } + step(.{ .cap = c.cap, .pos = c.pos, .rows = c.rows }, np, "decode select: planted scores"); + try (cuda.DeviceBuffer{ .d = gpu.d, .ptr = scores, .len = c.rows * np * 4, .borrowed = true }).upload(0, std.mem.sliceAsBytes(host)); + var sel: cuda.Args = .{}; + inline for (.{ scores, pa, @as(i64, @intCast(np)), dpos, @as(c_int, sp.topk_pools) }) |v| sel.add(v); + try cuda.launch.launch(old.glue.select_rows, .{ .grid = .{ .x = @intCast(c.rows) }, .block = .{ .x = 128 } }, s, &sel); + try sp.decodeSelect(new, s, scores, pb, np, dpos, c.pos, c.rows, bits, path); + try s.synchronize(); + var taken: [16]i32 = undefined; + try (cuda.DeviceBuffer{ .d = gpu.d, .ptr = path, .len = c.rows * 4, .borrowed = true }).download(0, std.mem.sliceAsBytes(taken[0..c.rows])); + for (taken[0..c.rows], 0..) |q, r| { + if (q < 0 or q > 3) { + std.debug.print("FAIL np {d} row {d} kind {d}: the decode select reported path {d}\n", .{ np, r, kind, q }); + return error.TestFailed; + } + dpaths[@intCast(q)] += 1; + } + const f = try same(gpu, "decode select pools", pa, pb, c.rows * sp.topk_pools * 8, np, .{ .cap = c.cap, .pos = c.pos, .rows = c.rows }); + if (f != 0) std.debug.print(" (kind {d}, paths {any})\n", .{ kind, taken[0..c.rows] }); + fails += f; + } + // selectTokens on tf_glm_scores' rows: today's set against the decode select's, pools and token lists + const qi = try gpa.alloc(u16, c.rows * 32 * d); + defer gpa.free(qi); + for (qi) |*x| x.* = bf16(rand.floatNorm(f32)); + const wts = try gpa.alloc(u16, c.rows * 32); + defer gpa.free(wts); + for (wts) |*x| x.* = bf16(rand.floatNorm(f32)); + const pk = try gpa.alloc(u16, c.cap * d); + defer gpa.free(pk); + for (pk) |*x| x.* = bf16(rand.floatNorm(f32) * 2); + step(.{ .cap = c.cap, .pos = c.pos, .rows = c.rows }, np, "decode select: selectTokens, both sets"); + const dq = try fromHost(gpu, &bufs, std.mem.sliceAsBytes(qi)); + const dw = try fromHost(gpu, &bufs, std.mem.sliceAsBytes(wts)); + const dk = try fromHost(gpu, &bufs, std.mem.sliceAsBytes(pk)); + var sa = try scratch(gpu, &bufs, c.rows, np); + var sb = try scratch(gpu, &bufs, c.rows, np); + sb.ls = try zeros(gpu, &bufs, sp.bitsBytes(c.rows, np)); + sb.bits_rows = c.rows; + sa.bits_rows = c.rows; // today's set ignores it + const tok_bytes = c.rows * sp.width * 4; + const ta = try zeros(gpu, &bufs, tok_bytes); + const tb = try zeros(gpu, &bufs, tok_bytes); + const ca = try zeros(gpu, &bufs, c.rows * 4); + const cb = try zeros(gpu, &bufs, c.rows * 4); + var ms_old: f64 = 0; + var ms_new: f64 = 0; + for (0..4) |rep| { + const t0 = std.Io.Timestamp.now(gpu.io, .awake); + try sp.selectTokens(old, ops, s, dq, dw, 32, dk, .{}, dpos, c.pos, c.rows, 32, d, c.cap, sa, ta, ca); + try s.synchronize(); + const t1 = std.Io.Timestamp.now(gpu.io, .awake); + try sp.selectTokens(new, ops, s, dq, dw, 32, dk, .{}, dpos, c.pos, c.rows, 32, d, c.cap, sb, tb, cb); + try s.synchronize(); + const t2 = std.Io.Timestamp.now(gpu.io, .awake); + if (rep > 0) { + ms_old += ms(t0, t1) / 3; + ms_new += ms(t1, t2) / 3; + } + } + const dc: Case = .{ .cap = c.cap, .pos = c.pos, .rows = c.rows }; + fails += try same(gpu, "decode scores", sa.scores, sb.scores, c.rows * np * 4, np, dc); + fails += try same(gpu, "decode pools", sa.pools, sb.pools, c.rows * sp.topk_pools * 8, np, dc); + fails += try same(gpu, "decode tokens", ta, tb, tok_bytes, np, dc); + fails += try same(gpu, "decode counts", ca, cb, c.rows * 4, np, dc); + std.debug.print("decode np {d} pos {d} rows {d}: selectTokens {d:.3} ms, with the decode select {d:.3} ms (host-timed, a launch each)\n", .{ np, c.pos, c.rows, ms_old, ms_new }); + } + return fails; } /// Every 512-row block's scores from tf_glm_scores and from glm_index_scores, as selectTokens launches them. diff --git a/zig/tests/cuda/main.zig b/zig/tests/cuda/main.zig index 7c113ec4aec..deea592ffd5 100644 --- a/zig/tests/cuda/main.zig +++ b/zig/tests/cuda/main.zig @@ -13,6 +13,7 @@ const libs_tests = @import("libs_tests.zig"); const rank_scatter_tests = @import("rank_scatter_tests.zig"); const roce_gather_tests = @import("roce_gather_tests.zig"); const sample_tests = @import("sample_tests.zig"); +const nemotron_draw_tests = @import("nemotron_draw_tests.zig"); const glue_tests = @import("glue_tests.zig"); const window_profile = @import("window_profile.zig"); const tree_accept = @import("tree_accept.zig"); @@ -183,6 +184,7 @@ const usage = \\ gdn-prep Gated DeltaNet conv, norms, g and beta against float64 (synthetic) \\ qk-rows QK norm, RoPE and the cache write against float64 references (synthetic) \\ sample sample.cu's keyed draws against the Metal rule's host references (synthetic rows) + \\ nemotron-draws Nemotron's batched draws and row kernels against the per-row path, byte for byte \\ glue Nemotron's glue kernels against their host references at its shapes (synthetic rows) \\ lfm2-kernels LFM2's glue kernels against their host references at d1's shapes (synthetic rows) \\ pocket [reps] the pocket's two kernels against tf_pocket_rows byte for byte; reps > 0 times them too @@ -345,8 +347,7 @@ fn arg(rest: []const [:0]const u8, i: usize) ![]const u8 { return rest[i]; } -/// The contract glue's device path, compiled with the runner: the device reaches prepare through the vtable. -fn compileContractGlue() !void { +fn compileContractGlue() !void { // the contract glue's device path, built with the runner: prepare through the vtable const cores = std.Thread.getCpuCount() catch 1; if (cores != 0) return; var g: glue_contract.Glue = undefined; @@ -467,6 +468,7 @@ fn run(gpu: check.Gpu, cmd: []const u8, rest: []const [:0]const u8) !void { if (std.mem.eql(u8, cmd, "exl3-contract")) return exl3_contract.run(gpu); if (std.mem.eql(u8, cmd, "exl3-tp2")) return exl3_tp2_tests.run(gpu, try arg(rest, 0), try arg(rest, 1), if (rest.len > 2) rest[2] else "none"); if (std.mem.eql(u8, cmd, "sample")) return sample_tests.draws(gpu); + if (std.mem.eql(u8, cmd, "nemotron-draws")) return nemotron_draw_tests.run(gpu); if (std.mem.eql(u8, cmd, "topk")) return sample_tests.topk(gpu); if (std.mem.eql(u8, cmd, "q35-argmax")) return sample_tests.q35Argmax(gpu); if (std.mem.eql(u8, cmd, "norms")) return norms_tests.run(gpu); diff --git a/zig/tests/cuda/nemotron_draw_tests.zig b/zig/tests/cuda/nemotron_draw_tests.zig new file mode 100644 index 00000000000..3e8428938a8 --- /dev/null +++ b/zig/tests/cuda/nemotron_draw_tests.zig @@ -0,0 +1,386 @@ +//! Nemotron's batched draws and row kernels: every row equals the stream-at-a-time path, byte for byte. +const std = @import("std"); +const cuda = @import("cuda"); +const lanes = @import("lanes"); +const nemotron = @import("nemotron"); +const check = @import("check.zig"); +const Gpu = check.Gpu; + +const Rule = cuda.sample.Rule; +const subset = 32768; +const vocab = 131072; +const most_rows = 8; + +fn bf16(x: f32) u16 { + const b: u32 = @bitCast(x); + return @intCast((b +% 0x7FFF +% ((b >> 16) & 1)) >> 16); +} + +fn fill(salt: u64, out: []u16) void { + var x: u64 = 0x9E37_79B9_7F4A_7C15 ^ (salt *% 0xD1B5_4A32_D192_ED03); + for (out, 0..) |*h, i| { + x = x *% 6364136223846793005 +% 1442695040888963407; + const r: f32 = @as(f32, @floatFromInt(x >> 40)) / 16777216.0; + const v: f32 = if (i % 2711 == 7) 2.0 + 6.0 * r else -3.0 * r; + h.* = bf16(v); + } +} + +fn ruleOf(seed: u64) Rule { + return cuda.sample.rule(lanes.Sampling{ .seed = seed, .temperature = 1, .top_k = 20, .top_p = 0.95 }); +} + +/// The batched draw over 1 to 8 rows equals the per-row draw under 8 rules, subset and whole head. +pub fn run(gpu: Gpu) !void { + const gpa = gpu.gpa; + var m = try cuda.Module.load(gpu.d, cuda.kernels.sample); + defer m.unload(); + const d = try cuda.sample.Draws.resolve(m); + var stream = try cuda.Stream.init(gpu.d, true); + defer stream.deinit(); + const host = try gpa.alloc(u16, most_rows * vocab); + defer gpa.free(host); + var logits = try cuda.DeviceBuffer.alloc(gpu.d, most_rows * vocab * 2); + defer logits.free(); + var rules = try cuda.DeviceBuffer.alloc(gpu.d, most_rows * @sizeOf(Rule)); + defer rules.free(); + var meta = try cuda.DeviceBuffer.alloc(gpu.d, most_rows * 4); + defer meta.free(); + var tok = try cuda.DeviceBuffer.alloc(gpu.d, most_rows * 4); + defer tok.free(); + var prob = try cuda.DeviceBuffer.alloc(gpu.d, most_rows * 4); + defer prob.free(); + var want_tok = try cuda.DeviceBuffer.alloc(gpu.d, most_rows * 4); + defer want_tok.free(); + var want_prob = try cuda.DeviceBuffer.alloc(gpu.d, most_rows * 4); + defer want_prob.free(); + const ids = try gpa.alloc(u32, subset); + defer gpa.free(ids); + for (ids, 0..) |*id, i| id.* = @intCast(4 * i + 1); + const wide_ids = try gpa.alloc(i64, subset); + defer gpa.free(wide_ids); + for (wide_ids, ids) |*w, id| w.* = id; + var ids_dev = try cuda.DeviceBuffer.fromHost(gpu.d, std.mem.sliceAsBytes(wide_ids)); + defer ids_dev.free(); + var diffs: usize = 0; + var checked: usize = 0; + for ([_]bool{ true, false }) |mapped| { + const n: usize = if (mapped) subset else vocab; + for (1..most_rows + 1) |rows| { + fill(rows, host[0 .. rows * n]); + try logits.uploadAsync(0, std.mem.sliceAsBytes(host[0 .. rows * n]), stream.handle); + var rule_bytes: [most_rows * @sizeOf(Rule)]u8 = undefined; + var meta_words: [most_rows]i32 = undefined; + for (0..rows) |r| { + const rl = ruleOf(0xA5A5 + r); + @memcpy(rule_bytes[r * @sizeOf(Rule) ..][0..@sizeOf(Rule)], std.mem.asBytes(&rl)); + meta_words[r] = @intCast(100 + r); + } + try rules.uploadAsync(0, rule_bytes[0 .. rows * @sizeOf(Rule)], stream.handle); + try meta.uploadAsync(0, std.mem.sliceAsBytes(meta_words[0..rows]), stream.handle); + try d.drawIdsRows(stream, logits.ptr, n, rules.ptr, meta.ptr, 1, tok.ptr, rows, if (mapped) ids_dev.ptr else null, prob.ptr); + for (0..rows) |r| try d.draw(stream, logits.ptr + r * n * 2, n, rules.ptr + r * @sizeOf(Rule), meta.ptr + r * 4, 1, want_tok.ptr + r * 4, 1, if (mapped) ids_dev.ptr else null, want_prob.ptr + r * 4); + try stream.synchronize(); + const got_tok = try gpa.alloc(u32, rows); + defer gpa.free(got_tok); + const want = try gpa.alloc(u32, rows); + defer gpa.free(want); + const got_prob = try gpa.alloc(f32, rows); + defer gpa.free(got_prob); + const ref_prob = try gpa.alloc(f32, rows); + defer gpa.free(ref_prob); + try tok.download(0, std.mem.sliceAsBytes(got_tok)); + try want_tok.download(0, std.mem.sliceAsBytes(want)); + try prob.download(0, std.mem.sliceAsBytes(got_prob)); + try want_prob.download(0, std.mem.sliceAsBytes(ref_prob)); + for (0..rows) |r| { + diffs += @intFromBool(got_tok[r] != want[r] or @as(u32, @bitCast(got_prob[r])) != @as(u32, @bitCast(ref_prob[r]))); + checked += 1; + } + } + } + try check.expect(diffs == 0, "nemotron-draws: {d} of {d} rows differ from the per-row draw", .{ diffs, checked }); + check.pass("nemotron-draws: {d} batched rows equal the per-row draw", .{checked}); + try greedy(gpu, stream); + try targetRows(gpu, stream); + try argmax(gpu, stream); + try rowKernels(gpu, stream); +} + +/// The target's rows draw over 1 to 8 rows equals one tf_draw a row at the same rule and position. +fn targetRows(gpu: Gpu, stream: cuda.Stream) !void { + const gpa = gpu.gpa; + var m = try cuda.Module.load(gpu.d, cuda.kernels.sample); + defer m.unload(); + const d = try cuda.sample.Draws.resolve(m); + const host = try gpa.alloc(u16, most_rows * vocab); + defer gpa.free(host); + var logits = try cuda.DeviceBuffer.alloc(gpu.d, most_rows * vocab * 2); + defer logits.free(); + var rules = try cuda.DeviceBuffer.alloc(gpu.d, most_rows * @sizeOf(Rule)); + defer rules.free(); + var meta = try cuda.DeviceBuffer.alloc(gpu.d, most_rows * 4); + defer meta.free(); + var tok = try cuda.DeviceBuffer.alloc(gpu.d, most_rows * 4); + defer tok.free(); + var want = try cuda.DeviceBuffer.alloc(gpu.d, most_rows * 4); + defer want.free(); + var diffs: usize = 0; + var checked: usize = 0; + for (1..most_rows + 1) |n| { + fill(n, host[0 .. n * vocab]); + try logits.uploadAsync(0, std.mem.sliceAsBytes(host[0 .. n * vocab]), stream.handle); + var rule_bytes: [most_rows * @sizeOf(Rule)]u8 = undefined; + var meta_words: [most_rows]i32 = undefined; + for (0..n) |r| { + const rl = ruleOf(0x5A5A + r); + @memcpy(rule_bytes[r * @sizeOf(Rule) ..][0..@sizeOf(Rule)], std.mem.asBytes(&rl)); + meta_words[r] = @intCast(700 + r); + } + try rules.uploadAsync(0, rule_bytes[0 .. n * @sizeOf(Rule)], stream.handle); + try meta.uploadAsync(0, std.mem.sliceAsBytes(meta_words[0..n]), stream.handle); + try d.drawRows(stream, logits.ptr, vocab, rules.ptr, meta.ptr, tok.ptr, n, null); + for (0..n) |r| try d.draw(stream, logits.ptr + r * vocab * 2, vocab, rules.ptr + r * @sizeOf(Rule), meta.ptr + r * 4, 0, want.ptr + r * 4, 1, null, null); + try stream.synchronize(); + const got = try gpa.alloc(u32, n); + defer gpa.free(got); + const ref = try gpa.alloc(u32, n); + defer gpa.free(ref); + try tok.download(0, std.mem.sliceAsBytes(got)); + try want.download(0, std.mem.sliceAsBytes(ref)); + for (0..n) |r| { + diffs += @intFromBool(got[r] != ref[r]); + checked += 1; + } + } + try check.expect(diffs == 0, "nemotron-draws: {d} of {d} target rows differ", .{ diffs, checked }); + check.pass("nemotron-draws: {d} target rows equal one tf_draw a row", .{checked}); +} + +fn greedy(gpu: Gpu, stream: cuda.Stream) !void { + const gpa = gpu.gpa; + var mods: [6]cuda.Module = undefined; + mods[0] = try cuda.Module.load(gpu.d, cuda.kernels.torch_argmax); + mods[1] = try cuda.Module.load(gpu.d, cuda.kernels.torch_topk); + mods[2] = try cuda.Module.load(gpu.d, cuda.kernels.torch_pointwise); + mods[3] = try cuda.Module.load(gpu.d, cuda.kernels.torch_indexing); + mods[4] = try cuda.Module.load(gpu.d, cuda.kernels.torch_movement); + mods[5] = try cuda.Module.load(gpu.d, cuda.kernels.torch_nemotron_constants); + defer for (&mods) |*m| m.unload(); + const tf = try nemotron.torch_ops.Functions.resolve(&mods); + const t: nemotron.torch_ops.Torch = .{ .f = &tf, .s = stream }; + var km = try cuda.Module.load(gpu.d, cuda.kernels.nemotron_keyed); + defer km.unload(); + var fns: nemotron.glue.Fns = undefined; + fns.keyed = try km.function("tf_nemo_keyed_greedy"); + const g: nemotron.glue.Glue = .{ .set = null, .f = &fns, .s = stream, .emb = undefined, .norms = undefined, .moe = undefined }; + const host = try gpa.alloc(u16, most_rows * subset); + defer gpa.free(host); + var logits = try cuda.DeviceBuffer.alloc(gpu.d, most_rows * subset * 2); + defer logits.free(); + var flog = try cuda.DeviceBuffer.alloc(gpu.d, most_rows * subset * 4); + defer flog.free(); + var vals = try cuda.DeviceBuffer.alloc(gpu.d, most_rows * cuda.sample.max_candidates * 4); + defer vals.free(); + var cols = try cuda.DeviceBuffer.alloc(gpu.d, most_rows * cuda.sample.max_candidates * 8); + defer cols.free(); + var cand = try cuda.DeviceBuffer.alloc(gpu.d, most_rows * cuda.sample.max_candidates * 8); + defer cand.free(); + var scratch = try cuda.DeviceBuffer.alloc(gpu.d, nemotron.torch_ops.topkScratchBytes(most_rows, subset)); + defer scratch.free(); + var invalid = try cuda.DeviceBuffer.alloc(gpu.d, 4); + defer invalid.free(); + var tok = try cuda.DeviceBuffer.alloc(gpu.d, most_rows * 4); + defer tok.free(); + var prob = try cuda.DeviceBuffer.alloc(gpu.d, most_rows * 4); + defer prob.free(); + var want_tok = try cuda.DeviceBuffer.alloc(gpu.d, most_rows * 4); + defer want_tok.free(); + var want_prob = try cuda.DeviceBuffer.alloc(gpu.d, most_rows * 4); + defer want_prob.free(); + const ids = try gpa.alloc(i64, subset); + defer gpa.free(ids); + for (ids, 0..) |*id, i| id.* = @intCast(4 * i + 1); + var ids_dev = try cuda.DeviceBuffer.fromHost(gpu.d, std.mem.sliceAsBytes(ids)); + defer ids_dev.free(); + const count = cuda.sample.count(nemotron.sampler.greedy_draft.k, subset); + var diffs: usize = 0; + var checked: usize = 0; + for (1..most_rows + 1) |rows| { + fill(rows, host[0 .. rows * subset]); + try logits.uploadAsync(0, std.mem.sliceAsBytes(host[0 .. rows * subset]), stream.handle); + try t.toF32(logits.ptr, flog.ptr, rows * subset); + try t.topk(flog.ptr, subset, rows, count, vals.ptr, cols.ptr, scratch.ptr); + try t.lookup(ids_dev.ptr, subset, cols.ptr, cand.ptr, rows * count, invalid.ptr); + try g.keyed(vals.ptr, cand.ptr, 0, tok.ptr, 0, 0, prob.ptr, 0, rows, count, nemotron.sampler.greedy_draft); + for (0..rows) |r| { + try t.toF32(logits.ptr + r * subset * 2, flog.ptr, subset); + try t.topk(flog.ptr, subset, 1, count, vals.ptr, cols.ptr, scratch.ptr); + try t.lookup(ids_dev.ptr, subset, cols.ptr, cand.ptr, count, invalid.ptr); + try g.keyed(vals.ptr, cand.ptr, 0, want_tok.ptr + r * 4, 0, 0, want_prob.ptr + r * 4, 0, 1, count, nemotron.sampler.greedy_draft); + } + try stream.synchronize(); + const got = try gpa.alloc(u32, rows); + defer gpa.free(got); + const want = try gpa.alloc(u32, rows); + defer gpa.free(want); + const gp = try gpa.alloc(f32, rows); + defer gpa.free(gp); + const wp = try gpa.alloc(f32, rows); + defer gpa.free(wp); + try tok.download(0, std.mem.sliceAsBytes(got)); + try want_tok.download(0, std.mem.sliceAsBytes(want)); + try prob.download(0, std.mem.sliceAsBytes(gp)); + try want_prob.download(0, std.mem.sliceAsBytes(wp)); + for (0..rows) |r| { + diffs += @intFromBool(got[r] != want[r] or @as(u32, @bitCast(gp[r])) != @as(u32, @bitCast(wp[r]))); + checked += 1; + } + } + try check.expect(diffs == 0, "nemotron-draws: {d} of {d} greedy rows differ", .{ diffs, checked }); + check.pass("nemotron-draws: {d} greedy rows equal the per-row keyed draw", .{checked}); +} + +fn argmax(gpu: Gpu, stream: cuda.Stream) !void { + const gpa = gpu.gpa; + var m = try cuda.Module.load(gpu.d, cuda.kernels.torch_argmax); + defer m.unload(); + const f = try m.function("tf_argmax_rows_i32_kernel"); + const host = try gpa.alloc(u16, most_rows * vocab); + defer gpa.free(host); + var logits = try cuda.DeviceBuffer.alloc(gpu.d, most_rows * vocab * 2); + defer logits.free(); + var out = try cuda.DeviceBuffer.alloc(gpu.d, most_rows * 4); + defer out.free(); + var want = try cuda.DeviceBuffer.alloc(gpu.d, most_rows * 4); + defer want.free(); + var diffs: usize = 0; + var checked: usize = 0; + for (1..most_rows + 1) |rows| { + fill(rows, host[0 .. rows * vocab]); + try logits.uploadAsync(0, std.mem.sliceAsBytes(host[0 .. rows * vocab]), stream.handle); + var a: cuda.Args = .{}; + a.add(logits.ptr); + a.add(out.ptr); + for ([_]usize{ rows, vocab, vocab }) |v| a.add(@as(i64, @intCast(v))); + a.add(@as(i32, 0)); + try cuda.launch.launch(f, .{ .grid = .{ .x = @intCast(rows) }, .block = .{ .x = 256 } }, stream, &a); + for (0..rows) |r| { + var b: cuda.Args = .{}; + b.add(logits.ptr + r * vocab * 2); + b.add(want.ptr + r * 4); + for ([_]usize{ 1, vocab, vocab }) |v| b.add(@as(i64, @intCast(v))); + b.add(@as(i32, 0)); + try cuda.launch.launch(f, .{ .grid = .{ .x = 1 }, .block = .{ .x = 256 } }, stream, &b); + } + try stream.synchronize(); + const got = try gpa.alloc(u32, rows); + defer gpa.free(got); + const ref = try gpa.alloc(u32, rows); + defer gpa.free(ref); + try out.download(0, std.mem.sliceAsBytes(got)); + try want.download(0, std.mem.sliceAsBytes(ref)); + for (0..rows) |r| { + diffs += @intFromBool(got[r] != ref[r]); + checked += 1; + } + } + try check.expect(diffs == 0, "nemotron-draws: {d} of {d} argmax rows differ", .{ diffs, checked }); + check.pass("nemotron-draws: {d} argmax rows equal the per-row argmax", .{checked}); +} + +fn rowKernels(gpu: Gpu, stream: cuda.Stream) !void { + const gpa = gpu.gpa; + var m = try cuda.Module.load(gpu.d, cuda.kernels.nemotron_ops); + defer m.unload(); + const gather = try m.function("tf_nemo_gather_rows"); + const last = try m.function("tf_nemo_gather_last"); + const scatter = try m.function("tf_nemo_scatter_rows"); + const words = 16; + var a = try cuda.DeviceBuffer.alloc(gpu.d, 3 * words * 4); + defer a.free(); + var b = try cuda.DeviceBuffer.alloc(gpu.d, 3 * words * 4); + defer b.free(); + var dst_a = try cuda.DeviceBuffer.alloc(gpu.d, 3 * words * 4); + defer dst_a.free(); + var dst_b = try cuda.DeviceBuffer.alloc(gpu.d, 3 * words * 4); + defer dst_b.free(); + const ha = try gpa.alloc(u32, 3 * words); + defer gpa.free(ha); + const hb = try gpa.alloc(u32, 3 * words); + defer gpa.free(hb); + for (ha, hb, 0..) |*x, *y, i| { + x.* = @intCast(i + 1); + y.* = @intCast(i + 101); + } + try a.uploadAsync(0, std.mem.sliceAsBytes(ha), stream.handle); + try b.uploadAsync(0, std.mem.sliceAsBytes(hb), stream.handle); + var g: nemotron.kernels.GatherRows = std.mem.zeroes(nemotron.kernels.GatherRows); + g.a[0] = a.ptr; + g.b[0] = b.ptr; + g.rows[0] = 1; + g.a[1] = a.ptr + words * 4; + g.b[1] = b.ptr + words * 4; + g.rows[1] = 1; + g.row0[1] = 1; + g.wa = words * 4; + g.wb = words * 4; + var args: cuda.Args = .{}; + args.add(g); + args.add(dst_a.ptr); + args.add(dst_b.ptr); + try cuda.launch.launch(gather, .{ .grid = .{ .x = 2 }, .block = .{ .x = 256 } }, stream, &args); + try stream.synchronize(); + const gathered = try gpa.alloc(u32, 2 * words); + defer gpa.free(gathered); + var diffs: usize = 0; + // the gather, read before the last-row gather overwrites both rows: part k's row lands at dst row k + try dst_a.download(0, std.mem.sliceAsBytes(gathered)); + if (!std.mem.eql(u32, gathered, ha[0 .. 2 * words])) diffs += 1; + try dst_b.download(0, std.mem.sliceAsBytes(gathered)); + if (!std.mem.eql(u32, gathered, hb[0 .. 2 * words])) diffs += 1; + var l: nemotron.kernels.LastRows = std.mem.zeroes(nemotron.kernels.LastRows); + l.a[0] = a.ptr + words * 4; + l.b[0] = b.ptr + words * 4; + l.a[1] = a.ptr; + l.b[1] = b.ptr; + var largs: cuda.Args = .{}; + largs.add(l); + largs.add(dst_a.ptr); + largs.add(dst_b.ptr); + for ([_]usize{ words * 4, words * 4, 2 }) |v| largs.add(@as(c_int, @intCast(v))); + try cuda.launch.launch(last, .{ .grid = .{ .x = 1 }, .block = .{ .x = 256 } }, stream, &largs); + var s: nemotron.kernels.ScatterRows = std.mem.zeroes(nemotron.kernels.ScatterRows); + s.tok[0] = dst_a.ptr; + s.prob[0] = dst_b.ptr; + s.rows[0] = 1; + s.tok_at = 2; + s.prob_at = 1; + var sargs: cuda.Args = .{}; + sargs.add(a.ptr); + sargs.add(b.ptr); + sargs.add(s); + try cuda.launch.launch(scatter, .{ .grid = .{ .x = 1 }, .block = .{ .x = 32 } }, stream, &sargs); + try stream.synchronize(); + const got_a = try gpa.alloc(u32, 2 * words); + defer gpa.free(got_a); + const got_b = try gpa.alloc(u32, 2 * words); + defer gpa.free(got_b); + try dst_a.download(0, std.mem.sliceAsBytes(got_a)); + try dst_b.download(0, std.mem.sliceAsBytes(got_b)); + // dst row 0 is source row 1 and row 1 row 0; row 0's token then at tok_at, its probability at prob_at (j, j - 1) + const want_a = try gpa.alloc(u32, 2 * words); + defer gpa.free(want_a); + const want_b = try gpa.alloc(u32, 2 * words); + defer gpa.free(want_b); + for ([_][]u32{ want_a, want_b }, [_][]const u32{ ha, hb }) |w, h| { + @memcpy(w[0..words], h[words .. 2 * words]); + @memcpy(w[words .. 2 * words], h[0..words]); + } + want_a[@intCast(s.tok_at)] = ha[0]; + want_b[@intCast(s.prob_at)] = hb[0]; + if (!std.mem.eql(u32, got_a, want_a)) diffs += 1; + if (!std.mem.eql(u32, got_b, want_b)) diffs += 1; + try check.expect(diffs == 0, "nemotron-draws: {d} row kernels differ", .{diffs}); + check.pass("nemotron-draws: gather, ordered last-row gather and scatter keep their rows", .{}); +} diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index 58fad54fe20..020324d65ac 100644 --- a/zig/tests/fixtures/gradient-serving.tsv +++ b/zig/tests/fixtures/gradient-serving.tsv @@ -14,10 +14,10 @@ zig/kernels/cuda/flashnext_attn.cu 9731e39b67a8adb4a0a42222e9f888877932f2aa7108b zig/kernels/cuda/flashnext_batch.cu 95260b964fb633d23df28970672d87688f21cdd9073e44f92a1523b54b4ecd99 raw zig/kernels/cuda/flashnext_gdn.cu c7b9712626778d452e18234e2dfc3b26f8112618cdc492957c4b5f5454d64126 raw zig/kernels/cuda/flashnext_hc.cu 54fa2cfa22e483341835f6349cf0a8f508459ed1b65804728cb1358ac82b24f1 raw main 5c7cf5c117, d88c1ed57d (sum_rn and rms_scale shared; same SASS) -zig/kernels/cuda/flashnext_mtp.cu 0b99c76b7ed0c4a76ea59b7f121eb8c806f76edafdaad807e86214a96ee9edec raw +zig/kernels/cuda/flashnext_mtp.cu 5d213b1b4a1d0588eea3acb4633a0c8bc4d9bdf6f27485604452a3b603677a09 raw #2927 zig/kernels/cuda/fp8_experts.cu 156aa7337b41c67d200d8b58a24422cc96cfa032c9fd0711080f09ddc733baee raw zig/kernels/cuda/gdn.cu a9caeec5b270dcab933a5eae0f500d7aabcd31cde156238225ae064ac92ba2e8 raw -zig/kernels/cuda/glm_glue.cu 8c71cb95fafdcc6a1540cb260edc40f5ef280b2d549e5b39a66ecdc60fbdaa9b raw +zig/kernels/cuda/glm_glue.cu 74e69a7c20827d498c190334fffaa896f2a4f05e107fdf9d2d34b09b55a1c75c raw #2722 (one added line, the include of glm_index_decode.cuh: the decode select's scan and merge) zig/kernels/cuda/glm_glue_attn.cuh abecbecf809292c0f82294fa688e47e574fa43c8ff3b1497966f9d3dd52b9881 raw main 42735f94f0 (#2335: MLA bodies to common/mla.cuh; glm_glue SASS identical on five SMs) zig/kernels/cuda/glm_glue_bmm.cuh 7fbaaa4517e309b17ebb41f84f94f9a939baa27a2fb5c9a6b7f5b857b5a21391 raw zig/kernels/cuda/glm_glue_hc.cuh c3aa26475c6ce05d2508c300c8e88d429adea4c0c173e3909734bb0ece06da2a raw @@ -41,7 +41,7 @@ zig/kernels/cuda/nemotron_attention.cu a8a6bc39c2620176aff6c5d436b4a93edf5c86c8d zig/kernels/cuda/nemotron_keyed.cu ed8bdd7012970d9896ec703bd7c3d5ec83e02f41dba4ce1f896fc39c1ee349c9 raw zig/kernels/cuda/nemotron_latent.cu 04fba97043d0948f82a3b9477f448dd76b21f6d11d1a445e020bd41cacb85c2b raw commits e40bd6eae, 8a8ff3d64; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/kernels/cuda/nemotron_mamba.cu dcaba12253d3931ae48c7ebd4e13dfb956f540ae19f4ab83130c3f21745be5ec raw commits fa2af585f, f0ef17e69; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate -zig/kernels/cuda/nemotron_ops.cu 45679c47d5c1cbca7877ad0d0df919d7b39a8c73330131404b7d29c205e0fa48 raw +zig/kernels/cuda/nemotron_ops.cu 2ef87c655b49d33214f8856d2ad775aacf6198ab2ca343f87fde588639ecccd1 raw #3124 zig/kernels/cuda/nemotron_route.cu 65da41432442f9fd99f73abefe87f34cf3c46b4971afe3c3557a48bca96f6511 raw commits 739c924de, 8cfdaa739, b77a33b08, 7f6f940eb, 05d0617af, bc76d90d6; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/kernels/cuda/norms.cu 89d3c6cea39fe3e1bf8d5a2fe60465f7ae272548f14711abb59ddac709d2d1db raw main d4541b00e0 (rms_scale shared; same SASS) zig/kernels/cuda/nvfp4_experts.cu 9ef08b957b02e1a3ef2ee814aaf79ed15d85ada6b99e6cca2c1cadc1cadd6964 raw @@ -84,7 +84,7 @@ zig/src/cuda/abi.zig fef21a6302d1863001496b3765899a265470cfdf78678d7f73fa7fd3115 zig/src/cuda/aot.zig bd4e41f32eebf8e75e6f40e036847aaca2900aee7628167552c661824c79d62b raw commits 9349e38bb; series patches 14-runtime-foundation.patch, 45-runtime-one-fallback.patch, 46-preserve-nospec-and-capture.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate; main 3a7e6fac7 (identity export for persisted serving states) zig/src/cuda/carveout.zig 5ebe77d420ec42d1494fbe7259ce12e20e56427d8f7d931d672b7ca1240b1759 raw main 6a1feb26e (malformed TF_CUDA_CARVEOUT settings refused by name) zig/src/cuda/ck.zig 5b247901025d0f001e44c98e022729d007758ffd4719ec34b957c55dcc008e46 raw commits 739c924de, a79678c56, e40bd6eae, 186c31eed, a6f4044fc, c0a58fd30, 48ea204ac, e367c8f55, 7e082a6df; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate -zig/src/cuda/context.zig 55bf6ff9c93e9adb395de623cc7317e02d6bd828dfb66426c1d0e6af9da2289b raw commits ac38ad1da, cc50aef49, e9bf05ffd, ef23b5934; series patches 14-runtime-foundation.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate +zig/src/cuda/context.zig f7c911e93cccd4f89d4a80a8a8786c765a94864a2c22102ff128a018eb55ec1f raw commits ac38ad1da, cc50aef49, e9bf05ffd, ef23b5934; series patches 14-runtime-foundation.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate; #2914 (the release SM refusal before any retain) zig/src/cuda/cublaslt.zig c6e3b8892cad23bd08c7d9843da8117670e3a881e0708a89cdf72f0cc7ad5c40 raw main f1ab10fe98 (Clef's joint schema head on the GPU; a new path), 52375ee098 (#2285: layout_cols, the split-K and reduction algo-config attributes and cublasLtMatmulAlgoConfigGetAttribute for Qwen3 embeddings; existing entries unchanged) zig/src/cuda/driver.zig f20856bd06afe9365ab9ca1bc39800ccb260ade2704197c033e1344a0c8dd742 raw commits e9bf05ffd, b923e554c, b2c75a98a; series patches 14-runtime-foundation.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/src/cuda/embed_rows.zig 09fb2e612f43297c19d2cb77d45139dd98212a20075da0a15069a70544f72f6b raw @@ -93,7 +93,7 @@ zig/src/cuda/experts.zig 8bfc2f15a742cceba87dd7eb8e80f3f1b4e3f7eb323b557eb1bb4bf zig/src/cuda/fp8.zig a9caf312cb451dc95572b493e69ae211dd1e8b5be5b2c48cae3febd5d9327143 raw series patches 65-pr-1024.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/src/cuda/graph.zig 17639aaef0298c934b3f5ad3511925169c096ae57ede8ebee655faa838844f7b raw zig/src/cuda/grouped.zig 5fa1f39394b701eab59383bc7ed214ea3e17652a1229236df49f5281e6e764b5 raw commits e1be0806d; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate -zig/src/cuda/kernels.zig 34361df431dc6419474f5460158fd29bcba90f2a3792092b25308b0cb413fd69 raw main 42735f94f0 (#2335: the mla image registered), f35900e60c (#2709: the dots_mocr image registered), #1630 (the experts_bf16 image registered) +zig/src/cuda/kernels.zig 4d70aa12e092f9837249978cef148b6e20d76b651181eddeb9a4ef5401cf3dfc raw main 42735f94f0 (#2335: the mla image registered), f35900e60c (#2709: the dots_mocr image registered), #1630 (the experts_bf16 image registered), #2914 (covers: the release SM check) zig/src/cuda/launch.zig 9ec64848834d82ddcea85a6123e975c95a5ae2bf85c2a71772244794b0bcd705 raw series patches 14-runtime-foundation.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/src/cuda/memory.zig 7d2a91bfca8a08ae59df16ddf30d22226aba773cc814dd106930840ab344fc52 raw commits 5dcf77d7c, f630f1a90, e9bf05ffd, 881cccaa4, a34cb6ded; series patches 14-runtime-foundation.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/src/cuda/modelopt.zig 648c9ba58197af0ce905f8792383502fc44a52c45d1413fe9e21d28d04c22253 raw @@ -107,7 +107,7 @@ zig/src/cuda/qmmf.zig 760f033510402806cb06e70eec45cfe068bd5cd029315a05c9c8c493c7 zig/src/cuda/rank_scatter.zig 303fd707713af732dd1d31c6a940dd4eeed44e9b26fe202919da5925654fc212 raw zig/src/cuda/root.zig 5dbca351bbf6a42cd83d7b615d4e4624809444d7d2e714b1d71d8eec53c6e606 raw main 42735f94f0 (#2335: cuda.mla exported) zig/src/cuda/route_rows.zig e23257dea1f244ebba4399d7bc0730953f75eebbd7789819d5785e88a8907206 raw -zig/src/cuda/sample.zig 5d374b5cd2108fd90b383cfec0a63bdce038eef8c380289495e5b9d080c590f2 raw series patches 02-cuda-rounds.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate; main 37b0776ce (#2680: adds ruleFor and rule, which reach the same core rule, byte-equal over a 25,480-setting grid; existing code unchanged) +zig/src/cuda/sample.zig 9e3a31bd0480284ff069148b2d3c92f1e2ba24f16c18362dae9de48ec7fc65fe raw series patches 02-cuda-rounds.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate; main 37b0776ce (#2680: adds ruleFor and rule, which reach the same core rule, byte-equal over a 25,480-setting grid; existing code unchanged), #3124 zig/src/cuda/segments.zig 8d029a27a7b2a77916c91c9e650cee07c25aec317efacfdb3f8f8967744899a9 raw zig/src/cuda/stream.zig 02c1879e72a35927466ab462d6b2a461691d1f5196da770decd1125db2199fa6 raw commits e9bf05ffd, ef23b5934; series patches 14-runtime-foundation.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/src/cuda/tp_group.zig 1a2acbdf2de6b827218deb45df5b5845beecde4eb718a4e4b3966582db51d7a7 raw commits b8d45ded3, 80afaf959; series patches 14-runtime-foundation.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate; main c8ad9872da (#2205: RoCE small gathers at any world up to roce.max_world when every rank asks; TF_ROCE's default unchanged, two ranks on, three or more on NCCL), 61a2651577 (#2789: a call failing after the group's abort ends as Aborted, not fatally); #2918 (communicator abort through its owner) @@ -141,11 +141,11 @@ zig/src/families/flashnext/cuda_mixed_experts.zig d0362f591e98c2d13581ae48fb75fb zig/src/families/flashnext/cuda_mlp.zig 8224a28003487487e69eb669be11eaafafdb1ce0bc4c5e57024cef0a6a29e66f raw zig/src/families/flashnext/cuda_modelopt_experts.zig de779975629770b33ad5c0ebf9aa6e334f7a98f173a452d2b7c33b50a08d968e raw zig/src/families/flashnext/cuda_moe.zig 87ba75343c1d228800ed9fcc6d933f1175df172c008e14a8c7a64ff7011bed44 raw -zig/src/families/flashnext/cuda_mtp.zig 78a4443f55d1f395261738b61a9c67b488f7983a7be5bbf5f3951eb34d8c6d59 raw main 80e0fd72c (#2753: non-finite draft rows refused by name; finite rows unchanged), dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning) +zig/src/families/flashnext/cuda_mtp.zig 1349889f35d942b527361f2a62928945885bd42087609368fe8f6bf6f4938a04 raw main 80e0fd72c (#2753: non-finite draft rows refused by name; finite rows unchanged), dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning), #2927 zig/src/families/flashnext/cuda_mtp_check.zig 35d9d0ad51171ca2d70a0458f90fe6a04dd5f759fd9f005593c9d1189fb7846d raw main dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning) zig/src/families/flashnext/cuda_mtp_draft.zig 41628480a1071c4a58a229f5e8b42e26fcd030a046ca6796d2dcb2fedb8daf28 raw main 80e0fd72c (#2753: non-finite draft rows refused by name; finite rows unchanged), dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning), 52479d3036 (#2585: a test of the blank TF_FLASHNEXT_KEEP_LATE reader) zig/src/families/flashnext/cuda_mtp_load.zig 095c8b71f984a7810adb1fb5e6d13da4a9abdc438de08405b4ad82d3f51f56e9 raw -zig/src/families/flashnext/cuda_mtp_ops.zig 526c946e7646214591397e37ead4451f62cefa0dc7373950309d6251d791db6a raw main 4b2679bf9 (grouped draft head carries its page table), 4f6017ced, ec76abd45 (reserveRows), 80e0fd72c, c6a337753 (#2753: verify rows checked after one completion wait, non-finite rows refused; finite rows unchanged) +zig/src/families/flashnext/cuda_mtp_ops.zig c6e07580378538c0131fc687003d7559bca8b2318373c1f889ef1a07423ffa3c raw main 4b2679bf9 (grouped draft head carries its page table), 4f6017ced, ec76abd45 (reserveRows), 80e0fd72c, c6a337753 (#2753: verify rows checked after one completion wait, non-finite rows refused; finite rows unchanged), #2927 zig/src/families/flashnext/cuda_norms.zig c6ca7f9c1a9049c0f9d512fe2a38c2672a2e96b5c060d6cec2bca0d39e34bad0 raw zig/src/families/flashnext/cuda_ple.zig 7c4b009de2e44a7c28db56725ed010bbc7e67dff4688640ecf8e22a1cbefeac7 raw main dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning) zig/src/families/flashnext/cuda_ple_check.zig e8b7cac1e0d3718f106482f6cff7375c0063e1757c46814bd40da435c83ba8ed raw diff --git a/zig/tests/server/golden/framing/chunked-bytes.json b/zig/tests/server/golden/framing/chunked-bytes.json index baa2e7c1eb1..5943f1ffe8a 100644 --- a/zig/tests/server/golden/framing/chunked-bytes.json +++ b/zig/tests/server/golden/framing/chunked-bytes.json @@ -25,10 +25,10 @@ ], [ "Content-Length", - "1618" + "1668" ] ], - "body": "{\"object\": \"list\", \"data\": [{\"id\": \"fake-model\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}}, {\"id\": \"fake-alias\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}}]}", + "body": "{\"object\": \"list\", \"data\": [{\"id\": \"fake-model\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}, \"input_types\": [\"text\"]}, {\"id\": \"fake-alias\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}, \"input_types\": [\"text\"]}]}", "interim": "" } ] diff --git a/zig/tests/server/golden/framing/connection-close.json b/zig/tests/server/golden/framing/connection-close.json index 90cfbb3e082..69732154d19 100644 --- a/zig/tests/server/golden/framing/connection-close.json +++ b/zig/tests/server/golden/framing/connection-close.json @@ -10,14 +10,14 @@ ], [ "Content-Length", - "1618" + "1668" ], [ "Connection", "close" ] ], - "body": "{\"object\": \"list\", \"data\": [{\"id\": \"fake-model\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}}, {\"id\": \"fake-alias\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}}]}", + "body": "{\"object\": \"list\", \"data\": [{\"id\": \"fake-model\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}, \"input_types\": [\"text\"]}, {\"id\": \"fake-alias\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}, \"input_types\": [\"text\"]}]}", "interim": "" } ] diff --git a/zig/tests/server/golden/framing/extensions-trailers.json b/zig/tests/server/golden/framing/extensions-trailers.json index baa2e7c1eb1..5943f1ffe8a 100644 --- a/zig/tests/server/golden/framing/extensions-trailers.json +++ b/zig/tests/server/golden/framing/extensions-trailers.json @@ -25,10 +25,10 @@ ], [ "Content-Length", - "1618" + "1668" ] ], - "body": "{\"object\": \"list\", \"data\": [{\"id\": \"fake-model\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}}, {\"id\": \"fake-alias\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}}]}", + "body": "{\"object\": \"list\", \"data\": [{\"id\": \"fake-model\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}, \"input_types\": [\"text\"]}, {\"id\": \"fake-alias\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}, \"input_types\": [\"text\"]}]}", "interim": "" } ] diff --git a/zig/tests/server/golden/framing/keepalive-three.json b/zig/tests/server/golden/framing/keepalive-three.json index 4edeed84fc0..884751a9420 100644 --- a/zig/tests/server/golden/framing/keepalive-three.json +++ b/zig/tests/server/golden/framing/keepalive-three.json @@ -40,10 +40,10 @@ ], [ "Content-Length", - "1618" + "1668" ] ], - "body": "{\"object\": \"list\", \"data\": [{\"id\": \"fake-model\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}}, {\"id\": \"fake-alias\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}}]}", + "body": "{\"object\": \"list\", \"data\": [{\"id\": \"fake-model\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}, \"input_types\": [\"text\"]}, {\"id\": \"fake-alias\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}, \"input_types\": [\"text\"]}]}", "interim": "" } ] diff --git a/zig/tests/server/golden/framing/pipelined.json b/zig/tests/server/golden/framing/pipelined.json index d7f94bd0872..3fec9877fb2 100644 --- a/zig/tests/server/golden/framing/pipelined.json +++ b/zig/tests/server/golden/framing/pipelined.json @@ -25,10 +25,10 @@ ], [ "Content-Length", - "1618" + "1668" ] ], - "body": "{\"object\": \"list\", \"data\": [{\"id\": \"fake-model\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}}, {\"id\": \"fake-alias\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}}]}", + "body": "{\"object\": \"list\", \"data\": [{\"id\": \"fake-model\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}, \"input_types\": [\"text\"]}, {\"id\": \"fake-alias\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}, \"input_types\": [\"text\"]}]}", "interim": "" } ] diff --git a/zig/tests/server/golden/keys/full-then-none.json b/zig/tests/server/golden/keys/full-then-none.json index a106f075329..49f8cb0ddf6 100644 --- a/zig/tests/server/golden/keys/full-then-none.json +++ b/zig/tests/server/golden/keys/full-then-none.json @@ -10,10 +10,10 @@ ], [ "Content-Length", - "1618" + "1668" ] ], - "body": "{\"object\": \"list\", \"data\": [{\"id\": \"fake-model\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}}, {\"id\": \"fake-alias\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}}]}", + "body": "{\"object\": \"list\", \"data\": [{\"id\": \"fake-model\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}, \"input_types\": [\"text\"]}, {\"id\": \"fake-alias\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}, \"input_types\": [\"text\"]}]}", "interim": "" }, { diff --git a/zig/tests/server/golden/keys/models-bare.json b/zig/tests/server/golden/keys/models-bare.json index 46f2b1cec86..29393acc256 100644 --- a/zig/tests/server/golden/keys/models-bare.json +++ b/zig/tests/server/golden/keys/models-bare.json @@ -10,10 +10,10 @@ ], [ "Content-Length", - "1618" + "1668" ] ], - "body": "{\"object\": \"list\", \"data\": [{\"id\": \"fake-model\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}}, {\"id\": \"fake-alias\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}}]}", + "body": "{\"object\": \"list\", \"data\": [{\"id\": \"fake-model\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}, \"input_types\": [\"text\"]}, {\"id\": \"fake-alias\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}, \"input_types\": [\"text\"]}]}", "interim": "" } ] diff --git a/zig/tests/server/golden/keys/models-cli.json b/zig/tests/server/golden/keys/models-cli.json index 46f2b1cec86..29393acc256 100644 --- a/zig/tests/server/golden/keys/models-cli.json +++ b/zig/tests/server/golden/keys/models-cli.json @@ -10,10 +10,10 @@ ], [ "Content-Length", - "1618" + "1668" ] ], - "body": "{\"object\": \"list\", \"data\": [{\"id\": \"fake-model\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}}, {\"id\": \"fake-alias\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}}]}", + "body": "{\"object\": \"list\", \"data\": [{\"id\": \"fake-model\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}, \"input_types\": [\"text\"]}, {\"id\": \"fake-alias\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}, \"input_types\": [\"text\"]}]}", "interim": "" } ] diff --git a/zig/tests/server/golden/keys/models-env.json b/zig/tests/server/golden/keys/models-env.json index 46f2b1cec86..29393acc256 100644 --- a/zig/tests/server/golden/keys/models-env.json +++ b/zig/tests/server/golden/keys/models-env.json @@ -10,10 +10,10 @@ ], [ "Content-Length", - "1618" + "1668" ] ], - "body": "{\"object\": \"list\", \"data\": [{\"id\": \"fake-model\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}}, {\"id\": \"fake-alias\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}}]}", + "body": "{\"object\": \"list\", \"data\": [{\"id\": \"fake-model\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}, \"input_types\": [\"text\"]}, {\"id\": \"fake-alias\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}, \"input_types\": [\"text\"]}]}", "interim": "" } ] diff --git a/zig/tests/server/golden/keys/models-file.json b/zig/tests/server/golden/keys/models-file.json index 46f2b1cec86..29393acc256 100644 --- a/zig/tests/server/golden/keys/models-file.json +++ b/zig/tests/server/golden/keys/models-file.json @@ -10,10 +10,10 @@ ], [ "Content-Length", - "1618" + "1668" ] ], - "body": "{\"object\": \"list\", \"data\": [{\"id\": \"fake-model\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}}, {\"id\": \"fake-alias\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}}]}", + "body": "{\"object\": \"list\", \"data\": [{\"id\": \"fake-model\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}, \"input_types\": [\"text\"]}, {\"id\": \"fake-alias\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}, \"input_types\": [\"text\"]}]}", "interim": "" } ] diff --git a/zig/tests/server/golden/keys/pooled-identity.json b/zig/tests/server/golden/keys/pooled-identity.json index a106f075329..49f8cb0ddf6 100644 --- a/zig/tests/server/golden/keys/pooled-identity.json +++ b/zig/tests/server/golden/keys/pooled-identity.json @@ -10,10 +10,10 @@ ], [ "Content-Length", - "1618" + "1668" ] ], - "body": "{\"object\": \"list\", \"data\": [{\"id\": \"fake-model\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}}, {\"id\": \"fake-alias\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}}]}", + "body": "{\"object\": \"list\", \"data\": [{\"id\": \"fake-model\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}, \"input_types\": [\"text\"]}, {\"id\": \"fake-alias\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}, \"input_types\": [\"text\"]}]}", "interim": "" }, { diff --git a/zig/tests/server/golden/keys/rotated-new.json b/zig/tests/server/golden/keys/rotated-new.json index 46f2b1cec86..29393acc256 100644 --- a/zig/tests/server/golden/keys/rotated-new.json +++ b/zig/tests/server/golden/keys/rotated-new.json @@ -10,10 +10,10 @@ ], [ "Content-Length", - "1618" + "1668" ] ], - "body": "{\"object\": \"list\", \"data\": [{\"id\": \"fake-model\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}}, {\"id\": \"fake-alias\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}}]}", + "body": "{\"object\": \"list\", \"data\": [{\"id\": \"fake-model\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}, \"input_types\": [\"text\"]}, {\"id\": \"fake-alias\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}, \"input_types\": [\"text\"]}]}", "interim": "" } ] diff --git a/zig/tests/server/golden/scopes/read-models.json b/zig/tests/server/golden/scopes/read-models.json index 46f2b1cec86..29393acc256 100644 --- a/zig/tests/server/golden/scopes/read-models.json +++ b/zig/tests/server/golden/scopes/read-models.json @@ -10,10 +10,10 @@ ], [ "Content-Length", - "1618" + "1668" ] ], - "body": "{\"object\": \"list\", \"data\": [{\"id\": \"fake-model\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}}, {\"id\": \"fake-alias\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}}]}", + "body": "{\"object\": \"list\", \"data\": [{\"id\": \"fake-model\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}, \"input_types\": [\"text\"]}, {\"id\": \"fake-alias\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}, \"input_types\": [\"text\"]}]}", "interim": "" } ] diff --git a/zig/tests/server/golden/status/get-models.json b/zig/tests/server/golden/status/get-models.json index 46f2b1cec86..29393acc256 100644 --- a/zig/tests/server/golden/status/get-models.json +++ b/zig/tests/server/golden/status/get-models.json @@ -10,10 +10,10 @@ ], [ "Content-Length", - "1618" + "1668" ] ], - "body": "{\"object\": \"list\", \"data\": [{\"id\": \"fake-model\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}}, {\"id\": \"fake-alias\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}}]}", + "body": "{\"object\": \"list\", \"data\": [{\"id\": \"fake-model\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}, \"input_types\": [\"text\"]}, {\"id\": \"fake-alias\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}, \"input_types\": [\"text\"]}]}", "interim": "" } ] diff --git a/zig/tests/server/golden/status/get-v1-models%3Fx=1.json b/zig/tests/server/golden/status/get-v1-models%3Fx=1.json index 46f2b1cec86..29393acc256 100644 --- a/zig/tests/server/golden/status/get-v1-models%3Fx=1.json +++ b/zig/tests/server/golden/status/get-v1-models%3Fx=1.json @@ -10,10 +10,10 @@ ], [ "Content-Length", - "1618" + "1668" ] ], - "body": "{\"object\": \"list\", \"data\": [{\"id\": \"fake-model\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}}, {\"id\": \"fake-alias\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}}]}", + "body": "{\"object\": \"list\", \"data\": [{\"id\": \"fake-model\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}, \"input_types\": [\"text\"]}, {\"id\": \"fake-alias\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}, \"input_types\": [\"text\"]}]}", "interim": "" } ] diff --git a/zig/tests/server/golden/status/get-v1-models.json b/zig/tests/server/golden/status/get-v1-models.json index 46f2b1cec86..29393acc256 100644 --- a/zig/tests/server/golden/status/get-v1-models.json +++ b/zig/tests/server/golden/status/get-v1-models.json @@ -10,10 +10,10 @@ ], [ "Content-Length", - "1618" + "1668" ] ], - "body": "{\"object\": \"list\", \"data\": [{\"id\": \"fake-model\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}}, {\"id\": \"fake-alias\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}}]}", + "body": "{\"object\": \"list\", \"data\": [{\"id\": \"fake-model\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}, \"input_types\": [\"text\"]}, {\"id\": \"fake-alias\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}, \"input_types\": [\"text\"]}]}", "interim": "" } ] diff --git a/zig/tests/server/golden/status/get-x-models.json b/zig/tests/server/golden/status/get-x-models.json index 46f2b1cec86..29393acc256 100644 --- a/zig/tests/server/golden/status/get-x-models.json +++ b/zig/tests/server/golden/status/get-x-models.json @@ -10,10 +10,10 @@ ], [ "Content-Length", - "1618" + "1668" ] ], - "body": "{\"object\": \"list\", \"data\": [{\"id\": \"fake-model\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}}, {\"id\": \"fake-alias\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}}]}", + "body": "{\"object\": \"list\", \"data\": [{\"id\": \"fake-model\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}, \"input_types\": [\"text\"]}, {\"id\": \"fake-alias\", \"object\": \"model\", \"created\": , \"owned_by\": \"tensorfold\", \"capabilities\": {\"text_generation\": true, \"context_fitted\": false, \"call_gates\": true, \"loop_guard\": false, \"thinking_budget\": true, \"reasoning\": true, \"answer_limit\": false, \"structures\": false, \"logprobs\": false, \"penalties\": false, \"prompt_logprobs\": false, \"prompt_cache\": false, \"warm_turns\": false, \"plain_only\": false, \"decides\": false, \"pictures\": false, \"greedy_only\": false, \"slide_conversations\": false, \"vision\": false, \"speech\": false, \"embeddings\": false, \"readouts\": false, \"rerank\": false, \"thinking_switch\": true, \"thinking_applicable\": true}, \"context_length\": 1024, \"max_model_len\": 1024, \"reasoning\": {\"default_enabled\": true, \"supported_efforts\": [\"xhigh\", \"medium\", \"low\", \"none\"]}, \"input_types\": [\"text\"]}]}", "interim": "" } ] diff --git a/zig/tests/server/security_check.py b/zig/tests/server/security_check.py index f901a673cce..9a2da5ef711 100644 --- a/zig/tests/server/security_check.py +++ b/zig/tests/server/security_check.py @@ -1,5 +1,6 @@ #!/usr/bin/env python3 import argparse +import errno import os import re import selectors @@ -44,20 +45,43 @@ def launch(binary, fixtures): selector.close() -def exchange(port, data): +# the server's close reaching a client that is still sending: a reset, a closed pipe or a socket no longer connected +CLOSED_FIRST = {errno.ECONNRESET, errno.EPIPE, errno.ENOTCONN} + + +def exchange(port, data, closes_ok=False): + """The bytes the server sent back, and whether it closed while the request was still being sent or read.""" + output = bytearray() with socket.create_connection(("127.0.0.1", port), timeout=5) as connection: connection.settimeout(5) - connection.sendall(data) - connection.shutdown(socket.SHUT_WR) - output = bytearray() - while True: - part = connection.recv(8192) - if not part: - break - output.extend(part) - if len(output) > 1 << 20: - raise AssertionError("fixture response exceeded 1 MiB") - return bytes(output) + try: + connection.sendall(data) + connection.shutdown(socket.SHUT_WR) + while True: + part = connection.recv(8192) + if not part: + break + output.extend(part) + if len(output) > 1 << 20: + raise AssertionError("fixture response exceeded 1 MiB") + except OSError as error: + if not closes_ok or error.errno not in CLOSED_FIRST: + raise + return bytes(output), True + return bytes(output), False + + +def refused_or_closed(output, expected): + """A close mid-request may cut the refusal off, but nothing it delivered may be a served (2xx) reply.""" + if re.match(rb"HTTP/1\.[01] 2", output): + raise AssertionError("the server answered a request it should have refused") + if b"\r\n\r\n" in output: + try: + actual = statuses(output) + except AssertionError: + return # the refusal itself was cut off by the close + if actual != expected: + raise AssertionError(f"expected {expected} or a close, got {actual}") def statuses(wire): @@ -112,11 +136,14 @@ def cases(): yield "GET conflicting framing is rejected", [400], ( b"GET /health HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Length: 0\r\n" b"Transfer-Encoding: chunked\r\n\r\n0\r\n\r\n") - # a body no route reads is taken only to keep the connection in step, so it has a small cap of its own + # an unread body has a small cap; past it the server refuses and closes, maybe before the whole body is sent for size, expected in ((65536, 200), (65537, 400)): yield f"GET body of {size} bytes against the unread cap", [expected], ( b"GET /health HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\nContent-Length: " - + str(size).encode() + b"\r\n\r\n" + b"x" * size) + + str(size).encode() + b"\r\n\r\n" + b"x" * size), expected != 200 + # the cap is decided on the declared length before any body is read, so a head alone shows it with no race + yield "GET declaring 65537 bytes is refused before its body is read", [400], ( + b"GET /health HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\nContent-Length: 65537\r\n\r\n") yield "GET body preserves a genuine following request", [200, 200], ( b"GET /health HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Length: 4\r\n\r\ndata" b"GET /v1/models HTTP/1.1\r\nHost: 127.0.0.1\r\nAuthorization: Bearer " + KEY @@ -133,7 +160,7 @@ def cases(): def answered(port): """True when a new client is served; a full server answers 503 or resets the connection.""" try: - return statuses(exchange(port, CLOSING)) == [200] + return statuses(exchange(port, CLOSING)[0]) == [200] except (AssertionError, OSError): return False @@ -176,12 +203,17 @@ def main(): failed = 0 total = 0 try: - for label, expected, data in cases(): + for label, expected, data, *closes_ok in cases(): total += 1 try: - actual = statuses(exchange(port, data)) - if actual != expected: - raise AssertionError(f"expected {expected}, got {actual}") + output, closed = exchange(port, data, bool(closes_ok and closes_ok[0])) + if closed: + refused_or_closed(output, expected) + label += " (the server closed first)" + else: + actual = statuses(output) + if actual != expected: + raise AssertionError(f"expected {expected}, got {actual}") print("PASS", label) except (AssertionError, OSError, ValueError) as error: failed += 1