diff --git a/CHANGELOG.md b/CHANGELOG.md index 93f00f5d37b..f87b67855d8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,102 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- CUDA: `nccl.Library.open()` and the tensor-parallel config now resolve `TF_NCCL_LIB` through the shared path rule, so GLM, Flash Next's `--tp 2` collective, MiniMax M3 and TP sessions open the same library; unset, empty or blank values keep `libnccl.so.2`, and a value with control characters is refused (#3106). Thanks to @vdalesandro. + +- Core KV pool: a host tier for the pool's pages, which refuses zero page bytes, partial host pages, zero frames and zero logical pages before it allocates (#1501, refs #1113). Thanks to @BlivionIaG. + +- Server: replies in recipient-addressed messages (`to=self` … `<|eom|>`, `to=user` … `<|eot|>`, as Muse Spark Open's chat template writes them) are split into reasoning, answer and tool calls, where the whole reply, markers included, ended up in `content` (#1336). Thanks to @ajensenwaud. + +- App: Room agents keep their own reasoning effort, and an agent without one inherits the run's default (#3514). Thanks to @AIFlowML. + +- GLM-5.3-Flash on Metal: on Macs without tensor units (before M5), prompt processing uses vectorized GLM-only matmul, KDA and indexer kernels with 32-row matmul tiles; M5 Macs and every other Metal family keep their kernels, and the author's token hashes match main (#3921, refs #3152). Thanks to @gilby. + +- Changelog: #3125's entry appears once, under 1.2.10; the copy in 1.2.9's section, a release published before #3125 landed, is removed (#3916, refs #3125). Thanks to @Bizuayeu. + +- Tests: the Zig cache restat tests read `.lib_dir` from `zig env` instead of guessing a `lib` folder beside the executable, so they work with Homebrew Zig (#3786, fixes #3785). Thanks to @AIFlowML. + +- `tensorfold device`: a saved macOS profile is refreshed when the live GPU wired-memory limit changes, so the reported available weight bytes match the current limit (#3780, fixes #3778). Thanks to @AIFlowML. + +- `tensorfold web`: after a PATH miss, the launcher looks in uv's tool directory for an existing Web executable before offering an install; PATH still wins and installing still needs an explicit yes (#3748, fixes #3747). Thanks to @AIFlowML. + +- Tests: the Metal kernel-contract gate checks the four `dsv41 xmma units` launches only where tensor units exist, so Gate 5 limits pass on Macs without them while the four simdgroup launches stay checked everywhere (#3522). Thanks to @gilby. + +- Desktop: a Qwen3.8-27B checkpoint is offered and loads, where the library applied the 2B geometry to every `qwen3_5` checkpoint and rejected the supported 27B at hidden size 5,120 (#3771). Thanks to @AIFlowML. + +- Intel Arc (XPU): two or four Level Zero GPUs open as peers in one context, with new peer-to-peer all-reduce collectives (FP16, BF16 and FP32; one shot up to 512 KiB, reduce-scatter then gather above) that sum in fixed rank order for exact bits, and `zig build xpu-tp-bench` builds `tf-xpu-tp-bench` to check and time them; nothing serves through them yet (#3585, part of #3583). Thanks to @supernovae. + +- Gemma 4 on Metal: an image input whose tower cannot load is refused cleanly instead of crashing during deinit, and a host test pins that a failed tower load leaves the model with none (#3421). Thanks to @jschmied. + +- Tests: `test-pull-host` no longer hangs on macOS, where the test allocator's stack capture on frees from the client's I/O threads deadlocked in Zig's Mach-O unwinder (#3740). + +- Tests: a new host step, `test-hip-followers-host`, runs the HIP followers' step-parser tests (the `hip_serve` protocol tests and the Flash Next, Qwen and Nemotron HIP worker security tests) in CI, where no build step ran them (#3091). + +- Kernel contract: the nvcc 13.2/13.3 usage table moves to its own registry_cuda_sets.zig, so registry.zig has room under the 600-line limit; the registered set is unchanged (#3865). + +- Tools: `tools/draft_divergence.py` checks drafted decoding returns exactly the plain token IDs on prompts around recorded BF16 near-ties, at draft caps 1, 4 and 8 (#3841). + +- Tests: a two-session KV isolation test pins that kept states across spill, offload and page reuse match by tokens only, never position (#3840). + +- CI: the last four host checks excluded under #2031 return to the aggregate; recording fixtures initialize runner state and affine kernel handles. + +- Server: `GET /v1/models/{id}` (and `/models/{id}`) returns the entry `/v1/models` lists for the served name or an alias, the id sent as written or percent-escaped (`org%2Fname`); any other id is a 404 `model_not_found`, and API keys and key scopes treat the route as they treat `/v1/models` (#3535). + +- CUDA and HIP: Qwen 3.5 settings go through the environment rules, so malformed text is refused at startup with the setting's name and accepted forms; names, defaults and clamps are unchanged (#3520). + +- Qwen3.8-27B on Metal: tensor-unit qk projections, flat glue kernels and Metal 4 verify passes each have their own off switch (`TF_Q27_QK=0`, `TF_Q27_FLAT_GLUE=0`, `TF_Q27_METAL4=0`) and are bit-identical to the kernels they replace; qk and Metal 4 stay off on chips without tensor units (#2342). + +- Tools: the served gates (`tools/conformance.py`, the Qwen and LFM3 serve checks and the Qwen3.8-27B HTTP gate) prove they ran what they claim: drafts landed, the sampler and the prompt cache were used, and concurrent requests overlapped (#3708, follows #2460). Thanks to @jschmied. + +- GLM on CUDA: a decode window's EXL3 routed experts launch on the 16-pair item plan instead of the group kernel's grid of mostly idle blocks, with the same output bytes (#2044). Thanks to @BadAd84. + +- Docs: the optimization ledger adds rows 30 to 32 (small-kernel fusion, stream-tile prefetch and the filled-item prompt grid), each `failed` for Flash Next on HIP with the measurements from #1603 (#3160, refs #1603). Thanks to @gilby. + +- Docs: the Qwen3.8-27B recipe says to serve with `--thinking-budget 4096` when thinking is on, and gives its GPQA Diamond result on TensorFold 1.2.7 and one GB10: replies cut at the limit from 78 of 198 to 0, and correct from 58.1% to 82.8% (#3373, fixes #3323). + +- Docs: the drafter training recipe gains a section on adapting an already released drafter, budgeted from a few passes over the scarcest class at a low learning rate with early checkpoints, with the Qwen3.8-27B pilot behind it (#3369, refs #2667). Thanks to @Maxrio9. + +- Desktop: searching the current conversation no longer carries a project picked under All saved conversations; the request, its results, filters and navigation use the scope's own project filter, and switching back restores the project (#3900, fixes #3849). Thanks to @AIFlowML. + +- Docs: GLM-5.3-Flash Jammed XSFP4 NZ5 is listed as in 1.2.10 in the supported models table and the GLM CUDA recipe, where both said "on main after 1.2.7" (#3869, refs #2894). Thanks to @Bizuayeu. + +- CUDA: NVFP4 expert decode streams its weights through a per-warp `cp.async` ring with the same output bits; on an RTX PRO 6000 (sm_120) with drafts off the author measured GLM-5.3 decode at 104.1 tok/s against 83.8, and on GB10 (sm_121) it is level (#2266). Thanks to @eleqtrizit. + +- Docs: the GLM-5.3-Flash CUDA recipe covers switchless RoCE links on separate IPv4 subnets: NCCL 2.30.7 or later with `NCCL_IB_SUBNET_AWARE_ROUTING=1` and `NCCL_IB_SUBNET_PREFIX_LEN`, and how to check the NCCL version and NIC each rank picked at startup (#2993). Thanks to @vdalesandro. + +- Families: Nemotron, GLM, Qwen 3.8 27B, MiniMax M3, Dory, tensor-parallel fabric, pictures and video settings read through platform/environment.zig (#3558). + +- Qwen3.5 on Metal: the text-only server no longer keeps the vision tower stored between the language-model tensors in GPU memory, so the 2B holds 1.7 GiB instead of 2.3 GiB measured with `footprint` after load, with replies unchanged (#3407). Thanks to @jschmied. + +- Server: `TENSORFOLD_REQUEST_JOURNAL=PATH` records each chat or completion request in three JSON lines (start, prepared, finish), so a request unfinished at a crash is flagged on the next start, one in flight at two crashes is refused with 400 `request_quarantined`, and `tools/replay_request.py` replays a journaled request and compares the reply's `tensorfold.token_sha256`; off unless set (#3221). + +- CLI: `tensorfold config validate FILE` (source builds only, not `tensorfold-native`) reads a cluster.json with the same parser and 16 MiB limit the server uses, prints the node and model counts on success or every problem the parser collected, and exits 0, 1 or 2 without planning models or probing hosts; `cluster check` is unchanged (#3189). Thanks to @mvanhorn. + +- Drama voices: `--manage-voices` (off by default) lets admin keys add a voice with `POST /v1/voices` (a WAV with its transcript, or an attested voice file, checked and encoded by the loaded model's own codec) and delete one with `DELETE /v1/voices/NAME`, and `--request-voices` lets a request carry an inline voice object; a running request keeps the voice it copied when it arrived (#3140). + +- Idol on Metal: Idol's released denoiser runs as a native Metal family, `idol`, with fp16 block projections and attention inputs summed in fp32 and fp32 norms, softmax and RePo as the SDK splits them; `tf-idol` checks it step by step against idol-sdk's float32 run, and its 27 kernels are in the kernel contract with 19 planted controls. The image encoders and decoders are separate changes (#1766, for #1757). Thanks to @jayleaton. + +- Code: a GPTQ reader in `core/quant` reads AutoGPTQ v1 4-bit symmetric group-128 weights as stored (`qweight`, fp16 `scales`, a `qzeros` zero point of 8) into an fp64 reference, and refuses every other GPTQ field, rule or tensor by name; host only, with no caller yet (#3611, refs #3368). + +- Desktop: an attachment in a saved draft keeps only its original diagnostic, and the reselection guidance is added once when the draft is rendered, so reopening and editing unrelated text no longer stores the composed message as the error; older drafts with repeated guidance show one copy and keep any surviving diagnostic (#3842, fixes #3837). Thanks to @AIFlowML. + +- Desktop: turning off `autoCheckUpdates` now cancels the first scheduled update check as well as the recurring interval, and scheduled callbacks recheck the saved setting before calling the feed; a manual check from Settings still works with automatic checks off (#3836, fixes #3833). Thanks to @AIFlowML. + +- Desktop: changing the run, mode or redaction in the export panel clears the old preview at once and leaves `Copy JSON` and `Save…` disabled until the new selection builds successfully; a late result cannot replace another selection's preview or its feedback (#3834, fixes #3829). Thanks to @AIFlowML. + +- Web: the engine address may be an OpenAI base URL ending in `/v1` as well as a server root; health, the relay and Connect derive the server root with `engine_root` and append the API suffix once, and settings keeps the supplied address so a reverse-proxy prefix ending in `/v1` survives a reload (#3831, fixes #3830). Thanks to @AIFlowML. + +- Desktop: the library scan uses four convolution taps for Qwen3.5-2B, so the supported checkpoint is offered instead of being refused at scan time; a checkpoint with the old value still gets a geometry refusal (#3768). Thanks to @AIFlowML. + +- Desktop: a ticket can finalize only after a current independent review of its actual builder work; reviewer blockers stay with their batch and ordinary later notes no longer revoke approval (#3484). Thanks to @AIFlowML. + +- Metal: Ling-3.0-tiny's MLA layers run on Kimi's `k3_mla` kernels with three added kernels for cache and query RoPE and gate widening, registered with planted controls in the kernel contract (#3609). Thanks to @ThinkOffApp. + +- Nemotron: the Living Weights copies left behind by the October revert are deleted and `cuda_pages` imports `living.lesson_route`, leaving one copy of the learner, pocket and lesson files (#3707). Thanks to @jschmied. + +- Flash Next on CUDA: after load, a mixed shard keeps only the n-gram table's pages in the page cache, and the final sweep reaches shards nested under `tensors/`, freeing about 3 GiB of page cache on the NVFP4 export with replies unchanged (#3467). Thanks to @jschmied. + +- CUDA: GLM's `TF_GLM_L2PF` site f now also prefetches a MoE layer's shared expert gate-up after its router within the same `TF_GLM_L2PF_MB` budget, giving about 1.0-1.2% faster decode at TP=2 on GB10 (mean of three alternating launches) with identical tokens (#3156). Thanks to @Bizuayeu. + - Desktop: the Terminal picker launches a registered Orchestrator CLI by its ID without forwarding the catalog command as a custom override, lists CLIs for the current project and host, and stops a click left stale by retargeting, project removal or a disabled host before dispatch; local custom commands and the remote refusal still apply (#3828, fixes #3824). Thanks to @AIFlowML. - Web: the OpenAI connection probe now uses the shared stream reader, so partial text followed by an error or early EOF fails the check instead of passing; the reader handles LF, CRLF and bare CR, including a CRLF split across chunks, and complete streams still pass the text-or-reasoning check (#3826, fixes #3823). Thanks to @AIFlowML. @@ -249,6 +345,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Flash Next at TP=2 on CUDA: the draft head, head-group and rollback passes replay as CUDA graphs on both ranks, and one-row split lanes skip their interleave copies; with Qwen3.8-Flash-Next NVFP4 and MTP at TP=2 on GB10s, decode is 1.2-1.4% faster and prompts 0.5-2.1% faster, with identical replies (#2837, for #2835). - Intel XPU: Qwen3.8-27B's prompt `gdn_out` kernel keeps its scale bookkeeping in cheaper exact forms, for 22.6% less kernel time on an Arc Pro B70 (736.3 to 570.2 ms over a 32K prompt) with byte-identical outputs, its fallback included (#2921, refs #2859). Thanks to @dinadur. - CI: the no-GPU host tests run as two parallel jobs, `zig` and `zig-b`, and a build check fails if any host check is in both or neither; a local `zig build test-host` still runs all of them (#3474). +- GLM-5.3-Flash on CUDA: while rank 0's vision tower encodes a prompt's images, the other ranks sleep on their liveness lines, as they do when no stream is left, instead of waiting in an NCCL receive for the whole pass, so a pass longer than a net plugin's operation timeout no longer stops every rank. On three GB10s at the mesh plugin's 30 s default, one 3840x2160 image (66 s), two 3072x1728 and fifteen 1920x1080 screenshots answer, with the same replies and short-image times (for #3614). +- GLM-5.3-Flash on CUDA: while rank 0's vision tower encodes a prompt's images, the other ranks sleep on their liveness lines, as they do when no stream is left, instead of waiting in an NCCL receive for the whole pass, so a pass longer than a net plugin's operation timeout no longer stops every rank. On three GB10s at the mesh plugin's 30 s default, one 3840x2160 image (66 s), two 3072x1728 and fifteen 1920x1080 screenshots answer, with the same replies and short-image times (#3675, for #3614). - Nemotron 3.5 Bolt on CUDA: the shared expert runs on the side stream in decode windows, as on Super, so decode on a GB10 is 2.9-3.0% faster at one stream and 1.4-2.1% at four, with identical replies (#2847, for #2840). @@ -258,6 +356,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Server: temporaries a crash left beside notes and the `--slide-graph` file are cleared when the server opens their folders, only the server's own and only when their process is gone (#3132). +- GLM-5.3-Flash on CUDA: while rank 0's vision tower encodes a prompt's images, the other ranks sleep on their liveness lines, as they do when no stream is left, instead of waiting in an NCCL receive for the whole pass, so a pass longer than a net plugin's operation timeout no longer stops every rank. On three GB10s at the mesh plugin's 30 s default, one 3840x2160 image (66 s), two 3072x1728 and fifteen 1920x1080 screenshots answer, with the same replies and short-image times (#3675, for #3614). + - LFM2.5-24B-A2B on CUDA: the five prompt-stream writes whose state a prompt-cache keep copies (a slot clear, a prompt chunk, a one-row step, a verify round and a commit) take their stream from one helper that first waits for the keeps' copies, and a host test fails if a write skips it. Replies are unchanged (#2989, after #1503). Thanks to @jschmied. - LFM2.5 on CUDA: attention pages come from the shared KV pool and chat states are kept in the prompt cache, with the kept states' copies off the first token's path; replies are unchanged (#1503). Thanks to @jschmied. @@ -350,8 +450,6 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel is identical to the release's own `infer` in torch bf16, or departs from it only where two candidate tokens lie within one bf16 step of each other, the same two torch's float32 run weighs. The five-page document is served the same way; its departures are listed in the recipe beside float32's (#2074). Thanks to @BobClawblaw. -- GLM-5.3-Flash on CUDA with `TF_KV_SHARE` and no `--prompt-cache-gib`: the kept states' slots, `TF_KV_SHARE` at most, now come where an asked cache goes, before the windows past the engine's own, so a room that holds one more whole window no longer keeps fewer states; Jammed XSFP4 at TP=3 on three GB10s keeps all 32 at `TF_KV_SHARE=32` instead of 8, with the same tokens (#3125). Thanks to @Bizuayeu. - - 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. diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index b79c755c447..6fd65005e19 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -335,6 +335,7 @@ These follow a model's release code or a library's model code for their math, ro - `zig/src/vision/qwen_cuda.zig`: `Qwen3_5VisionModel` in transformers. - `zig/src/core/picture/patches_test.zig`: recorded image-processor output data from `Lfm3VlImageProcessor` and `Qwen2VLImageProcessor` in transformers; the processing implementation is described below. - `zig/src/families/flashnext/rotary_config.zig`: `_compute_yarn_parameters` in transformers, for the 64 rotary dims. +- `zig/kernels/metal/idol.metal`: the rounding points of Idol's denoiser in [speridlabs/idol-sdk](https://github.com/speridlabs/idol-sdk) at `4702a7f0`. Copyright speridlabs, Apache License 2.0; see [the license text](LICENSES/Apache-2.0.txt). transformers is Copyright The HuggingFace Team, Apache License 2.0; see [the license text](LICENSES/Apache-2.0.txt). diff --git a/app/electron/agent/delegation-route.test.ts b/app/electron/agent/delegation-route.test.ts index c415c27e3a6..595d9f5c795 100644 --- a/app/electron/agent/delegation-route.test.ts +++ b/app/electron/agent/delegation-route.test.ts @@ -179,7 +179,7 @@ async function run() { // --- Source pins: both spawn paths route through the resolver ------------------------ { const source = (rel: string) => readFileSync(fileURLToPath(new URL(rel, import.meta.url)), 'utf8') - const roomIpc = source('../main/host/workspace-runtime-ipc.ts') + const roomIpc = source('../main/host/room-tools-runtime.ts') const delegateStart = roomIpc.indexOf('delegate: async (args, seat)') const delegateEnd = roomIpc.indexOf('read_file: async', delegateStart) assert.ok(delegateStart >= 0 && delegateEnd > delegateStart, 'room delegate tool remains discoverable') @@ -187,7 +187,7 @@ async function run() { assert.match(delegate, /resolveDelegationRoute\(store\.settings\.providers/, 'room delegate resolves the cross-model route') assert.match(delegate, /!routed\.route\) return `Cannot delegate:/, 'route errors surface as tool errors, not crashes') assert.match(delegate, /runReadOnlySubAgent\(created\.agent, prov, routed\.route\.model/, 'room delegate runs the sub-agent on the routed model') - assert.match(delegate, /parent: parentForRoomSeat\(room, s\)/, 'delegated sub-agent lineage stays under the delegating seat') + assert.match(delegate, /parent: parentForRoomSeat\(runtimeScope\.room, s\)/, 'delegated sub-agent lineage stays under the delegating seat') const threadRuntime = source('../main/host/tool-context-runtime.ts') assert.match(threadRuntime, /resolveDelegationRoute\(store\.settings\.providers/, 'thread sub-agent launcher resolves the cross-model route') diff --git a/app/electron/agent/delegation-route.ts b/app/electron/agent/delegation-route.ts index b9ebb0a0579..5af6c602825 100644 --- a/app/electron/agent/delegation-route.ts +++ b/app/electron/agent/delegation-route.ts @@ -1,4 +1,4 @@ -import type { Provider, Seat } from './types' +import type { Provider, ReasoningEffortSetting, Seat } from './types' import { resolveProviderModel, selectProviderAccount } from './provider-accounts' // Cross-model delegation routing (Traycer-style): a single spawn binds provider/account/model, @@ -10,6 +10,7 @@ export interface DelegationRouteBase { // "fall back to the active/default account" while null means "no account". providerAccountId?: string | null model: string + reasoningEffort?: ReasoningEffortSetting } export interface DelegationRouteOverride { @@ -49,10 +50,14 @@ export function resolveDelegationRoute( const seat = seats?.find((candidate) => candidate.name === targetSeat) if (!seat) return { error: `unknown seat "${targetSeat}"` } route = { providerId: seat.providerId, providerAccountId: seat.providerAccountId, model: seat.model } + if (seat.reasoningEffort !== undefined) route.reasoningEffort = seat.reasoningEffort } // A same-provider override keeps the inherited account; only a cross-provider switch // resets it (the account id is meaningless on the new provider). - if (providerId && providerId !== route.providerId) route = { providerId, model: route.model } + if (providerId && providerId !== route.providerId) { + route = { providerId, model: route.model, + ...(route.reasoningEffort === undefined ? {} : { reasoningEffort: route.reasoningEffort }) } + } const provider = providers.find((candidate) => candidate.id === route.providerId) if (!provider) return { error: `unknown provider "${route.providerId}"` } if (localOnly && provider.kind !== 'local') return { error: `provider "${provider.name}" must be a local provider for this local-only project` } diff --git a/app/electron/agent/engine/geometry.ts b/app/electron/agent/engine/geometry.ts index 7c8a95d2de1..3ac699088bc 100644 --- a/app/electron/agent/engine/geometry.ts +++ b/app/electron/agent/engine/geometry.ts @@ -32,7 +32,7 @@ const QWEN35: PinnedGeometry = { linear_num_value_heads: 16, linear_key_head_dim: 128, linear_value_head_dim: 128, - linear_conv_kernel_dim: 6144, + linear_conv_kernel_dim: 4, num_attention_heads: 8, num_key_value_heads: 2, head_dim: 256, @@ -40,6 +40,26 @@ const QWEN35: PinnedGeometry = { }, } +const QWEN27: PinnedGeometry = { + title: 'Qwen3.5 27B', + engineError: 'UnqualifiedQwenShape', + section: 'text_config', + dims: { + hidden_size: 5120, + vocab_size: 248320, + num_hidden_layers: 64, + intermediate_size: 17408, + linear_num_key_heads: 16, + linear_num_value_heads: 48, + linear_key_head_dim: 128, + linear_value_head_dim: 128, + linear_conv_kernel_dim: 4, + num_attention_heads: 24, + num_key_value_heads: 4, + head_dim: 256, + }, +} + const LFM2_MOE: PinnedGeometry = { title: 'LFM2.5', engineError: 'UnsupportedLfmGeometry', @@ -76,11 +96,15 @@ function layerTypesMatch(kind: string, layers: unknown): boolean { } export function admitGeometry(modelType: string, config: unknown): GeometryAdmission { - const pinned = PINNED[modelType] - if (!pinned) return { admitted: true, reason: null } + const defaultGeometry = PINNED[modelType] + if (!defaultGeometry) return { admitted: true, reason: null } if (!plain(config)) return { admitted: true, reason: null } - const section = pinned.section ? config[pinned.section] : config + const section = defaultGeometry.section ? config[defaultGeometry.section] : config if (!plain(section)) return { admitted: true, reason: null } + // The native dispatcher sends a tied head or the 2B hidden size to the 2B engine. + const useQwen27 = modelType === 'qwen3_5' && section.hidden_size === QWEN27.dims.hidden_size && + config.hidden_size !== QWEN35.dims.hidden_size && config.tie_word_embeddings !== true && section.tie_word_embeddings !== true + const pinned = useQwen27 ? QWEN27 : defaultGeometry for (const [key, expected] of Object.entries(pinned.dims)) { const value = section[key] if (value === undefined || value === null) continue @@ -91,7 +115,9 @@ export function admitGeometry(modelType: string, config: unknown): GeometryAdmis } } } - if (!layerTypesMatch(modelType, section.layer_types)) { + const interval = section.full_attention_interval + const wrongQwen27Interval = useQwen27 && typeof interval === 'number' && interval > 0 && interval !== 4 + if (wrongQwen27Interval || !layerTypesMatch(modelType, section.layer_types)) { return { admitted: false, reason: `This checkpoint's layer types are not the ones the bundled engine serves for ${pinned.title}; the engine refuses it (${pinned.engineError}).`, diff --git a/app/electron/agent/engine/library.test.ts b/app/electron/agent/engine/library.test.ts index 11027af03c5..5feee64a41f 100644 --- a/app/electron/agent/engine/library.test.ts +++ b/app/electron/agent/engine/library.test.ts @@ -85,7 +85,23 @@ try { await fs.writeFile(path.join(wrongGeometry, 'config.json'), JSON.stringify({ model_type: 'qwen3_5', quantization: { bits: 4, group_size: 64 }, max_position_embeddings: 32768, text_config: { hidden_size: 1024, num_hidden_layers: 24, vocab_size: 151936 } })) const servedGeometry = path.join(modelsDir, 'served-geometry') await checkpoint(servedGeometry) - await fs.writeFile(path.join(servedGeometry, 'config.json'), JSON.stringify({ model_type: 'qwen3_5', quantization: { bits: 4, group_size: 64 }, max_position_embeddings: 32768, text_config: { hidden_size: 2048, num_hidden_layers: 24, vocab_size: 248320, intermediate_size: 6144, linear_num_key_heads: 16, linear_num_value_heads: 16, linear_key_head_dim: 128, linear_value_head_dim: 128, linear_conv_kernel_dim: 6144, num_attention_heads: 8, num_key_value_heads: 2, head_dim: 256, full_attention_interval: 4 } })) + const servedConfig = { + model_type: 'qwen3_5', + quantization: { bits: 4, group_size: 64 }, + max_position_embeddings: 32768, + text_config: { + hidden_size: 2048, num_hidden_layers: 24, vocab_size: 248320, intermediate_size: 6144, + linear_num_key_heads: 16, linear_num_value_heads: 16, linear_key_head_dim: 128, linear_value_head_dim: 128, + linear_conv_kernel_dim: 4, num_attention_heads: 8, num_key_value_heads: 2, head_dim: 256, full_attention_interval: 4, + }, + } + await fs.writeFile(path.join(servedGeometry, 'config.json'), JSON.stringify(servedConfig)) + const wrongConvolution = path.join(modelsDir, 'wrong-convolution') + await checkpoint(wrongConvolution) + await fs.writeFile(path.join(wrongConvolution, 'config.json'), JSON.stringify({ + ...servedConfig, + text_config: { ...servedConfig.text_config, linear_conv_kernel_dim: 6144 }, + })) const incomplete = path.join(modelsDir, 'incomplete') await checkpoint(incomplete) await fs.writeFile(path.join(incomplete, 'model.safetensors.index.json'), JSON.stringify({ weight_map: { a: 'model-00001-of-00002.safetensors', b: 'model-00002-of-00002.safetensors' } })) @@ -111,6 +127,10 @@ try { assert.match(refused.reason!, /hidden size is 1024/) assert.match(refused.reason!, /UnsupportedQwenGeometry/) assert.equal(selected.models.find((model) => model.path === servedGeometry)?.loadable, true, 'the geometry the engine serves stays offered') + const refusedConvolution = selected.models.find((model) => model.path === wrongConvolution)! + assert.equal(refusedConvolution.complete, true) + assert.equal(refusedConvolution.loadable, false) + assert.match(refusedConvolution.reason!, /linear conv kernel dim is 6144/) assert.equal(selected.models.find((model) => model.path === foreign)?.complete, true) assert.match(selected.models.find((model) => model.path === incomplete)!.reason!, /missing.*shards/) assert.match(selected.models.find((model) => model.path === invalid)!.reason!, /safetensors/) @@ -180,6 +200,45 @@ try { const rescan = await lowMemory.scan() assert.deepEqual(rescan.models.map((model: any) => [model.id, model.loadable, model.reason]), lowered.models.map((model: any) => [model.id, model.loadable, model.reason]), 'a later rescan agrees with the refreshed state') + const qwen27 = { + hidden_size: 5120, vocab_size: 248320, num_hidden_layers: 64, intermediate_size: 17408, + linear_num_key_heads: 16, linear_num_value_heads: 48, linear_key_head_dim: 128, + linear_value_head_dim: 128, linear_conv_kernel_dim: 4, num_attention_heads: 24, + num_key_value_heads: 4, head_dim: 256, full_attention_interval: 4, + } + const qwen27Library = library({ appHome: path.join(root, 'qwen27-app') }) + const qwen27Models = path.join(root, 'qwen27-models') + const qwen27Cases = [ + { name: 'untied', tied: false, text: qwen27 }, + { name: 'wrong-kv-heads', tied: false, text: { ...qwen27, num_key_value_heads: 2 } }, + { name: 'wrong-interval', tied: false, text: { ...qwen27, full_attention_interval: 2 } }, + { name: 'tied-root', tied: true, text: qwen27 }, + { name: 'tied-tower', tied: false, text: { ...qwen27, tie_word_embeddings: true } }, + ] + for (const { name, tied, text } of qwen27Cases) { + const folder = path.join(qwen27Models, name) + await checkpoint(folder) + await fs.writeFile(path.join(folder, 'config.json'), JSON.stringify({ + model_type: 'qwen3_5', tie_word_embeddings: tied, quantization: { bits: 4, group_size: 64 }, + text_config: text, + })) + } + const qwen27Entries = (await qwen27Library.addFolder(qwen27Models)).models + const untied = qwen27Entries.find((model) => model.path === path.join(qwen27Models, 'untied'))! + assert.equal(untied.loadable, true, 'the qualified untied 27B is available in the library') + assert.equal((await qwen27Library.resolve(untied.id)).path, untied.path) + const wrongHeads = qwen27Entries.find((model) => model.path === path.join(qwen27Models, 'wrong-kv-heads'))! + assert.equal(wrongHeads.loadable, false) + assert.match(wrongHeads.reason!, /num key value heads is 2.*UnqualifiedQwenShape/) + const wrongInterval = qwen27Entries.find((model) => model.path === path.join(qwen27Models, 'wrong-interval'))! + assert.equal(wrongInterval.loadable, false) + assert.match(wrongInterval.reason!, /layer types/) + for (const name of ['tied-root', 'tied-tower']) { + const tied = qwen27Entries.find((model) => model.path === path.join(qwen27Models, name))! + assert.equal(tied.loadable, false) + assert.match(tied.reason!, /UnsupportedQwenGeometry/) + } + const validRegistry = await fs.readFile(lib.file, 'utf8') await fs.writeFile(lib.file, '{') await assert.rejects(() => library().snapshot(), /library is invalid/) diff --git a/app/electron/agent/room-delegation-effort.test.ts b/app/electron/agent/room-delegation-effort.test.ts new file mode 100644 index 00000000000..a8b26376c69 --- /dev/null +++ b/app/electron/agent/room-delegation-effort.test.ts @@ -0,0 +1,20 @@ +import assert from 'node:assert/strict' +import { resolveDelegationRoute } from './delegation-route' +import type { Provider, Seat } from './types' + +const provider: Provider = { id: 'fixture', name: 'Fixture', kind: 'local', apiKey: '', + baseUrl: 'http://127.0.0.1:1/v1', models: ['first', 'second'] } +const other: Provider = { ...provider, id: 'other' } +const base = { providerId: provider.id, model: 'first', reasoningEffort: 'low' as const } +const seats: Seat[] = [ + { id: 'reviewer', name: 'Reviewer', role: 'Review input', providerId: provider.id, model: 'second', reasoningEffort: 'high' }, + { id: 'legacy', name: 'Legacy', role: 'Review input', providerId: provider.id, model: 'first' }, +] +assert.deepEqual(resolveDelegationRoute([provider, other], base, {}).route, base) +assert.deepEqual(resolveDelegationRoute([provider, other], base, { targetSeat: 'Reviewer' }, seats).route, + { providerId: provider.id, providerAccountId: undefined, model: 'second', reasoningEffort: 'high' }) +assert.deepEqual(resolveDelegationRoute([provider, other], base, { targetSeat: 'Legacy' }, seats).route, + { providerId: provider.id, providerAccountId: undefined, model: 'first' }, 'an inherited target does not adopt the origin agent override') +assert.deepEqual(resolveDelegationRoute([provider, other], base, { providerId: other.id, model: 'second' }).route, + { providerId: other.id, model: 'second', reasoningEffort: 'low' }, 'explicit provider changes retain the originating effort') +console.log('Room delegation effort routing checks passed: origin, target agent, legacy target and explicit provider/model route.') diff --git a/app/electron/agent/room-heartbeats.ts b/app/electron/agent/room-heartbeats.ts new file mode 100644 index 00000000000..b7d65d7c678 --- /dev/null +++ b/app/electron/agent/room-heartbeats.ts @@ -0,0 +1,97 @@ +import type { RoomDeliberationEffort, Seat, SeatHeartbeat } from './types' + +// Minimal shape the heartbeat helpers need — lets tests exercise stall detection +// without standing up a full SeatRuntime (messages/recent are irrelevant here). +export interface SeatRuntimeLike { + seat: Pick + heartbeat: SeatHeartbeat +} + +// Default grace after nextDueAt before a slow seat is flagged stalled (BUG #53). +// Tolerates transient model latency so a normal slow turn does not false-positive. +const SEAT_STALL_GRACE_SECONDS = 30 + +// Heartbeat cadence derived from the room deliberation effort. Deeper sessions +// expect longer per-turn thinking, so we widen the interval to avoid false stalls. +export function seatHeartbeatIntervalSeconds(effort?: RoomDeliberationEffort | null): number { + switch (effort) { + case 'quick': return 30 + case 'deep': return 90 + case 'max': return 120 + case 'normal': + default: return 60 + } +} + +// Seed a healthy heartbeat for a seat at room start. +export function initSeatHeartbeat(seat: Pick, intervalSeconds: number, now: number): SeatHeartbeat { + return { + seatId: seat.id, + seatName: seat.name, + intervalSeconds, + stallGraceSeconds: SEAT_STALL_GRACE_SECONDS, + required: true, + count: 0, + lastBeatAt: now, + nextDueAt: now + intervalSeconds * 1000, + missedSince: null, + } +} + +// Record that a seat produced a turn: bump count, advance the clock, clear any stall. +export function recordSeatBeat(hb: SeatHeartbeat, now: number): void { + hb.count++ + hb.lastBeatAt = now + hb.nextDueAt = hb.required ? now + hb.intervalSeconds * 1000 : null + hb.missedSince = null +} + +// Names of seats currently flagged stalled (missedSince set), excluding one seat +// by name (the seat trying to FINAL is obviously alive). Used to block a premature +// finalize while a teammate is hung (BUG #53). +export function stalledSeatNames(runtimes: SeatRuntimeLike[], exclude?: string): string[] { + return runtimes + .filter((rt) => rt.heartbeat.required && rt.heartbeat.missedSince != null && rt.seat.name !== exclude) + .map((rt) => rt.seat.name) +} + +// Re-arm the stall window for seats that actually took a turn in the previous pass. +// A single pass over several slow models can take longer than interval+grace, so a +// seat that beat last pass and is merely waiting its turn must not be false-flagged; +// pushing its nextDueAt forward to this pass start prevents that. Crucially, seats +// that did NOT run last pass (e.g. one that keeps timing out without ever calling +// recordSeatBeat, or any seat on the very first pass) are left untouched so their +// window keeps counting and evaluateSeatHeartbeats can actually flag a real stall — +// re-arming every non-stalled seat unconditionally is what made stall detection dead +// code (BUG #53 regression). +export function rearmSeatHeartbeats( + runtimes: SeatRuntimeLike[], + ranLastPass: Set, + passStart: number, +): void { + for (const rt of runtimes) { + const hb = rt.heartbeat + if (hb.required && hb.missedSince == null && ranLastPass.has(rt.seat.id)) { + hb.nextDueAt = passStart + hb.intervalSeconds * 1000 + } + } +} + +// Detect seats whose turn is overdue past the grace window. Mutates each newly +// stalled heartbeat's missedSince so a stall is reported once (not every tick), +// and returns human-readable notices for the moderator to surface. +export function evaluateSeatHeartbeats(runtimes: SeatRuntimeLike[], now: number): string[] { + const stalled: string[] = [] + for (const rt of runtimes) { + const hb = rt.heartbeat + if (!hb.required || hb.lastBeatAt == null || hb.nextDueAt == null) continue + if (hb.missedSince != null) continue // already flagged; do not re-report + const stallAt = hb.nextDueAt + hb.stallGraceSeconds * 1000 + if (now >= stallAt) { + hb.missedSince = hb.nextDueAt + const ago = Math.round((now - hb.lastBeatAt) / 1000) + stalled.push(`Seat "${rt.seat.name}": heartbeat overdue (last beat ${ago}s ago)`) + } + } + return stalled +} diff --git a/app/electron/agent/room-protocol.ts b/app/electron/agent/room-protocol.ts new file mode 100644 index 00000000000..8c32d3dd60a --- /dev/null +++ b/app/electron/agent/room-protocol.ts @@ -0,0 +1,157 @@ +import type { Project, Provider, Room, RoomEventItem, Seat } from './types' +import { isExternalProvider } from '../../shared/provider-trust' +import { PROJECT_CONTEXT_WITHHELD_NOTE } from './planning-guard' +import { VONTRA_STYLE_PROMPT } from './prompt-style' +import { formatRoomMemory, seatCollaborationInstructions } from './room-collaboration' +import { roomModePromptBlock, roomOutcomeProfile } from './room-outcomes' +import { renderSharedMemory } from './shared-room-memory' + +// Ported from LLMComposer's room/huddle engine: multiple provider-bound seats +// deliberate on one shared problem as an attributed dialogue, with SENSE +// injection so each seat knows it is one of several real teammates. + +const VERBS = new Set(['SPEAK', 'ASK', 'OBJECT', 'ASSIGN', 'CLAIM', 'CHECK', 'VOTE', 'YIELD', 'FINAL', 'TOOL']) + +export function buildPrimer(project: Project, room: Room, seat: Seat, roster: Seat[], provider?: Provider): string { + const rosterText = roster.map((s) => `- ${s.name}: ${s.role} (model ${s.model})`).join('\n') + const roomMemory = formatRoomMemory(room) + const sharedMemory = room.sharedMemory ? renderSharedMemory(room.sharedMemory) : '' + return [ + `You are ${seat.name} in a live multi-agent working session with the teammates below.`, + '', + `ROOM ROLE\nYour visible room role is ${seat.role}. Use it to decide when to volunteer, challenge, defer, or take a ticket, but keep your general reasoning intact.`, + `\n${seatCollaborationInstructions(room, seat, provider)}`, + roomOutcomeProfile(room.mode) ? `\nROOM OUTCOME\n${roomModePromptBlock(roomOutcomeProfile(room.mode)!)}` : '', + project.team ? `\nTEAM CHARTER\n${project.team}` : '', + // External seats plan only and never see project memory (planning-guard.ts). + project.memory ? (isExternalProvider(provider) ? `\n${PROJECT_CONTEXT_WITHHELD_NOTE}` : `\nPROJECT MEMORY\n${project.memory}`) : '', + roomMemory ? `\nROOM MEMORY\n${roomMemory}` : '', + sharedMemory ? `\n${sharedMemory}` : '', + '', + 'ROOM CONTRACT', + 'Messages tagged [room] are what teammates actually said; [moderator] hands you the floor.', + 'Speak in first person, briefly and concretely. React to what was just said instead of restating it.', + "Never write [room] or [moderator] lines yourself, and never invent a teammate's reply.", + 'Never repeat a question or point you already made.', + 'End every reply with exactly one line: ACTION: .', + 'Verbs: SPEAK, ASK, OBJECT, ASSIGN, CLAIM, CHECK, VOTE, YIELD, FINAL, TOOL.', + 'ACTION: ASK addresses one teammate by name. ACTION: FINAL ends the room only when the task is genuinely done.', + 'When you answer a specific ASK or ASSIGN, cite it by appending RE: # to your ACTION line so the reply links back to the question.', + 'Only state what you can actually see in the [room] lines above. Do not claim progress that has not happened.', + '', + 'TEAMWORK CONTRACT', + 'Make handoffs explicit. If a teammate asks or assigns you something, answer that first and say what you are unblocking for them.', + 'Help the room finish the user goal: create or claim concrete tickets, attach evidence, start workers when ready, and yield when waiting.', + 'If you disagree, name the risk and offer the next useful move instead of reopening the whole plan.', + '', + VONTRA_STYLE_PROMPT, + '', + 'SHARED BOARD: coordinate through it so you never duplicate a teammate\'s work:', + 'ACTION: TOOL list_tickets: see every ticket and who is working on what.', + 'ACTION: TOOL claim_ticket {"title":"..."}: claim a ticket BEFORE you start it, so teammates know it is taken.', + 'ACTION: TOOL create_ticket {"title":"...","body":"...","priority":"high","risk":"medium","allowedCapabilities":["read"],"requiredEvidence":["files inspected","verification result"],"acceptanceCriteria":["..."]}: add an execution ticket to the board.', + 'ACTION: TOOL add_ticket_evidence {"title":"...","kind":"file","summary":"What you found","ref":"src/file.ts"}: attach evidence to a claimed ticket.', + 'ACTION: TOOL complete_ticket {"title":"...","evidence":[{"kind":"review","summary":"Reviewed X and found Y"}]}: mark your claimed ticket complete after attaching required evidence.', + 'ACTION: TOOL left_to_work: see the remaining room tickets, active workers, risks, and known file refs.', + 'ACTION: TOOL memory_write {"name":"decisions","content":"...","mode":"append-bullet"}: update the room\'s live shared memory (decisions, plan, blockers). Teammates see updates on their next turn.', + 'ACTION: TOOL start_ticket_work {"title":"...","phase":"build","paths":["src/x.ts"]}: ask the Room Supervisor to start a ticket worker thread in the room worktree. Use phase "review" for reviewer passes. If a file overlap is intentional, include "mergeDecision":"why this overlap is safe and how results will be merged".', + 'ACTION: TOOL delegate {"task":"..."}: hand a focused subtask to a sub-agent and get its result. Add "targetSeat":"SeatName" to run it on that seat\'s provider/model, or "providerId"/"accountId"/"model" for an explicit route; omit them to use your own.', + 'Always claim before working; never touch a ticket already claimed by someone else.', + 'Only start ticket workers for claimed or ready tickets. Declare paths when you know them so the supervisor can prevent overlapping edits.', + 'Do not ACTION: FINAL while room tickets are still open.', + '', + 'WORKSPACE: inspect the shared project safely:', + 'ACTION: TOOL read_file {"path":"src/x.ts"}: read a file.', + 'ACTION: TOOL search {"query":"..."}: find relevant code.', + 'ACTION: TOOL list_dir {"path":"src"}: inspect folders.', + 'Room agents are read-only by default. Do not attempt edit_file, write_file, or run_command unless the user opens an approved work thread for that ticket.', + 'When you know the change needed, create/claim a ticket and explain the proposed edit for an approved thread to execute.', + '', + 'TEAM ROSTER', + rosterText, + ].filter(Boolean).join('\n') +} + +export interface Action { verb: string; text: string; raw: string; prose?: string } + +// Lenient gate: missing action becomes SPEAK, empty body becomes YIELD. +export function gateAction(output: string): Action { + const raw = (output ?? '').trim() + if (!raw) return { verb: 'YIELD', text: '', raw } + const lines = raw.split('\n') + const actionLine = [...lines].reverse().find((l) => l.trim().toUpperCase().startsWith('ACTION:')) + const prose = lines.filter((l) => l !== actionLine).join('\n').trim() + if (!actionLine) return { verb: 'SPEAK', text: prose || raw, raw } + const body = actionLine.trim().slice(actionLine.trim().indexOf(':') + 1).trim() + const parts = body.split(/\s+/) + const verb = (parts[0] || '').toUpperCase() + const text = parts.slice(1).join(' ').trim() + if (!VERBS.has(verb)) return { verb: 'SPEAK', text: prose || raw, raw } + if (!text && verb !== 'YIELD') return { verb: 'YIELD', text: '', raw } + // Keep the prose so peers receive the model's actual reasoning, not just the one-line ACTION tagline. + return { verb, text, raw, prose } +} + +export function renderForRoom(ev: RoomEventItem, compact = false): string { + const label = ev.kind.toUpperCase() + // Addressed asks/assigns carry a short ref (#id8) so a teammate can answer with + // "RE: #"; replies show the ref they answer (re #id8). + const ref = (ev.kind === 'ask' || ev.kind === 'assign') ? ` #${ev.id.slice(0, 8)}` : '' + const reply = ev.replyTo ? ` re #${ev.replyTo.slice(0, 8)}` : '' + if (compact) return `[room] ${ev.seat} (${label}${reply}): ${ev.text}` + const head = ev.target && ev.target !== 'all' && ev.target !== ev.seat + ? `[room] ${ev.seat} (${label}, to ${ev.target}${ref}${reply}):` + : `[room] ${ev.seat} (${label}${ref}${reply}):` + return `${head}\n${ev.text}` +} + +export function signature(raw: string): string { + return raw.split('\n').filter((l) => !l.trim().toUpperCase().startsWith('ACTION:')).join(' ').trim().toLowerCase().slice(0, 400) +} + +export function blockerSignature(blockers: string[]): string { + return blockers.map((blocker) => blocker.replace(/\s+/g, ' ').trim().toLowerCase()).filter(Boolean).join('\n') +} + +export function oneLine(text: string, max = 180): string { + const compact = text.replace(/\s+/g, ' ').trim() + return compact.length > max ? `${compact.slice(0, Math.max(0, max - 3))}...` : compact +} + +export function roomTeamCue(room: Room, seat: Seat): string { + const recent = room.events.filter((event) => !['task', 'notice', 'user'].includes(event.kind)).slice(-10) + const directHandoffs = recent.filter((event) => (event.kind === 'ask' || event.kind === 'assign') && event.target === seat.name) + const latestDirect = directHandoffs[directHandoffs.length - 1] + const latestOtherHandoff = recent.filter((event) => + (event.kind === 'ask' || event.kind === 'assign') && + !!event.target && + event.target !== 'all' && + event.target !== seat.name + ).slice(-1)[0] + const latestClaim = recent.filter((event) => event.kind === 'claim').slice(-1)[0] + const latestUserSteer = room.events + .filter((event) => event.kind === 'user' && (event.target === 'all' || event.target === seat.name)) + .slice(-1)[0] + const cue: string[] = [] + + if (latestUserSteer) { + cue.push(`USER STEERING: "${oneLine(latestUserSteer.text, 220)}". Treat this as the user's latest direction and respond to it before lower-priority room chatter.`) + } + + if (latestDirect) { + cue.push(`TEAM CUE: ${latestDirect.seat} handed work to you: "${oneLine(latestDirect.text, 220)}". Answer or unblock that first, naming ${latestDirect.seat}.`) + } else if (latestOtherHandoff) { + cue.push(`TEAM CUE: ${latestOtherHandoff.seat} handed work to ${latestOtherHandoff.target}. Let that teammate respond unless you can unblock with new evidence.`) + } + + if (latestClaim) { + cue.push(`Latest claim: ${latestClaim.seat} claimed "${oneLine(latestClaim.text, 120)}". Build on it and do not duplicate it.`) + } + + cue.push('Work like a teammate: reference who you are helping, answer direct asks before new topics, create or claim the next useful ticket, start workers when ready, and ACTION: YIELD if you are waiting.') + return cue.join(' ') +} + +export function escapeReg(s: string): string { + return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') +} diff --git a/app/electron/agent/room-reasoning-effort.test.ts b/app/electron/agent/room-reasoning-effort.test.ts new file mode 100644 index 00000000000..88c1b0eebf0 --- /dev/null +++ b/app/electron/agent/room-reasoning-effort.test.ts @@ -0,0 +1,90 @@ +import assert from 'node:assert/strict' +import { createServer } from 'node:http' +import { runRoom, initSeatHeartbeat } from './rooms' +import { compactSeatRuntime, type SeatRuntime } from './room-seat-runtime' +import type { Project, Provider, Room, ReasoningEffortSetting } from './types' + +const requests: { model: string; reasoning_effort?: string }[] = [] +const reply = (model: string) => model === 'alpha' + ? 'I checked the synthetic input.\nACTION: ASK Beta confirm the result.' + : 'The synthetic result is confirmed.\nACTION: FINAL Synthetic review complete.' +let afterRequest = () => {} +const server = createServer((request, response) => { + if (request.method === 'GET') { + response.writeHead(200, { 'Content-Type': 'application/json' }) + response.end(JSON.stringify({ data: [{ id: 'alpha', object: 'model' }, { id: 'beta', object: 'model' }] })) + return + } + let raw = '' + request.on('data', chunk => { raw += chunk }) + request.on('end', () => { + const body = JSON.parse(raw) + requests.push(body) + afterRequest() + response.writeHead(200, { 'Content-Type': 'text/event-stream' }) + response.end(`data: ${JSON.stringify({ choices: [{ delta: { content: reply(body.model) }, finish_reason: 'stop' }] })}\n\ndata: [DONE]\n\n`) + }) +}) +await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)) +const baseUrl = `http://127.0.0.1:${(server.address() as { port: number }).port}/v1` +const project = { id: 'project', name: 'Synthetic project', cwd: '/workspace', workspace: null } as Project +const cases = [['high', 'low', 'high', false], ['low', 'high', 'low', false], + ['high', undefined, undefined, false], ['high', 'low', 'high', true]] as const +const observed: { transport: string; global: string; efforts: (string | undefined)[] }[] = [] +const expected: typeof observed = [] +try { + for (const transport of ['http', 'cli'] as const) { + for (const [global, alpha, beta, capturedByHost] of cases) { + const seats = [ + { id: 'alpha', name: 'Alpha', role: 'Review input', providerId: 'alpha', model: 'alpha', reasoningEffort: alpha as ReasoningEffortSetting | undefined }, + { id: 'beta', name: 'Beta', role: 'Check review', providerId: 'beta', model: 'beta', reasoningEffort: beta as ReasoningEffortSetting | undefined }, + ] + const room = { id: 'room', projectId: project.id, name: 'Synthetic room', problem: 'Review the synthetic input.', seats, events: [], memory: [], + memorySummary: '', finalText: '', state: 'queued', seatHeartbeats: {}, deliberationEffort: 'quick', + collaborationMode: 'balanced', createdAt: 1, updatedAt: 1 } as Room + const providers: Provider[] = seats.map(seat => ({ id: seat.id, name: seat.name, kind: 'local', baseUrl, + apiKey: '', models: [seat.model], transport: transport === 'http' ? 'chat-completions' : 'claude-cli' })) + const captured = new Map(seats.map(seat => [seat.id, seat.reasoningEffort ?? global])) + if (capturedByHost) for (const seat of seats) seat.reasoningEffort = 'medium' + const start = requests.length + const cliCalls: { reasoningEffort?: string }[] = [] + afterRequest = () => { + if (requests.length === start + 1) for (const seat of seats) seat.reasoningEffort = 'medium' + } + const controller = new AbortController() + const timer = setTimeout(() => controller.abort(), 5_000) + try { + await runRoom({ room, project, providers, problem: 'Review the synthetic input.', temperature: 0, + reasoningEffort: global, emit() {}, signal: controller.signal, maxTurns: 4, turnTimeoutMs: 1_000, + ...(capturedByHost ? { reasoningEffortForSeat: (seat) => captured.get(seat.id)! } : {}), + cliSeatTurn: async (params, onDelta) => { + cliCalls.push(params) + if (cliCalls.length === 1) for (const seat of seats) seat.reasoningEffort = 'medium' + const text = reply(params.model); onDelta(text); return text + }, + }) + } finally { clearTimeout(timer) } + assert.equal(room.state, 'complete', JSON.stringify(room.events)) + const efforts = transport === 'http' ? requests.slice(start).map(call => call.reasoning_effort) + : cliCalls.map(call => call.reasoningEffort) + assert.equal(efforts.length, 2, 'each real room run reaches both agents once') + observed.push({ transport, global, efforts }) + expected.push({ transport, global, efforts: [alpha ?? global, beta ?? global] }) + } + } + assert.deepEqual(observed, expected, 'HTTP and CLI room requests must retain each agent effort captured before turns start') + afterRequest = () => {} + const seat = { id: 'compact', name: 'Compact', role: 'Review input', providerId: 'alpha', model: 'alpha' } + const runtime: SeatRuntime = { seat, reasoningEffort: 'low', recent: [], heartbeat: initSeatHeartbeat(seat, 30, 1), + messages: Array.from({ length: 22 }, () => ({ role: 'user', content: 'Synthetic earlier context. '.repeat(20) })) } + const provider: Provider = { id: 'alpha', name: 'Synthetic API', kind: 'local', baseUrl, apiKey: '', models: ['alpha'] } + const before = requests.length + const compacted = await compactSeatRuntime(runtime, provider, 1, AbortSignal.timeout(2_000)) + assert.ok(compacted && compacted.folded > 0, 'real compaction folds earlier messages') + assert.equal(requests.length, before + 1) + assert.equal(requests.at(-1)?.reasoning_effort, 'low', 'private transcript compaction uses the same captured effort') + console.log('Room effort checks passed: HTTP/CLI requests, opposite agent/app settings, legacy fallback and startup snapshots.') +} finally { + server.closeAllConnections() + await new Promise(resolve => server.close(() => resolve())) +} diff --git a/app/electron/agent/room-reasoning-store.test.ts b/app/electron/agent/room-reasoning-store.test.ts new file mode 100644 index 00000000000..264a1ad8470 --- /dev/null +++ b/app/electron/agent/room-reasoning-store.test.ts @@ -0,0 +1,47 @@ +import assert from 'node:assert/strict' +import { promises as fs } from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import { execFileSync } from 'node:child_process' +import { fileURLToPath } from 'node:url' +import type { Room, Ticket } from './types' + +if (process.argv.includes('--reload')) { + const { loadRooms, loadTickets } = await import('../store') + const rooms = await loadRooms() + assert.equal(rooms.length, 1) + assert.deepEqual(rooms[0].seats.map(seat => seat.reasoningEffort), ['low', 'high', undefined]) + assert.equal(Object.hasOwn(rooms[0].seats[2], 'reasoningEffort'), false) + assert.equal((await loadTickets())[0].execution?.reasoningEffort, 'low', 'the settled worker capture survives reload') + console.log('A fresh process loaded the saved per-agent efforts and legacy fallback.') +} else { + const profile = await fs.mkdtemp(path.join(os.tmpdir(), 'tensorfold-room-effort-store-')) + const previousHome = process.env.VONTRA_HOME + process.env.VONTRA_HOME = profile + try { + const { saveRooms, saveTickets } = await import('../store') + const seat = { name: 'Reviewer', role: 'Review supplied input', providerId: 'fixture', model: 'fixture' } + const room: Room = { + id: 'room-effort', projectId: 'project', name: 'Synthetic room', problem: 'Review supplied input', + seats: [{ ...seat, id: 'low', reasoningEffort: 'low' }, { ...seat, id: 'high', reasoningEffort: 'high' }, + { ...seat, id: 'legacy' }], + state: 'ready', events: [], finalText: '', createdAt: 1, updatedAt: 1, + } + await saveRooms([room]) + const ticket: Ticket = { id: 'ticket', projectId: 'project', roomId: room.id, title: 'Synthetic work', body: '', + type: 'task', status: 'review', priority: 'medium', effort: 'small', tags: [], parentId: null, + assignee: 'Reviewer', threadId: 'worker', runState: 'done', order: 1, createdAt: 1, updatedAt: 2, + execution: { target: 'room', threadId: 'worker', reasoningEffort: 'low', startedAt: 1, finishedAt: 2, + checks: [], blockers: [], reviewVerdict: 'pending' } } + await saveTickets([ticket]) + const output = execFileSync(process.execPath, [ + 'node_modules/jiti/lib/jiti-cli.mjs', fileURLToPath(import.meta.url), '--reload', + ], { env: process.env, timeout: 15_000, encoding: 'utf8' }) + assert.match(output, /A fresh process loaded the saved per-agent efforts and legacy fallback/) + console.log('Protected Room settings survive a process restart without converting legacy defaults.') + } finally { + if (previousHome === undefined) delete process.env.VONTRA_HOME + else process.env.VONTRA_HOME = previousHome + await fs.rm(profile, { recursive: true, force: true }) + } +} diff --git a/app/electron/agent/room-seat-runtime.ts b/app/electron/agent/room-seat-runtime.ts new file mode 100644 index 00000000000..7be5de1f0ae --- /dev/null +++ b/app/electron/agent/room-seat-runtime.ts @@ -0,0 +1,107 @@ +import type { ApiMessage, Provider, Seat, SeatHeartbeat } from './types' +import type { RoomRunDeps, RoomSend } from './rooms' +import { streamChat } from './openai' +import { estimateTokens, renderTranscript } from './compaction' +import { ensureTensorFoldStudioStylePrompt } from './prompt-style' +import { isCliSeatProvider, runCliSeatTurn, type CliSeatTurnParams } from './room-cli-seat' + +export interface SeatRuntime { + seat: Seat + reasoningEffort: string + messages: { role: 'system' | 'user' | 'assistant'; content: string }[] + recent: string[] + heartbeat: SeatHeartbeat +} + +const ROOM_KEEP_PREFIX = 2 // system primer + SENSE/task +const ROOM_KEEP_RECENT = 8 + +async function summarizeRoomTranscript(provider: Provider, model: string, transcript: string, reasoningEffort: string, signal: AbortSignal): Promise { + const sys = ensureTensorFoldStudioStylePrompt([ + 'Compress a multi-agent room seat transcript into a dense private memory.', + 'Preserve the task, decisions, claims, blockers, files/tools used, open tickets, and anything directly addressed to this seat.', + 'Use terse bullets. Output only the summary.', + ].join('\n')) + let out = '' + for await (const ch of streamChat({ + provider, + baseUrl: provider.baseUrl, + apiKey: provider.apiKey, + model, + messages: [{ role: 'system', content: sys }, { role: 'user', content: transcript }], + temperature: 0.1, + reasoningEffort, + approvalMode: 'readonly', + cwd: null, + signal, + })) { + if (ch.type === 'content') out += ch.text + } + return out.trim() +} + +export async function compactSeatRuntime(rt: SeatRuntime, provider: Provider, limit: number, signal: AbortSignal): Promise<{ before: number; after: number; folded: number } | null> { + if (limit <= 0) return null + const before = estimateTokens(rt.messages as ApiMessage[]) + if (before <= limit) return null + const prefix = Math.min(ROOM_KEEP_PREFIX, rt.messages.length) + const cut = Math.max(prefix, rt.messages.length - ROOM_KEEP_RECENT) + if (cut - prefix < 2) return null + const toCompress = rt.messages.slice(prefix, cut) + const summary = await summarizeRoomTranscript(provider, rt.seat.model, renderTranscript(toCompress as ApiMessage[]), rt.reasoningEffort, signal) + if (!summary) return null + rt.messages = [ + ...rt.messages.slice(0, prefix), + { role: 'user', content: `[Earlier private room context auto-compacted to protect this model's context window. Running memory:]\n\n${summary}` }, + ...rt.messages.slice(cut), + ] + return { before, after: estimateTokens(rt.messages as ApiMessage[]), folded: toCompress.length } +} + +const DEFAULT_SEAT_TURN_TIMEOUT_MS = 180_000 + +export function createRoomSeatTurn(deps: RoomRunDeps, send: (event: RoomSend) => void) { + const { project, signal } = deps + const chat = deps.chat ?? streamChat + const cliSeatTurn = deps.cliSeatTurn ?? ((params: CliSeatTurnParams, onDelta: (text: string) => void) => runCliSeatTurn(params, onDelta)) + const streamSeatReply = async (rt: SeatRuntime, provider: Provider, turnSignal: AbortSignal): Promise => { + // CLI-backed seats run as a confined one-shot CLI invocation (room-cli-seat.ts); the + // per-turn timeout/abort wrapper in runSeatTurn applies unchanged either way. + if (isCliSeatProvider(provider)) { + return cliSeatTurn( + { provider, model: rt.seat.model, messages: rt.messages as ApiMessage[], cwd: project.cwd, reasoningEffort: rt.reasoningEffort, signal: turnSignal }, + (text) => send({ type: 'delta', seat: rt.seat.name, chunk: text }), + ) + } + let reply = '' + for await (const chunk of chat({ + provider, + baseUrl: provider.baseUrl, apiKey: provider.apiKey, model: rt.seat.model, + messages: rt.messages, temperature: deps.temperature, reasoningEffort: rt.reasoningEffort, approvalMode: 'readonly', cwd: project.cwd, signal: turnSignal, + })) { + if (chunk.type === 'content' && chunk.text) { reply += chunk.text; send({ type: 'delta', seat: rt.seat.name, chunk: chunk.text }) } + } + return reply + } + + // Run one seat turn under a per-turn timeout combined with the room signal. If the seat's model + // hangs/stalls, the turn is aborted (timedOut=true) and skipped so other models keep going, rather + // than the whole room freezing behind one slow seat. + return async (rt: SeatRuntime, provider: Provider): Promise<{ reply: string; timedOut: boolean }> => { + const timeoutMs = deps.turnTimeoutMs ?? DEFAULT_SEAT_TURN_TIMEOUT_MS + const ctrl = new AbortController() + const onAbort = () => ctrl.abort() + signal.addEventListener('abort', onAbort, { once: true }) + let timedOut = false + const timer = timeoutMs > 0 ? setTimeout(() => { timedOut = true; ctrl.abort() }, timeoutMs) : null + try { + return { reply: await streamSeatReply(rt, provider, ctrl.signal), timedOut: false } + } catch (e) { + if (timedOut) return { reply: '', timedOut: true } + throw e + } finally { + if (timer) clearTimeout(timer) + signal.removeEventListener('abort', onAbort) + } + } +} diff --git a/app/electron/agent/rooms.ts b/app/electron/agent/rooms.ts index b318ef31902..828ac93136f 100644 --- a/app/electron/agent/rooms.ts +++ b/app/electron/agent/rooms.ts @@ -1,38 +1,21 @@ +import { createRoomSeatTurn, compactSeatRuntime, type SeatRuntime } from './room-seat-runtime' +import { seatHeartbeatIntervalSeconds, initSeatHeartbeat, recordSeatBeat, stalledSeatNames, rearmSeatHeartbeats, evaluateSeatHeartbeats } from './room-heartbeats' +export { seatHeartbeatIntervalSeconds, initSeatHeartbeat, recordSeatBeat, stalledSeatNames, rearmSeatHeartbeats, evaluateSeatHeartbeats } from './room-heartbeats' +export type { SeatRuntimeLike } from './room-heartbeats' +import { buildPrimer, gateAction, renderForRoom, signature, blockerSignature, oneLine, roomTeamCue, escapeReg } from './room-protocol' import { randomUUID } from 'node:crypto' -import { streamChat } from './openai' -import { isExternalProvider } from '../../shared/provider-trust' -import { PROJECT_CONTEXT_WITHHELD_NOTE } from './planning-guard' -import { estimateTokens, kfmt, renderTranscript } from './compaction' -import { VONTRA_STYLE_PROMPT, ensureTensorFoldStudioStylePrompt } from './prompt-style' -import type { ApiMessage, Project, Provider, Room, RoomDeliberationEffort, RoomEventItem, RoomState, RoomStreamEvent, Seat, SeatHeartbeat } from './types' -import { buildRoomMemoryDiff, buildRoomRunMemoryEntry, deliberationBudgetText, deliberationProfile, formatRoomMemory, inferSeatLane, mergeRoomMemory, normalizeCollaborationMode, normalizeDeliberationEffort, roomShouldCloseOut, seatCollaborationInstructions, updateRoomMemorySummary } from './room-collaboration' +import { captureAgentReasoningEffort } from '../../shared/reasoning-effort' +import type { streamChat } from './openai' +import { kfmt } from './compaction' +import type { Project, Provider, Room, RoomEventItem, RoomState, RoomStreamEvent, Seat, SeatHeartbeat } from './types' +import { buildRoomMemoryDiff, buildRoomRunMemoryEntry, deliberationBudgetText, deliberationProfile, inferSeatLane, mergeRoomMemory, normalizeCollaborationMode, normalizeDeliberationEffort, roomShouldCloseOut, updateRoomMemorySummary } from './room-collaboration' import { validateRoomConfiguration, validateRoomTransition } from './room-invariants' -import { roomModePromptBlock, roomOutcomeGate, roomOutcomeProfile } from './room-outcomes' +import { roomOutcomeGate, roomOutcomeProfile } from './room-outcomes' import { renderSharedMemory } from './shared-room-memory' -import { isCliSeatProvider, runCliSeatTurn, type CliSeatTurnParams } from './room-cli-seat' +import type { CliSeatTurnParams } from './room-cli-seat' import { recordRoomEvent } from './orchestration-journal' import { emitRoomLifecycle } from '../main/host/orchestration-events' -// Ported from LLMComposer's room/huddle engine: multiple provider-bound seats -// deliberate on one shared problem as an attributed dialogue, with SENSE -// injection so each seat knows it is one of several real teammates. - -const VERBS = new Set(['SPEAK', 'ASK', 'OBJECT', 'ASSIGN', 'CLAIM', 'CHECK', 'VOTE', 'YIELD', 'FINAL', 'TOOL']) - -interface SeatRuntime { - seat: Seat - messages: { role: 'system' | 'user' | 'assistant'; content: string }[] - recent: string[] - heartbeat: SeatHeartbeat -} - -// Minimal shape the heartbeat helpers need — lets tests exercise stall detection -// without standing up a full SeatRuntime (messages/recent are irrelevant here). -export interface SeatRuntimeLike { - seat: Pick - heartbeat: SeatHeartbeat -} - interface SeatModelRecovery { provider: Provider providerAccountId: string | null @@ -40,242 +23,6 @@ interface SeatModelRecovery { notice: string } -// Default grace after nextDueAt before a slow seat is flagged stalled (BUG #53). -// Tolerates transient model latency so a normal slow turn does not false-positive. -const SEAT_STALL_GRACE_SECONDS = 30 - -// Heartbeat cadence derived from the room deliberation effort. Deeper sessions -// expect longer per-turn thinking, so we widen the interval to avoid false stalls. -export function seatHeartbeatIntervalSeconds(effort?: RoomDeliberationEffort | null): number { - switch (effort) { - case 'quick': return 30 - case 'deep': return 90 - case 'max': return 120 - case 'normal': - default: return 60 - } -} - -// Seed a healthy heartbeat for a seat at room start. -export function initSeatHeartbeat(seat: Pick, intervalSeconds: number, now: number): SeatHeartbeat { - return { - seatId: seat.id, - seatName: seat.name, - intervalSeconds, - stallGraceSeconds: SEAT_STALL_GRACE_SECONDS, - required: true, - count: 0, - lastBeatAt: now, - nextDueAt: now + intervalSeconds * 1000, - missedSince: null, - } -} - -// Record that a seat produced a turn: bump count, advance the clock, clear any stall. -export function recordSeatBeat(hb: SeatHeartbeat, now: number): void { - hb.count++ - hb.lastBeatAt = now - hb.nextDueAt = hb.required ? now + hb.intervalSeconds * 1000 : null - hb.missedSince = null -} - -// Names of seats currently flagged stalled (missedSince set), excluding one seat -// by name (the seat trying to FINAL is obviously alive). Used to block a premature -// finalize while a teammate is hung (BUG #53). -export function stalledSeatNames(runtimes: SeatRuntimeLike[], exclude?: string): string[] { - return runtimes - .filter((rt) => rt.heartbeat.required && rt.heartbeat.missedSince != null && rt.seat.name !== exclude) - .map((rt) => rt.seat.name) -} - -// Re-arm the stall window for seats that actually took a turn in the previous pass. -// A single pass over several slow models can take longer than interval+grace, so a -// seat that beat last pass and is merely waiting its turn must not be false-flagged; -// pushing its nextDueAt forward to this pass start prevents that. Crucially, seats -// that did NOT run last pass (e.g. one that keeps timing out without ever calling -// recordSeatBeat, or any seat on the very first pass) are left untouched so their -// window keeps counting and evaluateSeatHeartbeats can actually flag a real stall — -// re-arming every non-stalled seat unconditionally is what made stall detection dead -// code (BUG #53 regression). -export function rearmSeatHeartbeats( - runtimes: SeatRuntimeLike[], - ranLastPass: Set, - passStart: number, -): void { - for (const rt of runtimes) { - const hb = rt.heartbeat - if (hb.required && hb.missedSince == null && ranLastPass.has(rt.seat.id)) { - hb.nextDueAt = passStart + hb.intervalSeconds * 1000 - } - } -} - -// Detect seats whose turn is overdue past the grace window. Mutates each newly -// stalled heartbeat's missedSince so a stall is reported once (not every tick), -// and returns human-readable notices for the moderator to surface. -export function evaluateSeatHeartbeats(runtimes: SeatRuntimeLike[], now: number): string[] { - const stalled: string[] = [] - for (const rt of runtimes) { - const hb = rt.heartbeat - if (!hb.required || hb.lastBeatAt == null || hb.nextDueAt == null) continue - if (hb.missedSince != null) continue // already flagged; do not re-report - const stallAt = hb.nextDueAt + hb.stallGraceSeconds * 1000 - if (now >= stallAt) { - hb.missedSince = hb.nextDueAt - const ago = Math.round((now - hb.lastBeatAt) / 1000) - stalled.push(`Seat "${rt.seat.name}": heartbeat overdue (last beat ${ago}s ago)`) - } - } - return stalled -} - -const ROOM_KEEP_PREFIX = 2 // system primer + SENSE/task -const ROOM_KEEP_RECENT = 8 - -function buildPrimer(project: Project, room: Room, seat: Seat, roster: Seat[], provider?: Provider): string { - const rosterText = roster.map((s) => `- ${s.name}: ${s.role} (model ${s.model})`).join('\n') - const roomMemory = formatRoomMemory(room) - const sharedMemory = room.sharedMemory ? renderSharedMemory(room.sharedMemory) : '' - return [ - `You are ${seat.name} in a live multi-agent working session with the teammates below.`, - '', - `ROOM ROLE\nYour visible room role is ${seat.role}. Use it to decide when to volunteer, challenge, defer, or take a ticket, but keep your general reasoning intact.`, - `\n${seatCollaborationInstructions(room, seat, provider)}`, - roomOutcomeProfile(room.mode) ? `\nROOM OUTCOME\n${roomModePromptBlock(roomOutcomeProfile(room.mode)!)}` : '', - project.team ? `\nTEAM CHARTER\n${project.team}` : '', - // External seats plan only and never see project memory (planning-guard.ts). - project.memory ? (isExternalProvider(provider) ? `\n${PROJECT_CONTEXT_WITHHELD_NOTE}` : `\nPROJECT MEMORY\n${project.memory}`) : '', - roomMemory ? `\nROOM MEMORY\n${roomMemory}` : '', - sharedMemory ? `\n${sharedMemory}` : '', - '', - 'ROOM CONTRACT', - 'Messages tagged [room] are what teammates actually said; [moderator] hands you the floor.', - 'Speak in first person, briefly and concretely. React to what was just said instead of restating it.', - "Never write [room] or [moderator] lines yourself, and never invent a teammate's reply.", - 'Never repeat a question or point you already made.', - 'End every reply with exactly one line: ACTION: .', - 'Verbs: SPEAK, ASK, OBJECT, ASSIGN, CLAIM, CHECK, VOTE, YIELD, FINAL, TOOL.', - 'ACTION: ASK addresses one teammate by name. ACTION: FINAL ends the room only when the task is genuinely done.', - 'When you answer a specific ASK or ASSIGN, cite it by appending RE: # to your ACTION line so the reply links back to the question.', - 'Only state what you can actually see in the [room] lines above. Do not claim progress that has not happened.', - '', - 'TEAMWORK CONTRACT', - 'Make handoffs explicit. If a teammate asks or assigns you something, answer that first and say what you are unblocking for them.', - 'Help the room finish the user goal: create or claim concrete tickets, attach evidence, start workers when ready, and yield when waiting.', - 'If you disagree, name the risk and offer the next useful move instead of reopening the whole plan.', - '', - VONTRA_STYLE_PROMPT, - '', - 'SHARED BOARD: coordinate through it so you never duplicate a teammate\'s work:', - 'ACTION: TOOL list_tickets: see every ticket and who is working on what.', - 'ACTION: TOOL claim_ticket {"title":"..."}: claim a ticket BEFORE you start it, so teammates know it is taken.', - 'ACTION: TOOL create_ticket {"title":"...","body":"...","priority":"high","risk":"medium","allowedCapabilities":["read"],"requiredEvidence":["files inspected","verification result"],"acceptanceCriteria":["..."]}: add an execution ticket to the board.', - 'ACTION: TOOL add_ticket_evidence {"title":"...","kind":"file","summary":"What you found","ref":"src/file.ts"}: attach evidence to a claimed ticket.', - 'ACTION: TOOL complete_ticket {"title":"...","evidence":[{"kind":"review","summary":"Reviewed X and found Y"}]}: mark your claimed ticket complete after attaching required evidence.', - 'ACTION: TOOL left_to_work: see the remaining room tickets, active workers, risks, and known file refs.', - 'ACTION: TOOL memory_write {"name":"decisions","content":"...","mode":"append-bullet"}: update the room\'s live shared memory (decisions, plan, blockers). Teammates see updates on their next turn.', - 'ACTION: TOOL start_ticket_work {"title":"...","phase":"build","paths":["src/x.ts"]}: ask the Room Supervisor to start a ticket worker thread in the room worktree. Use phase "review" for reviewer passes. If a file overlap is intentional, include "mergeDecision":"why this overlap is safe and how results will be merged".', - 'ACTION: TOOL delegate {"task":"..."}: hand a focused subtask to a sub-agent and get its result. Add "targetSeat":"SeatName" to run it on that seat\'s provider/model, or "providerId"/"accountId"/"model" for an explicit route; omit them to use your own.', - 'Always claim before working; never touch a ticket already claimed by someone else.', - 'Only start ticket workers for claimed or ready tickets. Declare paths when you know them so the supervisor can prevent overlapping edits.', - 'Do not ACTION: FINAL while room tickets are still open.', - '', - 'WORKSPACE: inspect the shared project safely:', - 'ACTION: TOOL read_file {"path":"src/x.ts"}: read a file.', - 'ACTION: TOOL search {"query":"..."}: find relevant code.', - 'ACTION: TOOL list_dir {"path":"src"}: inspect folders.', - 'Room agents are read-only by default. Do not attempt edit_file, write_file, or run_command unless the user opens an approved work thread for that ticket.', - 'When you know the change needed, create/claim a ticket and explain the proposed edit for an approved thread to execute.', - '', - 'TEAM ROSTER', - rosterText, - ].filter(Boolean).join('\n') -} - -interface Action { verb: string; text: string; raw: string; prose?: string } - -// Lenient gate: missing action becomes SPEAK, empty body becomes YIELD. -function gateAction(output: string): Action { - const raw = (output ?? '').trim() - if (!raw) return { verb: 'YIELD', text: '', raw } - const lines = raw.split('\n') - const actionLine = [...lines].reverse().find((l) => l.trim().toUpperCase().startsWith('ACTION:')) - const prose = lines.filter((l) => l !== actionLine).join('\n').trim() - if (!actionLine) return { verb: 'SPEAK', text: prose || raw, raw } - const body = actionLine.trim().slice(actionLine.trim().indexOf(':') + 1).trim() - const parts = body.split(/\s+/) - const verb = (parts[0] || '').toUpperCase() - const text = parts.slice(1).join(' ').trim() - if (!VERBS.has(verb)) return { verb: 'SPEAK', text: prose || raw, raw } - if (!text && verb !== 'YIELD') return { verb: 'YIELD', text: '', raw } - // Keep the prose so peers receive the model's actual reasoning, not just the one-line ACTION tagline. - return { verb, text, raw, prose } -} - -function renderForRoom(ev: RoomEventItem, compact = false): string { - const label = ev.kind.toUpperCase() - // Addressed asks/assigns carry a short ref (#id8) so a teammate can answer with - // "RE: #"; replies show the ref they answer (re #id8). - const ref = (ev.kind === 'ask' || ev.kind === 'assign') ? ` #${ev.id.slice(0, 8)}` : '' - const reply = ev.replyTo ? ` re #${ev.replyTo.slice(0, 8)}` : '' - if (compact) return `[room] ${ev.seat} (${label}${reply}): ${ev.text}` - const head = ev.target && ev.target !== 'all' && ev.target !== ev.seat - ? `[room] ${ev.seat} (${label}, to ${ev.target}${ref}${reply}):` - : `[room] ${ev.seat} (${label}${ref}${reply}):` - return `${head}\n${ev.text}` -} - -function signature(raw: string): string { - return raw.split('\n').filter((l) => !l.trim().toUpperCase().startsWith('ACTION:')).join(' ').trim().toLowerCase().slice(0, 400) -} - -function blockerSignature(blockers: string[]): string { - return blockers.map((blocker) => blocker.replace(/\s+/g, ' ').trim().toLowerCase()).filter(Boolean).join('\n') -} - -function oneLine(text: string, max = 180): string { - const compact = text.replace(/\s+/g, ' ').trim() - return compact.length > max ? `${compact.slice(0, Math.max(0, max - 3))}...` : compact -} - -function roomTeamCue(room: Room, seat: Seat): string { - const recent = room.events.filter((event) => !['task', 'notice', 'user'].includes(event.kind)).slice(-10) - const directHandoffs = recent.filter((event) => (event.kind === 'ask' || event.kind === 'assign') && event.target === seat.name) - const latestDirect = directHandoffs[directHandoffs.length - 1] - const latestOtherHandoff = recent.filter((event) => - (event.kind === 'ask' || event.kind === 'assign') && - !!event.target && - event.target !== 'all' && - event.target !== seat.name - ).slice(-1)[0] - const latestClaim = recent.filter((event) => event.kind === 'claim').slice(-1)[0] - const latestUserSteer = room.events - .filter((event) => event.kind === 'user' && (event.target === 'all' || event.target === seat.name)) - .slice(-1)[0] - const cue: string[] = [] - - if (latestUserSteer) { - cue.push(`USER STEERING: "${oneLine(latestUserSteer.text, 220)}". Treat this as the user's latest direction and respond to it before lower-priority room chatter.`) - } - - if (latestDirect) { - cue.push(`TEAM CUE: ${latestDirect.seat} handed work to you: "${oneLine(latestDirect.text, 220)}". Answer or unblock that first, naming ${latestDirect.seat}.`) - } else if (latestOtherHandoff) { - cue.push(`TEAM CUE: ${latestOtherHandoff.seat} handed work to ${latestOtherHandoff.target}. Let that teammate respond unless you can unblock with new evidence.`) - } - - if (latestClaim) { - cue.push(`Latest claim: ${latestClaim.seat} claimed "${oneLine(latestClaim.text, 120)}". Build on it and do not duplicate it.`) - } - - cue.push('Work like a teammate: reference who you are helping, answer direct asks before new topics, create or claim the next useful ticket, start workers when ready, and ACTION: YIELD if you are waiting.') - return cue.join(' ') -} - -function escapeReg(s: string): string { - return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') -} - const ALWAYS_FULL = new Set(['final', 'task', 'user', 'file_change']) // `excludeSeatId` is a seat ID (not name): keying on id means two seats that happen to share a name @@ -290,50 +37,9 @@ function broadcast(runtimes: SeatRuntime[], item: RoomEventItem, excludeSeatId: } } -async function summarizeRoomTranscript(provider: Provider, model: string, transcript: string, signal: AbortSignal): Promise { - const sys = ensureTensorFoldStudioStylePrompt([ - 'Compress a multi-agent room seat transcript into a dense private memory.', - 'Preserve the task, decisions, claims, blockers, files/tools used, open tickets, and anything directly addressed to this seat.', - 'Use terse bullets. Output only the summary.', - ].join('\n')) - let out = '' - for await (const ch of streamChat({ - provider, - baseUrl: provider.baseUrl, - apiKey: provider.apiKey, - model, - messages: [{ role: 'system', content: sys }, { role: 'user', content: transcript }], - temperature: 0.1, - approvalMode: 'readonly', - cwd: null, - signal, - })) { - if (ch.type === 'content') out += ch.text - } - return out.trim() -} - -async function compactSeatRuntime(rt: SeatRuntime, provider: Provider, limit: number, signal: AbortSignal): Promise<{ before: number; after: number; folded: number } | null> { - if (limit <= 0) return null - const before = estimateTokens(rt.messages as ApiMessage[]) - if (before <= limit) return null - const prefix = Math.min(ROOM_KEEP_PREFIX, rt.messages.length) - const cut = Math.max(prefix, rt.messages.length - ROOM_KEEP_RECENT) - if (cut - prefix < 2) return null - const toCompress = rt.messages.slice(prefix, cut) - const summary = await summarizeRoomTranscript(provider, rt.seat.model, renderTranscript(toCompress as ApiMessage[]), signal) - if (!summary) return null - rt.messages = [ - ...rt.messages.slice(0, prefix), - { role: 'user', content: `[Earlier private room context auto-compacted to protect this model's context window. Running memory:]\n\n${summary}` }, - ...rt.messages.slice(cut), - ] - return { before, after: estimateTokens(rt.messages as ApiMessage[]), folded: toCompress.length } -} - // Distributive Omit so each union member keeps its own payload keys // (a plain Omit collapses to the members' common keys only). -type RoomSend = RoomStreamEvent extends infer T ? (T extends any ? Omit : never) : never +export type RoomSend = RoomStreamEvent extends infer T ? (T extends any ? Omit : never) : never export interface RoomRunDeps { room: Room @@ -342,6 +48,7 @@ export interface RoomRunDeps { problem: string temperature: number reasoningEffort: string + reasoningEffortForSeat?: (seat: Seat) => string emit: (e: RoomStreamEvent) => void signal: AbortSignal maxTurns?: number @@ -361,8 +68,6 @@ export interface RoomRunDeps { turnTimeoutMs?: number } -const DEFAULT_SEAT_TURN_TIMEOUT_MS = 180_000 - export async function runRoom(deps: RoomRunDeps): Promise { const { room, project, providers, problem, emit, signal } = deps const outcome = roomOutcomeProfile(room.mode) @@ -384,53 +89,13 @@ export async function runRoom(deps: RoomRunDeps): Promise { return true } const providerForSeat = (seat: Seat) => deps.providerForSeat?.(seat) ?? providers.find((p) => p.id === seat.providerId) - const chat = deps.chat ?? streamChat - const cliSeatTurn = deps.cliSeatTurn ?? ((params: CliSeatTurnParams, onDelta: (text: string) => void) => runCliSeatTurn(params, onDelta)) - const streamSeatReply = async (rt: SeatRuntime, provider: Provider, turnSignal: AbortSignal): Promise => { - // CLI-backed seats run as a confined one-shot CLI invocation (room-cli-seat.ts); the - // per-turn timeout/abort wrapper in runSeatTurn applies unchanged either way. - if (isCliSeatProvider(provider)) { - return cliSeatTurn( - { provider, model: rt.seat.model, messages: rt.messages as ApiMessage[], cwd: project.cwd, reasoningEffort: deps.reasoningEffort, signal: turnSignal }, - (text) => send({ type: 'delta', seat: rt.seat.name, chunk: text }), - ) - } - let reply = '' - for await (const chunk of chat({ - provider, - baseUrl: provider.baseUrl, apiKey: provider.apiKey, model: rt.seat.model, - messages: rt.messages, temperature: deps.temperature, reasoningEffort: deps.reasoningEffort, approvalMode: 'readonly', cwd: project.cwd, signal: turnSignal, - })) { - if (chunk.type === 'content' && chunk.text) { reply += chunk.text; send({ type: 'delta', seat: rt.seat.name, chunk: chunk.text }) } - } - return reply - } - - // Run one seat turn under a per-turn timeout combined with the room signal. If the seat's model - // hangs/stalls, the turn is aborted (timedOut=true) and skipped so other models keep going, rather - // than the whole room freezing behind one slow seat. - const runSeatTurn = async (rt: SeatRuntime, provider: Provider): Promise<{ reply: string; timedOut: boolean }> => { - const timeoutMs = deps.turnTimeoutMs ?? DEFAULT_SEAT_TURN_TIMEOUT_MS - const ctrl = new AbortController() - const onAbort = () => ctrl.abort() - signal.addEventListener('abort', onAbort, { once: true }) - let timedOut = false - const timer = timeoutMs > 0 ? setTimeout(() => { timedOut = true; ctrl.abort() }, timeoutMs) : null - try { - return { reply: await streamSeatReply(rt, provider, ctrl.signal), timedOut: false } - } catch (e) { - if (timedOut) return { reply: '', timedOut: true } - throw e - } finally { - if (timer) clearTimeout(timer) - signal.removeEventListener('abort', onAbort) - } - } + const runSeatTurn = createRoomSeatTurn(deps, send) const heartbeatInterval = seatHeartbeatIntervalSeconds(room.deliberationEffort) const heartbeatStart = Date.now() const runtimes: SeatRuntime[] = room.seats.map((seat) => ({ seat, + reasoningEffort: deps.reasoningEffortForSeat?.(seat) ?? captureAgentReasoningEffort(seat, deps.reasoningEffort), messages: [{ role: 'system', content: buildPrimer(project, room, seat, room.seats, providerForSeat(seat)) }], recent: [], heartbeat: initSeatHeartbeat(seat, heartbeatInterval, heartbeatStart), diff --git a/app/electron/agent/ticket-review-build.test.ts b/app/electron/agent/ticket-review-build.test.ts new file mode 100644 index 00000000000..b983eeb0934 --- /dev/null +++ b/app/electron/agent/ticket-review-build.test.ts @@ -0,0 +1,106 @@ +import assert from 'node:assert/strict' +import { summarizeTicketWorkerOutcome } from '../main/host/ticket-helpers' +import { roomFinalGateBlockers, ticketNeedsReviewAfterBuilder, ticketReviewGateState } from './tickets' +import type { Thread, Ticket, TicketEvidence } from './types' + +const build: TicketEvidence = { id: 'build', kind: 'file', summary: 'Inspected src/parser.ts.', createdBy: 'Builder', createdAt: 10 } +const approval: TicketEvidence = { id: 'approval', kind: 'review', summary: 'Reviewer approved.', createdBy: 'Reviewer', createdAt: 20 } +const rebuild: TicketEvidence = { ...build, id: 'rebuild', summary: 'Inspected the follow-up implementation.', createdAt: 30 } +const waiver: TicketEvidence = { ...approval, id: 'waiver', kind: 'note', summary: 'Review skipped: read-only source lookup, no code changes.' } + +function ticket(evidence: TicketEvidence[]): Ticket { + return { + id: 'ticket-fixture', projectId: 'project-fixture', roomId: 'room-fixture', title: 'Follow-up implementation', body: '', + type: 'task', status: 'completed', priority: 'medium', effort: 'medium', tags: [], assignee: 'Builder', + parentId: null, threadId: null, runState: null, startedAt: null, order: 0, createdAt: 1, updatedAt: 90, + risk: 'high', allowedCapabilities: ['read'], requiredEvidence: ['Findings'], acceptanceCriteria: [], evidence, + } +} + +let passed = 0 +function check(name: string, evidence: TicketEvidence[], allowed: boolean, builder = 'Builder') { + const current = ticket(evidence) + assert.equal(ticketReviewGateState(current).hasReviewOrSkipAfterBuilder, allowed, name) + assert.equal(ticketReviewGateState(current).builderEvidenceBy, builder, name) + assert.equal(ticketNeedsReviewAfterBuilder(current), !allowed, name) + assert.deepEqual(roomFinalGateBlockers({ tickets: [current], greenEvidenceAt: 100 }), allowed ? [] + : ['review evidence after builder or justified skip missing on: Follow-up implementation.'], name) + passed++ +} + +function worker(phase: 'build' | 'review', at: number, createdBy: string | null, changes = false): TicketEvidence[] { + const now = Date.now + Date.now = () => at + try { + const thread = { + id: `${phase}-thread-${at}`, + timeline: [ + { id: 'read', kind: 'tool', path: 'src/parser.ts', state: 'ok' }, + ...(changes ? [{ id: 'edit', kind: 'tool', path: 'src/parser.ts', diff: [{ type: 'add', text: 'const value = 1' }], state: 'ok' }] : []), + { id: 'status', kind: 'tool', command: 'git status --short', output: '', state: 'ok' }, + { id: 'test', kind: 'tool', command: 'npm test', output: '2 passed', state: 'ok' }, + ], + } as unknown as Thread + return summarizeTicketWorkerOutcome(ticket([]), thread, phase, false, createdBy).evidence + } finally { Date.now = now } +} + +check('an approval does not cover later builder findings', [build, approval, rebuild], false) +check('timestamp order wins over insertion order', [rebuild, build, approval], false) +check('a fresh independent approval covers the rebuild', [build, approval, rebuild, { ...approval, id: 'fresh', createdAt: 40 }], true) +check('a waiver does not cover later builder findings', [build, waiver, rebuild], false) +check('a fresh justified waiver covers read-only work', [build, waiver, rebuild, { ...waiver, id: 'fresh-waiver', createdAt: 40 }], true) +check('a new builder is reported as the current builder', [build, approval, { ...rebuild, createdBy: 'Second builder' }], false, 'Second builder') +check('a review cannot cover a build at the same timestamp', [build, approval, { ...rebuild, createdAt: 20 }], false) + +const reviewBlocker: TicketEvidence = { + id: 'review-blocker', kind: 'note', summary: 'Blocker: parser validation failed.', + createdBy: 'Reviewer', createdAt: 20, ref: 'thread:review-fixture', +} +const blockedBatch = [{ ...approval, ref: reviewBlocker.ref }, reviewBlocker] +check('a reviewer blocker preserves the original builder identity', [build, ...blockedBatch], false) +check('reviewer blocker batches are independent of insertion order', [build, ...[...blockedBatch].reverse()], false) +check('a fresh approval resolves the reviewer blocker without a new build', [build, ...blockedBatch, { + ...approval, id: 'resolved', createdAt: 30, +}], true) +check('an unrelated note cannot inherit a review blocker batch', [build, ...blockedBatch.slice(0, 1), { + ...reviewBlocker, ref: 'thread:other-review', +}], true) +check('another actor cannot attach a review blocker batch', [build, blockedBatch[0], { + ...reviewBlocker, createdBy: 'Another actor', +}], true) +check('another timestamp cannot attach a review blocker batch', [build, blockedBatch[0], { + ...reviewBlocker, createdAt: 21, +}], true) +check('a blocker describing changed code is still a review finding', [build, blockedBatch[0], { + ...reviewBlocker, summary: 'Blocker: changed parser behavior fails validation.', +}], false) +check('an explicit empty blocker does not reject a review', [build, blockedBatch[0], { + ...reviewBlocker, summary: 'Blocker: none', +}], true) +check('a later builder run still invalidates approval without file events', [build, approval, { + ...build, id: 'builder-run', kind: 'note', summary: 'Builder worker finished the follow-up.', createdAt: 30, +}], false) + +const reviewRun = worker('review', 20, 'Reviewer') +const reviewOnly = ticket(reviewRun) +assert.deepEqual(ticketReviewGateState(reviewOnly), { hasBuilderEvidence: false, builderEvidenceBy: null, hasReviewOrSkipAfterBuilder: false }) +assert.equal(ticketNeedsReviewAfterBuilder(reviewOnly), false, 'a review cannot create builder evidence for another review') +assert.deepEqual(roomFinalGateBlockers({ tickets: [reviewOnly] }), ['review evidence after builder or justified skip missing on: Follow-up implementation.']) +passed++ +check('real reviewer verification is not a new build', [build, ...reviewRun], true) +check('review batch order does not alter builder ownership', [build, ...[...reviewRun].reverse()], true) +check('anonymous review batches keep the same verification behavior', [build, ...worker('review', 20, null)], true) +check('an actual later build worker invalidates the review', [build, ...reviewRun, ...worker('build', 30, 'Builder')], false) +check('a new review worker covers the actual rebuilt output', [build, ...reviewRun, ...worker('build', 30, 'Builder'), ...worker('review', 40, 'Reviewer')], true) + +const testResult = reviewRun.find((item) => item.kind === 'test')! +assert.ok(testResult, 'the host fixture must produce a verification record') +check('another thread cannot inherit a review batch exemption', [build, ...reviewRun, { ...testResult, id: 'other-thread', ref: 'thread:other-run' }], false, 'Reviewer') +check('another actor cannot inherit a review batch exemption', [build, ...reviewRun, { ...testResult, id: 'other-actor', createdBy: 'Second builder' }], false, 'Second builder') +check('a missing thread reference cannot inherit a review batch exemption', [build, ...reviewRun, { ...testResult, id: 'missing-ref', ref: null }], false, 'Reviewer') +check('a later run cannot reuse an earlier batch timestamp', [build, ...reviewRun, { ...testResult, id: 'later-run', createdAt: 30 }], false, 'Reviewer') +check('code changes made during a review still need independent review', [build, ...worker('review', 20, 'Reviewer', true)], false, 'Reviewer') +check('a different reviewer can approve the reviewer-made changes', [build, ...worker('review', 20, 'Reviewer', true), { ...approval, id: 'independent', createdBy: 'Second reviewer', createdAt: 30 }], true, 'Reviewer') + +console.log(`ticket review build freshness: ${passed} cases passed`) diff --git a/app/electron/agent/ticket-review-verdict.test.ts b/app/electron/agent/ticket-review-verdict.test.ts new file mode 100644 index 00000000000..cf6825a6a4a --- /dev/null +++ b/app/electron/agent/ticket-review-verdict.test.ts @@ -0,0 +1,53 @@ +import assert from 'node:assert/strict' +import { roomFinalGateBlockers, ticketNeedsReviewAfterBuilder, ticketReviewGateState } from './tickets' +import type { Ticket, TicketEvidence } from './types' + +const finding: TicketEvidence = { id: 'finding', kind: 'file', summary: 'Inspected src/parser.ts.', createdBy: 'Builder', createdAt: 10 } +const approved: TicketEvidence = { id: 'approved', kind: 'review', summary: 'Reviewer approved; no blockers.', createdBy: 'Reviewer', createdAt: 20 } +const blocked: TicketEvidence = { id: 'blocked', kind: 'review', summary: 'Changes requested: regression in empty input handling.', createdBy: 'Reviewer', createdAt: 30 } +const waived: TicketEvidence = { id: 'waived', kind: 'note', summary: 'Review skipped: read-only source lookup, no code changes.', createdBy: 'Reviewer', createdAt: 20 } + +function ticket(evidence: TicketEvidence[], patch: Partial = {}): Ticket { + return { + id: 'ticket-fixture', projectId: 'project-fixture', roomId: 'room-fixture', title: 'Review the parser', body: '', + type: 'task', status: 'completed', priority: 'medium', effort: 'medium', tags: [], assignee: 'Builder', + parentId: null, threadId: null, runState: null, startedAt: null, order: 0, createdAt: 1, updatedAt: 40, + risk: 'high', allowedCapabilities: ['read'], requiredEvidence: ['Findings'], acceptanceCriteria: [], evidence, ...patch, + } +} + +let passed = 0 +function check(name: string, evidence: TicketEvidence[], allowed: boolean) { + const current = ticket(evidence) + assert.equal(ticketReviewGateState(current).hasReviewOrSkipAfterBuilder, allowed, name) + assert.equal(ticketNeedsReviewAfterBuilder(current), !allowed, name) + assert.deepEqual(roomFinalGateBlockers({ tickets: [current] }), allowed ? [] + : ['review evidence after builder or justified skip missing on: Review the parser.'], name) + passed++ +} + +check('an independent approval completes the gate', [finding, approved], true) +check('an ordinary later note does not revoke approval', [finding, approved, { + ...finding, id: 'reminder', kind: 'note', summary: 'Follow up with the documentation team tomorrow.', createdAt: 30, +}], true) +check('a later note describing code changes still requires review', [finding, approved, { + ...finding, id: 'changed-note', kind: 'note', summary: 'Changed the parser implementation.', createdAt: 30, +}, { ...finding, id: 'later-green', kind: 'test', summary: 'Parser tests passed.', createdAt: 31 }], false) +check('a later blocking verdict supersedes approval', [finding, approved, blocked], false) +check('another reviewer can reopen a ticket', [finding, approved, { ...blocked, createdBy: 'Second reviewer' }], false) +check('a fresh approval resolves the blocking verdict', [finding, approved, blocked, { ...approved, id: 'fresh', createdAt: 40 }], true) +check('an older blocking verdict does not override a newer approval', [finding, blocked, { ...approved, createdAt: 40 }], true) +check('timestamps take precedence over array order', [finding, blocked, approved], false) +check('the last verdict wins at equal timestamps', [finding, approved, { ...blocked, createdAt: 20 }], false) +check('a same-timestamp follow-up approval can resolve the verdict', [finding, blocked, { ...approved, createdAt: 30 }], true) +check('informational review notes do not revoke approval', [finding, approved, { ...blocked, summary: 'Reviewer inspected the examples.' }], true) +check('user approval records are not reviewer verdicts', [finding, approved, { ...blocked, kind: 'note', summary: 'User approval rejected for a separate action.' }], true) +check('a later blocking verdict supersedes a waiver', [finding, waived, blocked], false) +check('a justified later waiver can resolve read-only review', [finding, blocked, { ...waived, createdAt: 40 }], true) +check('a later self-review cannot reuse an older independent approval', [finding, approved, { ...approved, id: 'self', createdBy: 'Builder', createdAt: 40 }], false) + +const changed: TicketEvidence = { ...finding, kind: 'diff', summary: 'Changed src/parser.ts.' } +const green: TicketEvidence = { id: 'green', kind: 'test', summary: 'Parser tests passed.', createdBy: 'Builder', createdAt: 11 } +check('an invalid code-change waiver cannot bypass a blocking verdict', [changed, green, approved, blocked, { ...waived, createdAt: 40 }], false) + +console.log(`ticket review verdict: ${passed} cases passed`) diff --git a/app/electron/agent/tickets.ts b/app/electron/agent/tickets.ts index e7a68828e3f..e8cfaaba3e7 100644 --- a/app/electron/agent/tickets.ts +++ b/app/electron/agent/tickets.ts @@ -236,13 +236,12 @@ export interface TicketReviewGateState { export function ticketReviewGateState(ticket: Ticket): TicketReviewGateState { const evidence = meaningfulTicketEvidence(ticket) - const builder = newestEvidence(evidence.filter(isBuilderEvidence)) - const review = newestReviewPassAfterBuilder(evidence) - const skip = newestReviewSkipAfterBuilder(evidence, ticket) + const builder = newestBuilderEvidence(evidence, ticket) + const review = newestReviewDecisionAfterBuilder(evidence, builder) return { hasBuilderEvidence: !!builder, builderEvidenceBy: builder?.createdBy ?? null, - hasReviewOrSkipAfterBuilder: !!review || !!skip, + hasReviewOrSkipAfterBuilder: !!review, } } @@ -264,27 +263,33 @@ function newestEvidence(items: TicketEvidence[]): TicketEvidence | null { }, null) } -function newestReviewPassAfterBuilder(evidence: TicketEvidence[]): TicketEvidence | null { - return newestEvidence(evidence.filter((item) => { - if (!isReviewPassEvidence(item)) return false - const builder = newestBuilderEvidenceBefore(evidence, item) - if (!builder) return false - return !sameEvidenceCreator(builder, item) - })) +function newestReviewDecisionAfterBuilder(evidence: TicketEvidence[], builder: TicketEvidence | null): TicketEvidence | null { + const canSkip = !evidence.some(isCodeChangeEvidence) + const decision = newestEvidence(evidence.filter((item) => + isReviewPassEvidence(item) || canSkip && isReviewSkipEvidence(item) + || hasReviewerSignal(item) && isBlockingReviewEvidence(item), + )) + if (!decision || !(isReviewPassEvidence(decision) || canSkip && isReviewSkipEvidence(decision))) return null + const batch = reviewBatchKey(decision) + if (batch && evidence.some((item) => item.kind === 'note' && reviewBatchKey(item) === batch + && /^Blocker:/i.test(item.summary) && isBlockingReviewEvidence(item))) return null + return builder && builder.createdAt < decision.createdAt && !sameEvidenceCreator(builder, decision) ? decision : null } -function newestReviewSkipAfterBuilder(evidence: TicketEvidence[], ticket: Ticket): TicketEvidence | null { - if (hasCodeChangeEvidence(ticket)) return null +function newestBuilderEvidence(evidence: TicketEvidence[], ticket: Ticket): TicketEvidence | null { + const reviewBatches = new Set(evidence.filter((item) => item.kind === 'review') + .map(reviewBatchKey).filter((key): key is string => key !== null)) return newestEvidence(evidence.filter((item) => { - if (!isReviewSkipEvidence(item)) return false - const builder = newestBuilderEvidenceBefore(evidence, item) - if (!builder) return false - return !sameEvidenceCreator(builder, item) + if (!isBuilderEvidence(item, ticket)) return false + const verification = item.kind === 'test' || item.kind === 'command' + const batch = reviewBatchKey(item) + return !verification || isCodeChangeEvidence(item) || batch === null || !reviewBatches.has(batch) })) } -function newestBuilderEvidenceBefore(evidence: TicketEvidence[], item: TicketEvidence): TicketEvidence | null { - return newestEvidence(evidence.filter((candidate) => isBuilderEvidence(candidate) && candidate.createdAt < item.createdAt)) +function reviewBatchKey(item: TicketEvidence): string | null { + if (!item.ref?.startsWith('thread:') || item.ref.length === 'thread:'.length) return null + return JSON.stringify([item.createdAt, item.createdBy ?? null, item.ref]) } function sameEvidenceCreator(a: TicketEvidence, b: TicketEvidence): boolean { @@ -307,12 +312,11 @@ function hasUnresolvedExternalDestructiveApproval(ticket: Ticket): boolean { return !approvalAt || approvalAt < actionAt } -function hasCodeChangeEvidence(ticket: Ticket): boolean { - return meaningfulTicketEvidence(ticket).some(isCodeChangeEvidence) -} - -function isBuilderEvidence(item: TicketEvidence): boolean { - return !isReviewEvidence(item) && !isReviewSkipEvidence(item) +function isBuilderEvidence(item: TicketEvidence, ticket: Ticket): boolean { + if (isReviewEvidence(item) || isReviewSkipEvidence(item)) return false + if (item.kind === 'note' && /^Blocker:/i.test(item.summary)) return false + return item.kind !== 'note' || isCodeChangeEvidence(item) || /^Builder worker\b/i.test(item.summary) + || isExternalDestructiveActionEvidence(item, ticket) } function isReservationEvidence(item: TicketEvidence): boolean { @@ -325,12 +329,15 @@ function isReviewEvidence(item: TicketEvidence): boolean { return item.kind === 'review' || /\b(reviewed|reviewer|verdict|approved|approval|blocking issues?|ready for final)\b/i.test(text) } +function hasReviewerSignal(item: TicketEvidence): boolean { + return item.kind === 'review' || /\b(reviewed|reviewer|review verdict|verdict)\b/i.test(evidenceText(item)) +} + function isReviewPassEvidence(item: TicketEvidence): boolean { if (isReviewSkipEvidence(item)) return false if (isBlockingReviewEvidence(item)) return false const text = evidenceText(item) - const reviewerSignal = item.kind === 'review' || /\b(reviewed|reviewer|review verdict|verdict)\b/i.test(text) - if (!reviewerSignal) return false + if (!hasReviewerSignal(item)) return false return /\b(approved|approval|pass(?:ed)?|verified|accepted|ready for final|ready to final|ready|finished|looks good|lgtm|no blockers?|no blocking issues?)\b/i.test(text) } diff --git a/app/electron/agent/types/rooms.ts b/app/electron/agent/types/rooms.ts new file mode 100644 index 00000000000..620d73feeed --- /dev/null +++ b/app/electron/agent/types/rooms.ts @@ -0,0 +1,173 @@ +import type { RoomMode } from '../room-outcomes' +import type { SharedMemoryState } from '../shared-room-memory' +import type { WorkspaceLocation } from './workspace' +import type { ReasoningEffortSetting } from './settings' + +// ---- Multi-agent Rooms (Project → Room → Seats) ---- +export interface Seat { + id: string + name: string + role: string + providerId: string + providerAccountId?: string | null + model: string + reasoningEffort?: ReasoningEffortSetting + lane?: RoomSeatLane + roleProfileId?: AgentRoleProfileId + fanOutBudget?: FanOutBudget +} + +// Per-seat liveness for room deliberation (BUG #53). Parallels MissionHeartbeat: +// tracks when a seat last took a turn so a stuck/slow seat surfaces as stalled +// instead of silently locking the room. Runtime-ephemeral — stored on Room. +export interface SeatHeartbeat { + seatId: string + seatName: string + intervalSeconds: number // expected cadence between turns + stallGraceSeconds: number // tolerance after nextDueAt before signalling a stall + required: boolean + count: number // turns this seat has taken + lastBeatAt: number | null // when the seat last took a turn + nextDueAt: number | null // when the next turn is expected + missedSince: number | null // when the stall was first detected (null = healthy) +} + +export type RoomSeatLane = 'planning' | 'development' | 'review' | 'research' | 'operations' + +export type AgentRoleProfileId = 'planner' | 'builder' | 'reviewer' | 'researcher' | 'operator' + +export type FanOutBudget = 'single' | 'paired' | 'council' | 'swarm' + +export type RoomCollaborationMode = + | 'balanced' + | 'frontier_plans_local_builds' + | 'local_private' + | 'frontier_council' + | 'supervisor' + +export type RoomDeliberationEffort = 'quick' | 'normal' | 'deep' | 'max' + +export interface RoomWorkerBudget { + maxActive: number + maxStarts: number +} + +export interface RoomMemoryEntry { + id: string + kind: 'summary' | 'decision' | 'preference' | 'finding' + text: string + source: 'manual' | 'room' + createdAt: number + updatedAt: number +} + +export interface RoomMemoryDiff { + added: RoomMemoryEntry[] + removed: RoomMemoryEntry[] + summaryChanged: boolean + previousCount: number + nextCount: number +} + +export type RoomManualMemoryCommand = + | { action: 'add'; kind: RoomMemoryEntry['kind']; text: string } + | { action: 'remove'; entryId: string } + +export type RoomState = + | 'idle' + | 'created' + | 'ready' + | 'degraded' + | 'queued' + | 'running' + | 'waiting_user' + | 'waiting_external' + | 'complete' + | 'stopped' + | 'failed' + | 'archived' + | 'error' + +export interface RoomEventItem { + id: string + tick: number + kind: string // task | speak | ask | assign | object | claim | check | vote | yield | final | tool | notice | error + seat: string // seat name | 'you' | 'system' | 'moderator' + target: string + text: string + replyTo?: string // for ask/assign — the room event id this message answers (lenient RE: marker) + tool?: string // for kind 'tool' — the tool name (read_file, edit_file, run_command, …) + args?: Record // for kind 'tool' — normalized tool arguments and lifecycle metadata + subAgentId?: string // for delegate tool runs + parentSeat?: string // for delegate tool runs + status?: string // for delegate tool runs + path?: string // for file tools — the file the agent touched + createdAt: number +} + +export interface Room { + id: string + projectId: string + name: string + // Outcome mode (VST-019): what the room is FOR — sets its stop condition, expected + // final artifact, seat/moderator behavior, and default budget. Unset = legacy room + // with no outcome gate. See electron/agent/room-outcomes.ts. + mode?: RoomMode | null + seats: Seat[] + rootCwd?: string | null + workspaceCwd?: string | null + scratchpadCwd?: string | null + workspace?: WorkspaceLocation | null + collaborationMode?: RoomCollaborationMode + deliberationEffort?: RoomDeliberationEffort + workerBudget?: RoomWorkerBudget + memory?: RoomMemoryEntry[] + memorySummary?: string + // Live shared scratchpad (decisions/plan/blockers) seats read and write during a + // run via the memory_write room tool. Persisted with the room (rooms.json). + sharedMemory?: SharedMemoryState + // Per-seat liveness while the room is running (BUG #53). Keyed by seat id. + // Runtime-ephemeral; surfaced to the supervisor job + UI for stall detection. + seatHeartbeats?: Record + problem: string + state: RoomState + events: RoomEventItem[] + finalText: string + archivedAt?: number | null + /** Origin host for an Orchestrator-owned renderer projection/archive record. */ + orchestratorHostId?: string | null + createdAt: number + updatedAt: number +} + +// Room worktree merge-back result (room:mergeWorktree). 'gated' = final gates not green, +// 'blocked' = git-hygiene preflight refused, 'conflict' = merge aborted and ticketed. +export type RoomMergeStatus = 'merged' | 'nothing' | 'conflict' | 'gated' | 'blocked' | 'error' + +export interface RoomMergeConflictInfo { + branch: string + files: string[] + ticketId: string | null +} + +export interface RoomMergeResult { + ok: boolean + status: RoomMergeStatus + baseBranch: string | null + merged: string[] + remaining: string[] + conflict: RoomMergeConflictInfo | null + blockers: string[] + message: string +} + +export type RoomStreamEvent = ( + | { roomId: string; type: 'status'; state: Room['state'] } + | { roomId: string; type: 'turn'; seat: string } + | { roomId: string; type: 'delta'; seat: string; chunk: string } + | { roomId: string; type: 'event'; item: RoomEventItem } + | { roomId: string; type: 'memory'; memory: RoomMemoryEntry[]; memorySummary: string; diff?: RoomMemoryDiff } + | { roomId: string; type: 'final'; text: string } + | { roomId: string; type: 'done' } + | { roomId: string; type: 'error'; message: string; fatal?: boolean } +) & { orchestratorHostId?: string | null } diff --git a/app/electron/agent/types/workspace.ts b/app/electron/agent/types/workspace.ts index 740cfae463b..5dbcc659796 100644 --- a/app/electron/agent/types/workspace.ts +++ b/app/electron/agent/types/workspace.ts @@ -1,86 +1,26 @@ -import type { RoomMode } from '../room-outcomes' +export type { + Seat, + SeatHeartbeat, + RoomSeatLane, + AgentRoleProfileId, + FanOutBudget, + RoomCollaborationMode, + RoomDeliberationEffort, + RoomWorkerBudget, + RoomMemoryEntry, + RoomMemoryDiff, + RoomManualMemoryCommand, + RoomState, + RoomEventItem, + Room, + RoomMergeStatus, + RoomMergeConflictInfo, + RoomMergeResult, + RoomStreamEvent, +} from './rooms' export type { RoomMode, RoomArtifactKind, RoomOutcomeProfile } from '../room-outcomes' -import type { SharedMemoryState } from '../shared-room-memory' import type { ExportRedaction, ProjectKanbanSettings } from './timeline' - -// ---- Multi-agent Rooms (Project → Room → Seats) ---- -export interface Seat { - id: string - name: string - role: string - providerId: string - providerAccountId?: string | null - model: string - lane?: RoomSeatLane - roleProfileId?: AgentRoleProfileId - fanOutBudget?: FanOutBudget -} - -// Per-seat liveness for room deliberation (BUG #53). Parallels MissionHeartbeat: -// tracks when a seat last took a turn so a stuck/slow seat surfaces as stalled -// instead of silently locking the room. Runtime-ephemeral — stored on Room. -export interface SeatHeartbeat { - seatId: string - seatName: string - intervalSeconds: number // expected cadence between turns - stallGraceSeconds: number // tolerance after nextDueAt before signalling a stall - required: boolean - count: number // turns this seat has taken - lastBeatAt: number | null // when the seat last took a turn - nextDueAt: number | null // when the next turn is expected - missedSince: number | null // when the stall was first detected (null = healthy) -} - -export type RoomSeatLane = 'planning' | 'development' | 'review' | 'research' | 'operations' -export type AgentRoleProfileId = 'planner' | 'builder' | 'reviewer' | 'researcher' | 'operator' -export type FanOutBudget = 'single' | 'paired' | 'council' | 'swarm' -export type RoomCollaborationMode = - | 'balanced' - | 'frontier_plans_local_builds' - | 'local_private' - | 'frontier_council' - | 'supervisor' -export type RoomDeliberationEffort = 'quick' | 'normal' | 'deep' | 'max' -export interface RoomWorkerBudget { - maxActive: number - maxStarts: number -} - -export interface RoomMemoryEntry { - id: string - kind: 'summary' | 'decision' | 'preference' | 'finding' - text: string - source: 'manual' | 'room' - createdAt: number - updatedAt: number -} - -export interface RoomMemoryDiff { - added: RoomMemoryEntry[] - removed: RoomMemoryEntry[] - summaryChanged: boolean - previousCount: number - nextCount: number -} - -export type RoomManualMemoryCommand = - | { action: 'add'; kind: RoomMemoryEntry['kind']; text: string } - | { action: 'remove'; entryId: string } - -export type RoomState = - | 'idle' - | 'created' - | 'ready' - | 'degraded' - | 'queued' - | 'running' - | 'waiting_user' - | 'waiting_external' - | 'complete' - | 'stopped' - | 'failed' - | 'archived' - | 'error' +import type { ReasoningEffortSetting } from './settings' export type ProjectExecutionTarget = 'local' | 'orchestrator' @@ -195,23 +135,6 @@ export interface ProjectMemoryCandidateDiff { changes: Array<{ field: 'text' | 'kind' | 'confidence' | 'privacyScope' | 'sourceType' | 'sourceRef' | 'sourceIds' | 'owner' | 'lastVerifiedAt' | 'sourceThreadId' | 'sourceTurn'; before: string | null; after: string | null }> } -export interface RoomEventItem { - id: string - tick: number - kind: string // task | speak | ask | assign | object | claim | check | vote | yield | final | tool | notice | error - seat: string // seat name | 'you' | 'system' | 'moderator' - target: string - text: string - replyTo?: string // for ask/assign — the room event id this message answers (lenient RE: marker) - tool?: string // for kind 'tool' — the tool name (read_file, edit_file, run_command, …) - args?: Record // for kind 'tool' — normalized tool arguments and lifecycle metadata - subAgentId?: string // for delegate tool runs - parentSeat?: string // for delegate tool runs - status?: string // for delegate tool runs - path?: string // for file tools — the file the agent touched - createdAt: number -} - export type { AppendSubAgentMessageInput, CreateSubAgentInput, @@ -232,62 +155,6 @@ export type { SubAgentStatus, } from '../subagents' -export interface Room { - id: string - projectId: string - name: string - // Outcome mode (VST-019): what the room is FOR — sets its stop condition, expected - // final artifact, seat/moderator behavior, and default budget. Unset = legacy room - // with no outcome gate. See electron/agent/room-outcomes.ts. - mode?: RoomMode | null - seats: Seat[] - rootCwd?: string | null - workspaceCwd?: string | null - scratchpadCwd?: string | null - workspace?: WorkspaceLocation | null - collaborationMode?: RoomCollaborationMode - deliberationEffort?: RoomDeliberationEffort - workerBudget?: RoomWorkerBudget - memory?: RoomMemoryEntry[] - memorySummary?: string - // Live shared scratchpad (decisions/plan/blockers) seats read and write during a - // run via the memory_write room tool. Persisted with the room (rooms.json). - sharedMemory?: SharedMemoryState - // Per-seat liveness while the room is running (BUG #53). Keyed by seat id. - // Runtime-ephemeral; surfaced to the supervisor job + UI for stall detection. - seatHeartbeats?: Record - problem: string - state: RoomState - events: RoomEventItem[] - finalText: string - archivedAt?: number | null - /** Origin host for an Orchestrator-owned renderer projection/archive record. */ - orchestratorHostId?: string | null - createdAt: number - updatedAt: number -} - -// Room worktree merge-back result (room:mergeWorktree). 'gated' = final gates not green, -// 'blocked' = git-hygiene preflight refused, 'conflict' = merge aborted and ticketed. -export type RoomMergeStatus = 'merged' | 'nothing' | 'conflict' | 'gated' | 'blocked' | 'error' - -export interface RoomMergeConflictInfo { - branch: string - files: string[] - ticketId: string | null -} - -export interface RoomMergeResult { - ok: boolean - status: RoomMergeStatus - baseBranch: string | null - merged: string[] - remaining: string[] - conflict: RoomMergeConflictInfo | null - blockers: string[] - message: string -} - export type TicketStatus = 'todo' | 'ready' | 'in_progress' | 'needs_clarification' | 'review' | 'completed' export type TicketRisk = 'low' | 'medium' | 'high' export type TicketCapability = 'read' | 'write' | 'shell' | 'network' | 'browser' | 'connector' | 'mcp' @@ -320,6 +187,7 @@ export interface TicketExecutionRecord { hostId?: string | null providerId?: string | null model?: string | null + reasoningEffort?: ReasoningEffortSetting branch?: string | null threadId?: string | null /** Host-issued run identity for lifecycle correlation. */ @@ -375,17 +243,6 @@ export type TicketRemoteLifecycleCommand = | { action: 'start_failed'; message?: string } | { action: 'cancel' } -export type RoomStreamEvent = ( - | { roomId: string; type: 'status'; state: Room['state'] } - | { roomId: string; type: 'turn'; seat: string } - | { roomId: string; type: 'delta'; seat: string; chunk: string } - | { roomId: string; type: 'event'; item: RoomEventItem } - | { roomId: string; type: 'memory'; memory: RoomMemoryEntry[]; memorySummary: string; diff?: RoomMemoryDiff } - | { roomId: string; type: 'final'; text: string } - | { roomId: string; type: 'done' } - | { roomId: string; type: 'error'; message: string; fatal?: boolean } -) & { orchestratorHostId?: string | null } - // ---- Automations (model-pinned, scheduled headless runs) ---- export type AutomationSchedule = 'interval' | 'daily' | 'manual' // 'chat'/'agent' run a model; 'digest' composes a deterministic daily briefing from recent diff --git a/app/electron/main/host/local-delete-archive.test.ts b/app/electron/main/host/local-delete-archive.test.ts index 8b722c8b494..28163851077 100644 --- a/app/electron/main/host/local-delete-archive.test.ts +++ b/app/electron/main/host/local-delete-archive.test.ts @@ -108,9 +108,14 @@ assert.match(ticketWorker, /ticket\.archivedAt/, 'ticket worker rejects archived assert.ok(workerStart.lastIndexOf('inspectGitRepository') < workerStart.indexOf('ticket.status ='), 'all Git inspection awaits finish before ticket running state is committed') assert.ok(workerStart.indexOf('runLease.addWorkspaceKeys') < workerStart.indexOf('store.threads.unshift'), 'final-key lease conflicts fail before a new thread is persisted') -const roomStart = workspace.slice(workspace.indexOf('async function startRoomRun'), workspace.indexOf("handle('room:cancel'")) +const roomRuntime = source('./room-run-runtime.ts') +const roomStartAt = roomRuntime.indexOf('async function startRoomRun') +assert.ok(roomStartAt >= 0, 'the production Room startup remains discoverable') +const roomStart = roomRuntime.slice(roomStartAt) assert.match(roomStart, /Local room execution does not support SSH workspaces/, 'local room startup fails closed before SSH paths reach local Git') -assert.ok(roomStart.indexOf('reserveStart') < roomStart.indexOf('ensureRoomWorktree'), 'room startup reserves its workspace before asynchronous worktree setup') +const reservationAt = roomStart.indexOf('reserveRoomStartup(') +const worktreeAt = roomStart.indexOf('ensureRoomWorktree(') +assert.ok(reservationAt >= 0 && worktreeAt > reservationAt, 'room startup reserves its workspace before asynchronous worktree setup') assert.match(roomStart, /if \(!startupComplete\)[\s\S]*runLease\.release/, 'room prelaunch failures release the startup reservation') const instructionWriter = workspace.slice(workspace.indexOf('async function withProjectInstructionLease'), workspace.indexOf("handle('projects:get'")) diff --git a/app/electron/main/host/room-agent-effort-policy.test.ts b/app/electron/main/host/room-agent-effort-policy.test.ts new file mode 100644 index 00000000000..30b5689521f --- /dev/null +++ b/app/electron/main/host/room-agent-effort-policy.test.ts @@ -0,0 +1,16 @@ +import assert from 'node:assert/strict' +import { pickRoomConfigPatch } from './room-ticket-patch-policy' + +const seat = { id: 'reviewer', name: 'Reviewer', role: 'Review supplied input', providerId: 'fixture', model: 'fixture' } +for (const effort of ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultrathink', 'ultracode', 'dynamic', '512']) { + const seats = [{ ...seat, reasoningEffort: effort }] + const patch = pickRoomConfigPatch({ seats }) + assert.deepEqual(patch.seats, seats, 'a valid per-agent effort must survive the real room patch boundary') + assert.deepEqual(Object.keys(patch), ['seats']) + assert.equal(Object.getPrototypeOf(patch), null, 'the existing patch isolation boundary remains intact') +} +assert.deepEqual(pickRoomConfigPatch({ seats: [seat] }).seats, [seat], 'legacy agents keep their inherited app setting') +for (const effort of [null, '', ' ', 'HIGH', 'ultrathinks', 4, true]) { + assert.throws(() => pickRoomConfigPatch({ seats: [{ ...seat, reasoningEffort: effort }] }), /reasoningEffort/) +} +console.log('Room agent effort policy checks passed: supported saved values, legacy absence and rejected malformed values.') diff --git a/app/electron/main/host/room-child-effort.test.ts b/app/electron/main/host/room-child-effort.test.ts new file mode 100644 index 00000000000..3be5f908738 --- /dev/null +++ b/app/electron/main/host/room-child-effort.test.ts @@ -0,0 +1,67 @@ +import assert from 'node:assert/strict' +import { promises as fs } from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import { createServer } from 'node:http' +import { randomUUID } from 'node:crypto' + +const home = await fs.mkdtemp(path.join(os.tmpdir(), 'tensorfold-room-child-effort-')) +const previousHome = process.env.VONTRA_HOME +process.env.VONTRA_HOME = home +const { store } = await import('../state') +const storage = await import('../../store') +const { createToolContextRuntime } = await import('./tool-context-runtime') +const { createThreadRuntime } = await import('./thread-runtime') +const { createSubAgentFromLaunch, parentForRoomSeat } = await import('../../agent/subagents') +const previousStore = { ...store } +const requests: any[] = [] +const server = createServer((request, response) => { + if (request.method === 'GET') { response.end(JSON.stringify({ data: [{ id: 'fixture' }] })); return } + let raw = '' + request.on('data', chunk => { raw += chunk }) + request.on('end', () => { + requests.push(JSON.parse(raw)) + response.writeHead(200, { 'Content-Type': 'text/event-stream' }) + response.end(`data: ${JSON.stringify({ choices: [{ delta: { content: 'Synthetic child complete.' }, finish_reason: 'stop' }] })}\n\ndata: [DONE]\n\n`) + }) +}) +await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)) +const provider: any = { id: 'fixture', name: 'Synthetic API', kind: 'local', transport: 'chat-completions', + baseUrl: `http://127.0.0.1:${(server.address() as { port: number }).port}/v1`, apiKey: '', models: ['fixture'] } +const fold = createThreadRuntime({} as any).applyEventToThread +const runtime = createToolContextRuntime({ + sshManager: { backendForWorkspace: () => ({ kind: 'ssh' }) }, persistSubAgents() {}, persistThreads() {}, + applyEventToThread: fold, emitToRenderer() {}, emitPluginEvent() {}, renderProjectMemoryBucket: () => '', + recordEmailDraft() {}, recordEmailEvent() {}, recordCalendarEvent() {}, recordMessageEvent() {}, + runBrowserAutomation() {}, mcpToolContext: () => ({}), cancelThreadRun() {}, +} as any) +try { + store.settings = { ...storage.defaultSettings(), providers: [provider], activeProviderId: provider.id, activeModel: 'fixture' } + store.threads = []; store.projects = []; store.subAgents = [] + const cases = [['high', 'low'], ['low', 'high'], ['high', undefined]] as const + for (const [global, configured] of cases) { + store.settings.reasoningEffort = global + const seat = { id: 'builder', name: 'Builder', role: 'Inspect input', providerId: provider.id, model: 'fixture' } + const room: any = { id: 'room', projectId: 'project', name: 'Synthetic room', seats: [seat] } + const created = createSubAgentFromLaunch(store.subAgents, { source: 'room_delegate', parent: parentForRoomSeat(room, seat), + task: 'Inspect synthetic input.', providerId: provider.id, model: 'fixture', runId: randomUUID(), cwd: home }) + store.subAgents = created.agents + const input = { task: 'Inspect synthetic input.', parentLabel: 'Synthetic room agent', cwd: home, + signal: AbortSignal.timeout(5_000), reasoningEffort: configured } + const result = await runtime.runReadOnlySubAgent(created.agent, provider, 'fixture', input) + assert.equal(result.agent.status, 'succeeded', result.output) + } + assert.equal(requests.length, 3, 'every real child run reaches the HTTP provider once') + assert.deepEqual(requests.map(request => request.reasoning_effort), ['low', 'high', 'high'], + 'the actual child runtime forwards its explicit Room effort and preserves the inherited fallback') + console.log('Real Room child HTTP checks passed: independent Low/High requests and legacy app inheritance.') +} finally { + server.closeAllConnections() + await new Promise(resolve => server.close(() => resolve())) + while (storage.writeChains.size) await Promise.allSettled([...storage.writeChains.values()]) + Object.assign(store, previousStore) + storage.closeSessionSearchIndexes() + await fs.rm(home, { recursive: true, force: true, maxRetries: 10, retryDelay: 20 }) + if (previousHome === undefined) delete process.env.VONTRA_HOME + else process.env.VONTRA_HOME = previousHome +} diff --git a/app/electron/main/host/room-run-runtime.ts b/app/electron/main/host/room-run-runtime.ts new file mode 100644 index 00000000000..d37de52bc15 --- /dev/null +++ b/app/electron/main/host/room-run-runtime.ts @@ -0,0 +1,429 @@ + +import type { RoomSupervisorMetadataPatch } from '../../agent/jobs' + +import { buildUserContent, contentText } from '../../agent/content' +import { normalizeAttachments } from '../../agent/attachment-policy' +import type { Attachment, Job, Provider, Room, RoomStreamEvent, Seat, Ticket } from '../../agent/types' + +import { canonicalLocalWorkspaceKey, lexicalLocalWorkspaceKey } from './workspace-mutation-guard' + +import type { WorkspaceRuntimeIpcDeps } from './workspace-runtime-ipc' +import { reserveRoomStartup } from './workspace-startup-policy' +import { createRoomTools, type RoomToolScope } from './room-tools-runtime' +import { captureAgentReasoningEffort } from '../../../shared/reasoning-effort' + +export function createRoomRunRuntime(ctx: WorkspaceRuntimeIpcDeps) { + const { + path, + store, + workspaceMutationGuard, + requireSecurityRole, + persistRooms, + roomAborters, + ensureRoomWorktree, + emitRoom, + patchRoomSupervisorJob, + finishRoomSupervisorMission, + finishJob, + ensureRoomSupervisorMission, + roomWorkerBudget, + claimJob, + patchJob, + buildRoomSupervisorJobMetadata, + ticketsForRoom, + runtimeProvider, + inferSeatLane, + appendRoomSupervisorEvent, + ticketNeedsReviewAfterBuilder, + roomTicketConflictBlockers, + parkRoomIfWorkRemains, + modelRouter, + modelRouteAutoFailoverEnabled, + effectiveContextLimit, + roomContextLimit, + auditScopedModelRoute, + runtimeProviderWithFreshModels, + assertProviderEndpoint, + modelRouteFailoverText, + roomRouteHandoff, + modelRouteResetPolicy, + roomFinalGateBlockers, + runRoom, + } = ctx +async function startRoomRun(roomId: string, problem: string, attachments?: Attachment[]): Promise<{ ok: boolean; room?: Room }> { + requireSecurityRole('operator', 'start rooms') + const room = store.rooms.find((r) => r.id === roomId) + if (!room) throw new Error('Room not found') + if (room.archivedAt) throw new Error('Restore this archived room before starting it.') + // Don't start a second run for a room that's already running — it would overwrite the live + // aborter, making both the first run uncancellable and the second un-stoppable. + if (roomAborters.has(roomId)) return { ok: false, room } + const project = store.projects.find((p) => p.id === room.projectId) + if (!project) throw new Error('Project not found') + if (project.archivedAt) throw new Error('Restore the archived project before starting this room.') + // Rooms broadcast a single text problem to every seat (many are CLI/text-only), so fold + // attachments into text: documents become labelled blocks; images are noted (vision-capable + // seats can't receive pixels through the room channel). + const safeAttachments = normalizeAttachments(attachments) + const cleanProblem = contentText(buildUserContent(String(problem || '').trim(), safeAttachments)).trim() + if (!cleanProblem) throw new Error('Add a room objective before starting.') + if (room.seats.length < 1) throw new Error('Add at least one agent to the room first.') + const reasoningEffort = store.settings.reasoningEffort + const seatEfforts = new Map(room.seats.map((seat) => [seat.id, captureAgentReasoningEffort(seat, reasoningEffort)])) + const configuredWorkspace = room.workspace ?? project.workspace ?? null + if (configuredWorkspace?.kind === 'ssh') { + throw new Error('Local room execution does not support SSH workspaces; run this room on its remote Orchestrator.') + } + const initialPaths = [configuredWorkspace?.path, room.workspaceCwd, room.rootCwd, room.scratchpadCwd, project.cwd] + .filter((value): value is string => typeof value === 'string' && value.trim().length > 0) + const initialWorkspaceKeys = initialPaths.map((value: string) => lexicalLocalWorkspaceKey(value)) + const reservation = reserveRoomStartup(roomId, roomAborters, workspaceMutationGuard, initialWorkspaceKeys) + if (!reservation) return { ok: false, room } + const { controller, runLease } = reservation + const timeout = setTimeout(() => controller.abort(), 30 * 60_000) + roomAborters.set(roomId, controller) + let startupComplete = false + try { + const roomWorkspace = await ensureRoomWorktree(project, room) + const finalWorkspaceKey = await canonicalLocalWorkspaceKey(roomWorkspace) + runLease.addWorkspaceKeys?.([finalWorkspaceKey]) + if (room.archivedAt || project.archivedAt) throw new Error('Room or project was archived while the room was starting.') + if (room.workspaceCwd !== roomWorkspace) { + room.workspaceCwd = roomWorkspace + persistRooms() + } + const roomProject = { ...project, cwd: roomWorkspace } + + room.problem = cleanProblem + room.events = [] + room.finalText = '' + room.state = 'queued' + room.updatedAt = Date.now() + persistRooms() + emitRoom({ roomId, type: 'status', state: 'queued' }) + const supervisorMission = ensureRoomSupervisorMission(room, project, roomWorkspace, cleanProblem) + const supervisorRunId = `room:${room.id}:${Date.now()}` + const configuredWorkerBudget = roomWorkerBudget(room) + let job: Job | null = claimJob({ + kind: 'room', + owner: room.id, + projectId: room.projectId, + missionId: supervisorMission.id, + roomId: room.id, + currentThreadId: null, + metadata: buildRoomSupervisorJobMetadata({ + room, + project, + tickets: ticketsForRoom(room), + patch: { missionId: supervisorMission.id, workerBudget: configuredWorkerBudget, workerStarts: 0 }, + }), + }) + job = patchJob(job, { currentRunId: supervisorRunId }) + + let lastCodeChangeAt = 0 + let greenEvidenceAt = 0 + const providerForSeat = (seat: Seat): Provider | undefined => { + const provider = store.settings.providers.find((p) => p.id === seat.providerId) + return provider ? runtimeProvider(provider, seat.providerAccountId) : undefined + } + if (roomProject.localOnly) { + const cloudSeat = room.seats.find((seat) => providerForSeat(seat)?.kind !== 'local') + if (cloudSeat) { + room.state = 'failed' + persistRooms() + emitRoom({ roomId: room.id, type: 'error', message: `Project is local-only, but seat "${cloudSeat.name}" is not using a local provider.`, fatal: true }) + emitRoom({ roomId: room.id, type: 'status', state: 'failed' }) + emitRoom({ roomId: room.id, type: 'done' }) + clearTimeout(timeout) + roomAborters.delete(room.id) + job = patchRoomSupervisorJob(job, room, project) + finishRoomSupervisorMission(job, 'failed', `Project is local-only, but seat "${cloudSeat.name}" is not using a local provider.`) + finishJob(job, 'failed', `Project is local-only, but seat "${cloudSeat.name}" is not using a local provider.`) + return { ok: false } + } + } + const roomTickets = (): Ticket[] => ticketsForRoom(room) + // Resolve a ticket from free-form LLM tool input. Precedence: exact id, then exact (trimmed, + // case-insensitive) title equality, then a UNIQUE case-insensitive substring. A substring that + // matches multiple tickets is AMBIGUOUS — never silently pick the first (store-insertion-order) + // match, or claim/complete/start could act on the wrong ticket (e.g. "auth" hitting both + // "Add auth" and "Add auth tests"). On ambiguity, `error` is set and `ticket` is undefined. + const resolveTicket = (args: any): { ticket?: Ticket; error?: string } => { + const board = roomTickets() + const id = typeof args?.id === 'string' ? args.id : '' + if (id) { + const byId = board.find((t) => t.id === id) + if (byId) return { ticket: byId } + } + const rawTitle = typeof args?.title === 'string' ? args.title.trim() : '' + if (!rawTitle) return { ticket: undefined } + const wanted = rawTitle.toLowerCase() + const exact = board.filter((t) => t.title.trim().toLowerCase() === wanted) + if (exact.length === 1) return { ticket: exact[0] } + if (exact.length > 1) { + return { error: `"${rawTitle}" matches ${exact.length} tickets with that exact title; reference the ticket by id instead.` } + } + const substr = board.filter((t) => t.title.toLowerCase().includes(wanted)) + if (substr.length === 1) return { ticket: substr[0] } + if (substr.length > 1) { + return { error: `"${rawTitle}" is ambiguous — it matches ${substr.length} tickets (${substr.map((t) => `"${t.title}"`).join(', ')}); use a more specific title or the ticket id.` } + } + return { ticket: undefined } + } + const findTicket = (args: any): Ticket | undefined => resolveTicket(args).ticket + // Mirrors tickets.ts isReservationEvidence / meaningfulTicketEvidence (which are module-private + // there): a "Reserved for build/review worker." note placed by start_ticket_work is a placeholder, + // not real evidence, so it must not satisfy a ticket's required-evidence gate. + const isReservationEvidenceLocal = (item: { kind?: string; summary?: string; ref?: string | null }): boolean => + /\breserved for (?:build|review) worker\b/i.test(`${item.kind ?? ''} ${item.summary ?? ''} ${item.ref ?? ''}`) + const hasMeaningfulEvidence = (tk: Ticket): boolean => + (tk.evidence ?? []).some((item) => !isReservationEvidenceLocal(item)) + const workerBudget = configuredWorkerBudget + let workerStarts = 0 + const activeTicketWorkerCount = () => roomTickets().filter((ticket) => ticket.runState === 'queued' || ticket.runState === 'running').length + const touchSupervisor = (patch: RoomSupervisorMetadataPatch = {}) => { + job = patchRoomSupervisorJob(job, room, project, { workerBudget, workerStarts, ...patch }) + } + const selectAutomaticReviewSeat = (builderSeat: string): Seat | null => { + const candidates = room.seats + .map((seat, index) => { + if (seat.name === builderSeat) return null + if (!providerForSeat(seat)) return null + const reviewRank = inferSeatLane(seat) === 'review' || seat.roleProfileId === 'reviewer' ? 0 : 1 + return { seat, index, reviewRank } + }) + .filter((item): item is { seat: Seat; index: number; reviewRank: number } => !!item) + .sort((a, b) => a.reviewRank - b.reviewRank || a.index - b.index) + return candidates[0]?.seat ?? null + } + const blockAutomaticReview = (tk: Ticket, builderSeat: string, paths: string[], summary: string) => { + touchSupervisor({ phase: { phase: 'review', status: 'blocked', ticketId: tk.id, ticketTitle: tk.title, seat: builderSeat, paths, summary } }) + appendRoomSupervisorEvent(room, `Automatic review not started for "${tk.title}": ${summary}`, { + tool: 'auto_review_scheduler', + args: { ticketId: tk.id, phase: 'review', builderSeat, paths }, + }) + } + const scheduleAutomaticReviewAfterBuild = async (tk: Ticket, builderSeat: string, paths: string[]) => { + if (!ticketNeedsReviewAfterBuilder(tk)) return + const reviewSeat = selectAutomaticReviewSeat(builderSeat) + if (!reviewSeat) { + blockAutomaticReview(tk, builderSeat, paths, 'No suitable different room seat is available for review.') + return + } + const blockers: string[] = roomTicketConflictBlockers({ ticket: tk, tickets: roomTickets(), phase: 'review', seat: reviewSeat.name, paths }) + if (blockers.length) { + blockAutomaticReview(tk, reviewSeat.name, paths, blockers.join(' ')) + return + } + const activeWorkers = activeTicketWorkerCount() + if (activeWorkers >= workerBudget.maxActive) { + blockAutomaticReview(tk, reviewSeat.name, paths, `Worker budget busy: ${activeWorkers}/${workerBudget.maxActive} active.`) + return + } + if (workerStarts >= workerBudget.maxStarts) { + blockAutomaticReview(tk, reviewSeat.name, paths, `Worker budget exhausted: ${workerStarts}/${workerBudget.maxStarts} started.`) + return + } + appendRoomSupervisorEvent(room, `Automatic review queued for "${tk.title}" with ${reviewSeat.name}.`, { + tool: 'auto_review_scheduler', + args: { ticketId: tk.id, phase: 'review', builderSeat, reviewSeat: reviewSeat.name, paths }, + }) + try { + await roomTools.start_ticket_work({ id: tk.id, phase: 'review', paths }, reviewSeat.name) + } catch (err: any) { + blockAutomaticReview(tk, reviewSeat.name, paths, String(err?.message ?? err)) + } + } + const emitRoomProgress = (ev: RoomStreamEvent) => { + if (ev.type === 'status') { + room.state = ev.state + room.updatedAt = Date.now() + persistRooms() + touchSupervisor() + } else if (ev.type === 'turn') { + touchSupervisor({ currentTurnSeat: ev.seat }) + } else if (ev.type === 'event') { + room.updatedAt = Date.now() + persistRooms() + touchSupervisor({ lastEventKind: ev.item.kind, lastEventSeat: ev.item.seat, lastEventAt: ev.item.createdAt }) + } else if (ev.type === 'memory') { + room.updatedAt = Date.now() + persistRooms() + touchSupervisor() + } else if (ev.type === 'final' || ev.type === 'done' || ev.type === 'error') { + touchSupervisor() + } + emitRoom(ev) + } + touchSupervisor() + const roomTools: Record Promise> = createRoomTools(ctx, { + reasoningEffort, + seatEfforts, + roomTickets, + room, + resolveTicket, + findTicket, + hasMeaningfulEvidence, + touchSupervisor, + activeTicketWorkerCount, + workerBudget, + get workerStarts() { return workerStarts }, + set workerStarts(value: RoomToolScope['workerStarts']) { workerStarts = value }, + get lastCodeChangeAt() { return lastCodeChangeAt }, + set lastCodeChangeAt(value: RoomToolScope['lastCodeChangeAt']) { lastCodeChangeAt = value }, + get greenEvidenceAt() { return greenEvidenceAt }, + set greenEvidenceAt(value: RoomToolScope['greenEvidenceAt']) { greenEvidenceAt = value }, + scheduleAutomaticReviewAfterBuild, + roomProject, + roomWorkspace, + controller, + }) + + // Supervisor mode: an ASSIGN auto-starts the addressed seat's ticket worker. + // The ticket is resolved from the ASSIGN text (a verbatim ticket title inside the + // text wins; otherwise the text minus the seat name is used as a title query), then + // routed through the standard start_ticket_work path so budget/conflict gates apply. + const autoStartAssignedTicket = async ({ target, text }: { seat: string; target: string; text: string }): Promise => { + const board = roomTickets().filter((t) => t.status !== 'completed') + const hay = text.toLowerCase() + const inText = board.filter((t) => t.title.trim() && hay.includes(t.title.trim().toLowerCase())) + let tk = inText.length === 1 ? inText[0] : undefined + if (!tk && inText.length > 1) { + const matches = inText.slice(0, 4).map((t) => `"${t.title}"`).join(', ') + return `ASSIGN auto-start skipped: the text matches ${inText.length} open tickets (${matches}). Name one verbatim to start it.` + } + if (!tk && inText.length === 0) { + const remainder = text.replace(new RegExp(`\\b${target.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`, 'ig'), '').trim() + const resolved = resolveTicket({ title: remainder }) + if (resolved.error) return `ASSIGN auto-start skipped: ${resolved.error}` + tk = resolved.ticket + } + if (!tk) return `ASSIGN to ${target} noted, but no open ticket title matched. Create the ticket with create_ticket first, then assign it.` + if (tk.assignee && tk.assignee !== target) return `ASSIGN auto-start skipped: "${tk.title}" is already claimed by ${tk.assignee}.` + return roomTools.start_ticket_work({ id: tk.id, phase: 'build' }, target) + } + + runRoom({ + room, project: roomProject, providers: store.settings.providers, problem: cleanProblem, + temperature: store.settings.temperature, reasoningEffort, + reasoningEffortForSeat: (seat) => seatEfforts.get(seat.id) ?? captureAgentReasoningEffort(seat, reasoningEffort), + emit: emitRoomProgress, signal: controller.signal, tools: roomTools, + onAssign: autoStartAssignedTicket, + providerForSeat, + recoverSeatModel: async (seat, error) => { + const latestBaseProvider = store.settings.providers.find((p) => p.id === seat.providerId) + if (!latestBaseProvider) return null + const currentAccountId = seat.providerAccountId ?? null + const routed = modelRouter.routeAfterError({ + role: 'room_seat', + provider: latestBaseProvider, + accountId: currentAccountId, + model: seat.model, + error, + allowFailover: modelRouteAutoFailoverEnabled(latestBaseProvider, currentAccountId), + localOnly: roomProject.localOnly === true, + contextLimit: effectiveContextLimit(latestBaseProvider, seat.model, currentAccountId), + reasoningEffort: seatEfforts.get(seat.id) ?? captureAgentReasoningEffort(seat, reasoningEffort), + budget: room.workerBudget?.maxActive ?? null, + source: 'room_seat_recovery', + }) + if (routed.signal) { + for (const audit of routed.audit) { + await auditScopedModelRoute('room', audit, routed.signal, { + roomId: room.id, + seatId: seat.id, + seatName: seat.name, + jobId: job?.id ?? null, + missionId: supervisorMission.id, + }) + } + } + if (!routed.signal || !routed.route.selected || routed.route.selectedAccountId === currentAccountId) return null + const providerAccountId = routed.route.selectedAccountId + const provider = await runtimeProviderWithFreshModels(latestBaseProvider, providerAccountId) + assertProviderEndpoint(provider) + const liveSeat = room.seats.find((candidate) => candidate.id === seat.id) + if (liveSeat) { + liveSeat.providerId = latestBaseProvider.id + liveSeat.providerAccountId = providerAccountId + liveSeat.model = seat.model + } + room.updatedAt = Date.now() + persistRooms() + const failoverText = modelRouteFailoverText(latestBaseProvider, routed.route.audit, routed.signal) + const notice = `${failoverText}\n${roomRouteHandoff(room, seat, failoverText)}` + job = patchJob(job, { + metadata: { + modelRoute: { + action: 'room_failover', + seatId: seat.id, + seatName: seat.name, + providerId: latestBaseProvider.id, + model: seat.model, + preferredProviderAccountId: currentAccountId, + failoverProviderAccountId: providerAccountId, + resetPolicy: modelRouteResetPolicy(latestBaseProvider, currentAccountId), + resetAt: routed.signal.resetAt, + reason: routed.route.audit.reason, + }, + }, + }) + touchSupervisor() + return { provider, providerAccountId, model: seat.model, notice } + }, + contextLimitForSeat: (seat) => { + if (!store.settings.autoCompact) return 0 + const provider = providerForSeat(seat) + if (!provider) return 0 + // Task #41: in a mixed-model room every seat compacts to the lowest seat's + // limit so no model silently overflows. Fall back to this seat's own limit + // if the floor can't be computed (e.g. another seat is misconfigured). + const floor = roomContextLimit( + room.seats + .map((s) => ({ provider: providerForSeat(s), model: s.model })) + .filter((entry): entry is { provider: Provider; model: string } => !!entry.provider), + { + cloudLimit: store.settings.contextLimit, + localLimit: store.settings.localContextLimit, + contextLimitExplicit: store.settings.contextLimitExplicit, + localContextLimitExplicit: store.settings.localContextLimitExplicit, + override: store.settings.contextLimitOverride, + engineModelProfiles: store.settings.engineModelProfiles, + }, + ) + return floor > 0 ? floor : effectiveContextLimit(provider, seat.model) + }, + finalGate: () => { + return roomFinalGateBlockers({ tickets: roomTickets(), lastCodeChangeAt, greenEvidenceAt }) + }, + }) + .catch((err) => emitRoomProgress({ roomId, type: 'error', message: String(err?.message ?? err), fatal: true })) + .finally(() => { + clearTimeout(timeout) + roomAborters.delete(roomId) + runLease.release() + const failed = room.state === 'failed' || room.state === 'error' + const parked = !controller.signal.aborted && !failed && parkRoomIfWorkRemains(job, room, project) + if (!parked) { + touchSupervisor({ currentTurnSeat: null }) + const outcome = controller.signal.aborted ? 'paused' : failed ? 'failed' : 'completed' + const reason = failed ? 'Room ended with an error.' : controller.signal.aborted ? 'Room paused after the active run stopped.' : undefined + finishRoomSupervisorMission(job, outcome, reason) + finishJob(job, outcome, reason) + } + room.updatedAt = Date.now() + persistRooms() + }) + + startupComplete = true + return { ok: true, room } + } finally { + if (!startupComplete) { + clearTimeout(timeout) + if (roomAborters.get(roomId) === controller) roomAborters.delete(roomId) + runLease.release() + } + } +} + return { startRoomRun } +} diff --git a/app/electron/main/host/room-ticket-patch-policy.ts b/app/electron/main/host/room-ticket-patch-policy.ts index acf7b28864a..0fff1aa3614 100644 --- a/app/electron/main/host/room-ticket-patch-policy.ts +++ b/app/electron/main/host/room-ticket-patch-policy.ts @@ -1,4 +1,5 @@ import type { Project, Provider, Room, RoomEventItem, RoomManualMemoryCommand, RoomMemoryEntry, Seat, Ticket, TicketExecutionRecord, TicketRemoteLifecycleCommand, TimelineItem } from '../../agent/types' +import { isReasoningEffortSetting } from '../../../shared/reasoning-effort' const ROOM_CONFIG_KEYS = new Set([ 'seats', @@ -106,7 +107,7 @@ function assertStringList(value: unknown, field: string, maxItems = 64, maxLengt function validateSeats(value: unknown): void { if (!Array.isArray(value) || value.length > 16) throw new Error('seats must be an array with at most 16 entries.') const ids = new Set() - const allowed = new Set(['id', 'name', 'role', 'providerId', 'providerAccountId', 'model', 'lane', 'roleProfileId', 'fanOutBudget']) + const allowed = new Set(['id', 'name', 'role', 'providerId', 'providerAccountId', 'model', 'reasoningEffort', 'lane', 'roleProfileId', 'fanOutBudget']) for (const [index, candidate] of value.entries()) { const field = `seats[${index}]` assertPlainRecord(candidate, field) @@ -116,6 +117,9 @@ function validateSeats(value: unknown): void { assertBoundedString(candidate.role, `${field}.role`, 2_000) assertBoundedString(candidate.providerId, `${field}.providerId`, 256) assertBoundedString(candidate.model, `${field}.model`, 512) + if (candidate.reasoningEffort !== undefined && !isReasoningEffortSetting(candidate.reasoningEffort)) { + throw new Error(`${field}.reasoningEffort has an invalid value.`) + } if (candidate.providerAccountId !== undefined && candidate.providerAccountId !== null) assertBoundedString(candidate.providerAccountId, `${field}.providerAccountId`, 256) if (candidate.lane !== undefined) assertEnum(candidate.lane, SEAT_LANES, `${field}.lane`) if (candidate.roleProfileId !== undefined) assertEnum(candidate.roleProfileId, ROLE_PROFILES, `${field}.roleProfileId`) diff --git a/app/electron/main/host/room-ticket-work-launch.test.ts b/app/electron/main/host/room-ticket-work-launch.test.ts index d7c6cf597de..16c7ef4e501 100644 --- a/app/electron/main/host/room-ticket-work-launch.test.ts +++ b/app/electron/main/host/room-ticket-work-launch.test.ts @@ -5,15 +5,19 @@ // localOnly guard and the memory_write renderer notification. import assert from 'node:assert/strict' import os from 'node:os' +import { randomUUID } from 'node:crypto' +import { createSubAgentFromLaunch, parentForRoomSeat, startSubAgent } from '../../agent/subagents' import { createWorkspaceRuntimeIpc } from './workspace-runtime-ipc' interface HarnessOpts { startTicketWork: (input: any) => Promise localOnly?: boolean + beforeWorkspace?: () => void } function buildHarness(opts: HarnessOpts) { const store: any = { + subAgents: [], projects: [{ id: 'p1', name: 'P', cwd: os.tmpdir(), workspace: null, localOnly: opts.localOnly === true, archivedAt: null }], rooms: [{ id: 'room-1', projectId: 'p1', name: 'Room', problem: '', state: 'idle', archivedAt: null, @@ -35,6 +39,7 @@ function buildHarness(opts: HarnessOpts) { } const emittedTickets: any[] = [] + const delegated: any[] = [] const remote: any[] = [] let persistTicketsCalls = 0 let runDeps: any = null @@ -48,7 +53,12 @@ function buildHarness(opts: HarnessOpts) { auditPreview: (s: string) => s, roomAborters: new Map(), workspaceMutationGuard: { reserveStart: () => ({ addWorkspaceKeys: () => {}, release: () => {} }) }, - ensureRoomWorktree: async () => os.tmpdir(), + ensureRoomWorktree: async () => { opts.beforeWorkspace?.(); return os.tmpdir() }, + randomUUID, createSubAgentFromLaunch, parentForRoomSeat, startSubAgent, + runReadOnlySubAgent: async (agent: any, provider: any, model: string, input: any) => { + delegated.push({ provider: provider.id, model, ...input }) + return { agent, output: 'Synthetic delegated result' } + }, persistRooms: () => {}, persistTickets: () => { persistTicketsCalls++ }, emitRoom: () => {}, @@ -89,7 +99,8 @@ function buildHarness(opts: HarnessOpts) { }) const api = createWorkspaceRuntimeIpc(ctx as any) return { - api, store, emittedTickets, remote, + api, store, emittedTickets, remote, delegated, + get runDeps() { return runDeps }, get persistTicketsCalls() { return persistTicketsCalls }, // Start the room (which captures the live room tools), then settle the run. run: async () => { @@ -180,6 +191,28 @@ async function main() { console.log('ok - memory_write notifies the renderer on change and rejects oversize content') } + { + const workerSources: any[] = [] + const h = buildHarness({ startTicketWork: async (input) => { workerSources.push(input.source); return { id: 'worker' } }, beforeWorkspace: () => { + h.store.settings.reasoningEffort = 'medium' + for (const seat of h.store.rooms[0].seats) seat.reasoningEffort = 'medium' + } }) + h.store.settings.reasoningEffort = 'xhigh' + h.store.rooms[0].seats[0].reasoningEffort = 'low' + h.store.rooms[0].seats.push({ id: 'reviewer', name: 'Reviewer', role: 'Review', providerId: 'p-local', model: 'm1', reasoningEffort: 'high' }, + { id: 'legacy', name: 'Legacy', role: 'Review', providerId: 'p-local', model: 'm1' }) + await h.run() + assert.deepEqual(h.store.rooms[0].seats.map((seat: any) => h.runDeps.reasoningEffortForSeat(seat)), ['low', 'high', 'xhigh'], + 'the actual host passes the same captured values into the Room turn engine') + await h.tool('delegate', { task: 'Review synthetic input' }, 'Builder') + await h.tool('delegate', { task: 'Review synthetic input', targetSeat: 'Reviewer' }, 'Builder') + await h.tool('delegate', { task: 'Review synthetic input', targetSeat: 'Legacy' }, 'Builder') + assert.deepEqual(h.delegated.map(call => call.reasoningEffort), ['low', 'high', 'xhigh'], + 'actual Room delegation captures origin, target and legacy app effort before workspace awaits') + await h.tool('start_ticket_work', { id: 't1', phase: 'build' }, 'Builder') + assert.equal(workerSources[0]?.reasoningEffort, 'low', 'ticket workers inherit the same Room run capture') + console.log('ok - actual Room delegation forwards independent captured efforts') + } console.log('room ticket work launch tests passed') } diff --git a/app/electron/main/host/room-tools-runtime.ts b/app/electron/main/host/room-tools-runtime.ts new file mode 100644 index 00000000000..6043e85e1ae --- /dev/null +++ b/app/electron/main/host/room-tools-runtime.ts @@ -0,0 +1,364 @@ + +import type { RoomSupervisorMetadataPatch } from '../../agent/jobs' + +import type { Project, ReasoningEffortSetting, Room, Ticket, Thread } from '../../agent/types' + +import { resolveDelegationRoute } from '../../agent/delegation-route' +import { createSharedMemory, MEMORY_MAX_BLOCK_CHARS, MEMORY_MAX_BLOCKS, renderSharedMemory, writeBlock } from '../../agent/shared-room-memory' + +import type { WorkspaceRuntimeIpcDeps } from './workspace-runtime-ipc' +import type { RoomWorkerBudget } from '../../agent/types' + +export interface RoomToolScope { + reasoningEffort: ReasoningEffortSetting + seatEfforts: ReadonlyMap + roomTickets: () => Ticket[] + room: Room + resolveTicket: (args: any) => { ticket?: Ticket; error?: string; } + findTicket: (args: any) => Ticket | undefined + hasMeaningfulEvidence: (tk: Ticket) => boolean + touchSupervisor: (patch?: RoomSupervisorMetadataPatch) => void + activeTicketWorkerCount: () => number + workerBudget: RoomWorkerBudget + workerStarts: number + lastCodeChangeAt: number + greenEvidenceAt: number + scheduleAutomaticReviewAfterBuild: (tk: Ticket, builderSeat: string, paths: string[]) => Promise + roomProject: Project + roomWorkspace: string + controller: AbortController +} + +export function createRoomTools(ctx: WorkspaceRuntimeIpcDeps, runtimeScope: RoomToolScope): Record Promise> { + const { + path, + randomUUID, + store, + auditEvent, + auditPreview, + persistRooms, + persistTickets, + persistSubAgents, + emitTicket, + publishRemote, + activeJob, + runtimeProvider, + appendRoomSupervisorEvent, + roomTicketConflictBlockers, + summarizeRoomLeftToWork, + describeTicketForRoom, + mkTicket, + normalizeTicketCapabilities, + normalizeStringList, + ticketEvidenceFromArgs, + ticketFileRefs, + startTicketWork, + createSubAgentFromLaunch, + parentForRoomSeat, + persistSubAgents: persistSubAgentsFromCtx, + startSubAgent, + runReadOnlySubAgent, + executeTool, + } = ctx + const persistSubAgentsSafe = persistSubAgentsFromCtx ?? persistSubAgents + return { + list_tickets: async () => { + const board = runtimeScope.roomTickets() + return board.length ? board.map(describeTicketForRoom).join('\n') : 'The board is empty.' + }, + left_to_work: async () => summarizeRoomLeftToWork(runtimeScope.roomTickets()), + create_ticket: async (args) => { + const tk = mkTicket(runtimeScope.room.projectId, { + roomId: runtimeScope.room.id, + title: args?.title || 'Untitled', + body: args?.body || '', + priority: args?.priority, + effort: args?.effort, + type: args?.type || 'task', + status: 'ready', + tags: args?.tags, + risk: args?.risk, + allowedCapabilities: args?.allowedCapabilities, + requiredEvidence: args?.requiredEvidence, + acceptanceCriteria: args?.acceptanceCriteria, + evidence: args?.evidence, + }) + store.tickets.unshift(tk); persistTickets(); emitTicket(tk) + return `Created ticket "${tk.title}" with ${tk.risk ?? 'low'} risk, allowed capabilities ${normalizeTicketCapabilities(tk.allowedCapabilities, ['read']).join(', ')}, and ${tk.requiredEvidence?.length ?? 0} required evidence item(s).` + }, + claim_ticket: async (args, seat) => { + const resolved = runtimeScope.resolveTicket(args) + if (resolved.error) return resolved.error + const tk = resolved.ticket + if (!tk) return `No ticket matches "${args?.title ?? args?.id ?? ''}".` + if (tk.assignee && tk.assignee !== seat) return `Already claimed by ${tk.assignee}. Pick another ticket.` + tk.assignee = seat; tk.status = 'in_progress'; tk.updatedAt = Date.now(); persistTickets(); emitTicket(tk) + const required = normalizeStringList(tk.requiredEvidence, []) + const caps = normalizeTicketCapabilities(tk.allowedCapabilities, ['read']).join(', ') + return `You claimed "${tk.title}". Allowed capabilities: ${caps}. Required evidence: ${required.length ? required.join('; ') : 'none'}.` + }, + add_ticket_evidence: async (args, seat) => { + const tk = runtimeScope.findTicket(args) + if (!tk) return 'No matching ticket.' + if (tk.assignee && tk.assignee !== seat) return `Only ${tk.assignee} can add evidence to "${tk.title}".` + const evidence = ticketEvidenceFromArgs(args, seat) + if (!evidence.length) return 'No evidence summary was provided.' + tk.assignee = tk.assignee ?? seat + tk.evidence = [...(tk.evidence ?? []), ...evidence] + tk.updatedAt = Date.now() + persistTickets(); emitTicket(tk) + return `Added ${evidence.length} evidence item(s) to "${tk.title}".` + }, + complete_ticket: async (args, seat) => { + const resolved = runtimeScope.resolveTicket(args) + if (resolved.error) return resolved.error + const tk = resolved.ticket + if (!tk) return 'No matching ticket.' + if (tk.assignee && tk.assignee !== seat) return `Only ${tk.assignee} can complete "${tk.title}".` + const evidence = ticketEvidenceFromArgs(args, seat) + if (evidence.length) tk.evidence = [...(tk.evidence ?? []), ...evidence] + const required = normalizeStringList(tk.requiredEvidence, []) + // Only MEANINGFUL evidence satisfies the required-evidence gate — reservation/placeholder notes + // appended by start_ticket_work ("Reserved for build/review worker.") must not count, or a + // ticket can be flipped to 'completed' with zero real evidence (the room final gate uses the + // same meaningful filter, so this keeps the per-ticket gate consistent with it). + if (required.length && !runtimeScope.hasMeaningfulEvidence(tk)) return `Cannot complete "${tk.title}" until evidence is attached: ${required.join('; ')}.` + tk.assignee = seat; tk.status = 'completed'; tk.updatedAt = Date.now(); persistTickets(); emitTicket(tk) + return `Completed "${tk.title}" with ${tk.evidence?.length ?? 0} evidence item(s).` + }, + start_ticket_work: async (args, seat) => { + const resolved = runtimeScope.resolveTicket(args) + if (resolved.error) return resolved.error + const tk = resolved.ticket + if (!tk) return `No ticket matches "${args?.title ?? args?.id ?? ''}".` + const phase = args?.phase === 'review' ? 'review' : 'build' + const declaredPaths: string[] = normalizeStringList(args?.paths, []) + const mergeDecision = typeof args?.mergeDecision === 'string' ? args.mergeDecision.trim() : '' + const blockers: string[] = roomTicketConflictBlockers({ ticket: tk, tickets: runtimeScope.roomTickets(), phase, seat, paths: declaredPaths }) + const overlapBlockers = blockers.filter((blocker) => /\boverlaps with\b/i.test(blocker)) + const hardBlockers = blockers.filter((blocker) => !overlapBlockers.includes(blocker)) + const effectiveBlockers = mergeDecision && overlapBlockers.length ? hardBlockers : blockers + if (blockers.length) { + if (effectiveBlockers.length) { + runtimeScope.touchSupervisor({ phase: { phase, status: 'blocked', ticketId: tk.id, ticketTitle: tk.title, seat, paths: declaredPaths, summary: effectiveBlockers.join(' ') } }) + return `Blocked by room supervisor: ${effectiveBlockers.join(' ')}` + } + appendRoomSupervisorEvent(runtimeScope.room, `Merge decision accepted for "${tk.title}": ${mergeDecision}`, { + tool: 'merge_decision', + args: { ticketId: tk.id, phase, seat, paths: declaredPaths, blockers: overlapBlockers }, + }) + tk.evidence = [ + ...(tk.evidence ?? []), + { + id: randomUUID(), + kind: 'note', + summary: `Supervisor merge decision: ${mergeDecision}. Waived overlap blocker(s): ${overlapBlockers.join(' ')}`, + ref: declaredPaths[0] ?? null, + createdBy: 'room-supervisor', + createdAt: Date.now(), + }, + ] + } + const activeWorkers = runtimeScope.activeTicketWorkerCount() + if (activeWorkers >= runtimeScope.workerBudget.maxActive) { + runtimeScope.touchSupervisor({ phase: { phase, status: 'blocked', ticketId: tk.id, ticketTitle: tk.title, seat, paths: declaredPaths, summary: `Worker budget busy: ${activeWorkers}/${runtimeScope.workerBudget.maxActive} active.` } }) + return `Room worker budget busy: ${activeWorkers}/${runtimeScope.workerBudget.maxActive} active ticket workers. Use left_to_work and wait for a worker result.` + } + if (runtimeScope.workerStarts >= runtimeScope.workerBudget.maxStarts) { + runtimeScope.touchSupervisor({ phase: { phase, status: 'blocked', ticketId: tk.id, ticketTitle: tk.title, seat, paths: declaredPaths, summary: `Worker budget exhausted: ${runtimeScope.workerStarts}/${runtimeScope.workerBudget.maxStarts} started.` } }) + return `Room worker budget exhausted: ${runtimeScope.workerStarts}/${runtimeScope.workerBudget.maxStarts} ticket workers started in this room run.` + } + const seatConfig = runtimeScope.room.seats.find((candidate) => candidate.name === seat) + if (!seatConfig) return 'Cannot start worker: room seat is no longer configured.' + // Snapshot before the pre-launch mutation so a failed launch can restore the ticket + // instead of wedging it (runState 'queued' blocks retries via roomTicketConflictBlockers, + // counts against the worker budget, and keeps the final gate open). + const prevAssignee = tk.assignee + const prevStatus = tk.status + runtimeScope.workerStarts++ + // Only a BUILD-phase start takes ownership of the ticket. A review-phase start must NOT + // overwrite the builder's assignee with the reviewer — doing so erases the builder's claim and + // makes a later build-phase conflict check (roomTicketConflictBlockers) report the ticket as + // claimed by the reviewer, blocking the original builder from their own ticket. The reviewer's + // identity is tracked separately via the review evidence (createdBy), not tk.assignee. + if (phase === 'build') tk.assignee = seat + tk.status = 'in_progress' + tk.runState = 'queued' + if (declaredPaths.length) { + tk.evidence = [ + ...(tk.evidence ?? []), + ...declaredPaths.map((ref) => ({ id: randomUUID(), kind: 'file' as const, summary: `Reserved for ${phase} worker.`, ref, createdBy: seat, createdAt: Date.now() })), + ] + } + tk.updatedAt = Date.now() + persistTickets(); emitTicket(tk) + runtimeScope.touchSupervisor({ phase: { phase, status: 'queued', ticketId: tk.id, ticketTitle: tk.title, seat, paths: declaredPaths, summary: 'Ticket worker queued.' } }) + const knownPaths = ticketFileRefs(tk, declaredPaths) + let workerThreadId: string | null = null + let thread: Thread + try { + thread = await startTicketWork({ + ticketId: tk.id, + opts: { phase, providerId: seatConfig.providerId, providerAccountId: seatConfig.providerAccountId ?? null, model: seatConfig.model }, + source: { + roomId: runtimeScope.room.id, + seat, + reasoningEffort: runtimeScope.seatEfforts.get(seatConfig.id) ?? runtimeScope.reasoningEffort, + onSettled: ({ codeChanged, testsPassed, failed, jobId }) => { + if (codeChanged) runtimeScope.lastCodeChangeAt = Date.now() + if (testsPassed) runtimeScope.greenEvidenceAt = Date.now() + runtimeScope.touchSupervisor({ + phase: { + phase, + status: tk.status === 'needs_clarification' ? 'failed' : 'completed', + ticketId: tk.id, + ticketTitle: tk.title, + seat, + threadId: workerThreadId, + jobId: jobId ?? activeJob('ticket', tk.id)?.id ?? null, + paths: knownPaths, + summary: tk.status === 'needs_clarification' ? 'Ticket worker needs clarification.' : 'Ticket worker finished.', + }, + }) + if (phase === 'build' && !failed) void runtimeScope.scheduleAutomaticReviewAfterBuild(tk, seat, knownPaths) + }, + }, + }) + } catch (launchError: any) { + // Launch failed: unwind the pre-launch mutation so the ticket is retryable instead + // of wedged as 'queued' (which blocks retries, burns budget, and holds the gate). + runtimeScope.workerStarts-- + tk.runState = null + tk.status = prevStatus + tk.assignee = prevAssignee + tk.updatedAt = Date.now() + persistTickets(); emitTicket(tk) + runtimeScope.touchSupervisor({ phase: { phase, status: 'failed', ticketId: tk.id, ticketTitle: tk.title, seat, paths: declaredPaths, summary: `Worker launch failed: ${launchError?.message ?? launchError}` } }) + return `Cannot start worker: launch failed: ${launchError?.message ?? launchError}` + } + workerThreadId = thread.id + runtimeScope.touchSupervisor({ + phase: { + phase, + status: 'running', + ticketId: tk.id, + ticketTitle: tk.title, + seat, + threadId: thread.id, + jobId: activeJob('ticket', tk.id)?.id ?? null, + paths: knownPaths, + summary: 'Ticket worker running.', + }, + }) + return `Room Supervisor started ${phase} worker thread ${thread.id} for "${tk.title}"${knownPaths.length ? ` on ${knownPaths.slice(0, 4).join(', ')}` : ''}.` + }, + delegate: async (args, seat) => { + const s = runtimeScope.room.seats.find((x) => x.name === seat) + if (!s) return 'Cannot delegate: seat misconfigured.' + // Optional cross-model route: targetSeat adopts that seat's provider/account/model; + // explicit providerId/accountId/model override it; absent fields inherit this seat. + // A local-only project may not delegate out to a cloud provider (same guard the + // thread runtime and room seat config enforce). + const routed = resolveDelegationRoute(store.settings.providers, { + providerId: s.providerId, + providerAccountId: s.providerAccountId, + model: s.model, + reasoningEffort: runtimeScope.seatEfforts.get(s.id) ?? runtimeScope.reasoningEffort, + }, args ?? {}, runtimeScope.room.seats.map((seat) => ({ ...seat, + reasoningEffort: runtimeScope.seatEfforts.get(seat.id) ?? runtimeScope.reasoningEffort, + })), runtimeScope.roomProject.localOnly === true) + if (!routed.route) return `Cannot delegate: ${routed.error}.` + const routeAccountId = routed.route.providerAccountId ?? null + const routeProvider = store.settings.providers.find((p) => p.id === routed.route.providerId) + const prov = routeProvider ? runtimeProvider(routeProvider, routed.route.providerAccountId) : undefined + if (!prov) return s.providerId === routed.route.providerId ? 'Cannot delegate: seat misconfigured.' : `Cannot delegate: provider "${routed.route.providerId}" is not configured.` + const task = String(args?.task || '').trim() || 'Focused room subtask' + const name = typeof args?.name === 'string' ? args.name.trim() : '' + const runId = `subagent-${randomUUID()}` + const created = createSubAgentFromLaunch(store.subAgents, { + source: 'room_delegate', + parent: parentForRoomSeat(runtimeScope.room, s), + task, + name, + providerId: routed.route.providerId, + providerAccountId: routeAccountId, + model: routed.route.model, + runId, + cwd: runtimeScope.roomWorkspace, + }) + store.subAgents = created.agents + persistSubAgentsSafe() + if (args && typeof args === 'object') { + args.id = created.agent.id + args.name = created.agent.name + args.task = task + args.parentSeat = seat + args.providerId = routed.route.providerId + args.providerAccountId = routeAccountId + args.model = routed.route.model + if (routed.notice) args.notice = routed.notice + args.status = 'running' + } + const started = startSubAgent(store.subAgents, created.agent.id, runId) + store.subAgents = started.agents + persistSubAgentsSafe() + const launched = await runReadOnlySubAgent(created.agent, prov, routed.route.model, { + task, + parentLabel: `room seat "${seat}" in room "${runtimeScope.room.name}"`, + cwd: runtimeScope.roomWorkspace, + projectId: runtimeScope.room.projectId, + providerAccountId: routeAccountId, + signal: runtimeScope.controller.signal, + reasoningEffort: routed.route.reasoningEffort ?? runtimeScope.reasoningEffort, + project: runtimeScope.roomProject, + maxSteps: 10, + maxWallMs: 150_000, + }) + if (args && typeof args === 'object') { + args.status = launched.agent.status + args.result = launched.agent.result + args.error = launched.agent.error + } + return routed.notice ? `${routed.notice}\n${launched.output}` : launched.output + }, + // Room tools are read-only by default. Mutating tools need a future room-level approval UI. + // memory_write is room state (the shared scratchpad), not workspace mutation, so it is allowed. + memory_write: async (args, seat) => { + const name = typeof args?.name === 'string' ? args.name.trim() : '' + const content = typeof args?.content === 'string' ? args.content.trim() : '' + if (!name || !content) return 'memory_write needs a "name" (decisions, plan, blockers, or any label) and "content".' + if (!runtimeScope.room.sharedMemory) runtimeScope.room.sharedMemory = createSharedMemory() + const mode = args?.mode === 'append' || args?.mode === 'append-bullet' ? args.mode : 'replace' + const expectedRevision = typeof args?.expectedRevision === 'number' ? args.expectedRevision : undefined + const result = writeBlock(runtimeScope.room.sharedMemory, { name, content, author: seat, mode, expectedRevision }) + if (!result.ok) { + if (result.reason === 'conflict') return `Memory conflict on "${name}": current revision is ${result.currentRevision}. Re-read the block and retry.` + if (result.reason === 'content-too-large') return `Memory block "${name}" is too large: content is capped at ${MEMORY_MAX_BLOCK_CHARS} characters. Summarize it and retry.` + if (result.reason === 'block-limit') return `Shared memory is full (${MEMORY_MAX_BLOCKS} blocks). Update an existing block instead of adding a new one.` + return 'Memory write needs a non-empty name.' + } + runtimeScope.room.updatedAt = Date.now() + persistRooms() + // Live push so the renderer reflects the write without waiting for a full snapshot. + if (result.changed) publishRemote?.({ kind: 'room', data: runtimeScope.room }) + return result.changed + ? `Memory "${result.block.name}" updated (rev ${result.block.revision}).\n${renderSharedMemory(runtimeScope.room.sharedMemory)}` + : `Memory "${result.block.name}" already says that (rev ${result.block.revision}).` + }, + read_file: async (args) => { const r = await executeTool('read_file', args, { cwd: runtimeScope.roomWorkspace }); return r.output.slice(0, 4000) }, + list_dir: async (args) => { const r = await executeTool('list_dir', args, { cwd: runtimeScope.roomWorkspace }); return r.output.slice(0, 2000) }, + search: async (args) => { const r = await executeTool('search', args, { cwd: runtimeScope.roomWorkspace }); return r.output.slice(0, 2000) }, + write_file: async (args) => { + await auditEvent('room.tool_blocked', { roomId: runtimeScope.room.id, tool: 'write_file', path: auditPreview(args?.path) }) + return 'Blocked: room agents are read-only until a room-level approval gate is available. Create/claim a ticket and run the work in an approved thread.' + }, + edit_file: async (args) => { + await auditEvent('room.tool_blocked', { roomId: runtimeScope.room.id, tool: 'edit_file', path: auditPreview(args?.path) }) + return 'Blocked: room agents are read-only until a room-level approval gate is available. Create/claim a ticket and run the work in an approved thread.' + }, + run_command: async (args) => { + await auditEvent('room.tool_blocked', { roomId: runtimeScope.room.id, tool: 'run_command', command: auditPreview(args?.command) }) + return 'Blocked: room agents cannot run shell commands unattended. Ask the user to run an approved thread or terminal command.' + }, + } +} diff --git a/app/electron/main/host/room-worker-effort.test.ts b/app/electron/main/host/room-worker-effort.test.ts new file mode 100644 index 00000000000..9fd52c25c90 --- /dev/null +++ b/app/electron/main/host/room-worker-effort.test.ts @@ -0,0 +1,120 @@ +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import path from 'node:path' +import { randomUUID } from 'node:crypto' +import ts from 'typescript' +import * as tickets from '../../agent/tickets' +import { restrictTicketToolContext } from '../../agent/ticket-tool-policy' +import { requireTicketDependenciesReady } from '../../../shared/ticket-dependencies' +import { lexicalLocalWorkspaceKey } from './workspace-mutation-guard' +import * as reasoning from '../../../shared/reasoning-effort' + +const code = ts.transpileModule(readFileSync(path.join(__dirname, 'ticket-worker-runtime.ts'), 'utf8'), { + compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS, esModuleInterop: true }, +}).outputText +const observed: unknown[] = [] +const expected: unknown[] = [] +for (const [global, configured, sourceEffort] of [['high', 'low', undefined], ['low', 'high', undefined], + ['high', undefined, undefined], ['high', 'medium', 'low']] as const) { + for (const recover of [false, true]) { + let releaseWorkspace!: (cwd: string) => void + const workspace = new Promise(resolve => { releaseWorkspace = resolve }) + let releaseAgent!: () => void + const agent = new Promise(resolve => { releaseAgent = resolve }) + let finish!: () => void + const done = new Promise(resolve => { finish = resolve }) + const provider = { id: 'fixture', name: 'Fixture', kind: 'local', baseUrl: 'http://127.0.0.1:1/v1', models: ['fixture'] } + const seat: any = { id: 'builder', name: 'Builder', role: 'Review input', providerId: provider.id, + model: 'fixture', reasoningEffort: configured } + const ticket: any = { id: 'ticket', projectId: 'project', roomId: 'room', title: 'Review input', body: '', + type: 'task', status: 'ready', priority: 'medium', effort: 'small', tags: [], parentId: null, + assignee: null, threadId: null, allowedCapabilities: ['read'], requiredEvidence: [], acceptanceCriteria: [], + dependsOn: [], order: 1, createdAt: 1, updatedAt: 1 } + const store: any = { + projects: [{ id: 'project', name: 'Synthetic project', cwd: '/workspace/project' }], + rooms: [{ id: 'room', projectId: 'project', seats: [seat], state: 'running' }], tickets: [ticket], threads: [], + settings: { providers: [provider], reasoningEffort: global, approvalMode: 'suggest', temperature: 0 }, + } + const routeEfforts: unknown[] = [] + const requests: any[] = [] + const imports: Record = { + 'node:crypto': { randomUUID }, 'node:path': path, + '../../agent/response-language': { selectedResponseLocale: () => 'en' }, + '../../agent/loop': { runAgent: async (params: any) => { + requests.push(params) + if (recover && requests.length === 1) throw new Error('Synthetic provider limit') + await agent + } }, + '../../agent/security': { assertProviderEndpoint() {}, auditPreview: (value: string) => value }, + '../../agent/tickets': tickets, '../../agent/ticket-tool-policy': { restrictTicketToolContext }, + '../state': { store }, './audit': { requireSecurityRole() {}, auditEvent: async () => {} }, + './room-worktree': { ensureRoomWorktree: () => workspace }, + '../../../shared/ticket-dependencies': { requireTicketDependenciesReady }, + './workspace': { resolveWorkspaceCwd: async (cwd: string) => cwd, inspectGitRepository: async () => ({ branch: 'fixture' }) }, + './ticket-helpers': { summarizeTicketWorkerOutcome: () => ({ text: 'Synthetic result', evidence: [], + codeChanged: false, testsPassed: false, signals: { commands: [], blockers: [], files: [], diffs: [] } }) }, + './workspace-mutation-guard': { lexicalLocalWorkspaceKey }, + './renderer-events': { sendToRenderer() {} }, + '../../../shared/reasoning-effort': reasoning, + './provider-runtime': { + ticketWorkOptionsWithProjectRoute: (_project: any, opts: any) => opts, + resolveProjectProvider: () => ({ baseProvider: provider, provider, providerAccountId: null, model: 'fixture' }), + runtimeProviderWithFreshModels: async () => provider, + modelRouteAccountLabel: () => 'Fixture', modelRouteAutoFailoverEnabled: () => true, + modelRouteFailoverText: () => 'Synthetic recovery', modelRouteResetPolicy: () => 'rotate_on_limit', + modelRouter: { + select: (params: any) => { + routeEfforts.push(params.reasoningEffort) + return { selected: true, selectedAccountId: null, audit: { action: 'keep', reason: 'Fixture' } } + }, + routeAfterError: (params: any) => { + routeEfforts.push(params.reasoningEffort) + return { signal: { resetAt: 1, kind: 'rate_limit' }, audit: [], + route: { selected: true, selectedAccountId: 'recovery', audit: { reason: 'Fixture recovery' } } } + }, + }, + }, + } + const module = { exports: {} as any } + new Function('require', 'module', 'exports', code)((id: string) => { + assert.ok(id in imports, `Reviewed worker import ${id}`) + return imports[id] + }, module, module.exports) + const noop = () => {} + const runtime = module.exports.createTicketWorkerRuntime({ + persistThreads: noop, persistTickets: noop, emitTicket: noop, appendRoomSupervisorEvent: noop, + claimJob: () => ({ id: 'job', status: 'running' }), patchJob: (job: any) => job, + fullToolContext: () => ({}), drainThreadCues: () => [], waitForThreadCue: async () => {}, + approvalResolver: () => async () => 'deny', timelineErrorSince: () => null, + timelineError: () => new Error('Unexpected timeline error'), isHighRiskTool: () => false, + emitToRenderer: noop, addThreadNotice: noop, auditModelRoute: async () => {}, + markRouteErrorRecovered: noop, injectThreadRouteHandoff: () => '', aborters: new Map(), + workspaceMutationGuard: { assertThreadStartAllowed: noop, + reserveStart: () => ({ addWorkspaceKeys: noop, addThreadId: noop, release: noop }) }, + applyEventToThread: noop, activeJob: () => null, finishJob: () => finish(), + markUndrainedCues: noop, effectiveContextLimit: () => 16_384, + }) + const pending = runtime.startTicketWork({ ticketId: ticket.id, source: { roomId: 'room', seat: 'Builder', reasoningEffort: sourceEffort } }) + assert.equal(requests.length, 0, 'workspace preparation genuinely pauses the production launch') + seat.reasoningEffort = 'medium' + store.settings.reasoningEffort = 'medium' + releaseWorkspace('/workspace/room') + await pending + const captured = ticket.execution?.reasoningEffort + releaseAgent() + let timer: ReturnType | undefined + try { + await Promise.race([done, new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error('Worker did not settle')), 2_000) + })]) + } finally { clearTimeout(timer) } + assert.equal(requests.length, recover ? 2 : 1, 'the actual worker executes initial and recovery routes') + const effort = sourceEffort ?? configured ?? global + observed.push({ global, configured, recover, routes: routeEfforts, + requests: requests.map(request => request.reasoningEffort), captured, settled: ticket.execution?.reasoningEffort }) + expected.push({ global, configured, recover, routes: Array(recover ? 2 : 1).fill(effort), + requests: Array(recover ? 2 : 1).fill(effort), captured: effort, settled: effort }) + } +} +assert.deepEqual(observed, expected, 'Room workers snapshot effort before awaits and retain it through recovery and settlement') +console.log('Room worker effort checks passed: opposite defaults, legacy inheritance, delayed startup, recovery and execution records.') diff --git a/app/electron/main/host/ticket-worker-evidence.test.ts b/app/electron/main/host/ticket-worker-evidence.test.ts new file mode 100644 index 00000000000..d413c9885da --- /dev/null +++ b/app/electron/main/host/ticket-worker-evidence.test.ts @@ -0,0 +1,139 @@ +import assert from 'node:assert/strict' +import { ticketReviewGateState } from '../../agent/tickets' +import type { AgentEvent, Job, Thread, Ticket, TimelineItem } from '../../agent/types' +import { store } from '../state' +import { createTicketWorkerRuntime } from './ticket-worker-runtime' + +const oldDiff = { id: 'old-diff', kind: 'tool', path: 'src/parser.ts', state: 'ok', diff: [{ type: 'add', text: 'const value = 1' }] } as TimelineItem +const oldTest = { id: 'old-test', kind: 'tool', command: 'npm test', output: '2 passed', state: 'ok' } as TimelineItem +const currentRead = { id: 'current-read', kind: 'tool', path: 'src/parser.ts', state: 'ok' } as TimelineItem +const currentTest = { id: 'current-test', kind: 'tool', command: 'npm test', output: '3 passed', state: 'ok' } as TimelineItem + +interface Scenario { + phase?: 'build' | 'review' + rewrite?: 'trim' | 'replace' | 'reverse' | 'remove-current' + interrupted?: boolean +} + +function applyEvent(thread: Thread, event: AgentEvent): void { + if (event.type === 'item_add') thread.timeline.push(structuredClone(event.item)) + else if (event.type === 'item_update') Object.assign(thread.timeline.find((item) => item.id === event.id) ?? {}, event.patch) + else if (event.type === 'item_delta') { + const item = thread.timeline.find((candidate) => candidate.id === event.id) + if (item) item[event.field] = (item[event.field] ?? '') + event.chunk + } +} + +let passed = 0 +async function scenario(previous: TimelineItem[], current: TimelineItem[], options: Scenario = {}) { + const saved = { tickets: store.tickets, projects: store.projects, rooms: store.rooms, threads: store.threads, settings: store.settings } + const phase = options.phase ?? 'review' + const thread = { + id: 'reused-thread', projectId: 'project', title: 'Inspect parser', kind: 'task', cwd: '/workspace/project', + providerId: 'fixture', model: 'fixture', + status: 'idle', timeline: structuredClone(previous), apiMessages: [], createdAt: 1, updatedAt: 1, + } as Thread + const ticket = { + id: 'ticket', projectId: 'project', threadId: thread.id, title: 'Inspect parser', body: '', type: 'task', + status: 'review', priority: 'medium', effort: 'small', tags: [], order: 0, createdAt: 1, updatedAt: 1, + parentId: null, assignee: 'Builder', runState: null, + risk: 'high', allowedCapabilities: ['read'], + evidence: [{ id: 'builder', kind: 'file', summary: 'Inspected src/parser.ts.', createdBy: 'Builder', createdAt: 10 }], + } as Ticket + const provider = { id: 'fixture', name: 'Fixture', kind: 'local', models: ['fixture'], baseUrl: 'http://127.0.0.1:9897/v1', apiKey: '' } as const + const aborters = new Map() + let released = false, outcome: string | null = null, savedTimeline: TimelineItem[] = [], published = 0 + let settled!: () => void + const completion = new Promise((resolve) => { settled = resolve }) + let timer: ReturnType | undefined + try { + store.tickets = [ticket] + store.projects = [{ id: 'project', name: 'Fixture project', cwd: thread.cwd, memory: '', team: '', createdAt: 1, updatedAt: 1 }] + store.rooms = [] + store.threads = [thread] + store.settings = { ...saved.settings, providers: [{ ...provider, models: [...provider.models] }], activeProviderId: provider.id, activeModel: 'fixture' } + const runtime = createTicketWorkerRuntime({ + runAgent: async ({ emit, thread: active }) => { + const base = { runId: 'fixture-run', threadId: active.id } + for (const item of current) emit({ ...base, type: 'item_add', item: structuredClone(item) }) + if (options.rewrite === 'trim') active.timeline.splice(0, previous.length) + if (options.rewrite === 'replace') active.timeline = [] + if (options.rewrite === 'reverse') active.timeline.reverse() + if (options.rewrite === 'remove-current') { + active.timeline = active.timeline.filter((item) => item.id !== currentTest.id) + emit({ ...base, type: 'item_update', id: currentTest.id, patch: { state: 'ok', output: '3 ' } }) + emit({ ...base, type: 'item_delta', id: currentTest.id, field: 'output', chunk: 'passed' }) + } + emit({ ...base, type: 'item_update', id: oldDiff.id, patch: { state: 'ok' } }) + if (options.interrupted) aborters.get(active.id)!.abort() + savedTimeline = structuredClone(active.timeline) + }, + resolveWorkspaceCwd: async () => '/workspace/project', + inspectGitRepository: async () => ({ branch: 'fixture' }) as any, + persistThreads() {}, persistTickets() {}, emitTicket() { published++ }, appendRoomSupervisorEvent() {}, + claimJob: () => ({ id: 'job' }) as Job, patchJob: (job) => job, fullToolContext: () => ({}), + drainThreadCues: () => [], waitForThreadCue: async () => {}, approvalResolver: () => async () => 'deny', + timelineErrorSince: (active, start) => active.timeline.slice(start).find((item) => item.kind === 'error') ?? null, + timelineError: () => new Error('Synthetic agent error'), isHighRiskTool: () => false, emitToRenderer() {}, + addThreadNotice() {}, auditModelRoute: async () => {}, markRouteErrorRecovered() {}, injectThreadRouteHandoff: () => '', + aborters, workspaceMutationGuard: { + assertThreadStartAllowed() {}, + reserveStart: () => ({ addWorkspaceKeys() {}, addThreadId() {}, release() { released = true } }), + }, + applyEventToThread: applyEvent, activeJob: () => null, + finishJob: (_job, result) => { outcome = result; settled() }, markUndrainedCues() {}, effectiveContextLimit: () => 4096, + }) + assert.equal(await runtime.startTicketWork({ ticketId: ticket.id, opts: { phase } }), thread) + await Promise.race([completion, new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('Worker settlement timed out')), 2000) })]) + assert.ok(released, 'the production finalizer releases its run reservation') + assert.equal(aborters.size, 0, 'the production finalizer clears the active worker') + assert.equal(published, 2, 'startup and settlement both publish the ticket') + assert.equal(runtime.isTicketStarting(ticket.id), false) + assert.deepEqual(thread.timeline, savedTimeline, 'settlement leaves live conversation history intact') + passed++ + return { ticket, outcome } + } finally { + clearTimeout(timer) + Object.assign(store, saved) + } +} + +const clean = await scenario([oldDiff, oldTest], [currentRead, currentTest]) +assert.equal(clean.ticket.evidence!.filter((item) => item.kind === 'diff').length, 0, 'old diffs are not reviewer-made changes') +assert.equal(clean.ticket.status, 'completed') +assert.equal(clean.outcome, 'completed') +assert.equal(ticketReviewGateState(clean.ticket).hasReviewOrSkipAfterBuilder, true) +assert.equal(ticketReviewGateState(clean.ticket).builderEvidenceBy, 'Builder') + +for (const rewrite of ['trim', 'replace', 'reverse', 'remove-current'] as const) { + const result = await scenario([oldDiff, oldTest], [currentRead, currentTest], { rewrite }) + assert.deepEqual(result.ticket.execution!.checks, [{ command: 'npm test', passed: true }], `${rewrite} retains this run's verification`) + assert.ok(!result.ticket.evidence!.some((item) => item.kind === 'diff'), `${rewrite} excludes historical diffs`) +} + +const recovered = await scenario([{ id: 'old-error', kind: 'error', text: 'Previous run failed.' } as TimelineItem], [currentRead, currentTest]) +assert.equal(recovered.ticket.status, 'completed', 'old errors do not fail this review') + +const noCurrentTest = await scenario([oldTest], [currentRead]) +assert.ok(!noCurrentTest.ticket.evidence!.some((item) => item.kind === 'test')) +assert.deepEqual(noCurrentTest.ticket.execution!.checks, []) + +const changed = await scenario([], [{ ...oldDiff, id: 'current-diff' }, currentTest]) +assert.ok(changed.ticket.evidence!.some((item) => item.kind === 'diff')) +assert.equal(ticketReviewGateState(changed.ticket).hasReviewOrSkipAfterBuilder, false, 'reviewer-made changes need independent review') + +const failed = await scenario([], [{ id: 'current-error', kind: 'error', text: 'This review failed.' } as TimelineItem], { rewrite: 'replace' }) +assert.equal(failed.ticket.status, 'needs_clarification') +assert.equal(failed.outcome, 'failed') +assert.ok(failed.ticket.evidence!.some((item) => item.kind === 'review' && item.summary.includes('blocked'))) + +const rebuilt = await scenario([oldDiff, oldTest], [currentRead], { phase: 'build' }) +assert.equal(rebuilt.ticket.status, 'review') +assert.equal(rebuilt.outcome, 'completed') +assert.ok(!rebuilt.ticket.evidence!.some((item) => item.kind === 'test' || item.kind === 'diff')) + +const interrupted = await scenario([oldTest], [currentRead], { interrupted: true }) +assert.equal(interrupted.ticket.status, 'in_progress') +assert.equal(interrupted.ticket.runState, null) +assert.equal(interrupted.outcome, 'paused') +console.log(`ticket worker evidence: ${passed} exported-runtime scenarios passed`) diff --git a/app/electron/main/host/ticket-worker-runtime.ts b/app/electron/main/host/ticket-worker-runtime.ts index 80afcc2fb34..17334773af1 100644 --- a/app/electron/main/host/ticket-worker-runtime.ts +++ b/app/electron/main/host/ticket-worker-runtime.ts @@ -6,11 +6,12 @@ import { assertProviderEndpoint, auditPreview } from '../../agent/security' import { normalizeTicketCapabilities, settleTicketExecution, startTicketExecution, ticketFileRefs, ticketStateAfterRun, ticketWorkPrompt } from '../../agent/tickets' import { restrictTicketToolContext } from '../../agent/ticket-tool-policy' import type { JobPatch } from '../../agent/jobs' -import type { AgentCue, AgentEvent, Job, Project, Provider, Room, Thread, Ticket, TicketWorkOptions, TimelineItem } from '../../agent/types' +import type { AgentCue, AgentEvent, Job, Project, Provider, ReasoningEffortSetting, Room, Thread, Ticket, TicketWorkOptions, TimelineItem } from '../../agent/types' import { store } from '../state' import { auditEvent, requireSecurityRole } from './audit' import { ensureRoomWorktree } from './room-worktree' import { requireTicketDependenciesReady } from '../../../shared/ticket-dependencies' +import { captureAgentReasoningEffort } from '../../../shared/reasoning-effort' import { inspectGitRepository } from './workspace' import { summarizeTicketWorkerOutcome } from './ticket-helpers' import { modelRouteAccountLabel, modelRouteAutoFailoverEnabled, modelRouteFailoverText, modelRouteResetPolicy, modelRouter, resolveProjectProvider, runtimeProviderWithFreshModels, ticketWorkOptionsWithProjectRoute } from './provider-runtime' @@ -21,6 +22,7 @@ import { sendToRenderer } from './renderer-events' export interface TicketWorkerSource { roomId?: string | null seat?: string | null + reasoningEffort?: ReasoningEffortSetting onSettled?: (summary: { codeChanged: boolean; testsPassed: boolean; failed: boolean; jobId?: string | null }) => void } @@ -63,6 +65,9 @@ export async function awaitTicketStartupStep(pending: Promise, revalidate: } interface TicketWorkerRuntimeDeps { + runAgent?: typeof runAgent + resolveWorkspaceCwd?: typeof resolveWorkspaceCwd + inspectGitRepository?: typeof inspectGitRepository persistThreads(): void persistTickets(): void emitTicket(ticket: Ticket): void @@ -92,6 +97,9 @@ interface TicketWorkerRuntimeDeps { export function createTicketWorkerRuntime(deps: TicketWorkerRuntimeDeps): TicketWorkerRuntime { const { + runAgent: executeAgent = runAgent, + resolveWorkspaceCwd: resolveWorkerCwd = resolveWorkspaceCwd, + inspectGitRepository: inspectWorkerGit = inspectGitRepository, persistThreads, persistTickets, emitTicket, @@ -134,6 +142,10 @@ async function startTicketWork(input: TicketWorkerInput): Promise { requireTicketDependenciesReady(ticket, store.tickets) if (!project) throw new Error('Restore or choose an active project before starting ticket work.') if (existingThread && aborters.has(existingThread.id)) throw new Error('Ticket work is already running.') + const roomSeat = input.source?.roomId === room?.id + ? room?.seats.find((seat) => seat.name === input.source?.seat) : undefined + const configuredEffort = input.source?.reasoningEffort === undefined ? roomSeat : input.source + const reasoningEffort = captureAgentReasoningEffort(configuredEffort, store.settings.reasoningEffort) const configuredWorkspace = room?.workspace ?? project.workspace ?? null if (configuredWorkspace?.kind === 'ssh') { throw new Error('Local ticket workers do not support SSH workspaces; run this ticket on its remote Orchestrator.') @@ -167,7 +179,7 @@ async function startTicketWork(input: TicketWorkerInput): Promise { allowFailover: modelRouteAutoFailoverEnabled(routeBaseProvider, requestedProviderAccountId), localOnly: project?.localOnly === true, contextLimit: effectiveContextLimit(routeBaseProvider, resolvedRoute.model, requestedProviderAccountId), - reasoningEffort: store.settings.reasoningEffort, + reasoningEffort, budget: phase, source: 'ticket_worker_initial_route', }) @@ -178,12 +190,12 @@ async function startTicketWork(input: TicketWorkerInput): Promise { : await runtimeProviderWithFreshModels(routeBaseProvider, providerAccountId) let model = resolvedRoute.model assertProviderEndpoint(provider) - const cwd = await resolveWorkspaceCwd(roomWorkspace || project?.cwd || store.settings.defaultCwd, 'ticket workspace') + const cwd = await resolveWorkerCwd(roomWorkspace || project?.cwd || store.settings.defaultCwd, 'ticket workspace') assertActiveTicketWorkOwnership(ticket, project, room, existingThread) const executionBranch = await awaitTicketStartupStep( - inspectGitRepository(cwd, 'ticket workspace').then((repo) => repo.branch).catch(() => null), + inspectWorkerGit(cwd, 'ticket workspace').then((repo) => repo.branch).catch(() => null), () => assertActiveTicketWorkOwnership(ticket, project, room, existingThread), ) @@ -211,6 +223,8 @@ async function startTicketWork(input: TicketWorkerInput): Promise { store.threads.unshift(thread); persistThreads() sendToRenderer('thread:update', thread) } + const previousItemIds = new Set(thread.timeline.map((item) => item.id)) + const runItems = new Map() ticket.threadId = thread.id ticket.status = 'in_progress' ticket.runState = 'running' @@ -225,6 +239,7 @@ async function startTicketWork(input: TicketWorkerInput): Promise { threadId: thread.id, startedAt: ticket.startedAt, }) + ticket.execution.reasoningEffort = reasoningEffort ticket.updatedAt = Date.now() persistTickets(); emitTicket(ticket) if (room && input.source?.roomId) { @@ -264,7 +279,21 @@ async function startTicketWork(input: TicketWorkerInput): Promise { emitToRenderer({ runId: '', threadId: thread.id, type: 'item_add', item: userItem }) const t = thread - const emit = (e: AgentEvent) => { applyEventToThread(t, e); emitToRenderer(e) } + const emit = (e: AgentEvent) => { + applyEventToThread(t, e) + if (e.threadId === t.id && e.type === 'item_add' && !previousItemIds.has(e.item.id)) { + runItems.set(e.item.id, t.timeline.find((item) => item.id === e.item.id) ?? structuredClone(e.item)) + } else if (e.threadId === t.id && (e.type === 'item_update' || e.type === 'item_delta')) { + const owned = runItems.get(e.id) + if (owned) { + const live = t.timeline.find((item) => item.id === e.id) + if (live) runItems.set(e.id, live) + else if (e.type === 'item_update') Object.assign(owned, structuredClone(e.patch)) + else owned[e.field] = (owned[e.field] ?? '') + e.chunk + } + } + emitToRenderer(e) + } t.cwd = cwd t.providerId = baseProvider.id t.providerAccountId = providerAccountId @@ -301,14 +330,14 @@ async function startTicketWork(input: TicketWorkerInput): Promise { fullToolContext({ thread: t, provider: route.provider, model: route.model, signal: controller.signal }), allowedCapabilities, ) - await runAgent({ + await executeAgent({ responseLocale: selectedResponseLocale(store.settings.uiPreferences), thread: t, provider: route.provider, model: route.model, approvalMode: store.settings.approvalMode === 'auto' ? 'suggest' : store.settings.approvalMode, temperature: store.settings.temperature, - reasoningEffort: store.settings.reasoningEffort, + reasoningEffort, autoCompact: store.settings.autoCompact, contextLimit: effectiveContextLimit(route.provider, route.model), toolContext, @@ -339,7 +368,7 @@ async function startTicketWork(input: TicketWorkerInput): Promise { allowFailover: modelRouteAutoFailoverEnabled(latestBaseProvider, activeRoute.providerAccountId) || t.modelRoute?.resetPolicy === 'rotate_on_limit', localOnly: project?.localOnly === true, contextLimit: effectiveContextLimit(latestBaseProvider, activeRoute.model, activeRoute.providerAccountId), - reasoningEffort: store.settings.reasoningEffort, + reasoningEffort, budget: phase, source: 'ticket_worker_recovery', }) @@ -396,7 +425,8 @@ async function startTicketWork(input: TicketWorkerInput): Promise { markUndrainedCues(t, controller.signal.aborted ? 'canceled' : 'run ended') aborters.delete(t.id) runLease.release() - const failed = t.timeline.some((i) => i.kind === 'error') + const runTimeline = [...runItems.values()] + const failed = runTimeline.some((i) => i.kind === 'error') const interrupted = controller.signal.aborted t.status = failed ? 'error' : 'idle'; t.updatedAt = Date.now() // When the run was aborted/paused (no completion), park the ticket without @@ -406,7 +436,7 @@ async function startTicketWork(input: TicketWorkerInput): Promise { ticket.runState = settled.runState ticket.status = settled.status ticket.updatedAt = Date.now() - const summary = summarizeTicketWorkerOutcome(ticket, t, phase, failed, input.source?.seat ?? model) + const summary = summarizeTicketWorkerOutcome(ticket, { ...t, timeline: runTimeline }, phase, failed, input.source?.seat ?? model) if (ticket.execution) { ticket.execution = settleTicketExecution(ticket.execution, { outcome: { phase, failed, interrupted }, diff --git a/app/electron/main/host/tool-context-runtime.ts b/app/electron/main/host/tool-context-runtime.ts index 9af9084596a..51e62269100 100644 --- a/app/electron/main/host/tool-context-runtime.ts +++ b/app/electron/main/host/tool-context-runtime.ts @@ -1,3 +1,6 @@ +import type { ReadOnlySubAgentInput, ToolContextRuntime, ToolContextRuntimeDeps } from './tool-context-types' +export type { ToolContextRuntime } from './tool-context-types' +import { captureAgentReasoningEffort } from '../../../shared/reasoning-effort' import { documentEventAllowed, documentPolicySignature, scopedDocumentLibrary, scopedDocumentSettings, validateDocumentSourceIds } from '../../document-library/scope' import { selectedResponseLocale } from '../../agent/response-language' import { documentLibrary } from './document-library-runtime' @@ -41,7 +44,6 @@ import type { ControllerActionInput } from '../../agent/controller-actions' import { store } from '../state' import { addSuggestion, type SuggestionInput } from '../../agent/suggestions' import { persistArtifacts, persistSuggestions } from './persistence' -import type { SshManager } from './ssh' import { blindSearchToken, searchSessionIndex, saveThreads, vontraPath } from '../../store' import { sendToRenderer } from './renderer-events' import { createManagedOutputStore } from './managed-outputs' @@ -49,53 +51,6 @@ import { isWhatsAppEventInCurrentScope } from '../../../shared/whatsapp-event-sc import { createGoogleContextMarker, createGoogleWorkspaceToolRunner } from './google-workspace-tool-runtime' import { googleWorkspaceService } from './google-workspace-runtime' -export interface ToolContextRuntime { - fullToolContext(run?: { thread?: Thread; provider?: Provider; model?: string; signal?: AbortSignal; subAgentId?: string; memoryPolicy?: import('../../agent/types').ThreadMemoryPolicy; memoryOwner?: { id: string; revision: number } }): any - runReadOnlySubAgent( - agent: SubAgent, - provider: Provider, - model: string, - input: { - task: string - parentLabel: string - cwd: string - projectId?: string | null - providerAccountId?: string | null - project?: Project | null - workspace?: WorkspaceLocation | null - signal: AbortSignal - memoryPolicy?: import('../../agent/types').ThreadMemoryPolicy - incognito?: boolean - memoryOwner?: { id: string; revision: number } - maxSteps?: number - maxWallMs?: number - }, - ): Promise<{ agent: SubAgent; output: string }> -} - -interface ToolContextRuntimeDeps { - sshManager: SshManager - persistSubAgents(): void - persistThreads(): void - applyEventToThread(thread: Thread, event: AgentEvent): void - emitToRenderer(event: AgentEvent): void - emitPluginEvent(event: AgentEvent): void - renderProjectMemoryBucket(project: Project | undefined): string - recordEmailDraft: any - recordEmailEvent: any - recordCalendarEvent: any - recordMessageEvent: any - runBrowserAutomation: any - mcpToolContext(): any - // Ends a thread's run; the computer-use indicator's Stop uses it. - cancelThreadRun(threadId: string): void - // Trusted repo-authored skills for a project (VST-010), served from the scan cache so - // this stays synchronous. Absent → global skills only. - projectSkills?(projectId: string | null | undefined, workspace?: WorkspaceLocation | null): Skill[] - // Observer hooks (VST-012): subagent lifecycle observation, fail-open. - observe?: (kind: 'subagent.start' | 'subagent.end', payload: Record) => void -} - export function createToolContextRuntime(deps: ToolContextRuntimeDeps): ToolContextRuntime { const { sshManager, @@ -116,21 +71,7 @@ export function createToolContextRuntime(deps: ToolContextRuntimeDeps): ToolCont agent: SubAgent, provider: Provider, model: string, - input: { - task: string - parentLabel: string - cwd: string - projectId?: string | null - providerAccountId?: string | null - project?: Project | null - workspace?: WorkspaceLocation | null - signal: AbortSignal - memoryPolicy?: import('../../agent/types').ThreadMemoryPolicy - incognito?: boolean - memoryOwner?: { id: string; revision: number } - maxSteps?: number - maxWallMs?: number - }, + input: ReadOnlySubAgentInput, ) { const storedAgent = store.subAgents.find((candidate) => candidate.id === agent.id) if (!storedAgent) throw new Error('The owning sub-agent is unavailable; refusing to start an unregistered child.') @@ -158,6 +99,7 @@ export function createToolContextRuntime(deps: ToolContextRuntimeDeps): ToolCont } } assertRequestAllowed() + const reasoningEffort = captureAgentReasoningEffort(input, store.settings.reasoningEffort) const childThread: Thread = { id: `thread-${agent.id}`, documentSourceIds: owner?.documentSourceIds ? [...validateDocumentSourceIds(owner.documentSourceIds)!] : [], @@ -201,7 +143,7 @@ export function createToolContextRuntime(deps: ToolContextRuntimeDeps): ToolCont model, approvalMode: 'readonly', temperature: store.settings.temperature, - reasoningEffort: store.settings.reasoningEffort, + reasoningEffort, emit: (event) => applyEventToThread(childThread, event), requestApproval: async () => 'deny', signal: input.signal, diff --git a/app/electron/main/host/tool-context-types.ts b/app/electron/main/host/tool-context-types.ts new file mode 100644 index 00000000000..02d6cd61d49 --- /dev/null +++ b/app/electron/main/host/tool-context-types.ts @@ -0,0 +1,52 @@ +import type { AgentEvent, Project, Provider, ReasoningEffortSetting, Skill, SubAgent, Thread, WorkspaceLocation } from '../../agent/types' +import type { SshManager } from './ssh' + +export interface ReadOnlySubAgentInput { + task: string + parentLabel: string + cwd: string + projectId?: string | null + providerAccountId?: string | null + project?: Project | null + workspace?: WorkspaceLocation | null + reasoningEffort?: ReasoningEffortSetting + signal: AbortSignal + memoryPolicy?: import('../../agent/types').ThreadMemoryPolicy + incognito?: boolean + memoryOwner?: { id: string; revision: number } + maxSteps?: number + maxWallMs?: number + } + +export interface ToolContextRuntime { + fullToolContext(run?: { thread?: Thread; provider?: Provider; model?: string; signal?: AbortSignal; subAgentId?: string; memoryPolicy?: import('../../agent/types').ThreadMemoryPolicy; memoryOwner?: { id: string; revision: number } }): any + runReadOnlySubAgent( + agent: SubAgent, + provider: Provider, + model: string, + input: ReadOnlySubAgentInput, + ): Promise<{ agent: SubAgent; output: string }> +} + +export interface ToolContextRuntimeDeps { + sshManager: SshManager + persistSubAgents(): void + persistThreads(): void + applyEventToThread(thread: Thread, event: AgentEvent): void + emitToRenderer(event: AgentEvent): void + emitPluginEvent(event: AgentEvent): void + renderProjectMemoryBucket(project: Project | undefined): string + recordEmailDraft: any + recordEmailEvent: any + recordCalendarEvent: any + recordMessageEvent: any + runBrowserAutomation: any + mcpToolContext(): any + // Ends a thread's run; the computer-use indicator's Stop uses it. + cancelThreadRun(threadId: string): void + // Trusted repo-authored skills for a project (VST-010), served from the scan cache so + // this stays synchronous. Absent → global skills only. + projectSkills?(projectId: string | null | undefined, workspace?: WorkspaceLocation | null): Skill[] + // Observer hooks (VST-012): subagent lifecycle observation, fail-open. + observe?: (kind: 'subagent.start' | 'subagent.end', payload: Record) => void +} diff --git a/app/electron/main/host/update-schedule.test.ts b/app/electron/main/host/update-schedule.test.ts new file mode 100644 index 00000000000..beb555417f5 --- /dev/null +++ b/app/electron/main/host/update-schedule.test.ts @@ -0,0 +1,101 @@ +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import { createRequire } from 'node:module' +import { mock } from 'node:test' +import ts from 'typescript' + +const requireBuiltin = createRequire(__filename) +const source = readFileSync(new URL('./updates.ts', import.meta.url), 'utf8') +const compiled = ts.transpileModule(source, { + compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS }, +}).outputText + +function updater() { + const settings = { autoCheckUpdates: true } + const store = { settings, updateStatus: { state: 'idle' } } + const requests: string[] = [] + const feed = 'https://synthetic.invalid/feed' + const imports: Record = { + electron: { app: { getVersion: () => '1.0.0', isPackaged: false } }, + '../../../build/release-trust.json': {}, + '../../agent/update-checker': { + emptyUpdateStatus: () => ({ state: 'idle' }), + checkingUpdateStatus: () => ({ state: 'checking' }), + checkUpdateFeed: async (url: string) => { + requests.push(url) + return { state: 'current' } + }, + }, + '../../agent/update-feed': { resolveUpdateFeedUrl: () => feed }, + '../../agent/security': { assertUpdateFeedUrl: (url: string) => assert.equal(url, feed) }, + '../../store': {}, + '../state': { store }, + './audit': {}, + '../../agent/update-download': {}, + '../../agent/update-trust': {}, + '../../agent/update-install': {}, + './ipc': {}, + './update-profile': {}, + } + const loaded = { exports: {} as typeof import('./updates') } + new Function('require', 'module', 'exports', compiled)((id: string) => { + if (id.startsWith('node:')) return requireBuiltin(id) + assert.ok(Object.hasOwn(imports, id), `Reviewed updater import ${id}`) + return imports[id] + }, loaded, loaded.exports) + return { ...loaded.exports, settings, requests, feed } +} + +async function advance(ms: number) { + mock.timers.tick(ms) + // Let the synthetic feed response finish before advancing to another due callback. + for (let i = 0; i < 12; i++) await Promise.resolve() +} + +async function withClock(run: () => Promise) { + mock.timers.enable({ apis: ['setTimeout', 'setInterval'] }) + try { await run() } + finally { mock.timers.reset() } +} + +await withClock(async () => { + const update = updater() + update.startUpdateChecks() + await advance(100) + update.settings.autoCheckUpdates = false + update.startUpdateChecks() + await advance(6 * 60 * 60_000) + assert.deepEqual(update.requests, [], 'turning automatic checks off cancels the pending first check and interval') + await update.checkForAppUpdate() + assert.deepEqual(update.requests, [update.feed], 'a manual check still works when automatic checks are off') +}) + +await withClock(async () => { + const update = updater() + update.startUpdateChecks() + await advance(100) + // Settings are persisted before the asynchronous post-save work reschedules checks. + update.settings.autoCheckUpdates = false + await advance(1500) + assert.deepEqual(update.requests, [], 'the first callback honors saved Off before rescheduling') + await advance(6 * 60 * 60_000) + assert.deepEqual(update.requests, [], 'the periodic callback also honors saved Off before rescheduling') +}) + +await withClock(async () => { + const update = updater() + update.startUpdateChecks() + await advance(100) + update.startUpdateChecks() + await advance(100) + update.startUpdateChecks() + await advance(1300) + await advance(100) + assert.deepEqual(update.requests, [], 'staggered settings saves cancel the older first checks') + await advance(100) + assert.deepEqual(update.requests, [update.feed], 'only the latest first check reaches the feed') + await advance(6 * 60 * 60_000 - 1500) + assert.deepEqual(update.requests, [update.feed, update.feed], 'automatic checks keep their six-hour interval') +}) + +console.log('Automatic update checks honor saved preferences and coalesce settings reschedules') diff --git a/app/electron/main/host/updates.ts b/app/electron/main/host/updates.ts index e4b7c9eba28..5638e831b04 100644 --- a/app/electron/main/host/updates.ts +++ b/app/electron/main/host/updates.ts @@ -40,6 +40,7 @@ export function signedUpdatesRequired(): boolean { } let updateTimer: ReturnType | null = null +let initialUpdateTimer: ReturnType | null = null let updateCheckInFlight: Promise | null = null let updateDownloadInFlight: Promise<{ ok: boolean }> | null = null let downloadController: AbortController | null = null @@ -118,11 +119,18 @@ export async function checkForAppUpdate(): Promise { export function startUpdateChecks() { if (updateTimer) { clearInterval(updateTimer); updateTimer = null } + if (initialUpdateTimer) { clearTimeout(initialUpdateTimer); initialUpdateTimer = null } const feedUrl = updateFeedUrl() if (!busy()) setUpdateStatus(emptyUpdateStatus(app.getVersion(), feedUrl || null)) if (!store.settings?.autoCheckUpdates || !feedUrl) return - setTimeout(() => { void checkForAppUpdate() }, 1500) - updateTimer = setInterval(() => { void checkForAppUpdate() }, 6 * 60 * 60_000) + const checkIfEnabled = () => { + if (store.settings?.autoCheckUpdates) void checkForAppUpdate() + } + initialUpdateTimer = setTimeout(() => { + initialUpdateTimer = null + checkIfEnabled() + }, 1500) + updateTimer = setInterval(checkIfEnabled, 6 * 60 * 60_000) } export async function openUpdateDownload(): Promise<{ ok: boolean }> { diff --git a/app/electron/main/host/workspace-runtime-ipc.ts b/app/electron/main/host/workspace-runtime-ipc.ts index f3b1af81baf..df570176abc 100644 --- a/app/electron/main/host/workspace-runtime-ipc.ts +++ b/app/electron/main/host/workspace-runtime-ipc.ts @@ -1,42 +1,18 @@ +import { createRoomRunRuntime } from './room-run-runtime' +import type { TicketWorkerRuntime } from './ticket-worker-runtime' +import { reserveRoomStartup, assertLocalTicketGenerationProject, requireActiveRoomForCancel, assertRecordMetadataNotPatched } from './workspace-startup-policy' +export { reserveRoomStartup, assertLocalTicketGenerationProject, requireActiveRoomForCancel, assertRecordMetadataNotPatched } from './workspace-startup-policy' import { registerProjectMemoryIpc } from './project-memory-ipc' -import type { RoomSupervisorMetadataPatch } from '../../agent/jobs' + import type { runRoom as typedRunRoom } from '../../agent/rooms' -import { buildUserContent, contentText } from '../../agent/content' -import { normalizeAttachments } from '../../agent/attachment-policy' -import type { - Attachment, - Job, - Project, - ProjectMemoryCandidate, - ProjectMemoryEntry, - Provider, - RemoteControlEvent, - Room, - RoomManualMemoryCommand, - RoomMergeResult, - RoomStreamEvent, - Seat, - Skill, - Ticket, - TicketWorkOptions, - Thread, -} from '../../agent/types' + +import type { Attachment, Job, Project, RemoteControlEvent, Room, RoomManualMemoryCommand, RoomMergeResult, Skill, Ticket, TicketWorkOptions } from '../../agent/types' import type { store as typedStore } from '../state' import type { handle as typedHandle } from './ipc' import { roomModeDefaults } from '../../agent/room-outcomes' -import { resolveDelegationRoute } from '../../agent/delegation-route' -import { createSharedMemory, MEMORY_MAX_BLOCK_CHARS, MEMORY_MAX_BLOCKS, renderSharedMemory, writeBlock } from '../../agent/shared-room-memory' -import { canonicalLocalWorkspaceKey, lexicalLocalWorkspaceKey, type WorkspaceMutationGuard, type WorkspaceMutationLease } from './workspace-mutation-guard' -import { - applyRoomManualMemoryCommand, - assertRoomConfigUpdateAllowed, - assertRoomSeatRoutesConfigured, - assertTicketUserUpdateAllowed, - pickRoomConfigPatch, - pickRoomManualMemoryCommand, - pickTicketCreateInput, - pickTicketUserPatch, -} from './room-ticket-patch-policy' + +import { canonicalLocalWorkspaceKey, lexicalLocalWorkspaceKey } from './workspace-mutation-guard' +import { applyRoomManualMemoryCommand, assertRoomConfigUpdateAllowed, assertRoomSeatRoutesConfigured, assertTicketUserUpdateAllowed, pickRoomConfigPatch, pickRoomManualMemoryCommand, pickTicketCreateInput, pickTicketUserPatch } from './room-ticket-patch-policy' import { sanitizeProjectCreateInput, sanitizeProjectUpdatePatch, validateProjectExecutionTargetInput, validateProjectProviderDefaults } from './project-patch-policy' import { assertUniqueConfigName, sanitizeSkillSave } from './public-config-policy' import { scanGitHygiene } from '../../agent/git-hygiene' @@ -52,49 +28,7 @@ export interface WorkspaceRuntimeIpc { startRoomRun(roomId: string, problem: string, attachments?: Attachment[]): Promise<{ ok: boolean; room?: Room }> } -export function reserveRoomStartup( - roomId: string, - roomAborters: Map, - guard: Pick, - workspaceKeys: Iterable, -): { controller: AbortController; runLease: WorkspaceMutationLease } | null { - if (roomAborters.has(roomId)) return null - const runLease = guard.reserveStart({ workspaceKeys }) - const controller = new AbortController() - roomAborters.set(roomId, controller) - return { controller, runLease } -} - -export function assertLocalTicketGenerationProject(project: Pick): void { - if (project.workspace?.kind === 'ssh') { - throw new Error('Ticket generation for SSH projects is unavailable until the planner can run on the remote workspace.') - } -} - -export function requireActiveRoomForCancel(rooms: readonly Room[], roomId: string): Room { - const room = rooms.find((candidate) => candidate.id === roomId) - if (!room) throw new Error('Room not found') - if (room.archivedAt) throw new Error('Restore this archived room before cancelling it.') - return room -} - -export function assertRecordMetadataNotPatched(patch: object, additionalHostFields: readonly string[] = []): void { - for (const field of ['id', 'createdAt', 'updatedAt', ...additionalHostFields]) { - if (Object.prototype.hasOwnProperty.call(patch, field)) { - throw new Error(`${field} is host-owned and cannot be changed through update endpoints.`) - } - } -} - -type StartTicketWork = (input: { - ticketId: string - opts?: TicketWorkOptions - source?: { - roomId?: string | null - seat?: string | null - onSettled?: (summary: { codeChanged: boolean; testsPassed: boolean; failed: boolean; jobId?: string | null }) => void - } -}) => Promise +type StartTicketWork = TicketWorkerRuntime['startTicketWork'] export interface WorkspaceRuntimeIpcDeps { store: typeof typedStore @@ -124,64 +58,25 @@ export function createWorkspaceRuntimeIpc(ctx: WorkspaceRuntimeIpcDeps): Workspa auditEvent, auditPreview, persistProjects, - persistThreads, persistRooms, persistTickets, - persistSubAgents, persistSkills, - persistProjectMemory, - persistProjectMemoryCandidates, aborters, roomAborters, DEFAULT_ROOM_COLLABORATION_MODE, DEFAULT_ROOM_WORKER_BUDGET, - ensureRoomWorktree, emitRoom, emitTicket, - emitJob, publishRemote, activeJob, patchRoomSupervisorJob, finishRoomSupervisorMission, finishJob, - ensureRoomSupervisorMission, - roomWorkerBudget, - claimJob, - patchJob, - buildRoomSupervisorJobMetadata, - ticketsForRoom, - runtimeProvider, - inferSeatLane, - appendRoomSupervisorEvent, - ticketNeedsReviewAfterBuilder, - roomTicketConflictBlockers, - summarizeRoomLeftToWork, - describeTicketForRoom, mkTicket, assertTicketRelations, - normalizeTicketCapabilities, normalizeStringList, - ticketEvidenceFromArgs, - ticketFileRefs, startTicketWork, parkRoomIfWorkRemains, - createSubAgentFromLaunch, - parentForRoomSeat, - persistSubAgents: persistSubAgentsFromCtx, - startSubAgent, - runReadOnlySubAgent, - executeTool, - modelRouter, - modelRouteAutoFailoverEnabled, - effectiveContextLimit, - roomContextLimit, - auditScopedModelRoute, - runtimeProviderWithFreshModels, - assertProviderEndpoint, - modelRouteFailoverText, - roomRouteHandoff, - modelRouteResetPolicy, - roomFinalGateBlockers, runRoom, normalizeTicketExecution, ticketWorkOptionsWithProjectRoute, @@ -190,21 +85,12 @@ export function createWorkspaceRuntimeIpc(ctx: WorkspaceRuntimeIpcDeps): Workspa ensureTensorFoldStudioStylePrompt, streamChat, parseJsonLoose, - createProjectMemoryCandidate, - approveProjectMemoryCandidate, - rejectProjectMemoryCandidate, - projectMemoryCandidateDiff, - rollbackProjectMemoryEntry, - forgetProjectMemoryEntry, - scopeProjectMemoryEntries, - scopeProjectMemoryCandidates, registerWebhookIpc, webhookServer, rememberConnectorEvents, validateProjectCwd, confirmSensitiveAction, } = ctx - const persistSubAgentsSafe = persistSubAgentsFromCtx ?? persistSubAgents async function writeIfMissing(file: string, content: string): Promise { try { @@ -445,652 +331,7 @@ function cancelRoomRun(roomId: string): void { finishRoomSupervisorMission(job, 'cancelled', 'Room cancelled by user.') finishJob(job, 'cancelled', 'Room cancelled by user.') } - -async function startRoomRun(roomId: string, problem: string, attachments?: Attachment[]): Promise<{ ok: boolean; room?: Room }> { - requireSecurityRole('operator', 'start rooms') - const room = store.rooms.find((r) => r.id === roomId) - if (!room) throw new Error('Room not found') - if (room.archivedAt) throw new Error('Restore this archived room before starting it.') - // Don't start a second run for a room that's already running — it would overwrite the live - // aborter, making both the first run uncancellable and the second un-stoppable. - if (roomAborters.has(roomId)) return { ok: false, room } - const project = store.projects.find((p) => p.id === room.projectId) - if (!project) throw new Error('Project not found') - if (project.archivedAt) throw new Error('Restore the archived project before starting this room.') - // Rooms broadcast a single text problem to every seat (many are CLI/text-only), so fold - // attachments into text: documents become labelled blocks; images are noted (vision-capable - // seats can't receive pixels through the room channel). - const safeAttachments = normalizeAttachments(attachments) - const cleanProblem = contentText(buildUserContent(String(problem || '').trim(), safeAttachments)).trim() - if (!cleanProblem) throw new Error('Add a room objective before starting.') - if (room.seats.length < 1) throw new Error('Add at least one agent to the room first.') - const configuredWorkspace = room.workspace ?? project.workspace ?? null - if (configuredWorkspace?.kind === 'ssh') { - throw new Error('Local room execution does not support SSH workspaces; run this room on its remote Orchestrator.') - } - const initialPaths = [configuredWorkspace?.path, room.workspaceCwd, room.rootCwd, room.scratchpadCwd, project.cwd] - .filter((value): value is string => typeof value === 'string' && value.trim().length > 0) - const initialWorkspaceKeys = initialPaths.map((value: string) => lexicalLocalWorkspaceKey(value)) - const reservation = reserveRoomStartup(roomId, roomAborters, workspaceMutationGuard, initialWorkspaceKeys) - if (!reservation) return { ok: false, room } - const { controller, runLease } = reservation - const timeout = setTimeout(() => controller.abort(), 30 * 60_000) - roomAborters.set(roomId, controller) - let startupComplete = false - try { - const roomWorkspace = await ensureRoomWorktree(project, room) - const finalWorkspaceKey = await canonicalLocalWorkspaceKey(roomWorkspace) - runLease.addWorkspaceKeys?.([finalWorkspaceKey]) - if (room.archivedAt || project.archivedAt) throw new Error('Room or project was archived while the room was starting.') - if (room.workspaceCwd !== roomWorkspace) { - room.workspaceCwd = roomWorkspace - persistRooms() - } - const roomProject = { ...project, cwd: roomWorkspace } - - room.problem = cleanProblem - room.events = [] - room.finalText = '' - room.state = 'queued' - room.updatedAt = Date.now() - persistRooms() - emitRoom({ roomId, type: 'status', state: 'queued' }) - const supervisorMission = ensureRoomSupervisorMission(room, project, roomWorkspace, cleanProblem) - const supervisorRunId = `room:${room.id}:${Date.now()}` - const configuredWorkerBudget = roomWorkerBudget(room) - let job: Job | null = claimJob({ - kind: 'room', - owner: room.id, - projectId: room.projectId, - missionId: supervisorMission.id, - roomId: room.id, - currentThreadId: null, - metadata: buildRoomSupervisorJobMetadata({ - room, - project, - tickets: ticketsForRoom(room), - patch: { missionId: supervisorMission.id, workerBudget: configuredWorkerBudget, workerStarts: 0 }, - }), - }) - job = patchJob(job, { currentRunId: supervisorRunId }) - - let lastCodeChangeAt = 0 - let greenEvidenceAt = 0 - const providerForSeat = (seat: Seat): Provider | undefined => { - const provider = store.settings.providers.find((p) => p.id === seat.providerId) - return provider ? runtimeProvider(provider, seat.providerAccountId) : undefined - } - if (roomProject.localOnly) { - const cloudSeat = room.seats.find((seat) => providerForSeat(seat)?.kind !== 'local') - if (cloudSeat) { - room.state = 'failed' - persistRooms() - emitRoom({ roomId: room.id, type: 'error', message: `Project is local-only, but seat "${cloudSeat.name}" is not using a local provider.`, fatal: true }) - emitRoom({ roomId: room.id, type: 'status', state: 'failed' }) - emitRoom({ roomId: room.id, type: 'done' }) - clearTimeout(timeout) - roomAborters.delete(room.id) - job = patchRoomSupervisorJob(job, room, project) - finishRoomSupervisorMission(job, 'failed', `Project is local-only, but seat "${cloudSeat.name}" is not using a local provider.`) - finishJob(job, 'failed', `Project is local-only, but seat "${cloudSeat.name}" is not using a local provider.`) - return { ok: false } - } - } - const roomTickets = (): Ticket[] => ticketsForRoom(room) - // Resolve a ticket from free-form LLM tool input. Precedence: exact id, then exact (trimmed, - // case-insensitive) title equality, then a UNIQUE case-insensitive substring. A substring that - // matches multiple tickets is AMBIGUOUS — never silently pick the first (store-insertion-order) - // match, or claim/complete/start could act on the wrong ticket (e.g. "auth" hitting both - // "Add auth" and "Add auth tests"). On ambiguity, `error` is set and `ticket` is undefined. - const resolveTicket = (args: any): { ticket?: Ticket; error?: string } => { - const board = roomTickets() - const id = typeof args?.id === 'string' ? args.id : '' - if (id) { - const byId = board.find((t) => t.id === id) - if (byId) return { ticket: byId } - } - const rawTitle = typeof args?.title === 'string' ? args.title.trim() : '' - if (!rawTitle) return { ticket: undefined } - const wanted = rawTitle.toLowerCase() - const exact = board.filter((t) => t.title.trim().toLowerCase() === wanted) - if (exact.length === 1) return { ticket: exact[0] } - if (exact.length > 1) { - return { error: `"${rawTitle}" matches ${exact.length} tickets with that exact title; reference the ticket by id instead.` } - } - const substr = board.filter((t) => t.title.toLowerCase().includes(wanted)) - if (substr.length === 1) return { ticket: substr[0] } - if (substr.length > 1) { - return { error: `"${rawTitle}" is ambiguous — it matches ${substr.length} tickets (${substr.map((t) => `"${t.title}"`).join(', ')}); use a more specific title or the ticket id.` } - } - return { ticket: undefined } - } - const findTicket = (args: any): Ticket | undefined => resolveTicket(args).ticket - // Mirrors tickets.ts isReservationEvidence / meaningfulTicketEvidence (which are module-private - // there): a "Reserved for build/review worker." note placed by start_ticket_work is a placeholder, - // not real evidence, so it must not satisfy a ticket's required-evidence gate. - const isReservationEvidenceLocal = (item: { kind?: string; summary?: string; ref?: string | null }): boolean => - /\breserved for (?:build|review) worker\b/i.test(`${item.kind ?? ''} ${item.summary ?? ''} ${item.ref ?? ''}`) - const hasMeaningfulEvidence = (tk: Ticket): boolean => - (tk.evidence ?? []).some((item) => !isReservationEvidenceLocal(item)) - const workerBudget = configuredWorkerBudget - let workerStarts = 0 - const activeTicketWorkerCount = () => roomTickets().filter((ticket) => ticket.runState === 'queued' || ticket.runState === 'running').length - const touchSupervisor = (patch: RoomSupervisorMetadataPatch = {}) => { - job = patchRoomSupervisorJob(job, room, project, { workerBudget, workerStarts, ...patch }) - } - const selectAutomaticReviewSeat = (builderSeat: string): Seat | null => { - const candidates = room.seats - .map((seat, index) => { - if (seat.name === builderSeat) return null - if (!providerForSeat(seat)) return null - const reviewRank = inferSeatLane(seat) === 'review' || seat.roleProfileId === 'reviewer' ? 0 : 1 - return { seat, index, reviewRank } - }) - .filter((item): item is { seat: Seat; index: number; reviewRank: number } => !!item) - .sort((a, b) => a.reviewRank - b.reviewRank || a.index - b.index) - return candidates[0]?.seat ?? null - } - const blockAutomaticReview = (tk: Ticket, builderSeat: string, paths: string[], summary: string) => { - touchSupervisor({ phase: { phase: 'review', status: 'blocked', ticketId: tk.id, ticketTitle: tk.title, seat: builderSeat, paths, summary } }) - appendRoomSupervisorEvent(room, `Automatic review not started for "${tk.title}": ${summary}`, { - tool: 'auto_review_scheduler', - args: { ticketId: tk.id, phase: 'review', builderSeat, paths }, - }) - } - const scheduleAutomaticReviewAfterBuild = async (tk: Ticket, builderSeat: string, paths: string[]) => { - if (!ticketNeedsReviewAfterBuilder(tk)) return - const reviewSeat = selectAutomaticReviewSeat(builderSeat) - if (!reviewSeat) { - blockAutomaticReview(tk, builderSeat, paths, 'No suitable different room seat is available for review.') - return - } - const blockers: string[] = roomTicketConflictBlockers({ ticket: tk, tickets: roomTickets(), phase: 'review', seat: reviewSeat.name, paths }) - if (blockers.length) { - blockAutomaticReview(tk, reviewSeat.name, paths, blockers.join(' ')) - return - } - const activeWorkers = activeTicketWorkerCount() - if (activeWorkers >= workerBudget.maxActive) { - blockAutomaticReview(tk, reviewSeat.name, paths, `Worker budget busy: ${activeWorkers}/${workerBudget.maxActive} active.`) - return - } - if (workerStarts >= workerBudget.maxStarts) { - blockAutomaticReview(tk, reviewSeat.name, paths, `Worker budget exhausted: ${workerStarts}/${workerBudget.maxStarts} started.`) - return - } - appendRoomSupervisorEvent(room, `Automatic review queued for "${tk.title}" with ${reviewSeat.name}.`, { - tool: 'auto_review_scheduler', - args: { ticketId: tk.id, phase: 'review', builderSeat, reviewSeat: reviewSeat.name, paths }, - }) - try { - await roomTools.start_ticket_work({ id: tk.id, phase: 'review', paths }, reviewSeat.name) - } catch (err: any) { - blockAutomaticReview(tk, reviewSeat.name, paths, String(err?.message ?? err)) - } - } - const emitRoomProgress = (ev: RoomStreamEvent) => { - if (ev.type === 'status') { - room.state = ev.state - room.updatedAt = Date.now() - persistRooms() - touchSupervisor() - } else if (ev.type === 'turn') { - touchSupervisor({ currentTurnSeat: ev.seat }) - } else if (ev.type === 'event') { - room.updatedAt = Date.now() - persistRooms() - touchSupervisor({ lastEventKind: ev.item.kind, lastEventSeat: ev.item.seat, lastEventAt: ev.item.createdAt }) - } else if (ev.type === 'memory') { - room.updatedAt = Date.now() - persistRooms() - touchSupervisor() - } else if (ev.type === 'final' || ev.type === 'done' || ev.type === 'error') { - touchSupervisor() - } - emitRoom(ev) - } - touchSupervisor() - const roomTools: Record Promise> = { - list_tickets: async () => { - const board = roomTickets() - return board.length ? board.map(describeTicketForRoom).join('\n') : 'The board is empty.' - }, - left_to_work: async () => summarizeRoomLeftToWork(roomTickets()), - create_ticket: async (args) => { - const tk = mkTicket(room.projectId, { - roomId: room.id, - title: args?.title || 'Untitled', - body: args?.body || '', - priority: args?.priority, - effort: args?.effort, - type: args?.type || 'task', - status: 'ready', - tags: args?.tags, - risk: args?.risk, - allowedCapabilities: args?.allowedCapabilities, - requiredEvidence: args?.requiredEvidence, - acceptanceCriteria: args?.acceptanceCriteria, - evidence: args?.evidence, - }) - store.tickets.unshift(tk); persistTickets(); emitTicket(tk) - return `Created ticket "${tk.title}" with ${tk.risk ?? 'low'} risk, allowed capabilities ${normalizeTicketCapabilities(tk.allowedCapabilities, ['read']).join(', ')}, and ${tk.requiredEvidence?.length ?? 0} required evidence item(s).` - }, - claim_ticket: async (args, seat) => { - const resolved = resolveTicket(args) - if (resolved.error) return resolved.error - const tk = resolved.ticket - if (!tk) return `No ticket matches "${args?.title ?? args?.id ?? ''}".` - if (tk.assignee && tk.assignee !== seat) return `Already claimed by ${tk.assignee}. Pick another ticket.` - tk.assignee = seat; tk.status = 'in_progress'; tk.updatedAt = Date.now(); persistTickets(); emitTicket(tk) - const required = normalizeStringList(tk.requiredEvidence, []) - const caps = normalizeTicketCapabilities(tk.allowedCapabilities, ['read']).join(', ') - return `You claimed "${tk.title}". Allowed capabilities: ${caps}. Required evidence: ${required.length ? required.join('; ') : 'none'}.` - }, - add_ticket_evidence: async (args, seat) => { - const tk = findTicket(args) - if (!tk) return 'No matching ticket.' - if (tk.assignee && tk.assignee !== seat) return `Only ${tk.assignee} can add evidence to "${tk.title}".` - const evidence = ticketEvidenceFromArgs(args, seat) - if (!evidence.length) return 'No evidence summary was provided.' - tk.assignee = tk.assignee ?? seat - tk.evidence = [...(tk.evidence ?? []), ...evidence] - tk.updatedAt = Date.now() - persistTickets(); emitTicket(tk) - return `Added ${evidence.length} evidence item(s) to "${tk.title}".` - }, - complete_ticket: async (args, seat) => { - const resolved = resolveTicket(args) - if (resolved.error) return resolved.error - const tk = resolved.ticket - if (!tk) return 'No matching ticket.' - if (tk.assignee && tk.assignee !== seat) return `Only ${tk.assignee} can complete "${tk.title}".` - const evidence = ticketEvidenceFromArgs(args, seat) - if (evidence.length) tk.evidence = [...(tk.evidence ?? []), ...evidence] - const required = normalizeStringList(tk.requiredEvidence, []) - // Only MEANINGFUL evidence satisfies the required-evidence gate — reservation/placeholder notes - // appended by start_ticket_work ("Reserved for build/review worker.") must not count, or a - // ticket can be flipped to 'completed' with zero real evidence (the room final gate uses the - // same meaningful filter, so this keeps the per-ticket gate consistent with it). - if (required.length && !hasMeaningfulEvidence(tk)) return `Cannot complete "${tk.title}" until evidence is attached: ${required.join('; ')}.` - tk.assignee = seat; tk.status = 'completed'; tk.updatedAt = Date.now(); persistTickets(); emitTicket(tk) - return `Completed "${tk.title}" with ${tk.evidence?.length ?? 0} evidence item(s).` - }, - start_ticket_work: async (args, seat) => { - const resolved = resolveTicket(args) - if (resolved.error) return resolved.error - const tk = resolved.ticket - if (!tk) return `No ticket matches "${args?.title ?? args?.id ?? ''}".` - const phase = args?.phase === 'review' ? 'review' : 'build' - const declaredPaths: string[] = normalizeStringList(args?.paths, []) - const mergeDecision = typeof args?.mergeDecision === 'string' ? args.mergeDecision.trim() : '' - const blockers: string[] = roomTicketConflictBlockers({ ticket: tk, tickets: roomTickets(), phase, seat, paths: declaredPaths }) - const overlapBlockers = blockers.filter((blocker) => /\boverlaps with\b/i.test(blocker)) - const hardBlockers = blockers.filter((blocker) => !overlapBlockers.includes(blocker)) - const effectiveBlockers = mergeDecision && overlapBlockers.length ? hardBlockers : blockers - if (blockers.length) { - if (effectiveBlockers.length) { - touchSupervisor({ phase: { phase, status: 'blocked', ticketId: tk.id, ticketTitle: tk.title, seat, paths: declaredPaths, summary: effectiveBlockers.join(' ') } }) - return `Blocked by room supervisor: ${effectiveBlockers.join(' ')}` - } - appendRoomSupervisorEvent(room, `Merge decision accepted for "${tk.title}": ${mergeDecision}`, { - tool: 'merge_decision', - args: { ticketId: tk.id, phase, seat, paths: declaredPaths, blockers: overlapBlockers }, - }) - tk.evidence = [ - ...(tk.evidence ?? []), - { - id: randomUUID(), - kind: 'note', - summary: `Supervisor merge decision: ${mergeDecision}. Waived overlap blocker(s): ${overlapBlockers.join(' ')}`, - ref: declaredPaths[0] ?? null, - createdBy: 'room-supervisor', - createdAt: Date.now(), - }, - ] - } - const activeWorkers = activeTicketWorkerCount() - if (activeWorkers >= workerBudget.maxActive) { - touchSupervisor({ phase: { phase, status: 'blocked', ticketId: tk.id, ticketTitle: tk.title, seat, paths: declaredPaths, summary: `Worker budget busy: ${activeWorkers}/${workerBudget.maxActive} active.` } }) - return `Room worker budget busy: ${activeWorkers}/${workerBudget.maxActive} active ticket workers. Use left_to_work and wait for a worker result.` - } - if (workerStarts >= workerBudget.maxStarts) { - touchSupervisor({ phase: { phase, status: 'blocked', ticketId: tk.id, ticketTitle: tk.title, seat, paths: declaredPaths, summary: `Worker budget exhausted: ${workerStarts}/${workerBudget.maxStarts} started.` } }) - return `Room worker budget exhausted: ${workerStarts}/${workerBudget.maxStarts} ticket workers started in this room run.` - } - const seatConfig = room.seats.find((candidate) => candidate.name === seat) - if (!seatConfig) return 'Cannot start worker: room seat is no longer configured.' - // Snapshot before the pre-launch mutation so a failed launch can restore the ticket - // instead of wedging it (runState 'queued' blocks retries via roomTicketConflictBlockers, - // counts against the worker budget, and keeps the final gate open). - const prevAssignee = tk.assignee - const prevStatus = tk.status - workerStarts++ - // Only a BUILD-phase start takes ownership of the ticket. A review-phase start must NOT - // overwrite the builder's assignee with the reviewer — doing so erases the builder's claim and - // makes a later build-phase conflict check (roomTicketConflictBlockers) report the ticket as - // claimed by the reviewer, blocking the original builder from their own ticket. The reviewer's - // identity is tracked separately via the review evidence (createdBy), not tk.assignee. - if (phase === 'build') tk.assignee = seat - tk.status = 'in_progress' - tk.runState = 'queued' - if (declaredPaths.length) { - tk.evidence = [ - ...(tk.evidence ?? []), - ...declaredPaths.map((ref) => ({ id: randomUUID(), kind: 'file' as const, summary: `Reserved for ${phase} worker.`, ref, createdBy: seat, createdAt: Date.now() })), - ] - } - tk.updatedAt = Date.now() - persistTickets(); emitTicket(tk) - touchSupervisor({ phase: { phase, status: 'queued', ticketId: tk.id, ticketTitle: tk.title, seat, paths: declaredPaths, summary: 'Ticket worker queued.' } }) - const knownPaths = ticketFileRefs(tk, declaredPaths) - let workerThreadId: string | null = null - let thread: Thread - try { - thread = await startTicketWork({ - ticketId: tk.id, - opts: { phase, providerId: seatConfig.providerId, providerAccountId: seatConfig.providerAccountId ?? null, model: seatConfig.model }, - source: { - roomId: room.id, - seat, - onSettled: ({ codeChanged, testsPassed, failed, jobId }) => { - if (codeChanged) lastCodeChangeAt = Date.now() - if (testsPassed) greenEvidenceAt = Date.now() - touchSupervisor({ - phase: { - phase, - status: tk.status === 'needs_clarification' ? 'failed' : 'completed', - ticketId: tk.id, - ticketTitle: tk.title, - seat, - threadId: workerThreadId, - jobId: jobId ?? activeJob('ticket', tk.id)?.id ?? null, - paths: knownPaths, - summary: tk.status === 'needs_clarification' ? 'Ticket worker needs clarification.' : 'Ticket worker finished.', - }, - }) - if (phase === 'build' && !failed) void scheduleAutomaticReviewAfterBuild(tk, seat, knownPaths) - }, - }, - }) - } catch (launchError: any) { - // Launch failed: unwind the pre-launch mutation so the ticket is retryable instead - // of wedged as 'queued' (which blocks retries, burns budget, and holds the gate). - workerStarts-- - tk.runState = null - tk.status = prevStatus - tk.assignee = prevAssignee - tk.updatedAt = Date.now() - persistTickets(); emitTicket(tk) - touchSupervisor({ phase: { phase, status: 'failed', ticketId: tk.id, ticketTitle: tk.title, seat, paths: declaredPaths, summary: `Worker launch failed: ${launchError?.message ?? launchError}` } }) - return `Cannot start worker: launch failed: ${launchError?.message ?? launchError}` - } - workerThreadId = thread.id - touchSupervisor({ - phase: { - phase, - status: 'running', - ticketId: tk.id, - ticketTitle: tk.title, - seat, - threadId: thread.id, - jobId: activeJob('ticket', tk.id)?.id ?? null, - paths: knownPaths, - summary: 'Ticket worker running.', - }, - }) - return `Room Supervisor started ${phase} worker thread ${thread.id} for "${tk.title}"${knownPaths.length ? ` on ${knownPaths.slice(0, 4).join(', ')}` : ''}.` - }, - delegate: async (args, seat) => { - const s = room.seats.find((x) => x.name === seat) - if (!s) return 'Cannot delegate: seat misconfigured.' - // Optional cross-model route: targetSeat adopts that seat's provider/account/model; - // explicit providerId/accountId/model override it; absent fields inherit this seat. - // A local-only project may not delegate out to a cloud provider (same guard the - // thread runtime and room seat config enforce). - const routed = resolveDelegationRoute(store.settings.providers, { - providerId: s.providerId, - providerAccountId: s.providerAccountId, - model: s.model, - }, args ?? {}, room.seats, roomProject.localOnly === true) - if (!routed.route) return `Cannot delegate: ${routed.error}.` - const routeAccountId = routed.route.providerAccountId ?? null - const routeProvider = store.settings.providers.find((p) => p.id === routed.route.providerId) - const prov = routeProvider ? runtimeProvider(routeProvider, routed.route.providerAccountId) : undefined - if (!prov) return s.providerId === routed.route.providerId ? 'Cannot delegate: seat misconfigured.' : `Cannot delegate: provider "${routed.route.providerId}" is not configured.` - const task = String(args?.task || '').trim() || 'Focused room subtask' - const name = typeof args?.name === 'string' ? args.name.trim() : '' - const runId = `subagent-${randomUUID()}` - const created = createSubAgentFromLaunch(store.subAgents, { - source: 'room_delegate', - parent: parentForRoomSeat(room, s), - task, - name, - providerId: routed.route.providerId, - providerAccountId: routeAccountId, - model: routed.route.model, - runId, - cwd: roomWorkspace, - }) - store.subAgents = created.agents - persistSubAgentsSafe() - if (args && typeof args === 'object') { - args.id = created.agent.id - args.name = created.agent.name - args.task = task - args.parentSeat = seat - args.providerId = routed.route.providerId - args.providerAccountId = routeAccountId - args.model = routed.route.model - if (routed.notice) args.notice = routed.notice - args.status = 'running' - } - const started = startSubAgent(store.subAgents, created.agent.id, runId) - store.subAgents = started.agents - persistSubAgentsSafe() - const launched = await runReadOnlySubAgent(created.agent, prov, routed.route.model, { - task, - parentLabel: `room seat "${seat}" in room "${room.name}"`, - cwd: roomWorkspace, - projectId: room.projectId, - providerAccountId: routeAccountId, - signal: controller.signal, - project: roomProject, - maxSteps: 10, - maxWallMs: 150_000, - }) - if (args && typeof args === 'object') { - args.status = launched.agent.status - args.result = launched.agent.result - args.error = launched.agent.error - } - return routed.notice ? `${routed.notice}\n${launched.output}` : launched.output - }, - // Room tools are read-only by default. Mutating tools need a future room-level approval UI. - // memory_write is room state (the shared scratchpad), not workspace mutation, so it is allowed. - memory_write: async (args, seat) => { - const name = typeof args?.name === 'string' ? args.name.trim() : '' - const content = typeof args?.content === 'string' ? args.content.trim() : '' - if (!name || !content) return 'memory_write needs a "name" (decisions, plan, blockers, or any label) and "content".' - if (!room.sharedMemory) room.sharedMemory = createSharedMemory() - const mode = args?.mode === 'append' || args?.mode === 'append-bullet' ? args.mode : 'replace' - const expectedRevision = typeof args?.expectedRevision === 'number' ? args.expectedRevision : undefined - const result = writeBlock(room.sharedMemory, { name, content, author: seat, mode, expectedRevision }) - if (!result.ok) { - if (result.reason === 'conflict') return `Memory conflict on "${name}": current revision is ${result.currentRevision}. Re-read the block and retry.` - if (result.reason === 'content-too-large') return `Memory block "${name}" is too large: content is capped at ${MEMORY_MAX_BLOCK_CHARS} characters. Summarize it and retry.` - if (result.reason === 'block-limit') return `Shared memory is full (${MEMORY_MAX_BLOCKS} blocks). Update an existing block instead of adding a new one.` - return 'Memory write needs a non-empty name.' - } - room.updatedAt = Date.now() - persistRooms() - // Live push so the renderer reflects the write without waiting for a full snapshot. - if (result.changed) publishRemote?.({ kind: 'room', data: room }) - return result.changed - ? `Memory "${result.block.name}" updated (rev ${result.block.revision}).\n${renderSharedMemory(room.sharedMemory)}` - : `Memory "${result.block.name}" already says that (rev ${result.block.revision}).` - }, - read_file: async (args) => { const r = await executeTool('read_file', args, { cwd: roomWorkspace }); return r.output.slice(0, 4000) }, - list_dir: async (args) => { const r = await executeTool('list_dir', args, { cwd: roomWorkspace }); return r.output.slice(0, 2000) }, - search: async (args) => { const r = await executeTool('search', args, { cwd: roomWorkspace }); return r.output.slice(0, 2000) }, - write_file: async (args) => { - await auditEvent('room.tool_blocked', { roomId: room.id, tool: 'write_file', path: auditPreview(args?.path) }) - return 'Blocked: room agents are read-only until a room-level approval gate is available. Create/claim a ticket and run the work in an approved thread.' - }, - edit_file: async (args) => { - await auditEvent('room.tool_blocked', { roomId: room.id, tool: 'edit_file', path: auditPreview(args?.path) }) - return 'Blocked: room agents are read-only until a room-level approval gate is available. Create/claim a ticket and run the work in an approved thread.' - }, - run_command: async (args) => { - await auditEvent('room.tool_blocked', { roomId: room.id, tool: 'run_command', command: auditPreview(args?.command) }) - return 'Blocked: room agents cannot run shell commands unattended. Ask the user to run an approved thread or terminal command.' - }, - } - - // Supervisor mode: an ASSIGN auto-starts the addressed seat's ticket worker. - // The ticket is resolved from the ASSIGN text (a verbatim ticket title inside the - // text wins; otherwise the text minus the seat name is used as a title query), then - // routed through the standard start_ticket_work path so budget/conflict gates apply. - const autoStartAssignedTicket = async ({ target, text }: { seat: string; target: string; text: string }): Promise => { - const board = roomTickets().filter((t) => t.status !== 'completed') - const hay = text.toLowerCase() - const inText = board.filter((t) => t.title.trim() && hay.includes(t.title.trim().toLowerCase())) - let tk = inText.length === 1 ? inText[0] : undefined - if (!tk && inText.length > 1) { - const matches = inText.slice(0, 4).map((t) => `"${t.title}"`).join(', ') - return `ASSIGN auto-start skipped: the text matches ${inText.length} open tickets (${matches}). Name one verbatim to start it.` - } - if (!tk && inText.length === 0) { - const remainder = text.replace(new RegExp(`\\b${target.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`, 'ig'), '').trim() - const resolved = resolveTicket({ title: remainder }) - if (resolved.error) return `ASSIGN auto-start skipped: ${resolved.error}` - tk = resolved.ticket - } - if (!tk) return `ASSIGN to ${target} noted, but no open ticket title matched. Create the ticket with create_ticket first, then assign it.` - if (tk.assignee && tk.assignee !== target) return `ASSIGN auto-start skipped: "${tk.title}" is already claimed by ${tk.assignee}.` - return roomTools.start_ticket_work({ id: tk.id, phase: 'build' }, target) - } - - runRoom({ - room, project: roomProject, providers: store.settings.providers, problem: cleanProblem, - temperature: store.settings.temperature, reasoningEffort: store.settings.reasoningEffort, - emit: emitRoomProgress, signal: controller.signal, tools: roomTools, - onAssign: autoStartAssignedTicket, - providerForSeat, - recoverSeatModel: async (seat, error) => { - const latestBaseProvider = store.settings.providers.find((p) => p.id === seat.providerId) - if (!latestBaseProvider) return null - const currentAccountId = seat.providerAccountId ?? null - const routed = modelRouter.routeAfterError({ - role: 'room_seat', - provider: latestBaseProvider, - accountId: currentAccountId, - model: seat.model, - error, - allowFailover: modelRouteAutoFailoverEnabled(latestBaseProvider, currentAccountId), - localOnly: roomProject.localOnly === true, - contextLimit: effectiveContextLimit(latestBaseProvider, seat.model, currentAccountId), - reasoningEffort: store.settings.reasoningEffort, - budget: room.workerBudget?.maxActive ?? null, - source: 'room_seat_recovery', - }) - if (routed.signal) { - for (const audit of routed.audit) { - await auditScopedModelRoute('room', audit, routed.signal, { - roomId: room.id, - seatId: seat.id, - seatName: seat.name, - jobId: job?.id ?? null, - missionId: supervisorMission.id, - }) - } - } - if (!routed.signal || !routed.route.selected || routed.route.selectedAccountId === currentAccountId) return null - const providerAccountId = routed.route.selectedAccountId - const provider = await runtimeProviderWithFreshModels(latestBaseProvider, providerAccountId) - assertProviderEndpoint(provider) - const liveSeat = room.seats.find((candidate) => candidate.id === seat.id) - if (liveSeat) { - liveSeat.providerId = latestBaseProvider.id - liveSeat.providerAccountId = providerAccountId - liveSeat.model = seat.model - } - room.updatedAt = Date.now() - persistRooms() - const failoverText = modelRouteFailoverText(latestBaseProvider, routed.route.audit, routed.signal) - const notice = `${failoverText}\n${roomRouteHandoff(room, seat, failoverText)}` - job = patchJob(job, { - metadata: { - modelRoute: { - action: 'room_failover', - seatId: seat.id, - seatName: seat.name, - providerId: latestBaseProvider.id, - model: seat.model, - preferredProviderAccountId: currentAccountId, - failoverProviderAccountId: providerAccountId, - resetPolicy: modelRouteResetPolicy(latestBaseProvider, currentAccountId), - resetAt: routed.signal.resetAt, - reason: routed.route.audit.reason, - }, - }, - }) - touchSupervisor() - return { provider, providerAccountId, model: seat.model, notice } - }, - contextLimitForSeat: (seat) => { - if (!store.settings.autoCompact) return 0 - const provider = providerForSeat(seat) - if (!provider) return 0 - // Task #41: in a mixed-model room every seat compacts to the lowest seat's - // limit so no model silently overflows. Fall back to this seat's own limit - // if the floor can't be computed (e.g. another seat is misconfigured). - const floor = roomContextLimit( - room.seats - .map((s) => ({ provider: providerForSeat(s), model: s.model })) - .filter((entry): entry is { provider: Provider; model: string } => !!entry.provider), - { - cloudLimit: store.settings.contextLimit, - localLimit: store.settings.localContextLimit, - contextLimitExplicit: store.settings.contextLimitExplicit, - localContextLimitExplicit: store.settings.localContextLimitExplicit, - override: store.settings.contextLimitOverride, - engineModelProfiles: store.settings.engineModelProfiles, - }, - ) - return floor > 0 ? floor : effectiveContextLimit(provider, seat.model) - }, - finalGate: () => { - return roomFinalGateBlockers({ tickets: roomTickets(), lastCodeChangeAt, greenEvidenceAt }) - }, - }) - .catch((err) => emitRoomProgress({ roomId, type: 'error', message: String(err?.message ?? err), fatal: true })) - .finally(() => { - clearTimeout(timeout) - roomAborters.delete(roomId) - runLease.release() - const failed = room.state === 'failed' || room.state === 'error' - const parked = !controller.signal.aborted && !failed && parkRoomIfWorkRemains(job, room, project) - if (!parked) { - touchSupervisor({ currentTurnSeat: null }) - const outcome = controller.signal.aborted ? 'paused' : failed ? 'failed' : 'completed' - const reason = failed ? 'Room ended with an error.' : controller.signal.aborted ? 'Room paused after the active run stopped.' : undefined - finishRoomSupervisorMission(job, outcome, reason) - finishJob(job, outcome, reason) - } - room.updatedAt = Date.now() - persistRooms() - }) - - startupComplete = true - return { ok: true, room } - } finally { - if (!startupComplete) { - clearTimeout(timeout) - if (roomAborters.get(roomId) === controller) roomAborters.delete(roomId) - runLease.release() - } - } -} + const { startRoomRun } = createRoomRunRuntime(ctx) handle('room:cancel', async (_e, roomId: string) => cancelRoomRun(roomId)) handle('room:start', async (_e, { roomId, problem, attachments }: { roomId: string; problem: string; attachments?: Attachment[] }) => startRoomRun(roomId, problem, attachments)) diff --git a/app/electron/main/host/workspace-startup-policy.ts b/app/electron/main/host/workspace-startup-policy.ts new file mode 100644 index 00000000000..f1ef24fd0b8 --- /dev/null +++ b/app/electron/main/host/workspace-startup-policy.ts @@ -0,0 +1,36 @@ +import type { Project, Room } from '../../agent/types' +import type { WorkspaceMutationGuard, WorkspaceMutationLease } from './workspace-mutation-guard' + +export function reserveRoomStartup( + roomId: string, + roomAborters: Map, + guard: Pick, + workspaceKeys: Iterable, +): { controller: AbortController; runLease: WorkspaceMutationLease } | null { + if (roomAborters.has(roomId)) return null + const runLease = guard.reserveStart({ workspaceKeys }) + const controller = new AbortController() + roomAborters.set(roomId, controller) + return { controller, runLease } +} + +export function assertLocalTicketGenerationProject(project: Pick): void { + if (project.workspace?.kind === 'ssh') { + throw new Error('Ticket generation for SSH projects is unavailable until the planner can run on the remote workspace.') + } +} + +export function requireActiveRoomForCancel(rooms: readonly Room[], roomId: string): Room { + const room = rooms.find((candidate) => candidate.id === roomId) + if (!room) throw new Error('Room not found') + if (room.archivedAt) throw new Error('Restore this archived room before cancelling it.') + return room +} + +export function assertRecordMetadataNotPatched(patch: object, additionalHostFields: readonly string[] = []): void { + for (const field of ['id', 'createdAt', 'updatedAt', ...additionalHostFields]) { + if (Object.prototype.hasOwnProperty.call(patch, field)) { + throw new Error(`${field} is host-owned and cannot be changed through update endpoints.`) + } + } +} diff --git a/app/shared/bot-reasoning.ts b/app/shared/bot-reasoning.ts index ac8e5c8bf1e..7a2f26c4599 100644 --- a/app/shared/bot-reasoning.ts +++ b/app/shared/bot-reasoning.ts @@ -1,12 +1,9 @@ import type { ReasoningEffortSetting, Thread } from '../electron/agent/types' - -const efforts = new Set([ - 'none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultrathink', 'ultracode', 'dynamic', '512', -]) +import { isReasoningEffortSetting } from './reasoning-effort' export function normalizeBotReasoningEffort(value: unknown): ReasoningEffortSetting | undefined { if (value === undefined) return undefined - if (typeof value !== 'string' || !efforts.has(value as ReasoningEffortSetting)) { + if (!isReasoningEffortSetting(value)) { throw new Error('Invalid bot reasoning effort; choose an available effort level.') } return value as ReasoningEffortSetting diff --git a/app/shared/reasoning-effort.ts b/app/shared/reasoning-effort.ts new file mode 100644 index 00000000000..5d9670146e1 --- /dev/null +++ b/app/shared/reasoning-effort.ts @@ -0,0 +1,19 @@ +import type { ReasoningEffortSetting } from '../electron/agent/types' + +const efforts = new Set([ + 'none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultrathink', 'ultracode', 'dynamic', '512', +]) + +export function isReasoningEffortSetting(value: unknown): value is ReasoningEffortSetting { + return typeof value === 'string' && efforts.has(value as ReasoningEffortSetting) +} + +export function captureAgentReasoningEffort( + agent: { reasoningEffort?: ReasoningEffortSetting } | undefined, + fallback: T, +): ReasoningEffortSetting | T { + const value = agent?.reasoningEffort + if (value === undefined) return fallback + if (!isReasoningEffortSetting(value)) throw new Error('Invalid agent reasoning effort; choose an available effort level.') + return value +} diff --git a/app/src/components/ExportPanel.test.tsx b/app/src/components/ExportPanel.test.tsx new file mode 100644 index 00000000000..c94f52d734b --- /dev/null +++ b/app/src/components/ExportPanel.test.tsx @@ -0,0 +1,129 @@ +import assert from 'node:assert/strict' +import { find, harness, jsx, load, settle, text } from './reading/reading-test-harness' + +type Request = { threadId: string; options: { mode: string; redact: boolean } } +const hook = harness() +hook.hooks.useCallback = (callback: unknown) => hook.hooks.useRef(callback).current +const builds: (Request & { finish: (label: string) => void; fail: () => void })[] = [] +const saves: (Request & { finish: () => void })[] = [] +const copies: { json: string; finish: () => void }[] = [] +const windowFixture = new EventTarget() +Object.defineProperty(globalThis, 'window', { configurable: true, value: windowFixture }) +Object.defineProperty(globalThis, 'navigator', { configurable: true, value: { + clipboard: { writeText: (json: string) => new Promise((finish) => copies.push({ json, finish })) }, +} }) + +const api = { + buildExport: (threadId: string, options: Request['options']) => new Promise((resolve, reject) => { + builds.push({ + threadId, + options, + finish: (label) => resolve({ json: label, bundle: { + thread: { title: label }, + stats: { messages: 0, toolCalls: 0, diffs: 0, denied: 0, errors: 0 }, + redactionReport: [], + } }), + fail: () => reject(new Error('synthetic build failure')), + }) + }), + saveExport: (threadId: string, options: Request['options']) => new Promise((resolve) => { + saves.push({ threadId, options, finish: () => resolve({ saved: true }) }) + }), +} +const { ExportPanel } = load('src/components/ExportPanel.tsx', { + react: hook.hooks, 'react/jsx-runtime': jsx, + clsx: (...classes: string[]) => classes.filter(Boolean).join(' '), + '../lib/ipc': { api }, '../lib/icons': { Icon: () => null }, +}) +const render = () => hook.render(() => ExportPanel()) +const open = () => windowFixture.dispatchEvent(new CustomEvent('vontra:export', { detail: { threadId: 'test-run' } })) +const button = (tree: ReturnType, label: string) => find(tree, (node) => node.type === 'button' && text(node) === label) +const setRedact = (checked: boolean) => find(render(), (node) => node.type === 'input').props.onChange({ target: { checked } }) +const preview = (tree: ReturnType) => text(find(tree, (node) => node.type === 'pre')) +const assertUnavailable = (tree: ReturnType) => { + assert.equal(button(tree, 'Copy JSON').props.disabled, true) + assert.equal(button(tree, 'Save…').props.disabled, true) +} + +render() +hook.flush() +open() +render() +hook.flush() +builds[0].finish('first preview') +await settle() +const ready = render() +assert.equal(preview(ready), 'first preview') +assert.equal(button(ready, 'Copy JSON').props.disabled, false) +assert.equal(button(ready, 'Save…').props.disabled, false) +const copy = button(ready, 'Copy JSON').props.onClick +const save = button(ready, 'Save…').props.onClick +const copying = copy() +const saving = save() +assert.equal(copies[0].json, 'first preview') +assert.deepEqual(saves[0].options, { mode: 'full', redact: true }) + +setRedact(false) +const staleCopy = copy() +const staleSave = save() +const pending = render() +assert.equal(preview(pending), 'Building…') +assert.equal(text(pending).includes('first preview'), false) +assertUnavailable(pending) +await Promise.all([staleCopy, staleSave]) +assert.equal(copies.length, 1) +assert.equal(saves.length, 1) +hook.flush() +assert.deepEqual(builds[1].options, { mode: 'full', redact: false }) +setRedact(true) +render() +hook.flush() +assert.deepEqual(builds[2].options, { mode: 'full', redact: true }) +copies[0].finish() +saves[0].finish() +await Promise.all([copying, saving]) +assert.equal(text(render()).includes('Saved'), false) +assertUnavailable(render()) +builds[2].finish('replacement preview') +await settle() +builds[1].fail() +await settle() +assert.equal(preview(render()), 'replacement preview') + +button(render(), 'Share packet').props.onClick() +render() +hook.flush() +assert.deepEqual(builds[3].options, { mode: 'share', redact: true }) +builds[3].fail() +await settle() +assert.equal(preview(render()), 'Nothing to export.') +assertUnavailable(render()) +button(render(), 'Full run').props.onClick() +render() +hook.flush() +button(render(), 'esc').props.onClick() +assert.equal(render(), null) +hook.flush() +open() +assertUnavailable(render()) +hook.flush() +assert.equal(builds[5].threadId, 'test-run') +builds[4].finish('closed preview') +await settle() +assert.equal(preview(render()), 'Building…') +assertUnavailable(render()) +builds[5].finish('reopened preview') +await settle() +const reopened = render() +assert.equal(preview(reopened), 'reopened preview') +const reopenedCopy = button(reopened, 'Copy JSON').props.onClick() +const reopenedSave = button(reopened, 'Save…').props.onClick() +assert.equal(copies[1].json, 'reopened preview') +assert.equal(saves[1].threadId, 'test-run') +assert.deepEqual(saves[1].options, { mode: 'full', redact: true }) +copies[1].finish() +saves[1].finish() +await Promise.all([reopenedCopy, reopenedSave]) +assert.ok(button(render(), 'Copied')) +assert.equal(text(render()).includes('Saved'), true) +hook.cleanup() diff --git a/app/src/components/ExportPanel.tsx b/app/src/components/ExportPanel.tsx index 51111c4e049..5c5e8d154d9 100644 --- a/app/src/components/ExportPanel.tsx +++ b/app/src/components/ExportPanel.tsx @@ -1,7 +1,7 @@ import { useAuthoredText } from '../lib/preferences/useAuthoredText' import { authoredText } from '../lib/preferences/language-packs' import { useStore as useLocaleStore } from '../lib/store' -import { useEffect, useRef, useState } from 'react' +import { useCallback, useEffect, useRef, useState } from 'react' import clsx from 'clsx' import { api } from '../lib/ipc' import { Icon, type IconName } from '../lib/icons' @@ -17,40 +17,52 @@ const MODES: { id: ExportMode; label: string; icon: IconName; blurb: string }[] { id: 'eval', get label() { return authoredText(useLocaleStore.getState().settings?.uiPreferences?.locale, "Eval replay") }, icon: 'spark', blurb: 'Replay skeleton — prompts, tool calls and outcomes only; reasoning dropped, anonymized.' }, ] +type ExportSelection = { threadId: string; mode: ExportMode; redact: boolean } +type ExportPreview = { selection: ExportSelection; result: ExportResult | null } + export function ExportPanel() { const tx = useAuthoredText() - const [threadId, setThreadId] = useState(null) - const [mode, setMode] = useState('full') - const [redact, setRedact] = useState(true) - const [result, setResult] = useState(null) - const [building, setBuilding] = useState(false) + const [selection, setSelection] = useState(null) + const [preview, setPreview] = useState(null) const [saved, setSaved] = useState(null) const [copied, setCopied] = useState(false) - const reqRef = useRef(0) + const selectionRef = useRef(selection) + const choose = useCallback((next: ExportSelection | null) => { + selectionRef.current = next + setSelection(next) + setPreview(null) + setSaved(null) + setCopied(false) + }, []) useEffect(() => { const onOpen = (e: Event) => { const id = (e as CustomEvent).detail?.threadId - if (typeof id !== 'string') return - setThreadId(id); setMode('full'); setRedact(true); setSaved(null); setCopied(false) + if (typeof id !== 'string' || !id) return + choose({ threadId: id, mode: 'full', redact: true }) } window.addEventListener('vontra:export', onOpen as EventListener) return () => window.removeEventListener('vontra:export', onOpen as EventListener) - }, []) + }, [choose]) - // Rebuild the bundle whenever the target or options change (request-id guards races). useEffect(() => { - if (!threadId) { setResult(null); return } - const req = ++reqRef.current - setBuilding(true); setSaved(null); setCopied(false) + if (!selection) return + const { threadId, mode, redact } = selection + let active = true + const finish = (result: ExportResult | null) => { + if (active && selectionRef.current === selection) setPreview({ selection, result }) + } api.buildExport(threadId, { mode, redact }) - .then((r) => { if (req === reqRef.current) setResult(r) }) - .catch(() => { if (req === reqRef.current) setResult(null) }) - .finally(() => { if (req === reqRef.current) setBuilding(false) }) - }, [threadId, mode, redact]) - - if (!threadId) return null - const close = () => setThreadId(null) + .then(finish, () => finish(null)) + return () => { active = false } + }, [selection]) + + if (!selection) return null + const { threadId, mode, redact } = selection + const currentPreview = preview?.selection === selection ? preview : null + const building = currentPreview === null + const result = currentPreview?.result + const close = () => { if (selectionRef.current === selection) choose(null) } const bundle = result?.bundle const totalRedactions = bundle?.redactionReport.reduce((n, r) => n + r.count, 0) ?? 0 const evidence = bundle?.evidence @@ -59,13 +71,18 @@ export function ExportPanel() { : 0 const onCopy = async () => { - if (!result) return - try { await navigator.clipboard.writeText(result.json); setCopied(true); setTimeout(() => setCopied(false), 1600) } catch { /* clipboard blocked */ } + if (!result || selectionRef.current !== selection) return + try { + await navigator.clipboard.writeText(result.json) + if (selectionRef.current !== selection) return + setCopied(true) + setTimeout(() => { if (selectionRef.current === selection) setCopied(false) }, 1600) + } catch { /* clipboard blocked */ } } const onSave = async () => { - if (!threadId) return + if (!result || selectionRef.current !== selection) return const res = await api.saveExport(threadId, { mode, redact }) - if (res.saved) setSaved(res.path ?? 'saved') + if (res.saved && selectionRef.current === selection) setSaved(res.path ?? 'saved') } return ( @@ -86,7 +103,9 @@ export function ExportPanel() { {/* mode picker */}
{MODES.map((m) => ( - ))} @@ -95,7 +114,9 @@ export function ExportPanel() { {/* redaction control */}
diff --git a/app/src/components/bots/BotComposerSettings.test.tsx b/app/src/components/bots/BotComposerSettings.test.tsx index 472b124aacd..2dddba1e72b 100644 --- a/app/src/components/bots/BotComposerSettings.test.tsx +++ b/app/src/components/bots/BotComposerSettings.test.tsx @@ -55,7 +55,7 @@ function productionElement(file: string, tag: string, wrapper?: string) { } const renderThreadComposer = productionElement('../Thread.tsx', 'Composer', 'BotComposerSettings') const provider: Provider = { id: 'fixture', name: 'Fixture', kind: 'local', baseUrl: 'http://127.0.0.1', apiKey: '', models: ['fixture'] } -function composer(bot: BotThreadConfig | undefined, effort: ReasoningEffortSetting) { +function composer(bot: BotThreadConfig | undefined, effort: ReasoningEffortSetting, roomWorkerEffort?: ReasoningEffortSetting) { const thread = { id: 'captured-bot-fixture', bot } function Composer() { return React.createElement(picker.ModelPickerMenu, { @@ -65,10 +65,10 @@ function composer(bot: BotThreadConfig | undefined, effort: ReasoningEffortSetti detail: metadata.effortDisplayLabel(provider, 'fixture', effort), disabled: !!bot, }) } - return renderThreadComposer({ thread, Composer, BotComposerSettings: context.BotComposerSettings }) + return renderThreadComposer({ thread, roomWorkerEffort, Composer, BotComposerSettings: context.BotComposerSettings }) } const bot = (reasoningEffort?: ReasoningEffortSetting) => ({ reasoningEffort } as BotThreadConfig) -const markup = (captured: BotThreadConfig | undefined, global: ReasoningEffortSetting) => renderToStaticMarkup(composer(captured, global)) +const markup = (captured: BotThreadConfig | undefined, global: ReasoningEffortSetting, room?: ReasoningEffortSetting) => renderToStaticMarkup(composer(captured, global, room)) assert.match(markup(bot('low'), 'high'), />Low<\/span>/, 'the real thread/provider/picker wiring displays captured Low, not global High') assert.match(markup(bot('high'), 'low'), />High<\/span>/, 'captured High remains independent of global Low') assert.match(markup(bot(), 'high'), />High<\/span>/, 'a legacy bot without captured effort displays its global fallback') @@ -79,4 +79,7 @@ assert.match(markup(captured, 'medium'), />Low<\/span>/, 'changing the app setti const siblings = renderToStaticMarkup(React.createElement(React.Fragment, null, composer(captured, 'high'), composer(undefined, 'high'))) assert.equal((siblings.match(/>Low<\/span>/g) ?? []).length, 1) assert.equal((siblings.match(/>High<\/span>/g) ?? []).length, 1, 'a captured value cannot leak into an adjacent ordinary composer') +assert.match(markup(undefined, 'high', 'low'), />Low<\/span>/, 'the real worker composer displays captured Low instead of app High') +assert.match(markup(undefined, 'low', 'high'), />High<\/span>/, 'captured Room effort stays independent from app Low') +assert.match(markup(undefined, 'high'), />High<\/span>/, 'a completed worker returns to the ordinary app fallback') console.log('Bot composer checks passed: captured/legacy/global badges, actual parent wiring and sibling isolation.') diff --git a/app/src/components/bots/BotComposerSettings.tsx b/app/src/components/bots/BotComposerSettings.tsx index 0773efefeaa..bb77ae0eb8a 100644 --- a/app/src/components/bots/BotComposerSettings.tsx +++ b/app/src/components/bots/BotComposerSettings.tsx @@ -1,9 +1,10 @@ import { createContext, useContext, type ReactNode } from 'react' import type { BotThreadConfig } from '../../lib/types' -const BotComposerContext = createContext(undefined) +type CapturedComposerSettings = Pick +const BotComposerContext = createContext(undefined) -export function BotComposerSettings({ bot, children }: { bot?: BotThreadConfig; children: ReactNode }) { +export function BotComposerSettings({ bot, children }: { bot?: CapturedComposerSettings; children: ReactNode }) { return {children} } diff --git a/app/src/components/bots/BotReasoningEffort.test.tsx b/app/src/components/bots/BotReasoningEffort.test.tsx index 511d986e5bd..c1e66982748 100644 --- a/app/src/components/bots/BotReasoningEffort.test.tsx +++ b/app/src/components/bots/BotReasoningEffort.test.tsx @@ -7,18 +7,23 @@ import ts from 'typescript' import * as metadata from '../../lib/provider-model-metadata' import type { Provider } from '../../lib/types' -const source = readFileSync(new URL('./BotReasoningEffort.tsx', import.meta.url), 'utf8') -const output = ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS, jsx: ts.JsxEmit.ReactJSX } }).outputText const jsx = (type: any, props: any, key: any) => React.createElement(type, { ...props, ...(key == null ? {} : { key }) }) -const imports: Record = { 'react/jsx-runtime': { jsx, jsxs: jsx }, '../../lib/provider-model-metadata': metadata } -const module = { exports: {} as any } -new Function('require', 'module', 'exports', output)((id: string) => { - const reviewed = reviewedLanguageImport(id, imports) - if (reviewed.matched) return reviewed.value - assert.ok(id in imports, `Reviewed component import ${id}`) - return imports[id] -}, module, module.exports) -const { BotReasoningEffort, effortForBotModel } = module.exports +function load(file: string, imports: Record) { + const source = readFileSync(new URL(file, import.meta.url), 'utf8') + const output = ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS, jsx: ts.JsxEmit.ReactJSX } }).outputText + const module = { exports: {} as any } + new Function('require', 'module', 'exports', output)((id: string) => { + const reviewed = reviewedLanguageImport(id, imports) + if (reviewed.matched) return reviewed.value + assert.ok(id in imports, `Reviewed component import ${id}`) + return imports[id] + }, module, module.exports) + return module.exports +} +const control = load('../ReasoningEffortSelect.tsx', { + 'react/jsx-runtime': { jsx, jsxs: jsx }, '../lib/provider-model-metadata': metadata, +}) +const { BotReasoningEffort, effortForBotModel } = load('./BotReasoningEffort.tsx', { '../ReasoningEffortSelect': control }) const gemini: Provider = { id: 'gemini', name: 'Gemini API', kind: 'cloud', baseUrl: 'https://model.example.test/v1', apiKey: '', models: ['gemini-2.5-pro', 'gemini-3-pro'] } const choices = (provider?: Provider, model?: string) => { const tree = BotReasoningEffort({ provider, model, value: 'low', onChange() {} }) @@ -42,4 +47,5 @@ select.props.onChange({ target: { value: 'low' } }) assert.equal(selected, 'low', 'changing the rendered control updates the stored bot parameter') select.props.onChange({ target: { value: '' } }) assert.equal(selected, undefined) +assert.match(renderToStaticMarkup(BotReasoningEffort({ disabled: true, onChange() {} })), / onChange(event.target.value ? event.target.value as ReasoningEffortSetting : undefined)} className="h-10 w-full min-w-0 rounded-lg border border-line bg-card-2 px-2 text-[13px] text-ink"> - - {unavailable && } - {options.map((option) => )} - - -} +export { ReasoningEffortSelect as BotReasoningEffort, effortForModel as effortForBotModel } from '../ReasoningEffortSelect' diff --git a/app/src/components/rooms/RoomAgentsSection.tsx b/app/src/components/rooms/RoomAgentsSection.tsx new file mode 100644 index 00000000000..cfa93cc5d43 --- /dev/null +++ b/app/src/components/rooms/RoomAgentsSection.tsx @@ -0,0 +1,383 @@ +import { useAuthoredText } from '../../lib/preferences/useAuthoredText' +import { authoredText } from '../../lib/preferences/language-packs' +import { useStore as useLocaleStore } from '../../lib/store' +import { useEffect, useMemo, useState, type Dispatch, type SetStateAction } from 'react' +import clsx from 'clsx' +import { useStore } from '../../lib/store' +import { basename, relativeTime } from '../../lib/format' +import { Icon, type IconName } from '../../lib/icons' +import { FileGlyph } from '../../lib/fileicon' +import { Button, Input } from '../ui' +import { allowedProviders, projectDefaultModel } from '../../lib/policy' +import { accountLabel, modelDisplayName, providerAccountChoices, providerModelGroups } from '../../lib/provider-accounts' +import { buildRoomAgentTree, type RoomAgentTreeNode } from '../../lib/room-agent-tree' +import type { AgentPreset, AgentRoleProfileId, FanOutBudget, Provider, Room, RoomSeatLane, Seat, Ticket } from '../../lib/types' +import { FAN_OUT_OPTIONS, FILE_TOOL_VERB, ROLE_PROFILES, Avatar, availableSeatName, isActiveRunState, modelChoiceValue, parseModelChoice, pickProvider, seatModelChoice } from './helpers' +import { ReasoningEffortSelect, effortForModel } from '../ReasoningEffortSelect' +import type { ReasoningEffortSetting } from '../../lib/types' + +const AGENT_NODE_STATUS_LABEL: Record = { + get idle() { return authoredText(useLocaleStore.getState().settings?.uiPreferences?.locale, "Idle") }, + get active() { return authoredText(useLocaleStore.getState().settings?.uiPreferences?.locale, "Active") }, + get done() { return authoredText(useLocaleStore.getState().settings?.uiPreferences?.locale, "Done") }, + get failed() { return authoredText(useLocaleStore.getState().settings?.uiPreferences?.locale, "Failed") }, +} + +function AgentStatusDot({ status }: { status: RoomAgentTreeNode['status'] }) { + const tx = useAuthoredText() + return ( + + ) +} + +function RoomAgentDelegates({ node }: { node: RoomAgentTreeNode | undefined }) { + const tx = useAuthoredText() + if (!node?.children.length) return null + return ( +
+
+ + {tx("Delegates")} + {node.children.length} +
+
+ {node.children.map((child) => )} +
+
+ ) +} + +function RoomAgentDelegateRow({ node }: { node: RoomAgentTreeNode }) { + const tx = useAuthoredText() + return ( +
+
+ +
+
+ {node.name} + {node.children.length > 0 && {node.children.length}} + {AGENT_NODE_STATUS_LABEL[node.status]} +
+
{node.detail}
+
+
+ {node.children.length > 0 && ( +
+ {node.children.map((child) => )} +
+ )} +
+ ) +} + +function roomSeatFocus(room: Room, tickets: Ticket[], seat: Seat, node: RoomAgentTreeNode | undefined): { label: string; detail: string; icon: IconName; tone: 'active' | 'blocked' | 'done' | 'idle' } { + const heartbeat = room.seatHeartbeats?.[seat.id] + if (heartbeat?.missedSince) { + return { get label() { return authoredText(useLocaleStore.getState().settings?.uiPreferences?.locale, "Stalled") }, detail: `missed heartbeat ${relativeTime(heartbeat.missedSince)}`, icon: 'warning', tone: 'blocked' } + } + + const pendingHandoff = [...room.events].reverse().find((event) => { + if (!(event.kind === 'ask' || event.kind === 'assign') || event.target !== seat.name) return false + return !room.events.some((candidate) => + candidate.createdAt > event.createdAt && + candidate.seat === seat.name && + !['yield', 'notice', 'error'].includes(candidate.kind), + ) + }) + if (pendingHandoff) { + return { get label() { return authoredText(useLocaleStore.getState().settings?.uiPreferences?.locale, "Answering handoff") }, detail: `${pendingHandoff.seat} is waiting`, icon: 'message', tone: 'active' } + } + + const claimed = tickets.find((t) => t.assignee === seat.name && t.projectId === room.projectId && t.roomId === room.id && (t.status === 'in_progress' || t.status === 'review' || isActiveRunState(t.runState))) + if (claimed) { + const running = isActiveRunState(claimed.runState) + return { label: running ? 'Worker running' : claimed.status === 'review' ? 'Reviewing' : 'Working ticket', detail: claimed.title, icon: running ? 'play' : 'check', tone: 'active' } + } + + if (node?.children.some((child) => child.status === 'active')) { + return { get label() { return authoredText(useLocaleStore.getState().settings?.uiPreferences?.locale, "Delegated") }, detail: `${node.children.filter((child) => child.status === 'active').length} active delegate${node.children.filter((child) => child.status === 'active').length === 1 ? '' : 's'}`, icon: 'branch', tone: 'active' } + } + + const last = [...room.events].reverse().find((event) => event.seat === seat.name && event.kind !== 'yield') + if (last) { + const label = last.kind === 'tool' ? `Used ${last.tool ?? 'tool'}` : last.kind === 'claim' ? 'Claimed work' : last.kind === 'final' ? 'Concluded' : `${last.kind[0]?.toUpperCase() ?? ''}${last.kind.slice(1)}` + return { label, detail: last.text.replace(/\s+/g, ' ').trim().slice(0, 90), icon: last.kind === 'tool' ? 'grid' : last.kind === 'final' ? 'check' : 'spark', tone: last.kind === 'final' ? 'done' : 'idle' } + } + + return { get label() { return authoredText(useLocaleStore.getState().settings?.uiPreferences?.locale, "Available") }, detail: seat.lane ? `${seat.lane} lane` : 'Ready for a handoff', icon: 'clock', tone: 'idle' } +} + +function SeatFocusLine({ focus }: { focus: ReturnType }) { + const tx = useAuthoredText() + return ( +
+ + {focus.label} + {focus.detail} +
+ ) +} + +export function RoomAgentsSection({ + room, + providers, + tickets, + running, + adding, + setAdding, + setSeats, +}: { + room: Room + providers: Provider[] + tickets: Ticket[] + running: boolean + adding: boolean + setAdding: Dispatch> + setSeats: (seats: Seat[]) => void +}) { + const tx = useAuthoredText() + const defaultEffort = useStore((state) => state.settings?.reasoningEffort) + const modelGroups = providers.flatMap((provider) => providerModelGroups(provider).map((group) => ({ provider, group }))) + const agentTree = useMemo(() => buildRoomAgentTree(room), [room, tx]) + const agentTreeBySeat = useMemo(() => new Map(agentTree.map((node) => [node.seatName, node])), [agentTree, tx]) + const updateSeatModel = (seat: Seat, value: string) => { + const picked = parseModelChoice(value) + if (!picked) return + const provider = providers.find((candidate) => candidate.id === picked.providerId) + setSeats(room.seats.map((candidate) => candidate.id === seat.id ? { + ...candidate, ...picked, reasoningEffort: effortForModel(candidate.reasoningEffort, provider, picked.model), + } : candidate)) + } + const removeSeat = (seatId: string) => setSeats(room.seats.filter((seat) => seat.id !== seatId)) + + return ( +
+
+
+
{tx("Room agents")}
+
{tx("Pick the model each local or cloud agent uses.")}
+
+ +
+
+ {room.seats.map((seat) => { + const claimed = tickets.find((t) => t.assignee === seat.name && t.projectId === room.projectId && t.roomId === room.id && (t.status === 'in_progress' || t.status === 'review')) + const recentFiles = [...new Set([...room.events].reverse().filter((ev) => ev.seat === seat.name && ev.tool && ev.path && FILE_TOOL_VERB[ev.tool]).map((ev) => ev.path!))].slice(0, 2) + const seatProvider = providers.find((p) => p.id === seat.providerId) + const choiceValue = seatModelChoice(seat, providers) + const treeNode = agentTreeBySeat.get(seat.name) + const focus = roomSeatFocus(room, tickets, seat, treeNode) + return ( +
+
+ +
+
+ {seat.name} + {seat.roleProfileId && {seat.roleProfileId}} +
+
{seat.lane ? `${seat.lane} · ` : ''}{seat.role}
+
+ +
+ + +
+ setSeats(room.seats.map((candidate) => + candidate.id === seat.id ? { ...candidate, reasoningEffort } : candidate))} /> +
+ {seatProvider &&
{seatProvider.name}
} + {claimed &&
{claimed.title}
} + {recentFiles.length > 0 && ( +
+ {recentFiles.map((path) =>
{basename(path)}
)} +
+ )} + +
+ ) + })} + {adding && { setSeats([...room.seats, seat]); setAdding(false) }} onCancel={() => setAdding(false)} />} + {room.seats.length === 0 && !adding &&
{tx("No agents yet. Add one or use the preset below.")}
} +
+
+ ) +} + +function AddSeat({ room, running, onAdd, onCancel }: { room: Room; running: boolean; onAdd: (s: Seat) => void; onCancel: () => void }) { + const tx = useAuthoredText() + const settings = useStore((s) => s.settings)! + const project = useStore((s) => s.projects.find((p) => p.id === room.projectId)) ?? null + const agentPresets = (settings.agentPresets ?? []).filter((preset) => !preset.archivedAt && !preset.paused) + const pickerProviders = allowedProviders(settings.providers, project) + const def = projectDefaultModel(project, settings.providers) + // Name seats after their role (planner, planner-2, …) so the chosen role is + // visible in the name, and suggest a fitting model per role (#47): builders and + // operators run local; planners, reviewers and researchers run on a frontier + // (cloud) model. + const roleSeatName = (base: string) => { + const used = new Set(room.seats.map((s) => s.name.toLowerCase())) + if (!used.has(base.toLowerCase())) return base + for (let i = 2; i < 99; i++) if (!used.has(`${base}-${i}`)) return `${base}-${i}` + return base + } + const suggestModelFor = (laneFor: RoomSeatLane) => + pickProvider(pickerProviders, laneFor === 'development' || laneFor === 'operations' ? 'local' : 'cloud', def) + const [roleProfileId, setRoleProfileId] = useState('builder') + const [name, setName] = useState(() => roleSeatName('builder')) + const [nameTouched, setNameTouched] = useState(false) + const [role, setRole] = useState('Engineer') + const [lane, setLane] = useState('development') + const [fanOutBudget, setFanOutBudget] = useState('single') + // Seed the form with the model that fits the default 'builder' role (local). + const initialPick = suggestModelFor('development') + const [providerId, setProviderId] = useState(initialPick.provider?.id || def.providerId || pickerProviders[0]?.id || '') + const provider = pickerProviders.find((p) => p.id === providerId) || pickerProviders[0] + const [providerAccountId, setProviderAccountId] = useState(initialPick.provider ? initialPick.providerAccountId : (project?.defaultProviderAccountId ?? provider?.defaultAccountId ?? null)) + const accountChoices = provider ? providerAccountChoices(provider) : [] + const selectedAccount = accountChoices.find((account) => account.id === (providerAccountId ?? null)) ?? accountChoices[0] + const modelChoices = selectedAccount?.models?.length ? selectedAccount.models : (provider?.models ?? []) + const [model, setModel] = useState(initialPick.model || def.model || modelChoices[0] || '') + const [reasoningEffort, setReasoningEffort] = useState() + const selectedAccountLabel = provider ? accountLabel(provider, providerAccountId) : null + const noAllowedProviders = pickerProviders.length === 0 + const currentModelChoice = provider && model ? modelChoiceValue(provider.id, providerAccountId, model) : '' + + useEffect(() => { + setReasoningEffort((current) => effortForModel(current, provider, model)) + }, [provider, model]) + + useEffect(() => { + if (!provider) return + const account = providerAccountChoices(provider).find((choice) => choice.id === (providerAccountId ?? null)) ?? providerAccountChoices(provider)[0] + if ((providerAccountId ?? null) !== (account?.id ?? null)) setProviderAccountId(account?.id ?? null) + const models = account?.models?.length ? account.models : provider.models + if (models.length && !models.includes(model)) setModel(models[0]) + }, [provider?.id, providerAccountId, model, pickerProviders.length]) // eslint-disable-line + + const add = () => { + if (running || !provider || !model) return + const n = (name.trim() || role.toLowerCase()).replace(/\s+/g, '-') + onAdd({ id: crypto.randomUUID(), name: n, role: role.trim() || 'Agent', lane, roleProfileId, fanOutBudget, providerId: provider.id, providerAccountId: providerAccountId ?? null, model, reasoningEffort }) + } + const pickModel = (value: string) => { + const picked = parseModelChoice(value) + if (!picked) return + setProviderId(picked.providerId) + setProviderAccountId(picked.providerAccountId) + setModel(picked.model) + } + const applyAgentPreset = (presetId: string) => { + const preset = agentPresets.find((candidate) => candidate.id === presetId) + if (!preset) return + setName(availableSeatName(preset.name, room.seats)) + setNameTouched(true) + setRole(preset.role) + setLane(preset.lane) + setProviderId(preset.providerId) + setProviderAccountId(preset.providerAccountId ?? null) + setModel(preset.model) + setReasoningEffort(effortForModel(preset.reasoningEffort, pickerProviders.find((candidate) => candidate.id === preset.providerId), preset.model)) + } + + return ( +
+ {agentPresets.length > 0 && ( + + )} + + { setNameTouched(true); setName(e.target.value) }} placeholder={tx("Name (e.g. architect)")} className="mb-2 h-8" /> + setRole(e.target.value)} placeholder={tx("Role (e.g. Architect)")} className="mb-2 h-8" /> +
+ + +
+ {noAllowedProviders ? ( +
+ {tx("This project is local-only, but no local providers are configured.")}
+ ) : ( +
+ +
{provider?.name}{selectedAccountLabel ? ` · ${selectedAccountLabel}` : ''}
+
+ )} +
+ +
+
+ + +
+
+ ) +} diff --git a/app/src/components/rooms/RoomPanels.tsx b/app/src/components/rooms/RoomPanels.tsx index 4b99d5d7e1a..d9ba0cb7ba1 100644 --- a/app/src/components/rooms/RoomPanels.tsx +++ b/app/src/components/rooms/RoomPanels.tsx @@ -1,44 +1,18 @@ import { useAuthoredText } from '../../lib/preferences/useAuthoredText' -import { authoredText } from '../../lib/preferences/language-packs' -import { useStore as useLocaleStore } from '../../lib/store' -import { useEffect, useMemo, useState, type Dispatch, type SetStateAction } from 'react' +import { useState } from 'react' import clsx from 'clsx' -import { useStore } from '../../lib/store' -import { basename, relativeTime } from '../../lib/format' -import { Icon, type IconName } from '../../lib/icons' +import { basename } from '../../lib/format' +import { Icon } from '../../lib/icons' import { FileGlyph } from '../../lib/fileicon' -import { Button, Input } from '../ui' -import { allowedProviders, projectDefaultModel } from '../../lib/policy' -import { accountLabel, modelDisplayName, providerAccountChoices, providerModelGroups } from '../../lib/provider-accounts' -import { buildRoomAgentTree, type RoomAgentTreeNode } from '../../lib/room-agent-tree' -import type { AgentPreset, AgentRoleProfileId, FanOutBudget, Job, Project, Provider, Room, RoomCollaborationMode, RoomEventItem, RoomMode, RoomSeatLane, RoomState, Seat, Ticket } from '../../lib/types' -import { - ACTIVE_ROOM_STATES, - FAN_OUT_OPTIONS, - FILE_TOOL_VERB, - ROLE_PROFILES, - ROOM_COLLABORATION_OPTIONS, - ROOM_MODE_OPTIONS, - ROOM_STATE_LABEL, - Avatar, - availableSeatName, - presetSeats, - seatForRole, - isActiveRunState, - modelChoiceValue, - parseModelChoice, - pickProvider, - roomJobDetail, - roomJobTitle, - roomSupervisorPhase, - seatModelChoice, - ticketFileRefsForDisplay, - ticketPhaseLabel, - ticketStatusLabel, - ticketWorkerLabel, -} from './helpers' +import { Button } from '../ui' +import { allowedProviders } from '../../lib/policy' +import { modelDisplayName } from '../../lib/provider-accounts' +import type { AgentRoleProfileId, Job, Project, Provider, Room, RoomCollaborationMode, RoomEventItem, RoomMode, RoomState, Seat, Ticket } from '../../lib/types' +import { ACTIVE_ROOM_STATES, ROLE_PROFILES, ROOM_COLLABORATION_OPTIONS, ROOM_MODE_OPTIONS, ROOM_STATE_LABEL, Avatar, presetSeats, seatForRole, isActiveRunState, roomJobDetail, roomJobTitle, roomSupervisorPhase, ticketFileRefsForDisplay, ticketPhaseLabel, ticketStatusLabel, ticketWorkerLabel } from './helpers' import type { RoomConflictBlocker } from './helpers' +export { RoomAgentsSection } from './RoomAgentsSection' + export function RoomSupervisorPanel({ room, roomState, @@ -295,212 +269,6 @@ export function RoomStat({ icon, label, value, accent }: { icon: 'cpu' | 'list' ) } -const AGENT_NODE_STATUS_LABEL: Record = { - get idle() { return authoredText(useLocaleStore.getState().settings?.uiPreferences?.locale, "Idle") }, - get active() { return authoredText(useLocaleStore.getState().settings?.uiPreferences?.locale, "Active") }, - get done() { return authoredText(useLocaleStore.getState().settings?.uiPreferences?.locale, "Done") }, - get failed() { return authoredText(useLocaleStore.getState().settings?.uiPreferences?.locale, "Failed") }, -} - -function AgentStatusDot({ status }: { status: RoomAgentTreeNode['status'] }) { - const tx = useAuthoredText() - return ( - - ) -} - -function RoomAgentDelegates({ node }: { node: RoomAgentTreeNode | undefined }) { - const tx = useAuthoredText() - if (!node?.children.length) return null - return ( -
-
- - {tx("Delegates")} - {node.children.length} -
-
- {node.children.map((child) => )} -
-
- ) -} - -function RoomAgentDelegateRow({ node }: { node: RoomAgentTreeNode }) { - const tx = useAuthoredText() - return ( -
-
- -
-
- {node.name} - {node.children.length > 0 && {node.children.length}} - {AGENT_NODE_STATUS_LABEL[node.status]} -
-
{node.detail}
-
-
- {node.children.length > 0 && ( -
- {node.children.map((child) => )} -
- )} -
- ) -} - -function roomSeatFocus(room: Room, tickets: Ticket[], seat: Seat, node: RoomAgentTreeNode | undefined): { label: string; detail: string; icon: IconName; tone: 'active' | 'blocked' | 'done' | 'idle' } { - const heartbeat = room.seatHeartbeats?.[seat.id] - if (heartbeat?.missedSince) { - return { get label() { return authoredText(useLocaleStore.getState().settings?.uiPreferences?.locale, "Stalled") }, detail: `missed heartbeat ${relativeTime(heartbeat.missedSince)}`, icon: 'warning', tone: 'blocked' } - } - - const pendingHandoff = [...room.events].reverse().find((event) => { - if (!(event.kind === 'ask' || event.kind === 'assign') || event.target !== seat.name) return false - return !room.events.some((candidate) => - candidate.createdAt > event.createdAt && - candidate.seat === seat.name && - !['yield', 'notice', 'error'].includes(candidate.kind), - ) - }) - if (pendingHandoff) { - return { get label() { return authoredText(useLocaleStore.getState().settings?.uiPreferences?.locale, "Answering handoff") }, detail: `${pendingHandoff.seat} is waiting`, icon: 'message', tone: 'active' } - } - - const claimed = tickets.find((t) => t.assignee === seat.name && t.projectId === room.projectId && t.roomId === room.id && (t.status === 'in_progress' || t.status === 'review' || isActiveRunState(t.runState))) - if (claimed) { - const running = isActiveRunState(claimed.runState) - return { label: running ? 'Worker running' : claimed.status === 'review' ? 'Reviewing' : 'Working ticket', detail: claimed.title, icon: running ? 'play' : 'check', tone: 'active' } - } - - if (node?.children.some((child) => child.status === 'active')) { - return { get label() { return authoredText(useLocaleStore.getState().settings?.uiPreferences?.locale, "Delegated") }, detail: `${node.children.filter((child) => child.status === 'active').length} active delegate${node.children.filter((child) => child.status === 'active').length === 1 ? '' : 's'}`, icon: 'branch', tone: 'active' } - } - - const last = [...room.events].reverse().find((event) => event.seat === seat.name && event.kind !== 'yield') - if (last) { - const label = last.kind === 'tool' ? `Used ${last.tool ?? 'tool'}` : last.kind === 'claim' ? 'Claimed work' : last.kind === 'final' ? 'Concluded' : `${last.kind[0]?.toUpperCase() ?? ''}${last.kind.slice(1)}` - return { label, detail: last.text.replace(/\s+/g, ' ').trim().slice(0, 90), icon: last.kind === 'tool' ? 'grid' : last.kind === 'final' ? 'check' : 'spark', tone: last.kind === 'final' ? 'done' : 'idle' } - } - - return { get label() { return authoredText(useLocaleStore.getState().settings?.uiPreferences?.locale, "Available") }, detail: seat.lane ? `${seat.lane} lane` : 'Ready for a handoff', icon: 'clock', tone: 'idle' } -} - -function SeatFocusLine({ focus }: { focus: ReturnType }) { - const tx = useAuthoredText() - return ( -
- - {focus.label} - {focus.detail} -
- ) -} - -export function RoomAgentsSection({ - room, - providers, - tickets, - running, - adding, - setAdding, - setSeats, -}: { - room: Room - providers: Provider[] - tickets: Ticket[] - running: boolean - adding: boolean - setAdding: Dispatch> - setSeats: (seats: Seat[]) => void -}) { - const tx = useAuthoredText() - const modelGroups = providers.flatMap((provider) => providerModelGroups(provider).map((group) => ({ provider, group }))) - const agentTree = useMemo(() => buildRoomAgentTree(room), [room, tx]) - const agentTreeBySeat = useMemo(() => new Map(agentTree.map((node) => [node.seatName, node])), [agentTree, tx]) - const updateSeatModel = (seat: Seat, value: string) => { - const picked = parseModelChoice(value) - if (!picked) return - setSeats(room.seats.map((candidate) => candidate.id === seat.id ? { ...candidate, ...picked } : candidate)) - } - const removeSeat = (seatId: string) => setSeats(room.seats.filter((seat) => seat.id !== seatId)) - - return ( -
-
-
-
{tx("Room agents")}
-
{tx("Pick the model each local or cloud agent uses.")}
-
- -
-
- {room.seats.map((seat) => { - const claimed = tickets.find((t) => t.assignee === seat.name && t.projectId === room.projectId && t.roomId === room.id && (t.status === 'in_progress' || t.status === 'review')) - const recentFiles = [...new Set([...room.events].reverse().filter((ev) => ev.seat === seat.name && ev.tool && ev.path && FILE_TOOL_VERB[ev.tool]).map((ev) => ev.path!))].slice(0, 2) - const seatProvider = providers.find((p) => p.id === seat.providerId) - const choiceValue = seatModelChoice(seat, providers) - const treeNode = agentTreeBySeat.get(seat.name) - const focus = roomSeatFocus(room, tickets, seat, treeNode) - return ( -
-
- -
-
- {seat.name} - {seat.roleProfileId && {seat.roleProfileId}} -
-
{seat.lane ? `${seat.lane} · ` : ''}{seat.role}
-
- -
- - - {seatProvider &&
{seatProvider.name}
} - {claimed &&
{claimed.title}
} - {recentFiles.length > 0 && ( -
- {recentFiles.map((path) =>
{basename(path)}
)} -
- )} - -
- ) - })} - {adding && { setSeats([...room.seats, seat]); setAdding(false) }} onCancel={() => setAdding(false)} />} - {room.seats.length === 0 && !adding &&
{tx("No agents yet. Add one or use the preset below.")}
} -
-
- ) -} - // #52/#54 — the center "build your room" canvas. Drag a role into the room (or // click) to add an agent with a fitting model, then pick how they collaborate. // Shown before the huddle has a transcript, so room-building happens in the @@ -602,142 +370,3 @@ export function RoomCanvas({ room, providers, project, onSetSeats, onSetCollabor ) } - -function AddSeat({ room, onAdd, onCancel }: { room: Room; onAdd: (s: Seat) => void; onCancel: () => void }) { - const tx = useAuthoredText() - const settings = useStore((s) => s.settings)! - const project = useStore((s) => s.projects.find((p) => p.id === room.projectId)) ?? null - const agentPresets = (settings.agentPresets ?? []).filter((preset) => !preset.archivedAt && !preset.paused) - const pickerProviders = allowedProviders(settings.providers, project) - const def = projectDefaultModel(project, settings.providers) - // Name seats after their role (planner, planner-2, …) so the chosen role is - // visible in the name, and suggest a fitting model per role (#47): builders and - // operators run local; planners, reviewers and researchers run on a frontier - // (cloud) model. - const roleSeatName = (base: string) => { - const used = new Set(room.seats.map((s) => s.name.toLowerCase())) - if (!used.has(base.toLowerCase())) return base - for (let i = 2; i < 99; i++) if (!used.has(`${base}-${i}`)) return `${base}-${i}` - return base - } - const suggestModelFor = (laneFor: RoomSeatLane) => - pickProvider(pickerProviders, laneFor === 'development' || laneFor === 'operations' ? 'local' : 'cloud', def) - const [roleProfileId, setRoleProfileId] = useState('builder') - const [name, setName] = useState(() => roleSeatName('builder')) - const [nameTouched, setNameTouched] = useState(false) - const [role, setRole] = useState('Engineer') - const [lane, setLane] = useState('development') - const [fanOutBudget, setFanOutBudget] = useState('single') - // Seed the form with the model that fits the default 'builder' role (local). - const initialPick = suggestModelFor('development') - const [providerId, setProviderId] = useState(initialPick.provider?.id || def.providerId || pickerProviders[0]?.id || '') - const provider = pickerProviders.find((p) => p.id === providerId) || pickerProviders[0] - const [providerAccountId, setProviderAccountId] = useState(initialPick.provider ? initialPick.providerAccountId : (project?.defaultProviderAccountId ?? provider?.defaultAccountId ?? null)) - const accountChoices = provider ? providerAccountChoices(provider) : [] - const selectedAccount = accountChoices.find((account) => account.id === (providerAccountId ?? null)) ?? accountChoices[0] - const modelChoices = selectedAccount?.models?.length ? selectedAccount.models : (provider?.models ?? []) - const [model, setModel] = useState(initialPick.model || def.model || modelChoices[0] || '') - const selectedAccountLabel = provider ? accountLabel(provider, providerAccountId) : null - const noAllowedProviders = pickerProviders.length === 0 - const currentModelChoice = provider && model ? modelChoiceValue(provider.id, providerAccountId, model) : '' - - useEffect(() => { - if (!provider) return - const account = providerAccountChoices(provider).find((choice) => choice.id === (providerAccountId ?? null)) ?? providerAccountChoices(provider)[0] - if ((providerAccountId ?? null) !== (account?.id ?? null)) setProviderAccountId(account?.id ?? null) - const models = account?.models?.length ? account.models : provider.models - if (models.length && !models.includes(model)) setModel(models[0]) - }, [provider?.id, providerAccountId, model, pickerProviders.length]) // eslint-disable-line - - const add = () => { - if (!provider || !model) return - const n = (name.trim() || role.toLowerCase()).replace(/\s+/g, '-') - onAdd({ id: crypto.randomUUID(), name: n, role: role.trim() || 'Agent', lane, roleProfileId, fanOutBudget, providerId: provider.id, providerAccountId: providerAccountId ?? null, model }) - } - const pickModel = (value: string) => { - const picked = parseModelChoice(value) - if (!picked) return - setProviderId(picked.providerId) - setProviderAccountId(picked.providerAccountId) - setModel(picked.model) - } - const applyAgentPreset = (presetId: string) => { - const preset = agentPresets.find((candidate) => candidate.id === presetId) - if (!preset) return - setName(availableSeatName(preset.name, room.seats)) - setNameTouched(true) - setRole(preset.role) - setLane(preset.lane) - setProviderId(preset.providerId) - setProviderAccountId(preset.providerAccountId ?? null) - setModel(preset.model) - } - - return ( -
- {agentPresets.length > 0 && ( - - )} - - { setNameTouched(true); setName(e.target.value) }} placeholder={tx("Name (e.g. architect)")} className="mb-2 h-8" /> - setRole(e.target.value)} placeholder={tx("Role (e.g. Architect)")} className="mb-2 h-8" /> -
- - -
- {noAllowedProviders ? ( -
- {tx("This project is local-only, but no local providers are configured.")}
- ) : ( -
- -
{provider?.name}{selectedAccountLabel ? ` · ${selectedAccountLabel}` : ''}
-
- )} -
- - -
-
- ) -} diff --git a/app/src/components/search/ConversationSearchHost.tsx b/app/src/components/search/ConversationSearchHost.tsx index f7cbdf939e6..d900b24d9ee 100644 --- a/app/src/components/search/ConversationSearchHost.tsx +++ b/app/src/components/search/ConversationSearchHost.tsx @@ -31,6 +31,7 @@ export function ConversationSearchHost({ navigationBlocked = false }: { navigati const [open, setOpen] = useState(false), [query, setQuery] = useState('') const [scope, setScope] = useState<'all' | 'thread'>('all'), [projectId, setProjectId] = useState('') const [archived, setArchived] = useState(false), [selected, setSelected] = useState(0), [retry, setRetry] = useState(0) + const scopedProjectId = scope === 'all' ? projectId : '' const panel = useRef(null), input = useRef(null) const close = () => { client.clear(); setOpen(false); setQuery('') } useAccessibleDialog({ open, onClose: close, dialogRef: panel, initialFocusRef: input }) @@ -54,19 +55,19 @@ export function ConversationSearchHost({ navigationBlocked = false }: { navigati useEffect(() => { client.clear(); setSelected(0) if (!open || filterState.error || scope === 'thread' && !activeThreadId) return - const timer = setTimeout(() => void client.search({ scope, query, ...(scope === 'thread' ? { threadId: activeThreadId } : {}), ...(projectId ? { projectId } : {}), includeArchived: archived, filters: filterState.filters, limit: 50 }), 180) + const timer = setTimeout(() => void client.search({ scope, query, ...(scope === 'thread' ? { threadId: activeThreadId } : {}), ...(scopedProjectId ? { projectId: scopedProjectId } : {}), includeArchived: archived, filters: filterState.filters, limit: 50 }), 180) return () => { clearTimeout(timer); client.clear() } - }, [open, query, scope, activeThreadId, projectId, archived, filterKey, filterState.error, retry, client]) + }, [open, query, scope, activeThreadId, scopedProjectId, archived, filterKey, filterState.error, retry, client]) const ownsState = open && state.request?.query === query.trim().replace(/\s+/g, ' ') && state.request.scope === scope && (scope !== 'thread' || state.request.threadId === activeThreadId) - && (state.request.projectId ?? '') === projectId && !!state.request.includeArchived === archived && !filterState.error && conversationSearchFilterKey(state.request.filters) === filterKey + && (state.request.projectId ?? '') === scopedProjectId && !!state.request.includeArchived === archived && !filterState.error && conversationSearchFilterKey(state.request.filters) === filterKey const filterThreads = (threads ?? []).filter(thread => !thread.orchestratorHostId && (scope === 'thread' ? thread.id === activeThreadId : !thread.incognito && !thread.phoneLocalOnly && !thread.googleLocalOnly && !thread.bot && (archived || !thread.archivedAt)) - && (!projectId || thread.projectId === projectId)) + && (!scopedProjectId || thread.projectId === scopedProjectId)) const current = ownsState ? state : { result: null, error: '', busy: false } const matches = current.result?.matches ?? [] const navigationOwner = useRef('') - const ownership = JSON.stringify([open, scope, query.trim().replace(/\s+/g, ' '), activeThreadId, projectId, archived, filterKey, filterState.error, navigationBlocked]) + const ownership = JSON.stringify([open, scope, query.trim().replace(/\s+/g, ' '), activeThreadId, scopedProjectId, archived, filterKey, filterState.error, navigationBlocked]) navigationOwner.current = ownership useEffect(() => { document.getElementById(`conversation-search-result-${selected}`)?.scrollIntoView({ block: 'nearest' }) diff --git a/app/src/components/search/usability-search.integration.test.tsx b/app/src/components/search/usability-search.integration.test.tsx index 22aa0e96e6a..46e31f62a6e 100644 --- a/app/src/components/search/usability-search.integration.test.tsx +++ b/app/src/components/search/usability-search.integration.test.tsx @@ -69,6 +69,49 @@ assert.equal(nodes(tree).some((node) => node.type === 'result-fixture'), false); input().props.onChange({ target: { value: 'late' } }); await commit(); tickTimers(); await commit() find(render(), (node) => node.type === 'button' && text(node) === 'Close search').props.onClick(); await commit() resolve(4, 'late', [match('late', 'current')]); await settle(); assert.equal(render(), null, 'Closing search discards delayed private snippets') + +store.projects = [{ id: 'project-a', name: 'Project A' }, { id: 'project-b', name: 'Project B' }] +store.threads = [{ id: 'thread-a', projectId: 'project-a' }, { id: 'current', projectId: 'project-b' }] +const picker = (label: string) => find(render(), (node) => node.type === 'select' && node.props['aria-label'] === label) +const nextSearch = async () => { + const index = pending.length + await commit() + tickTimers() + await commit() + assert.equal(pending.length, index + 1) + return index +} +events.requestConversationSearch({ scope: 'all', query: 'needle' }) +await commit() +picker('Conversation search project').props.onChange({ target: { value: 'project-a' } }) +find(render(), (node) => node.type === 'input' && node.props.type === 'checkbox').props.onChange({ target: { checked: true } }) +const projectSearch = await nextSearch() +assert.equal(pending[projectSearch].request.projectId, 'project-a') +assert.equal(pending[projectSearch].request.includeArchived, true) +resolve(projectSearch, 'needle', [{ ...match('needle', 'thread-a'), projectId: 'project-a' }]) +await settle() +const oldProjectRow = find(render(), (node) => node.type === 'result-fixture') +assert.ok(oldProjectRow) + +picker('Conversation search scope').props.onChange({ target: { value: 'thread' } }) +assert.equal(picker('Conversation search project'), undefined, 'the project filter is hidden in current-conversation scope') +oldProjectRow.props.onOpen() +assert.deepEqual(opened, [], 'a cached global project result cannot navigate once the scope changes') +const currentSearch = await nextSearch() +const currentRequest = pending[currentSearch].request +assert.equal(currentRequest.scope, 'thread') +assert.equal(currentRequest.threadId, 'current') +assert.equal(currentRequest.projectId, undefined, 'a global project filter must not restrict the current conversation') +assert.deepEqual(find(render(), (node) => node.type === 'filter-controls').props.threads, [store.threads[1]]) +resolve(currentSearch, 'needle', [{ ...match('needle', 'current'), projectId: 'project-b' }]) +await settle() +assert.equal(find(render(), (node) => node.type === 'result-fixture').props.match.threadId, 'current') + +picker('Conversation search scope').props.onChange({ target: { value: 'all' } }) +const restoredSearch = await nextSearch() +assert.equal(picker('Conversation search project').props.value, 'project-a') +assert.equal(pending[restoredSearch].request.projectId, 'project-a', 'returning to global scope restores the project filter') +assert.equal(pending[restoredSearch].request.includeArchived, true) hooks.cleanup() const anchorHooks = harness(), windowHooks = harness(), revealed: string[] = [], focused: string[] = [] diff --git a/app/src/lib/conversation-drafts.test.ts b/app/src/lib/conversation-drafts.test.ts index 879a3b8734e..736a6bf0a30 100644 --- a/app/src/lib/conversation-drafts.test.ts +++ b/app/src/lib/conversation-drafts.test.ts @@ -1,5 +1,5 @@ import assert from 'node:assert/strict' -import { ConversationDrafts, draftAttachmentReferences } from './conversation-drafts' +import { ConversationDrafts, draftAttachmentReferences, restoreDraftAttachments } from './conversation-drafts' import { composerDraftKey, emptyComposerDraft } from '../../shared/composer-drafts' import type { ComposerDraftPort, ComposerDraftScope, ComposerDraftSnapshot, ComposerDraftWrite, ComposerDraftWriteResult } from '../../shared/composer-drafts' import type { Attachment } from './types' @@ -148,6 +148,44 @@ function memoryPort() { drafts.dispose(); restarted.dispose() } +{ + const { port, saved } = memoryPort() + const reason = 'The synthetic PDF is password-protected.' + const attachment: Attachment = { + id: 'fixture', name: 'fixture.pdf', kind: 'document', mime: 'application/pdf', + status: 'error', error: reason, + } + const seed = new ConversationDrafts(port, 60_000) + seed.update(a, { attachments: [attachment] }) + await seed.flush(a) + seed.dispose() + const key = composerDraftKey(a) + const display = 'Select this file again after restarting TensorFold; its contents were not stored with the draft.' + const prefix = `${display} Previous file error: ` + for (let i = 0; i < 3; i++) { + const reopened = new ConversationDrafts(port, 60_000) + reopened.get(a) + await tick() + assert.equal(reopened.get(a).attachments[0].error, prefix + reason) + reopened.update(a, { text: `Unrelated edit ${i}` }) + await reopened.flush(a) + assert.equal(saved.get(key)!.attachments[0].error, reason) + reopened.dispose() + } + + const ref = saved.get(key)!.attachments[0] + const recoverable = restoreDraftAttachments([{ ...ref, error: prefix.repeat(2) + reason }]) + assert.equal(recoverable[0].error, prefix + reason) + assert.equal(draftAttachmentReferences(recoverable)[0].error, reason) + + const clipped = restoreDraftAttachments([{ ...ref, error: prefix.repeat(12).slice(0, 1000) }]) + assert.equal(clipped[0].error, display) + const longError = 'x'.repeat(999) + 'YZ' + const long = draftAttachmentReferences([{ ...attachment, error: longError }]) + assert.equal(long[0].error, longError.slice(0, 1000)) + assert.deepEqual(draftAttachmentReferences(restoreDraftAttachments(long)), long) +} + { const { port, saved, writes } = memoryPort() let readCalls = 0; port.getComposerDraft = async () => { readCalls++; throw new Error('Incognito must not call disk') } diff --git a/app/src/lib/conversation-drafts.ts b/app/src/lib/conversation-drafts.ts index d896749965c..73ba1f829f3 100644 --- a/app/src/lib/conversation-drafts.ts +++ b/app/src/lib/conversation-drafts.ts @@ -40,6 +40,17 @@ interface Entry { } const RESELECT = 'Select this file again after restarting TensorFold; its contents were not stored with the draft.' +const PREVIOUS_ERROR = `${RESELECT} Previous file error: ` +const ATTACHMENT_ERROR_LIMIT = 1_000 + +function attachmentDiagnostic(error = ''): string { + let diagnostic = error + while (diagnostic.startsWith(PREVIOUS_ERROR)) diagnostic = diagnostic.slice(PREVIOUS_ERROR.length) + if (diagnostic === RESELECT) return '' + // Older drafts could fill the storage limit with repeated guidance and no diagnostic. + if (error.length === ATTACHMENT_ERROR_LIMIT && diagnostic !== error && PREVIOUS_ERROR.startsWith(diagnostic)) return '' + return diagnostic +} /** Strictly omit payloads, paths and source objects from durable references. */ export function draftAttachmentReferences(attachments: Attachment[]): DraftAttachmentReference[] { @@ -47,26 +58,29 @@ export function draftAttachmentReferences(attachments: Attachment[]): DraftAttac return attachments.map((attachment) => { const extraction = (attachment as Attachment & { extraction?: { state: string; text: string } }).extraction if (extraction?.state === 'accepted' && extraction.text.length > MAX_DRAFT_ACCEPTED_TEXT_CHARS) throw new Error('Accepted extracted text exceeds the draft storage limit; copy it to a document before restarting.') - const rawError = (attachment as Attachment & { error?: string }).error + const error = attachment.status === 'needs-reselection' ? attachmentDiagnostic(attachment.error) : attachment.error return { id: attachment.id, name: attachment.name, kind: attachment.kind, mime: attachment.mime, ...(attachment.bytes === undefined ? {} : { bytes: attachment.bytes }), - status: 'needs-reselection', error: rawError ? rawError.slice(0, 1_000) : RESELECT, + status: 'needs-reselection', error: error ? error.slice(0, ATTACHMENT_ERROR_LIMIT) : RESELECT, ...(extraction?.state === 'accepted' && typeof extraction.text === 'string' && extraction.text.length <= MAX_DRAFT_ACCEPTED_TEXT_CHARS ? { acceptedText: extraction.text } : {}), } }) } export function restoreDraftAttachments(references: DraftAttachmentReference[]): Attachment[] { - return references.map((reference) => ({ - id: reference.id, name: reference.name, kind: reference.kind, mime: reference.mime, - ...(reference.bytes === undefined ? {} : { bytes: reference.bytes }), - status: 'needs-reselection', error: reference.error && reference.error !== RESELECT ? `${RESELECT} Previous file error: ${reference.error}` : RESELECT, - ...(reference.acceptedText === undefined ? {} : { - text: reference.acceptedText, - extraction: { method: 'apple-vision', state: 'accepted', text: reference.acceptedText, confidence: null, warnings: ['Original file must be selected again before sending. Previously accepted extracted text was retained.'], pageCount: 0, processedPages: 0, truncated: false }, - }), - })) + return references.map((reference) => { + const diagnostic = attachmentDiagnostic(reference.error) + return { + id: reference.id, name: reference.name, kind: reference.kind, mime: reference.mime, + ...(reference.bytes === undefined ? {} : { bytes: reference.bytes }), + status: 'needs-reselection', error: diagnostic ? PREVIOUS_ERROR + diagnostic : RESELECT, + ...(reference.acceptedText === undefined ? {} : { + text: reference.acceptedText, + extraction: { method: 'apple-vision', state: 'accepted', text: reference.acceptedText, confidence: null, warnings: ['Original file must be selected again before sending. Previously accepted extracted text was retained.'], pageCount: 0, processedPages: 0, truncated: false }, + }), + } + }) } function detached(attachments: Attachment[]): Attachment[] { diff --git a/app/src/lib/room-worker-effort.test.ts b/app/src/lib/room-worker-effort.test.ts new file mode 100644 index 00000000000..8f0721b7d64 --- /dev/null +++ b/app/src/lib/room-worker-effort.test.ts @@ -0,0 +1,20 @@ +import assert from 'node:assert/strict' +import { activeRoomWorkerEffort } from './room-worker-effort' +import type { Ticket } from './types' + +const ticket: Ticket = { + id: 'ticket', projectId: 'project', title: 'Synthetic work', body: '', type: 'task', status: 'in_progress', + priority: 'medium', effort: 'small', tags: [], parentId: null, assignee: 'Builder', threadId: 'worker', + runState: 'running', order: 1, createdAt: 1, updatedAt: 1, + execution: { target: 'room', threadId: 'worker', reasoningEffort: 'low', startedAt: 1, finishedAt: null, + checks: [], blockers: [], reviewVerdict: null }, +} +assert.equal(activeRoomWorkerEffort([ticket], 'worker'), 'low') +assert.equal(activeRoomWorkerEffort([ticket], 'other-thread'), undefined, 'effort is scoped to the actual thread') +assert.equal(activeRoomWorkerEffort([{ ...ticket, runState: null }], 'worker'), undefined, 'parked runs clear the override') +assert.equal(activeRoomWorkerEffort([{ ...ticket, runState: 'done' }], 'worker'), undefined, 'settled runs restore manual defaults') +assert.equal(activeRoomWorkerEffort([{ ...ticket, execution: { ...ticket.execution!, finishedAt: 2 } }], 'worker'), undefined) +assert.equal(activeRoomWorkerEffort([{ ...ticket, execution: { ...ticket.execution!, threadId: 'old-worker' } }], 'worker'), undefined) +assert.equal(activeRoomWorkerEffort([{ ...ticket, execution: { ...ticket.execution!, target: 'solo' } }], 'worker'), undefined) +assert.equal(activeRoomWorkerEffort([{ ...ticket, execution: { ...ticket.execution!, reasoningEffort: undefined } }], 'worker'), undefined) +console.log('Room worker effort display checks passed: explicit thread ownership, active lifecycle and legacy/manual fallback.') diff --git a/app/src/lib/room-worker-effort.ts b/app/src/lib/room-worker-effort.ts new file mode 100644 index 00000000000..849b449905c --- /dev/null +++ b/app/src/lib/room-worker-effort.ts @@ -0,0 +1,7 @@ +import type { ReasoningEffortSetting, Ticket } from './types' + +export function activeRoomWorkerEffort(tickets: readonly Ticket[], threadId: string): ReasoningEffortSetting | undefined { + return tickets.find((ticket) => ticket.runState === 'running' && ticket.threadId === threadId + && ticket.execution?.target === 'room' && ticket.execution.threadId === threadId + && ticket.execution.finishedAt === null)?.execution?.reasoningEffort +} diff --git a/docs/api.md b/docs/api.md index db5ffae36bc..19b292d4939 100644 --- a/docs/api.md +++ b/docs/api.md @@ -45,11 +45,12 @@ different scopes, or scopes a key the flags or environment already give, is refu | Scope | Routes | | --- | --- | -| `inference` | POST `/v1/chat/completions`, `/v1/completions`, `/v1/responses`, `/v1/messages`, `/v1/messages/count_tokens`, `/v1/tokenize`, `/v1/detokenize`, `/v1/apply-template`, `/v1/audio/speech`, `/v1/images/generations`, `/v1/embeddings`, `/v1/decisions`, `/v1/systemone`, `/score`, `/v1/score`, `/v2/rerank`, `/v1/rerank` (also by PUT), `/v1/ocr`, and the same paths without `/v1` where the server has them; GET `/v1/models`, `/models`, `/v1/voices`; a WebSocket upgrade on GET `/v1/responses` or `/responses` | -| `read` | GET `/metrics`, `/v1/metrics`, `/v1/load`, `/memory`, `/v1/memory`, `/stats`, `/dashboard`, `/v1/benchmark/manifest`, `/v1/models`, `/models`, `/v1/voices` | +| `inference` | POST `/v1/chat/completions`, `/v1/completions`, `/v1/responses`, `/v1/messages`, `/v1/messages/count_tokens`, `/v1/tokenize`, `/v1/detokenize`, `/v1/apply-template`, `/v1/audio/speech`, `/v1/images/generations`, `/v1/embeddings`, `/v1/decisions`, `/v1/systemone`, `/score`, `/v1/score`, `/v2/rerank`, `/v1/rerank` (also by PUT), `/v1/ocr`, and the same paths without `/v1` where the server has them; GET `/v1/models`, `/models`, `/v1/models/{id}`, `/models/{id}`, `/v1/voices`; a WebSocket upgrade on GET `/v1/responses` or `/responses` | +| `read` | GET `/metrics`, `/v1/metrics`, `/v1/load`, `/memory`, `/v1/memory`, `/stats`, `/dashboard`, `/v1/benchmark/manifest`, `/v1/models`, `/models`, `/v1/models/{id}`, `/models/{id}`, `/v1/voices` | A scoped key reaches nothing else: not the stored Responses (GET or DELETE `/v1/responses/ID`), Recall, Sliding Weights, -`/v1/imprint`, another method, or a suffix alias such as `/alt/completions` that the server answers for a full key. The route +`/v1/imprint`, adding or deleting voices (`--manage-voices`), another method, or a suffix alias such as `/alt/completions` +that the server answers for a full key. The route is matched exactly after the query and trailing slashes are cut. A refused route answers 403 with the code `insufficient_scope` (Messages routes: an Anthropic `permission_error`) and closes the connection before the body is read or a parked model reloads. The public routes stay public. @@ -113,6 +114,7 @@ routes still require when keys are on. Without the flag no reply carries a CORS | Route | Behavior | | --- | --- | | `GET /v1/models` | Served model ID and any configured aliases (both servers); native entries carry [capabilities](#model-capabilities) | +| `GET /v1/models/{id}` | One served ID or alias: the entry `/v1/models` lists for it, or 404 `model_not_found` (native server; see [One model](#one-model)) | | `GET /health` | Liveness, the served model, the queue and live rates; open with keys (see [Health](#health)) | | `GET /memory`, `GET /v1/memory` | Native read-only memory snapshot ([memory diagnostics](memory-diagnostics.md)) | | `GET /metrics`, `GET /v1/metrics` | Prometheus text: requests, KV occupancy, drafts and latency (both servers) | @@ -180,6 +182,16 @@ Discovery and boolean request checks use the same loaded flag reader. Publicatio Flags describe the engine; request combinations, context, template and format constraints still apply. greedy_only and plain_only describe restrictions, and context_fitted says the context was limited to memory. +## One model + +`GET /v1/models/{id}` (or `/models/{id}`) is OpenAI's retrieve-model route on the native server. For the served name or +one of its `--alias` names it returns the object `GET /v1/models` lists for that id, capabilities included. The id is +percent-decoded once, so `org/name` may be sent as written or as `org%2Fname`; an id holding a `%` that starts no hex +pair is matched as written. Any other id answers 404 with `"code": "model_not_found"`, `"type": "invalid_request_error"`, +`"param": "model"` and the decoded id in the message. A path that ends in `/models` still lists every model; send an +id ending in `/models` as `org%2Fmodels`. Keys and [key scopes](#key-scopes) apply as they do to `GET /v1/models`. +The Python 0.6.6 server, the other server that lists models, has no such route. + ## Decisions `POST /v1/decisions` is served by Flash Next on one CUDA GPU, by LFM2 on CUDA and by Gemma 4 on XPU. @@ -1740,3 +1752,61 @@ streamed. ```bash curl http://127.0.0.1:8080/api/embed -d '{"model":"local-model","input":"hello"}' ``` + +## Request journal and replay + +`TENSORFOLD_REQUEST_JOURNAL=PATH` turns on a request journal; it is off unless set, and only `PATH` and its siblings are +written. **It holds every chat and completion prompt and reply in full**: treat it like the conversations themselves. +Image URLs and PDF data are replaced with ``, as in `TENSORFOLD_REQUEST_LOG`, which is unchanged. No HTTP header +is journaled, so API keys and `Authorization` values never reach it. The server creates `PATH` and `PATH.lock` +owner-only (0600), refuses a symbolic link or a file others can read, and holds `PATH.lock` while it runs, so a second +server on the same journal does not start. Benchmark child servers never inherit the variable. + +Each request writes three JSON lines: `start` before any work (its reply id, route, fingerprint, the client's seed and +the redacted body), `prepared` before the engine sees it (the seed and sampling the server resolved, the token limit, +thinking, drafts and the prompt's token count and SHA-256), and `finish` once the reply has gone (status, outcome, the +reply's size and SHA-256, its `token_sha256`, and the reply bytes in base64 when they fit 4 MiB). Responses and Messages +requests are journaled in the chat form they are translated to. A raw completion whose `prompt` is a list is not +replay-exact: its per-prompt prepared records are not written, and its individual drawn seeds are not journaled. + +Size is bounded: a file rotates at 64 MiB to `PATH.1`, older files move up, and `PATH.3` is the last kept, so the +journal holds at most 256 MiB. A body or reply too large for one 8 MiB record keeps its size and hash only. Each record +is one `write` with no sync, so the journal adds three small appends to a request and nothing to its tokens; a full +disk or a write error loses that record (the server logs it once), never the request. A record survives the server +process crashing, not a power loss. + +On the next start the server reads the kept files. A request that started and never finished, with no clean stop after +it, was in flight at a crash: a `quarantine` line flags it, and the server never retries it. Its fingerprint is SHA-256 +over the API key's label (as in the access log), the route and the whole body, so it matches only the same key sending +the same request. One crash only flags what was in flight, since a crash can come from elsewhere (another route, the +machine) and the requests beside it are not to blame. A request whose fingerprint was in flight at two crashes is +refused with a 400 `request_quarantined` before the engine sees it, which ends a client's retry loop after the second +crash. Other requests, and other keys sending the same body, are served as before; the check is one hash lookup. Without +API keys every client shares one label. A quarantine lapses 24 hours after its last crash, and a clean stop (SIGTERM, +Ctrl-C) quarantines nothing. + +`tools/replay_request.py` lists, clears and replays journaled requests: + +```sh +python3 tools/replay_request.py requests.jsonl --list +python3 tools/replay_request.py requests.jsonl --id chatcmpl-example --base http://127.0.0.1:8080 +python3 tools/replay_request.py requests.jsonl --clear chatcmpl-example # or a fingerprint, or all; server stopped +``` + +`--list` sends nothing. A replay sends the journaled body once to its route; when the client sent no seed, it adds the +seed the server drew. It compares the reply's output: every choice's text, reasoning, tool calls (without their ids), +logprobs and finish reason, the token counts, the stop sequence and `tensorfold.token_sha256`, the SHA-256 of the reply's +token ids, so equal means the same tokens. Streams compare their joined deltas, whatever their frame boundaries. Reply +ids, `created`, timings, `cached_tokens` and keepalives are left out; `--whole-body` compares every byte instead and +will differ on those. A reply too large to keep is compared by its token hash. Exit 0 is equal, 1 is different, and 2 +means there was no finished reply to compare. `--body FILE` supplies the original request when images or a PDF were +redacted or the body was too large; `--allow-quarantined` sends a quarantined request on purpose; `--key-env NAME` +names the variable holding the API key (`TENSORFOLD_API_KEY` by default), which is sent and never written. + +A replay is exact on the same build, checkpoint, tokenizer, drafter and server flags, since TensorFold's decode gives the +same tokens for the same prompt and seed with or without drafts, alone or batched. It is not exact across builds or +checkpoints, after the server's defaults change, when a Messages request relied on the server's thinking default, when +the body was restored with different media, or for a request whose server ran several generations for it (Cortheon) +without a client seed or `--prompt-seed`, since only the last drawn seed is journaled. +Unseeded prompt lists are not replay-exact either: each prompt draws its own seed, and those per-prompt prepared +records are omitted. Send a client seed or keep the same `--prompt-seed` setting for an exact list replay. diff --git a/docs/drama-http-voices.md b/docs/drama-http-voices.md index 1599ebdab32..3f5a2ca4279 100644 --- a/docs/drama-http-voices.md +++ b/docs/drama-http-voices.md @@ -1,8 +1,8 @@ # Attested HTTP voices -`tensorfold-native serve MODEL --voices DIR --default-voice NAME` loads the catalog at startup. Without these flags the built-in voice and speech request lowering are unchanged. `--default-voice` defaults to `default`; a configured name must exist. A missing, malformed or unattested catalog file refuses startup rather than silently substituting a voice. Restart to reload files. +`tensorfold-native serve MODEL --voices DIR --default-voice NAME` loads the catalog at startup. Without these flags the built-in voice and speech request lowering are unchanged. `--default-voice` defaults to `default`; a configured name must exist. A missing, malformed or unattested catalog file refuses startup rather than silently substituting a voice. Without `--manage-voices`, restart to reload files. -`POST /v1/audio/speech` selects a catalog entry with `voice` (or the existing `speaker` alias). An absent, empty or case-insensitive `default` selects the configured default. Other names match exactly. Request-supplied reference arrays and paths remain unsupported. `GET /v1/voices` returns `{"voices": ["default", ...], "details": [{"id": NAME, "description": TEXT}, ...]}` with catalog names sorted, without transcripts, codes or attestation notes; `description` is the file's optional one-line description (at most 200 bytes), else empty. Non-speech models return the existing unknown-route response. +`POST /v1/audio/speech` selects a catalog entry with `voice` (or the existing `speaker` alias). An absent, empty or case-insensitive `default` selects the configured default. Other names match exactly. Reference arrays, `ref_audio`, `ref_text` and paths in a request remain unsupported; an inline voice object needs `--request-voices` (below). `GET /v1/voices` returns `{"voices": ["default", ...], "details": [{"id": NAME, "description": TEXT}, ...]}` with catalog names sorted, without transcripts, codes or attestation notes; `description` is the file's optional one-line description (at most 200 bytes), else empty. Non-speech models return the existing unknown-route response. Each regular `NAME.json` file contains: @@ -25,6 +25,19 @@ Reference `text` is the exact transcript. Codes are frame-major signed integers, The loader enforces the family's reference count, transcript length, frame count and codebook ranges before serving. It also rejects empty references, structural prompt tokens, malformed speaker tags, oversized files and oversized catalogs. The assembled prompt must still fit the engine's advertised prompt budget. Reference rows go through the same family `prompt.build` used by the generation CLI; only the tokenizer interface is adapted. +## Voices added while serving + +`--manage-voices` (off by default) adds two routes for keys with the `admin` scope, or any key in a key file without scopes; `inference` and `read` keys get 403. Without an API key every client is an admin, so serve with `--api-key-file` before turning it on. Without the flag both routes answer as before, with the unknown-route 404. + +- `POST /v1/voices` adds or replaces `name`. The body is `{"name": NAME, ...}` plus either a voice file's own fields (`format`, `source`, `references`, optional `description`), or `{"audio": BASE64, "text": TRANSCRIPT, "source": {...}}` with optional `description`. `audio` is a WAV file (PCM 8, 16, 24 or 32-bit, or float32, any channel count, at most 30 seconds, and a rate from 1 to 192,000 Hz whose reduced ratio `rate / gcd(rate, 44100)` is at most 640; this includes 8/16/24/32/44.1/48/64/88.2/96/176.4/192 kHz) in standard base64, resampled and encoded by the loaded model's own codec, on the speech engine's thread when a lane is free. The attestation and transcript are checked before any audio is encoded. The reply is `{"id": NAME, "description": TEXT, "added": true}` with 201, or `"added": false` with 200 for a replaced voice. +- `DELETE /v1/voices/NAME` deletes a voice; the configured `--default-voice` cannot be deleted (409), and an unknown name is a 404. + +With `--voices DIR`, an added voice is written to `DIR/NAME.json` (through a temporary file renamed into place, before the catalog changes) and a deleted one's file is removed, so a restart loads the same catalog. Without a directory, changes last until the server stops. A request reads its voice once, when it arrives: a voice deleted or replaced while it runs does not change its audio. The reference prompt cache keys on the reference rows themselves, so a replaced voice never reuses the old voice's saved rows. + +## Inline voices + +`--request-voices` (off by default) lets `voice` in `POST /v1/audio/speech` be a voice file's object instead of a name: `"voice": {"format": "drama3-http-voice/1", "source": {...}, "references": [...]}`, checked as the catalog checks a file, attestation included. It builds the same prompt as a catalog voice with the same references, and takes no `speaker` field. Without the flag, an object `voice` gets the same refusal as before. + ## Speech limits and discovery `GET /v1/models` includes a `speech` object only for a loaded speech engine. `max_assembled_prompt_rows` counts all backbone prompt rows, including wrappers, reference transcripts and acoustic reference codes. `max_generated_acoustic_frames` is the output budget, not a text-token limit. `sample_rate_hz` and `samples_per_acoustic_frame` describe the output geometry. `max_input_code_points` is the separate HTTP input-text policy; it is not a tokenizer or assembled-row budget. diff --git a/docs/environment.md b/docs/environment.md index 9d53fab2db2..c6496f62375 100644 --- a/docs/environment.md +++ b/docs/environment.md @@ -27,6 +27,19 @@ Diagnostics quote and escape the supplied text so it cannot create another termi | `TF_Q27_COPY_ROWS` | Whole u32 count; zero disables copied rows; default 48 | | `TF_Q27_DRAFT_SLOTS` | Whole u32 count, clamped to 1 through the lane stream limit; default 8. DFlash2 can draft for at most the smaller of this count and the admitted streams, and none without a drafter. | | `TF_MTP_DRAFTS` | Whole u32 count, clamped to 1 through the drafter's window less one; existing depth when unset | +| `TF_TIMING` | Exactly `0` or `1`; default off (each call's wall time on stderr while set) | +| `TF_NO_TREES` | Exactly `0` or `1`; default off. `1` keeps the CUDA drafter's chains only, and retains precedence over `TF_DRAFT_NODES` | +| `TF_MTP_TREES` | Exactly `0` or `1`; default off (1 turns the MTP drafter's trees on) | +| `TF_MTP_BATCH` | Exactly `0` or `1`; default on. `0` keeps one stream at a time | +| `TF_QWEN_KEEP_LATE` | Exactly `0` or `1`; default off | +| `TF_QWEN_KV_PAGE_TEST` | Whole page size from 1 to 2147483647; unset off. Each cache's own buffer reads through a table of n-position pages in reverse order (checks) | +| `TF_QWEN_POOL_LOG` | Exactly `0` or `1`; default off (the pool's census after a prompt pass) | +| `TF_COST_KEY_TRACE` | Exactly `0` or `1`; default off (each cost key's parts on stderr) | +| `TF_Q27_POCKET_OFF` | `all`, or a list of `layer:neuron` pairs; default off (pocket diagnostics) | +| `TF_Q27_TAIL` | Exactly `off`; default off — each nudged sequence's tail rows are the backward's rows | +| `TF_Q27_GEMM` | Exactly `narrow`; default the 128x128 tiles | +| `TENSORFOLD_MEMORY_RESERVE_GIB` | A finite GiB amount; the HIP admission's floor (0.5, or 2 on shared memory) and the memory's size still bound it | +| `TENSORFOLD_HIP_MEMORY_LIMIT_GB` | A positive finite GiB amount whose byte count fits a 64-bit size | | `TF_DSPINE_WINDOW` | Qwen3.8-27B on CUDA with a DSpine `--drafter`: whole row count 16 through 8192 that narrows the drafter's sliding window; it must be at least the block (16) and at most the checkpoint's own `sliding_window`, else the drafter is refused when it opens; unset or blank keeps the checkpoint's (8192 for tencent/Qwen3.8-27B-DSpine-b16) | | `TF_DRAFT_NODES` | Whole native-size nonnegative count, capped by the drafter's window; zero disables trees | | `TF_QMMF_HALF_BELOW` | Whole native-size nonnegative block count; zero disables half tiles; default 96 | @@ -51,6 +64,14 @@ Diagnostics quote and escape the supplied text so it cannot create another termi | `TF_GLM_DRAFT_CONFIDENCE` | Finite number 0 through 1 where a DFlash2 chain's chance product stops it; default 0.7 | | `TF_GLM_CONTEXT_CEILING` | GLM-5.3-Flash on CUDA: whole token count 1 through 2147483616, the window `--context` may ask for and `--context 0` serves, in place of config.json's 1048576; read at GLM's open. Past that length the model's quality is the operator's to check. Unset keeps config.json's window | | `TF_GLM_EXPERT_FORM` | `classic` or `factored`: the expert form GLM's CUDA decode windows use (the same bits either way), also at a load that times nothing; unset or blank races the two when a build first loads with drafts and scratch context and keeps the winner, else classic; read on rank 0, which chooses every rank's form | +| `TF_GLM_INDEX_CUDA` | GLM on CUDA: exactly `1` (both DSA indexer kernels), `0` (neither) or `scores` (scores only); unset or blank is `both` | +| `TF_GLM_KV_HOST_GIB` | GLM on CUDA: a finite GiB amount of at least 0 for the DSA layers' pinned host pages; unset or blank uses one full window and 16 rows a page | +| `TF_GLM_RANK` | GLM-5.3-Flash on CUDA: a whole rank index from 0 through 4294967295, set with `TF_GLM_WORLD`; unset with it gives one rank | +| `TF_GLM_WORLD` | GLM-5.3-Flash on CUDA: a whole rank count from 1 through 4294967295, set with `TF_GLM_RANK`; unset with it gives one rank | +| `TF_NEMOTRON_RANK` | Nemotron 3.5 Super on CUDA: a whole rank index from 0 through 4294967295, set with `TF_NEMOTRON_WORLD`; unset with it gives one rank | +| `TF_NEMOTRON_WORLD` | Nemotron 3.5 Super on CUDA: a whole rank count from 1 through 4294967295, set with `TF_NEMOTRON_RANK`; unset with it gives one rank | +| `TF_MINIMAX_RANK` | MiniMax-M3.1-Flash on CUDA: a whole rank index, 0 or 1 at two ranks, set with `TF_MINIMAX_WORLD`; unset with it gives one rank | +| `TF_MINIMAX_WORLD` | MiniMax-M3.1-Flash on CUDA: a whole rank count, 2 at CUDA, set with `TF_MINIMAX_RANK`; unset with it gives one rank | | `TF_PROMPT_ROWS` | Native serving: a multiple of 16 from 128 through 2048; unset keeps the chip/family default | | `TF_ANE_COLUMNS` | Whole u32 count; zero disables the experimental share; default zero | | `TF_FLASHNEXT_SCALE_INDEX` | Flash Next on Metal before tensor units: exactly `0` or `1`; default 1, where the 4-bit expert kernels (decode, grouped and prompt gathers) read each group's scale and bias through a 16-bit index into its tensor's table of pairs, the same values from fewer weight bytes, and the routed experts' stored scales and biases are not kept in memory; `0` keeps and reads the stored arrays; ignored with `--ssd-experts` | @@ -161,6 +182,7 @@ These settings retain their existing boolean policies rather than gaining new al - Flash Next keeps its lenient readers where they are: `TF_FLASHNEXT_TP` and `TF_FLASHNEXT_LOGITS` take a path, `TF_FLASHNEXT_OWNED` a list, `TF_FLASHNEXT_DEPTH_LOG` and `TF_TP_TRACE`/`TF_TP_LOCAL`/`TF_TP_STATS` select by presence, and the tool-only sampling settings of the MTP check and the `FZ_` developer switches keep their semantics. +The fabric/tp config helper keeps its runtime-name lookup instead of gaining a startup row: it carries the lenient switches above and transport names read only by tools, which no server would set. The profile registry reports selected arithmetic/experimental overrides; it does not change their parsing or defaults. See [profiles](profiles.md) for classes, scopes and grouped slide-learning names. diff --git a/docs/evaluating.md b/docs/evaluating.md index d90b8627169..0d249d85a74 100644 --- a/docs/evaluating.md +++ b/docs/evaluating.md @@ -43,6 +43,9 @@ These need no GPU, driver or checkpoint: - `tensorfold capabilities --json` lists the backends, model families, formats, serve flags and `optional_libraries`, each with a `found` flag. - `tensorfold info REPO` prints a pulled checkpoint's family, format, context, weights size and memory floor. +- From a source build (`tensorfold` built from source, or `tf-cluster`), `tensorfold config validate FILE` + reads a cluster.json, prints every problem, and does not plan models or probe hosts. The release + binary, `tensorfold-native`, does not have this command. ## Container diff --git a/docs/kernel-contract.md b/docs/kernel-contract.md index ffaf4740529..028e0210ba0 100644 --- a/docs/kernel-contract.md +++ b/docs/kernel-contract.md @@ -351,6 +351,10 @@ HIP also checks the router over the rows a checkpoint already holds in bf16 (`tf form), bit-equal to the fp32-rows router it replaces at 1 to 16 rows, with both kinds' non-finite plants through gate 1 and the exact sums of gate 4. +Metal also checks Idol's denoiser (`metal_idol*.zig`): its fp16 projections and GELU form, the split-K fp32 rows, +`id_gemm32` (true fp32 sums: the NAX fp32 path in its place is a control gate 4 must catch), the LayerNorms, RePo's +angles, the heads, the elementwise steps and the attention's four forms, each at idol-sdk's fp16 points (19 controls). + HIP also checks the DeltaNet prompt recurrence at half a value head a block (`tf_gdn_prompt_128`, its y and state), bit-equal to the plain window scan `gated_delta_tile` on the same tokens. Its prompt prework in one launch (`tf_gdn_prompt_prep`: conv, q and k head norms, v, gate, beta and the new conv state) diff --git a/docs/optimization-ledger.md b/docs/optimization-ledger.md index e67ea9e1304..658aa868898 100644 --- a/docs/optimization-ledger.md +++ b/docs/optimization-ledger.md @@ -78,6 +78,9 @@ last two hold the families with only a Metal, HIP or scoring backend. | 27. Profiles | done [#1944] | done [#1944] | done [#1959] | done [#1944] | done [#2061] | | 28. Scale index | ? | done M[#2760], open M[#2805] | ? | ? | ? | | 29. DSpine | done C[#2633] | no (no drafter) | no (no drafter) | no (no drafter) | no (no drafter) | +| 30. Small-kernel fusion | ? | failed H[#1603] | ? | ? | ? | +| 31. Stream-tile prefetch | ? | failed H[#1603] | ? | ? | ? | +| 32. Filled-item prompt grid | ? | failed H[#1603] | ? | ? | ? | | Optimization | kol1 | spk25 | dory | mm3 | dsv41 | | --- | --- | --- | --- | --- | --- | @@ -110,6 +113,9 @@ last two hold the families with only a Metal, HIP or scoring backend. | 27. Profiles | done [#1944] | done [#1944] | open [#2306] | yes | yes | | 28. Scale index | ? | ? | ? | ? | ? | | 29. DSpine | no (no drafter) | no (no drafter) | no (no drafter) | no (no drafter) | no (no drafter) | +| 30. Small-kernel fusion | ? | ? | ? | ? | ? | +| 31. Stream-tile prefetch | ? | ? | ? | ? | ? | +| 32. Filled-item prompt grid | ? | ? | ? | ? | ? | | Optimization | lfm2m | lfm3 | qwen4 | ling | | --- | --- | --- | --- | --- | @@ -142,6 +148,9 @@ last two hold the families with only a Metal, HIP or scoring backend. | 27. Profiles | yes | yes | yes | yes | | 28. Scale index | ? | ? | ? | ? | | 29. DSpine | no (no drafter) | no (no drafter) | no (no drafter) | no (no drafter) | +| 30. Small-kernel fusion | ? | ? | ? | ? | +| 31. Stream-tile prefetch | ? | ? | ? | ? | +| 32. Filled-item prompt grid | ? | ? | ? | ? | q3.5 `qwen3_5` (C, M, H, X), fnext `flashnext` (C, M, H), glm `glm` (C, M), gem4 `gemma4` (C, M, X), nemo `nemotron` (C, M, H, X), kol1 `kolibri1` (C), spk25 `spark25` (C, M), @@ -180,6 +189,9 @@ ling `ling` (host package only, no engine yet; CUDA plan in [#850]). | 27. Profiles | yes | yes | yes | yes | | 28. Scale index | ? | ? | ? | ? | | 29. DSpine | open M[#2634] | no (scores) | no (no drafter) | no (no drafter) | +| 30. Small-kernel fusion | ? | ? | ? | ? | +| 31. Stream-tile prefetch | ? | ? | ? | ? | +| 32. Filled-item prompt grid | ? | ? | ? | ? | | Optimization | gdsa | kimi | qwen3 | | --- | --- | --- | --- | @@ -212,6 +224,9 @@ ling `ling` (host package only, no engine yet; CUDA plan in [#850]). | 27. Profiles | yes | yes | yes | | 28. Scale index | ? | ? | ? | | 29. DSpine | no (no drafter) | no (no drafter) | no (prompt) | +| 30. Small-kernel fusion | ? | ? | ? | +| 31. Stream-tile prefetch | ? | ? | ? | +| 32. Filled-item prompt grid | ? | ? | ? | q27 `qwen27` (M: Qwen3.8-27B and Qwen3.5-MoE), lfm2 `lfm2` (C: LFM2-VL, scores decisions and writes no text), llama `llama` (M), step5 `step5` (M), gdsa `glm_dsa` (M), kimi `kimi_k3` (M, native serving on [#2221]), @@ -258,6 +273,9 @@ below; these are estimates for planning a port, not results. | 27. Profiles | none | none | none | names the opt-in switches | | 28. Scale index | none | low | 5 % of the weights once prompts read it too | one stream's decode before tensor units | | 29. DSpine | none | medium | low | Qwen3.8-27B; agent 2–20 % faster, chat and code 10–19 % slower | +| 30. Small-kernel fusion | none | low | none | HIP Flash Next: 1.2–2.0 % of a round for the hyper-connection block, 2.4–4.0 % for all four groups | +| 31. Stream-tile prefetch | none | none | none | HIP Flash Next: the hyper-connection projections, no gain | +| 32. Filled-item prompt grid | low | none | none | HIP Flash Next: prompt tok/s at most 1.2 % better | ## The optimizations @@ -480,6 +498,30 @@ below; these are estimates for planning a port, not results. ([#2633]); the Metal binding ([#2634]) is still open. On a GB10, against DFlash2: agent prompts decode 2–20 % faster, chat and code 10–19 % slower. It needs the checkpoint's own DSpine drafter, so other families have none. +30. **Small-kernel fusion.** Launches under 20 µs, fused into one launch where they sit next to each other, to save the + gap between dispatches (2.0 µs median) and the per-launch floor (the cheapest kernels run 1.3 µs). Bounded under the + bar on Flash Next HIP, so the row is `failed` ([#1603]). + + | Family | Gain (measured) | Where | + | --- | --- | --- | + | flashnext (H) | hyper-connection block 1.2–2.0 % of a round, all four groups together 2.4–4.0 %; estimates from measured gaps and launch counts, not built | [#1603], main `6c5cef894`, gfx1151 | + +31. **Prefetched and double-buffered stream tiles.** A separate stream-tile family for the hyper-connection + projections that prefetches or double-buffers the weight loads, bit-equal to the plain kernel at 1–8 rows. On + Flash Next HIP it gained nothing, so the row is `failed` ([#1603]). + + | Family | Gain (measured) | Where | + | --- | --- | --- | + | flashnext (H) | code 46.01–46.30 tok/s and chat 39.87–40.10 tok/s against main, every token hash equal | [#1603], one Strix Halo iGPU (gfx1151) | + +32. **Routed-expert prompt grid sized by filled items.** The prompt launch's grid follows the items actually filled + and not the decode tile's capacity, where about 91 % of the blocks exit empty at 4,096 rows. On Flash Next HIP the + empty blocks cost almost nothing, so the row is `failed` ([#1603]). + + | Family | Gain (measured) | Where | + | --- | --- | --- | + | flashnext (H) | first-token ratios 0.99–1.01, prompt tok/s at most 1.2 % better, decode and concurrency level | [#1603], one Strix Halo iGPU (gfx1151) | + [#458]: https://github.com/ashhart/TensorFold/pull/458 [#468]: https://github.com/ashhart/TensorFold/pull/468 [#519]: https://github.com/ashhart/TensorFold/pull/519 @@ -630,5 +672,6 @@ below; these are estimates for planning a port, not results. [#2634]: https://github.com/ashhart/TensorFold/pull/2634 [#2784]: https://github.com/ashhart/TensorFold/pull/2784 [#2764]: https://github.com/ashhart/TensorFold/issues/2764 +[#1603]: https://github.com/ashhart/TensorFold/issues/1603 [#2977]: https://github.com/ashhart/TensorFold/pull/2977 [#2805]: https://github.com/ashhart/TensorFold/pull/2805 diff --git a/docs/recipes/glm-5.3-flash-cuda.md b/docs/recipes/glm-5.3-flash-cuda.md index 2b74f04efd5..4eb79aed667 100644 --- a/docs/recipes/glm-5.3-flash-cuda.md +++ b/docs/recipes/glm-5.3-flash-cuda.md @@ -5,7 +5,7 @@ The native CUDA build serves GLM-5.3-Flash at tensor parallel over hosts: from N ([1.1.0](../../CHANGELOG.md#110), [the checkpoint](glm-5.3-flash.md#exl3)), and in [1.1.5](../../CHANGELOG.md#115) (#1050) from NVIDIA's FP4-Local checkpoint as stored and from XSFP4, which keeps FP4-Local's tensors outside the routed experts. Jammed XSFP4, in [1.2.3](../../CHANGELOG.md#123) ([#2041](https://github.com/ashhart/TensorFold/pull/2041)), holds those experts at block 32 in the `csf0_v1` form and loads the same way. -Jammed XSFP4 NZ5, on `main` after 1.2.7 ([#2894](https://github.com/ashhart/TensorFold/pull/2894)), is Jammed XSFP4 refitted with E2M1's -0 code read as +5 (`NVFP4_NZ5`) and loads the same way. +Jammed XSFP4 NZ5, in [1.2.10](../../CHANGELOG.md#1210) ([#2894](https://github.com/ashhart/TensorFold/pull/2894)), is Jammed XSFP4 refitted with E2M1's -0 code read as +5 (`NVFP4_NZ5`) and loads the same way. Rank 0 serves HTTP and the other ranks follow its steps, with MTP drafts, concurrent streams and kept prompt states. The [Python 0.6.6 recipe](glm-5.3-flash.md) and its `--tp`, `--rank` and `--master` flags belong to the frozen engine. @@ -219,6 +219,18 @@ missing link (#1971). The ring also needs these NCCL settings at start (#1971): - `NCCL_ALGO=Ring`, and a graph for each rank that receives on the port toward the previous rank and sends toward the next. +For switchless RoCE links on separate IPv4 subnets, use NCCL 2.30.7 or later: [subnet-aware +routing](https://github.com/NVIDIA/nccl/blob/v2.30.7-1/src/transport/net_ib/connect.cc#L61-L62) +first shipped in [v2.30.7-1](https://github.com/NVIDIA/nccl/commit/5c1c4288e6627e9b442eda997aa6ee9136cda0bd). +Point each rank at a newer `libnccl.so.2` with `LD_LIBRARY_PATH=/path/to/nccl/lib`, retaining other trusted library +directories. +Set `NCCL_IB_SUBNET_AWARE_ROUTING=1` and `NCCL_IB_SUBNET_PREFIX_LEN=24`, keeping the settings above; +the prefix must match the links' IPv4 subnets (24 for /24). +On every rank, check `rank N startup: entering NCCL init (..., NCCL X.Y.Z, ...)` and `NCCL_DEBUG=INFO` +for the selected NIC and subnet-aware overrides. +With gather prefill, replacing 2.28.9 with a build reporting 2.30.7 and enabling these settings fixed startup timeouts +and completed requests. + `TF_GLM_ROCE_MULTI=1` with `TF_TP_ROCE_RELAY=1` relays gathers through both neighbours on such a ring instead of NCCL (#2352, opt-in, four ranks only). Gathers up to `TF_TP_ROCE_RELAY_MAX_KB` a rank go on the wire (64 KiB by default, 4 to 1024); larger ones, reductions and exchanges stay on NCCL. On the ring with gather, @Bizuayeu measured diff --git a/docs/recipes/idol.md b/docs/recipes/idol.md new file mode 100644 index 00000000000..05fe83036f9 --- /dev/null +++ b/docs/recipes/idol.md @@ -0,0 +1,137 @@ +# Idol's denoiser on Metal + +Idol (speridlabs) turns one image into a 3D Gaussian splat. A 0.37B flow transformer denoises 8,192 latent rows of 16 +channels, conditioned on the image's DINOv3 and FLUX.2 VAE rows; two decoders then grow an octree from that latent and +emit the Gaussians. `zig/src/families/idol` runs the denoiser on the Metal runtime from the released checkpoint: + +- once an image: the condition embedding (DINOv3's 1,280 channels and the VAE's 128, each projected to 1,024 and + summed) and the two condition-refiner blocks (no modulation, affine LayerNorms); +- at each step: the two noise-refiner blocks over the latent rows, then the 24 joint blocks over 12,294 rows (8,192 + latent, 4,101 condition, one camera token), then the output head and the camera velocity. + +Every block is 16 heads of 64 at width 1,024 with a tanh-GELU MLP of 4,096. Its rotary is RePo: a learned map from +each row's LayerNorm to per-head 3D positions, angles from 10, 10 and 12 frequencies per axis. + +The sampler's defaults: 50 Euler steps, `t = 3u / (1 + 2u)`, guidance `v = 4 v_cond - 3 v_uncond` (two passes a step: +with the condition, and with zeros). + +The image encoders, the decoders and the PLY writer are not ported yet. `tools/zig/idol_case.py` runs the publisher's +SDK in torch, a development reference. It is a denoiser, not a token family: it does not register with the lane +engine, the server or `families.detect`. + +It runs on the M5's tensor units alone, the only chip it was checked on: `Model.load` refuses a GPU without them. + +## Checkpoint + +`speridlabs/idol` at `2731c2291fc65a797c5cb627a5e5526fc1490902`, Apache 2.0, ungated. `config.json` must name +`LatentSeqMMFlowModel` at the released geometry, and `denoiser.safetensors` must hold its 560 tensors; anything else is +refused. The reference is idol-sdk at `4702a7f00850e34b6e83a2170cc123c3e9570744` (Apache 2.0). + +## Precision + +The SDK loads the checkpoint's fp32 weights and converts the blocks' linear layers to fp16; everything else stays fp32. +This family keeps that split: + +- fp16 block projections with fp32 sums; the bias joins the sums before one fp16 rounding, GELU after it. +- LayerNorms in fp32, rounded to fp16; the modulation's shift and scale in fp16 ops, as torch's fp16 tensors run them. +- RePo in fp32: its LayerNorm, both 1,024 to 128 maps, the 128 to 48 map and the angles. +- Attention: fp16 q, k and v, fp32 scores and sums. q and k are rotated, then L2-normalized and scaled by the + checkpoint's gamma times 8. The tensor units take an fp32 P short, which left outputs 3.5e-4 low on average, so + `id_attention` rounds P to fp16 itself and sums the softmax's denominator over those same values. +- The condition embedding and the output projection in fp32; the time MLP, modulation and camera MLPs on the host. + +### The tensor units' fp32 matmul is not fp32 + +On the M5, a GEMM whose inputs are fp32 on the tensor units (`tfp::gemm_nax`, the Qwen-VL tower's +`qwv_gemm_f32`, MLX's fp32 matmul) truncates each input to 10 mantissa bits, toward zero (#1772): its error against +float64 is about 7.5e-4 of the result, against about 1e-7 for an fp32 FMA. RePo's maps at that precision move +block 8's attention out of its gate. + +`id_norm_split` therefore writes each RePo input row as fp16 `[hi | hi | lo]` (`lo = x - hi`), and the map's weights are +stored `[hi | lo | hi]`, scaled by a power of two so `lo` stays normal. One fp16 split-K GEMM with K = 3,072 then sums +`hi*hi + hi*lo + lo*hi` in fp32; `id_repo` undoes the scale. With it every block passes its gate. `id_gemm32`, +an fp32 FMA GEMM on simdgroup matrices, is exact but takes 0.47 s a forward if it runs RePo; it serves the condition +embedding (once an image) and the output projection. + +## Kernel contract + +`zig/tests/contract/metal_idol*.zig` registers every kernel of `idol.metal` and `idol_attention.metal`: + +- `id_linear`'s eight forms (plain and GELU, each tile tail) and the split-K halves `id_split_0` and `id_split_1`; +- `id_norm` (plain, affine, modulated), `id_norm32` (affine, modulated) and `id_norm_split`; +- `id_repo`, `id_qk`, `id_gate_add`, `id_embed`, `id_cond`, `id_bias32` and `id_gemm32`; +- the attention's four forms. + +Each output must lie in the range its fp32 steps allow at the SDK's fp16 rounding points. Nineteen controls drop or +add one rounding point or sum in fp16, and each must go red at its gate. One runs the tensor units' fp32 GEMM in +`id_gemm32`'s place: gate 4 misses it by 13 million times the exact-sum bound. `id_qk` keeps a NaN norm as +`F.normalize` does. Forms no engine call reaches (`id_linear_00` and `_10`, attention `01` and `10`, plain `id_norm`, +affine `id_norm32`) are checked at made-up shapes. The tensor-unit kernels do not build for M1 or M2 offline, as +MOSS-Image's do not; the rest build at their reserved thread counts. + +`tf-kernel-contract --only "metal idol"` on the M5 Ultra: + +``` +SUMMARY 27 kernels: 27 pass gates 1-4, 0 fail, 0 known findings; 19 controls: 19 red as planted, 0 missed; 0 limit problems +``` + +## Run a case + +`idol_case.py` imports the SDK's `dit.py`, `layers.py` and `sampler.py` only when each file's sha256 is the pinned +commit's, and the snapshot only when it is the pinned revision. + +```sh +hf download speridlabs/idol --revision 2731c2291fc65a797c5cb627a5e5526fc1490902 --local-dir WEIGHTS +git clone https://github.com/speridlabs/idol-sdk SDK && git -C SDK checkout 4702a7f00850e34b6e83a2170cc123c3e9570744 +python3 tools/zig/idol_case.py case WEIGHTS SDK case/ --features dino.safetensors vae.safetensors +python3 tools/zig/idol_case.py case WEIGHTS SDK case/ --synthetic-conditioning --cond-seed N # or: no encoders +python3 tools/zig/idol_case.py exact WEIGHTS SDK case/ # the same steps with an fp32 denoiser +python3 tools/zig/idol_case.py blocks WEIGHTS SDK case/ --step 0 # each block's input and output, fp16 and fp32 +zig build tf-idol -Dcpu=apple_m1 +zig-out/bin/tf-idol WEIGHTS case/ +zig-out/bin/tf-idol WEIGHTS case/ blocks 0 +``` + +The features are the SDK's own `feature1` [1, 4101, 1280] and `feature2` [1, 4101, 128] for an image. The case holds the +seeded noise (torch's CPU generator), the schedule, the SDK's input, both velocities and camera velocities at every +step, and its final sample. `exact` adds fp32 velocities on the same inputs; `blocks` adds every block's input and +output at one step, and each joint block run alone in fp32 on the SDK's fp16 input. + +`tf-idol` gates: + +- **Each step**, both branches on the SDK's own input: cosine against the fp32 velocity within 2x the SDK's own + distance (`1 - cos`). Worst row over the run within 2x the SDK's worst row. Fifty fp16 steps make single rows chaotic, + so the per-row gate runs per block instead: +- **Each block** alone on the SDK's fp16 input, against that block in fp32: worst row and cosine within 2x the SDK's. +- **Repeat**: the same step twice, another between, byte for byte. + +It then runs the whole guided schedule from the noise, times it, and writes `sample.f32`. `reference.zig`'s tests plant +a 5% error in one row and require the gate to fail it. + +## Measured + +Setup: + +- Mac Studio M5 Ultra 256 GB, macOS 27; this commit's `tf-idol`. +- The SDK on torch 2.13.0 (MPS, fp16 blocks, `ATTN_BACKEND=sdpa`). +- The SDK's avocado example: its own DINOv3 and VAE features, seed 42, 50 steps, guidance 3. + +Results: + +- **Velocity**, both branches of all 50 steps on the SDK's own input (100 of 100 pass): + - against the SDK: cosine 0.999998 or better; + - against fp32: our worst row over the run 0.0474, the SDK's 0.0398; per step our `1 - cos` is the SDK's within + the 2x bound at every step, and the smaller at 75 of the 100. +- **Blocks**, at steps 1 and 41, each of the 23 joint blocks after the first on the SDK's input: all pass, worst rows + 0.0008 to 0.0017 against fp32, where the SDK's are 0.0007 to 0.0025. +- **Sample:** our 50 guided steps from the same noise end at cosine 0.999993 to the SDK's sample. +- **Repeat:** identical bytes. +- **Speed**, one session: 0.275 s a forward (27.5 s for 50 guided steps), 3.4x the SDK's 0.939 s (the median of its + 100). Load 0.2 to 1.6 s; the condition, once an image, 0.07 s. +- **Memory:** 1.84 GB peak process footprint (`/usr/bin/time -l`, the whole `tf-idol` run with its case), the + denoiser's fp16 weights in shared Metal buffers. + +The shared synthetic case (release `idol-synthetic-case-2731c229`, `--synthetic-conditioning`), jayleaton's run of +`tf-idol` at 9aaf5d318 on an M5 Ultra: exit 0, 100 of 100 branch-steps pass, worst row over the run 0.0932 against the +SDK's 0.1009, `blocks 0` all 23 joint blocks pass, repeat identical bytes, final cosine 0.998918, 27.55 s for 50 guided +steps. diff --git a/docs/recipes/qwen3.8-27b.md b/docs/recipes/qwen3.8-27b.md index 478350c3cad..76485984510 100644 --- a/docs/recipes/qwen3.8-27b.md +++ b/docs/recipes/qwen3.8-27b.md @@ -22,6 +22,17 @@ tensorfold pull z-lab/Qwen3.8-27B-DFlash2 tensorfold serve TensorFold/Qwen3.8-27B-MLX-4bit --drafter z-lab/Qwen3.8-27B-DFlash2 --name bench ``` +With thinking on, serve with `--thinking-budget 4096`; a client can set its own positive `thinking_budget` per request +([API](../api.md#request-fields)). Measured on GPQA Diamond (198 questions) with TensorFold 1.2.7, +`TensorFold/Qwen3.8-27B-MLX-4bit` and the DFlash2 drafter on one GB10, the model card's thinking sampling, a +16,384-token reply limit and one attempt per question and setting: without a budget 78 of 198 replies were cut at the +limit and with 4096 none were; the correct share went from 58.1% to 82.8%, and the 198 questions finished 3.2 times +sooner (60 against 194 minutes at 8 parallel requests). Budgets from 4096 to 8192 measured the same within noise, and +2048 was too tight. The table, the method and the per-question files are in +[#3323](https://github.com/ashhart/TensorFold/issues/3323). + +`--thinking-reserve` ([API](../api.md#reasoning)) keeps a client's `max_tokens` for the answer; it was not tested. + A lone Metal DFlash2 stream can verify 16, 32 or 64 rows (`TF_QWEN27_WINDOW`), on tensor units and earlier chips. Both device classes retain the 16-row default. Startup prices every row count through the selected width, in a width-tagged cache. diff --git a/docs/recipes/training-a-drafter.md b/docs/recipes/training-a-drafter.md index 4a1df718ff9..5c9e2dacaae 100644 --- a/docs/recipes/training-a-drafter.md +++ b/docs/recipes/training-a-drafter.md @@ -109,6 +109,50 @@ over 213.6M tokens. On Kolibri's held-out recordings it accepts 1.937 / 1.321 / German), against 1.38 / 1.23 / 0.95 for the chain drafter it replaced. Those slices chose the checkpoint, so they are development numbers, not a test set. +## Adapting a released drafter + +In the Qwen3.8-27B DSpine-b16 pilot below, no adapted checkpoint beat the released drafter on the independent agent set: +the short budget lost the least rather than gaining. Budget a warm-started adaptation from a few passes over the +scarcest class at a low learning rate, rather than from throughput times a time budget. With replacement and fixed class +quotas, estimate +`expected draws per context = class batch slots * training steps / available class contexts`. +These draws are not complete epochs. Save early checkpoints and follow each class's held-out curve before extending +the run; a first snapshot taken after many repeats can miss the useful part of an adaptation. + +In the [pilot][dspine-pilot], 203 agent contexts with four of nine batch slots had about 13 expected draws each by the +first checkpoint at step 662 of two 5,300-step runs at peak learning rate 3e-5. A 660-step run at peak learning rate +1e-5, with one agent slot, ended at about 3.3 draws per context. Offline tree acceptance on the independent agent set +(110 prompts, 48 SWE instances), tokens per round, with the paired difference to the released drafter and its 95% +group-bootstrap interval: + +| Checkpoint | Steps | Tokens per round | Difference | +| --- | ---: | ---: | --- | +| Released DSpine-b16 | none | 6.079 | | +| Short run, peak LR 1e-5 | 660 | 6.053 | -0.026 [-0.116, +0.048] | +| Long run, SpecForge PR 1038 objective, first checkpoint | 662 of 5,300 | 5.922 | -0.157 [-0.226, -0.091] | +| Long run, loss cut at the first miss, final checkpoint | 5,296 of 5,300 | 5.868 | -0.211 [-0.317, -0.126] | + +The short run stayed closest to the released drafter; both long runs fell significantly below it. The schedule, +objective and class quotas changed together: this supports a short adaptation budget, not an isolated learning-rate +effect or a universal setting. Five later checkpoints were also scored on this set after the first three (a 660-step +run at 5e-6, a 1,320-step run at 1e-5 and three of the expanded-agent run below); none beat the released drafter +either (-0.013 to -0.085). + +Split agent development data by session or repository, and check transfer on a scaffold and tool format absent from +training. Later turns repeat earlier context, and repository holdout alone does not test a different agent framework. +Keep the independent set out of training and checkpoint ranking, and disclose retrospective selection. If that +framework later enters the training mix, label the result as held-out task/repository transfer instead. + +More framework variety is a hypothesis to test. The later expanded-agent run's [selected checkpoint][am] +(step 823) still did not demonstrate improved transfer: on the same 110 prompts its offline delta was -0.0745 tokens +per round, with a paired 95% group-bootstrap interval of [-0.1758, +0.0197]. Mini-SWE was now represented in training, +and duration and quotas changed too, so this was neither an unseen-framework test nor a data-only ablation. An +interval spanning zero does not establish non-regression. Qualify served speed separately, per class, with unchanged +replies; offline acceptance estimates alone do not establish a speedup. + +[dspine-pilot]: https://github.com/ashhart/TensorFold/issues/2667#issuecomment-6822414789 +[am]: https://huggingface.co/Maxrio/Qwen3.8-27B-DSpine-b16-TF4bit-AgentMix/tree/a494b31c665d66719b9fc963f167e9cd7c8419d1 + ## Check it in TensorFold - **Replies.** Drafted replies equal `"draft": false` ones, greedy and sampled with a seed, solo and concurrent, and a diff --git a/docs/supported-models.md b/docs/supported-models.md index eacf45d43d5..88554e13bac 100644 --- a/docs/supported-models.md +++ b/docs/supported-models.md @@ -38,7 +38,7 @@ Conversions are explicitly marked: their upstream weights need the linked conver | GLM-5.3-Flash, FP4-Local | `tensorfold pull nvidia/GLM-5.3-Flash-FP4-Local@76348ddb2be2e35e39ecfc00e75dc07703f4f3d5` | Two GB10s at TP=2, or three at TP=3 over a ring of direct links: @Bizuayeu loaded it as stored and served it at both sizes. 165.3 GiB of weights, 13% less than NVFP4's. | [Native CUDA](recipes/glm-5.3-flash-cuda.md), in 1.1.5 (#1050). NVIDIA's mixed-precision checkpoint: NVFP4 routed experts, FP8 for most of the rest. As close to BF16 as NVFP4 at its smaller size ([receipt](receipts/glm-fp4local-80517fc3/README.md)). | | GLM-5.3-Flash, XSFP4 | `tensorfold pull Bizuayeu/GLM-5.3-Flash-XSFP4@88736f916f8939607fde8a4b881dcae749f7551d` | Two GB10s at TP=2, or three at TP=3 over a ring of direct links: @Bizuayeu served it at both sizes. 165.7 GiB of weights. | [Native CUDA](recipes/glm-5.3-flash-cuda.md), in 1.1.5 through FP4-Local's path. FP4-Local with its routed experts refitted from the BF16 weights and a smoothing folded in, on the same kernels. Closer to BF16 than FP4-Local and NVFP4 by all three measures in [its card](https://huggingface.co/Bizuayeu/GLM-5.3-Flash-XSFP4#measured). | | GLM-5.3-Flash, Jammed XSFP4 | `tensorfold pull Bizuayeu/GLM-5.3-Flash-Jammed-XSFP4@0a22bb46ecef3d0f5f96e41dc6011be12974fbf1` | Two GB10s at TP=2, or three at TP=3 over a ring of direct links: @Bizuayeu served it at both sizes. 160.2 GiB of weights; at TP=2 each GB10 holds [6.6 GiB less](https://huggingface.co/Bizuayeu/GLM-5.3-Flash-Jammed-XSFP4#memory) than at block 16. | [Native CUDA](recipes/glm-5.3-flash-cuda.md), in 1.2.3 (#2041). Refitted from BF16 at block 32 with XSFP4's smoothing, each row's scales packed (`csf0_v1`, read only by this path), at XSFP4's speed. Its KL and top-1 are nearer BF16 than NVIDIA's two checkpoints', short of XSFP4's ([its card](https://huggingface.co/Bizuayeu/GLM-5.3-Flash-Jammed-XSFP4#measured)). | -| GLM-5.3-Flash, Jammed XSFP4 NZ5 | `tensorfold pull Bizuayeu/GLM-5.3-Flash-Jammed-XSFP4-NZ5@1c900ea0294e28a8e9ab56c1156c0338eed60aef` | Two GB10s at TP=2: @Bizuayeu served it. 160.2 GiB of weights. | [Native CUDA](recipes/glm-5.3-flash-cuda.md), on main after 1.2.7 (#2894). Jammed XSFP4 refitted with E2M1's -0 code read as +5 (`NVFP4_NZ5`, read only by this path). Nearer BF16 than Jammed XSFP4 ([its card](https://huggingface.co/Bizuayeu/GLM-5.3-Flash-Jammed-XSFP4-NZ5#measured)). | +| GLM-5.3-Flash, Jammed XSFP4 NZ5 | `tensorfold pull Bizuayeu/GLM-5.3-Flash-Jammed-XSFP4-NZ5@1c900ea0294e28a8e9ab56c1156c0338eed60aef` | Two GB10s at TP=2: @Bizuayeu served it. 160.2 GiB of weights. | [Native CUDA](recipes/glm-5.3-flash-cuda.md), in 1.2.10 (#2894). Jammed XSFP4 refitted with E2M1's -0 code read as +5 (`NVFP4_NZ5`, read only by this path). Nearer BF16 than Jammed XSFP4 ([its card](https://huggingface.co/Bizuayeu/GLM-5.3-Flash-Jammed-XSFP4-NZ5#measured)). | | GLM-5.3, EXLR8 `home` | `tensorfold pull kindlingai/glm-5.3-exlr8-k2-k3-k4@f459f5d0272a529403dd9b3fd32f771f4250a0d4 --exlr8 home --node 0/2 --dir ~/models/glm-5.3-exlr8-home` | Two M5 Ultra Macs, 256 GB each; about 160 GB resident per Mac at 8k context / four streams. | [Two-Mac recipe](glm-5.3-exlr8.md). Use `--node 1/2` on the other Mac; Thunderbolt 5 and MCDMA required. No CUDA backend. | | LFM2.5-24B-A2B, MLX 4 / 6 / 8-bit | `tensorfold pull LiquidAI/LFM2.5-24B-A2B-MLX-4bit@667408d494bde191c2cb9dd4f4549827816b9275`
`tensorfold pull LiquidAI/LFM2.5-24B-A2B-MLX-6bit@1deec53eb49571e21cdcbf82fd5839248f07ed88`
`tensorfold pull LiquidAI/LFM2.5-24B-A2B-MLX-8bit@67ab417dd02d0c9545802a726df668620eae049d` | One Mac (M4 Pro checked), or one NVIDIA GPU with the 4-bit export (GB10 checked). | [Native recipe](recipes/lfm2.5-24b-a2b.md) ([CUDA](recipes/lfm2.5-24b-a2b.md#cuda)), [release history](../CHANGELOG.md). Weights: LFM Open License v1.0. | | Qwen3.6-35B-A3B, MLX with MTP | `tensorfold pull TensorFold/Qwen3.6-35B-A3B-MLX-4bit-MTP@81169a9bc511a27c1b4eedb77a2cd98ced431847` | One GB10; 20.9 GB checkpoint. | [Qwen3.6](recipes/qwen3.6-moe.md). Native CUDA receipt here. Metal also registers this model type; the recipe's Metal commands describe Python 0.6.6. | diff --git a/docs/web.md b/docs/web.md index b630c9b9a37..4f496c6610d 100644 --- a/docs/web.md +++ b/docs/web.md @@ -13,7 +13,7 @@ For example, a binary built with `-Dversion=1.2.0` prints: uv tool install "tensorfold-web @ git+https://github.com/ashhart/TensorFold@v1.2.0#subdirectory=web" ``` -After installation, the launcher checks PATH and then `uv tool dir --bin` for the executable. +The launcher checks PATH first, then `uv tool dir --bin` if uv is available. It repeats the lookup after a successful install. On systems where process replacement is available it execs the application; on Windows it waits for the child. The application's exit status is retained. diff --git a/tools/conformance.py b/tools/conformance.py index d49f94e10cd..7bc6af81d74 100644 --- a/tools/conformance.py +++ b/tools/conformance.py @@ -2,13 +2,17 @@ """Served exactness gates for one family profile: drafted, repeat, concurrent, resumed, refusals, cancel and evict. Each gate prints one PASS or FAIL line with its counts; any FAIL exits 1. Equality is the reply's full token-id hash -(``tensorfold.token_sha256``), so a reply without one is unverified and fails its gate. +(``tensorfold.token_sha256``, reasoning included), so a reply without one, or without a token, is unverified and fails +its gate: two empty replies hash the same. -- drafted: every prompt, greedy and seeded-sampled, equals its ``"draft": false`` reply; at least one draft must be - accepted, or the gate fails as vacuous. -- repeat: the drafted replies again, one at a time, equal the first ones. +- drafted: every prompt, greedy and seeded-sampled, equals its ``"draft": false`` reply; each sampling mode must + accept a draft and the plain replies must draft none, or the gate fails as vacuous. +- repeat: the drafted replies again, one at a time, equal the first ones; a sampled reply under another seed must + differ from its first for some prompt, or the seed never reached the sampler and the gate fails. - concurrent: at each level, that many requests at once (drafted and plain) each equal their solo reply; a long - prompt sent among three decoding streams leaves them unchanged and equals its solo reply. + prompt sent among three decoding streams leaves them unchanged and equals its solo reply. While each batch runs, + ``GET /v1/load`` must show at least two chat requests open at once, or the batch never overlapped and fails; at + each level the drafted rows must accept a draft and the plain rows draft none. - resumed: a multi-turn chat on the cached server equals the same chat on a server with the prompt cache off; the fresh side must report ``cached_tokens == 0`` and every later resumed turn ``cached_tokens > 0``. A profile's ``conversation_context_items`` puts a long document in the first turn, for families that keep only long prompts. @@ -61,6 +65,7 @@ def lifecycle_gaps(profile: dict) -> list[str]: return [g for g in SKIPPABLE if not (isinstance(skip, dict) and skip.get(g)) and not (isinstance(profile.get(g), dict) and profile[g].get(NEEDS[g]))] SHA256 = re.compile(r"[0-9a-f]{64}") +POLL_S = 0.005 # seconds between the census reads that look for overlapping requests def reply_row(status: int, doc) -> dict: @@ -104,8 +109,9 @@ def count(value): def same(a: dict, b: dict): - """True or False when both replies carry a full token hash; None (unverified) otherwise.""" - if a.get("error") or b.get("error") or not a.get("sha") or not b.get("sha"): + """True or False when both replies carry a full token hash and a token; None (unverified) otherwise.""" + if a.get("error") or b.get("error") or not a.get("sha") or not b.get("sha") or not a.get("tokens") \ + or not b.get("tokens"): return None return a["sha"] == b["sha"] @@ -128,17 +134,43 @@ def equality_gate(name: str, pairs, extra_ok=True, extra="") -> dict: return {"gate": name, "passed": passed, "counts": counts, "line": equal_line(counts) + extra} -def drafted_gate(pairs) -> dict: - """drafted == plain over (plain, drafted) pairs; fails as vacuous when no drafted reply accepted a draft.""" - accepted = sum(d.get("accepted", 0) for _, d in pairs) - drafted = sum(d.get("drafted", 0) for _, d in pairs) - gate = equality_gate("drafted == plain", pairs, accepted > 0, f"; {accepted} of {drafted} drafts accepted") - gate["counts"].update(accepted=accepted, drafted=drafted) - if accepted == 0: - gate["line"] += " (vacuous: no draft accepted)" +def drafted_gate(by_mode: dict) -> dict: + """drafted == plain over each mode's (plain, drafted) pairs; vacuous if a mode accepts no draft or plain drafts.""" + pairs = [pair for mode_pairs in by_mode.values() for pair in mode_pairs] + accepted, drafted = sum(d.get("accepted", 0) for _, d in pairs), sum(d.get("drafted", 0) for _, d in pairs) + idle = [mode for mode, mode_pairs in by_mode.items() if not sum(d.get("accepted", 0) for _, d in mode_pairs)] + plain = sum(p.get("drafted", 0) for p, _ in pairs) + extra = f"; {accepted} of {drafted} drafts accepted" + gate = equality_gate("drafted == plain", pairs, not idle and not plain, extra) + gate["counts"].update(accepted=accepted, drafted=drafted, plain_drafted=plain) + if idle: + gate["line"] += f" (vacuous: no draft accepted {'/'.join(idle)})" + if plain: + gate["line"] += f"; the plain replies drafted {plain} tokens (\"draft\": false not honoured)" return gate +def seeded_problem(pairs) -> str | None: + """Why the sampled arm is unproven: each (first, other seed) pair is equal, so the seed never reached sampling.""" + vacuous = pairs and not any(same(a, b) is False for a, b in pairs) + return f"another seed gave the same reply for all {len(pairs)} prompts tried (the seed never reached sampling)" \ + if vacuous else None + + +def batch_drafts_problem(drafts: dict) -> str | None: + """Why drafting under batching is unproven: a level whose drafted rows accept none, or whose plain rows draft.""" + idle = [level for level, (accepted, _) in drafts.items() if not accepted] + plain = {level: drafted for level, (_, drafted) in drafts.items() if drafted} + return f"drafted rows accepted no draft at {idle}; plain rows drafted at {plain}" if idle or plain else None + + +def overlap_problem(peaks) -> str | None: + """Why concurrency is unproven: a batch whose census never showed two chat requests open at once.""" + alone = len([p for p in peaks if not p or p < 2]) + return f"{alone} of {len(peaks)} batches never showed two chat requests open at once in GET /v1/load" \ + if alone else None + + def resumed_gate(turns) -> dict: """resumed == fresh over per-turn (fresh, resumed) pairs, with the cache counts both sides must show.""" counts = tally(turns) @@ -246,6 +278,25 @@ def inventory(items: int) -> str: return "An inventory: " + " ".join(f"crate{i % 89}-{(i * 6151) % 997}" for i in range(items)) +def watched(client: Client, run): + """``run()``'s result and, in a list, the most chat requests ``GET /v1/load`` showed open at once meanwhile.""" + from conformance_lifecycle import census + done, peak = threading.Event(), [None] + + def poll(): + while not done.is_set(): + seen = (census(client) or {}).get("active") + peak[0] = max(peak[0] or 0, seen) if type(seen) is int else peak[0] + done.wait(POLL_S) + thread = threading.Thread(target=poll, daemon=True) + thread.start() + try: + return run(), peak + finally: + done.set() + thread.join(timeout=60) + + def together(client: Client, bodies, delays=None) -> list: """Send every body at once (or after its delay) and return the reply rows in order.""" out = [None] * len(bodies) @@ -286,9 +337,8 @@ def record(self, kind, key, row): return row def drafted(self) -> dict: - pairs = [(self.solo(n, m, False), self.solo(n, m, True)) for n in self.plan.profile["prompts"] - for m in self.plan.modes] - return drafted_gate(pairs) + return drafted_gate({m: [(self.solo(n, m, False), self.solo(n, m, True)) for n in self.plan.profile["prompts"]] + for m in self.plan.modes}) def repeat(self) -> dict: pairs = [] @@ -297,30 +347,52 @@ def repeat(self) -> dict: first = self.solo(n, m, True) again = self.client.post(self.plan.ask(n, m, True, self.plan.plant == "repeat")) pairs.append((first, self.record("repeat", (n, m, True), again))) - return equality_gate("repeat == first", pairs) + problem = seeded_problem(self.other_seeds()) + return equality_gate("repeat == first", pairs, not problem, "; " + (problem or "another seed differs")) + + def other_seeds(self) -> list: + """(first, next seed) pairs of sampled drafted replies, prompt by prompt until one differs.""" + out = [] + for m, mode in self.plan.modes.items(): + for n in self.plan.profile["prompts"] if mode.get("temperature") else []: + body = self.plan.ask(n, m, True, self.plan.plant == "drafted") # the drafted solo's seed + body["seed"] += 1 + out.append((self.solo(n, m, True), self.record("other-seed", (n, m), self.client.post(body)))) + if same(*out[-1]) is False: + break + return out def concurrent(self) -> dict: names, pairs, planted = list(self.plan.profile["prompts"]), [], self.plan.plant == "concurrent" levels = self.plan.profile.get("levels", [1, 2, 4, 8]) + peaks, drafts = [], {} for level in levels: for draft in (True, False): for mode in self.plan.modes: picks = [names[i % len(names)] for i in range(level)] - rows = together(self.client, [self.plan.ask(n, mode, draft, planted) for n in picks]) + bodies = [self.plan.ask(n, mode, draft, planted) for n in picks] + rows, peak = watched(self.client, lambda: together(self.client, bodies)) + peaks += [peak[0]] if level > 1 else [] for n, row in zip(picks, rows): row = self.record(f"concurrent{level}", (n, mode, draft), row) pairs.append((self.solo(n, mode, draft), row)) + drafts.setdefault(level, [0, 0])[not draft] += row.get("accepted" if draft else "drafted") or 0 mixed = 0 for draft in (True, False): for mode in self.plan.modes: picks = names[:3] + ["long"] bodies = [self.plan.ask(n, mode, draft, planted) for n in picks] - rows = together(self.client, bodies, delays=[0, 0, 0, 0.5]) + rows, peak = watched(self.client, lambda: together(self.client, bodies, [0, 0, 0, 0.5])) + peaks.append(peak[0]) mixed += len(rows) for n, row in zip(picks, rows): pairs.append((self.solo(n, mode, draft), self.record("mixed", (n, mode, draft), row))) - return equality_gate("concurrent == solo", pairs, extra=f" (levels {levels}, drafted and plain, " - f"{mixed} with a long prompt among decoders)") + drafts.setdefault("mixed", [0, 0])[not draft] += row.get("accepted" if draft else "drafted") or 0 + self.rows.append({"kind": "overlap", "peaks": peaks}) + problem = "; ".join(filter(None, (overlap_problem(peaks), batch_drafts_problem(drafts)))) + extra = f" (levels {levels}, drafted and plain, {mixed} with a long prompt among decoders); " + return equality_gate("concurrent == solo", pairs, not problem, + extra + (problem or f"chat requests open at once: {min(peaks)} to {max(peaks)}")) def refusals(self) -> dict: results = [] diff --git a/tools/draft_divergence.md b/tools/draft_divergence.md new file mode 100644 index 00000000000..58cd3010db9 --- /dev/null +++ b/tools/draft_divergence.md @@ -0,0 +1,142 @@ +# Exact drafted/plain tokens near BF16 ties + +`draft_divergence.py` selects a small set of token prefixes from recorded greedy +traces, then compares one serial completion with requested draft caps 1, 4 and 8. +Every token ID must match. A `near-tie` label explains a mismatch; it never waives +one. Selection and labels reuse `zig/qwen27_margins.py`'s BF16 spacing rule. + +Run from the repository root. Python's standard library is sufficient. The +`--replay` mode opens no endpoint and needs no model or GPU: + +```sh +python3 tools/draft_divergence.py \ + --recording tools/tests/fixtures/draft_divergence/recording.json \ + --profiles tools/tests/fixtures/draft_divergence/profiles.json \ + --replay tools/tests/fixtures/draft_divergence/equal.json \ + --lookback 2 --tokens 8 --output equal-result.json +``` + +The example prints exactly: + +```text +DRAFT_DIVERGENCE status=pass cases=1 comparisons=3 divergences=0 +``` + +Replacing `equal.json` with `divergent.json` exits 1 and identifies the first +mismatch at output index 2 for requested depth 4. These files are **synthetic unit +fixtures**, not measurements of a checkpoint, backend, GPU or numerical error. + +## Recordings and selection + +A recording has `schema: 1`, an `identity` object of nonempty strings, and `traces`. +Use pinned checkpoint, tokenizer, backend, precision and configuration identifiers +in the identity; every endpoint profile must repeat the same identity exactly. +This is the operator's declaration, not server attestation. + +Each trace has a unique `name`, a nonempty `prompt` of token IDs, generated +`tokens`, and one ordered raw `top2` row per generated token: + +```json +{ + "schema": 1, + "identity": {"checkpoint": "pinned-revision", "tokenizer": "pinned-tokenizer", "backend": "precision-and-config"}, + "traces": [{"name": "example", "prompt": [1, 2], "tokens": [12], + "top2": [{"ids": [12, 99], "logits": [16.0, 15.9375], "position": 2}]}] +} +``` + +`position` is the absolute zero-based generated token position, including the +prompt. Its first entry is `len(prompt)`. The first top-two ID must equal the +recorded greedy token. All logits must be finite raw scores, ordered largest +first. Do not substitute log-softmax values: BF16 spacing depends on absolute +magnitude and is not invariant under that transformation. + +Select positions whose margin is at most one BF16 spacing of the highest raw +logit. Defaults: at most 8 distinct prefixes, up to 8 generated tokens before +the tie, and up to 32 generated tokens per run. Cases are ranked by margin divided +by spacing, then name. Their prompt is the original token prefix, with no text +round trip. Increase `--tokens` above `--lookback`; windows stop at the end of the +recording. No selected positions is an error, not a passing empty test. + +## Served endpoints and draft depths + +The current server accepts `draft: false/true`; it has no per-request depth cap. +Configure one server endpoint per supported cap using that family's actual +configuration. Do not add a fictitious `draft_depth` request field. Each profile +has `depth`, `url`, `model` and the recording's exact `identity`. The fixture +`profiles.json` illustrates this shape but contains placeholder URLs only. + +For a real family run, prepare `recording.json` from that same checkpoint, +tokenizer, backend and configuration, and `profiles.json` from its configured +servers. Run on the hardware selected for the family: + +```sh +python3 tools/draft_divergence.py --recording recording.json \ + --profiles profiles.json --depths 1,4,8 --cases 8 --lookback 8 --tokens 32 \ + --timeout 120 --output divergence-result.json +``` + +For each requested cap, the nearest supplied supported cap is selected; ties +choose the smaller cap. JSON records both numbers. Different configured caps +require distinct URLs. The operator must ensure their configurations differ +only in draft cap and all resolve to the same model. Caps are configuration +metadata; the response does not attest the actual draft length at every round. + +The lowest-cap endpoint also provides the serial reference with `draft: false`. +Requests use `/v1/completions`, token-ID-array prompts, greedy sampling, +`ignore_eos: true`, `return_token_ids: true` and nonstreaming responses. A base URL +may end with `/v1` or `/v1/completions`. Redirects are refused. Authentication is +not implemented; URLs containing credentials or query strings are refused. + +The tool requires `tensorfold.token_ids`, a matching `tensorfold.drafts` boolean, +and consistent completion-token counts. It also requires positive +`speculative.drafted` work for each drafted run. Equality without observed draft +work, an early stop, or failure of the serial run to reproduce the selected +recording window yields `incomplete`, never `pass`. + +## Divergence JSON and logits + +Every case contains serial and drafted IDs and the first mismatch for each cap. +`output_index` is zero-based within the generated window; `absolute_position` +includes the complete prompt. A length mismatch reports a null missing token. +Any mismatch returns `divergent`, even if coverage is also incomplete. + +The current API does not expose raw logits. Its logprobs are not raw logits and +are never used here. JSON retains the source recording's two raw scores and +reports each `recorded_logits_for_tokens` entry only when the first-divergence +history matches that recording and its token is present in the recorded top two. +These are historical scores, not new plain/drafted measurements. Missing scores +are null. +Live results leave `plain_top2` and `drafted_top2` null. + +Offline observations may additionally carry per-run raw captures. Their shape is +`{"response": , "top2": }`. A replay file maps +`CASE:plain` and `CASE:REQUESTED_DEPTH` to these observations; `CASE` is +`TRACE_NAME:SOURCE_GENERATED_INDEX`. The tool's output retains the observations +and can itself be replayed by saving its `observations` object as a replay file. +Each optional capture must align with that run's IDs and absolute positions. +When both captures are supplied, `plain_top2` and `drafted_top2` report both +measured score pairs and the shared helper labels `near-tie` or `bug`. Without +them, `recorded-near-tie` explicitly describes the historical source alone. +Never claim fresh per-run logits from an ordinary live API result. + +Exit codes: 0 strict equality with complete coverage, 1 any divergence, 2 an +incomplete run or malformed input/response. A JSON file and one summary line are +written for completed evaluations and handled errors. Endpoint errors stop the +run and produce `status: error`; rerun that input after resolving the endpoint. + +## Fixture checks + +```sh +python3 -m pytest tools/tests/test_draft_divergence.py +python3 -m pytest tools/tests +``` + +The new fixture tests also run without pytest: + +```sh +python3 -m unittest discover -s tools/tests -p test_draft_divergence.py -v +``` + +Fixture checks exercise request construction with an injected client. They do +not run a device, open a socket, or replace the family's actual hardware check. diff --git a/tools/draft_divergence.py b/tools/draft_divergence.py new file mode 100644 index 00000000000..a041a01db84 --- /dev/null +++ b/tools/draft_divergence.py @@ -0,0 +1,291 @@ +"""Compare exact drafted/plain IDs on token-prefix prompts selected from recorded raw-logit near-ties.""" +from __future__ import annotations + +import argparse +import hashlib +import itertools +import json +import math +from pathlib import Path +import urllib.error +import urllib.parse +import urllib.request + +from zig.qwen27_margins import bf16_spacing, verdict + + +def require(ok, message): + if not ok: + raise ValueError(message) + + +def ids(value): + require(isinstance(value, list) and value, "expected nonempty token IDs") + require(all(type(x) is int and 0 <= x < 2**32 for x in value), "invalid token ID") + return value + + +def top2(row, position): + require(isinstance(row, dict), "missing raw top-two record") + tokens, logits = ids(row.get("ids")), row.get("logits") + require(len(tokens) == 2 and tokens[0] != tokens[1], "expected two distinct top-two IDs") + require(isinstance(logits, list) and len(logits) == 2, "expected two raw logits, not logprobs") + require(all(type(x) in (int, float) and math.isfinite(x) for x in logits), "nonfinite raw logit") + require(logits[0] >= logits[1], "top-two logits are not ordered") + require(row.get("position", position) == position, "raw-logit position is not aligned") + return {"ids": tokens, "logits": logits, "position": position} + + +def near(row): + return row["logits"][0] - row["logits"][1] <= bf16_spacing(row["logits"][0]) + + +def select_prompts(recording, limit=8, lookback=8, tokens=32): + require(type(limit) is int and 1 <= limit <= 64, "case limit must be 1..64") + require(type(tokens) is int and 1 <= tokens <= 512, "token limit must be 1..512") + require(type(lookback) is int and 0 <= lookback < tokens, "lookback must be below token limit") + require(isinstance(recording, dict) and type(recording.get("schema")) is int + and recording["schema"] == 1, "recording schema missing") + identity = recording.get("identity") + require(isinstance(identity, dict) and identity + and all(isinstance(k, str) and isinstance(v, str) and v for k, v in identity.items()), "identity missing") + traces = recording.get("traces") + require(isinstance(traces, list) and traces, "no recorded traces") + candidates, names = [], set() + for trace in traces: + require(isinstance(trace, dict), "invalid trace") + name = trace.get("name") + require(isinstance(name, str) and name and name not in names, "trace names must be unique") + names.add(name) + prompt, emitted = ids(trace.get("prompt")), ids(trace.get("tokens")) + rows = trace.get("top2") + require(isinstance(rows, list) and len(rows) == len(emitted), "one raw top-two row per emitted ID required") + rows = [top2(row, len(prompt) + i) for i, row in enumerate(rows)] + require(all(row["ids"][0] == token for row, token in zip(rows, emitted)), "recording must be greedy") + for i, row in enumerate(rows): + if not near(row): + continue + start = max(0, i - lookback) + prefix = prompt + emitted[:start] + count = min(tokens, len(emitted) - start) + candidates.append({"id": f"{name}:{i}", "prompt": prefix, "tokens": emitted[start:start + count], + "top2": rows[start:start + count], "near_tie_offset": i - start, + "source_position": len(prompt) + i, "margin": row["logits"][0] - row["logits"][1], + "bf16_spacing": bf16_spacing(row["logits"][0])}) + candidates.sort(key=lambda c: (c["margin"] / c["bf16_spacing"], c["id"])) + selected, seen = [], set() + for case in candidates: + key = tuple(case["prompt"]) + if key not in seen: + selected.append(case) + seen.add(key) + if len(selected) == limit: + break + require(selected, "no recorded BF16 near-ties selected") + return selected + + +def completion_url(base): + base = base.rstrip("/") + if base.endswith("/v1/completions"): + return base + return base + ("/completions" if base.endswith("/v1") else "/v1/completions") + + +def profiles_for(profiles, identity, depths): + require(isinstance(profiles, list) and profiles, "no configured endpoint profiles") + seen, urls = set(), set() + for p in profiles: + require(isinstance(p, dict), "invalid endpoint profile") + depth = p.get("depth") + require(type(depth) is int and 1 <= depth <= 128 and depth not in seen, "invalid/duplicate configured depth") + require(p.get("identity") == identity, "checkpoint/tokenizer/backend identity mismatch") + require(isinstance(p.get("model"), str) and p["model"], "profile model missing") + require(isinstance(p.get("url"), str), "endpoint URL missing") + u = urllib.parse.urlsplit(p["url"]) + require(u.scheme in ("http", "https") and u.hostname and not u.username and not u.password + and not u.query and not u.fragment, "invalid endpoint URL or URL credentials") + endpoint = completion_url(p["url"]) + require(endpoint not in urls, "different depth caps need separately configured endpoints") + seen.add(depth) + urls.add(endpoint) + require(depths and all(type(d) is int and 1 <= d <= 128 for d in depths), "invalid requested depths") + require(len(set(depths)) == len(depths), "duplicate requested depth") + return [(d, min(profiles, key=lambda p: (abs(p["depth"] - d), p["depth"]))) for d in depths] + + +def request(case, profile, drafted): + return {"model": profile["model"], "prompt": case["prompt"], "max_tokens": len(case["tokens"]), + "temperature": 0, "top_k": 0, "top_p": 1, "min_p": 0, "seed": 1234, + "draft": drafted, "ignore_eos": True, "return_token_ids": True, "stream": False} + + +def observe(observation, body, case): + require(isinstance(observation, dict) and isinstance(observation.get("response"), dict), "response missing") + response = observation["response"] + require("error" not in response and response.get("model") == body["model"], "server error or model mismatch") + choices = response.get("choices") + require(isinstance(choices, list) and len(choices) == 1 and isinstance(choices[0], dict), "expected one completion") + finish = choices[0].get("finish_reason") + require(finish in ("length", "stop"), "incomplete/refused completion") + runtime = response.get("tensorfold", {}) + require(isinstance(runtime, dict), "token runtime missing") + emitted = ids(runtime.get("token_ids")) + require(runtime.get("drafts") is body["draft"], "serial/draft switch not acknowledged") + require(isinstance(response.get("usage"), dict), "usage missing") + usage = response["usage"].get("completion_tokens") + require(type(usage) is int and usage == len(emitted), "ID/usage count mismatch") + require(len(emitted) <= body["max_tokens"], "server exceeded requested length") + speculative = response.get("speculative", {}) + require(isinstance(speculative, dict), "invalid speculative counters") + drafted = speculative.get("drafted") + require(drafted is None or (type(drafted) is int and drafted >= 0), "invalid draft-work counter") + if not body["draft"]: + require(drafted in (None, 0), "serial reference performed draft work") + rows = observation.get("top2") + if rows is not None: + require(isinstance(rows, list) and len(rows) == len(emitted), "captured logits/IDs are not aligned") + rows = [top2(row, len(case["prompt"]) + i) for i, row in enumerate(rows)] + require(all(r["ids"][0] == t for r, t in zip(rows, emitted)), "capture and emitted argmax disagree") + return {"tokens": emitted, "top2": rows, "finish_reason": finish, "drafted": drafted, + "complete": finish == "length" and len(emitted) == body["max_tokens"], + "draft_work_observed": not body["draft"] or (drafted is not None and drafted > 0)} + + +def first_difference(case, plain, drafted): + for i, (wanted, actual) in enumerate(itertools.zip_longest(plain["tokens"], drafted["tokens"])): + if wanted == actual: + continue + recorded = case["top2"][i] if i < len(case["top2"]) else None + same_history = plain["tokens"][:i] == case["tokens"][:i] + scores = dict(zip(recorded["ids"], recorded["logits"])) if recorded and same_history else {} + a = plain["top2"][i] if plain["top2"] and i < len(plain["top2"]) else None + b = drafted["top2"][i] if drafted["top2"] and i < len(drafted["top2"]) else None + label = "divergence" + if a and b and wanted is not None and actual is not None: + label = verdict(a, b, wanted, actual)["verdict"] + elif recorded and same_history and {wanted, actual} == set(recorded["ids"]) and near(recorded): + label = "recorded-near-tie" + return {"output_index": i, "absolute_position": len(case["prompt"]) + i, + "plain_token_id": wanted, "drafted_token_id": actual, "label": label, + "strict_equal": False, "plain_top2": a, "drafted_top2": b, + "recorded_top2": recorded, "recorded_history_matches": same_history, + "recorded_logits_for_tokens": {"plain": scores.get(wanted), "drafted": scores.get(actual)}, + "logit_source": "raw per-run captures when supplied; otherwise recorded source, never API logprobs"} + return None + + +def evaluate(recording, profiles, fetch, depths=(1, 4, 8), limit=8, lookback=8, tokens=32): + cases = select_prompts(recording, limit, lookback, tokens) + selected = profiles_for(profiles, recording["identity"], depths) + plain_profile = min(profiles, key=lambda p: p["depth"]) + results, observations = [], {} + divergent, complete = False, True + for case in cases: + body = request(case, plain_profile, False) + observation = fetch(plain_profile, body, case["id"], "plain") + observations[case["id"] + ":plain"] = observation + plain = observe(observation, body, case) + reproduced = plain["tokens"] == case["tokens"] + complete = complete and plain["complete"] and reproduced + variants = [] + for depth, profile in selected: + body = request(case, profile, True) + observation = fetch(profile, body, case["id"], str(depth)) + observations[case["id"] + ":" + str(depth)] = observation + run = observe(observation, body, case) + difference = first_difference(case, plain, run) + divergent = divergent or difference is not None + complete = complete and run["complete"] and run["draft_work_observed"] + variants.append({"requested_depth": depth, "configured_depth": profile["depth"], + "depth_control": "operator-configured endpoint cap, not per-request API control", + "run": run, "first_divergence": difference, "token_equal": difference is None}) + results.append({"id": case["id"], "prompt": case["prompt"], "source_position": case["source_position"], + "near_tie_offset": case["near_tie_offset"], "recorded_margin": case["margin"], + "bf16_spacing": case["bf16_spacing"], "source_reproduced": reproduced, + "plain": plain, "variants": variants}) + status = "divergent" if divergent else "pass" if complete else "incomplete" + return {"schema": 1, "status": status, "passed": status == "pass", "identity": recording["identity"], + "identity_source": "recording and operator profiles; not server-attested", + "near_tie_policy": "BF16 labels are diagnostics; every token divergence fails", + "cases": results, "observations": observations} + + +class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + raise ValueError("endpoint redirect refused") + + +def live_fetch(timeout): + opener = urllib.request.build_opener(NoRedirect()) + + def fetch(profile, body, case_id, depth): + req = urllib.request.Request(completion_url(profile["url"]), data=json.dumps(body, allow_nan=False).encode(), + headers={"Content-Type": "application/json", "Accept": "application/json"}) + with opener.open(req, timeout=timeout) as response: + data = response.read(16 * 1024 * 1024 + 1) + require(len(data) <= 16 * 1024 * 1024, "response too large") + return {"response": decode(data)} + + return fetch + + +def decode(data): + def reject(value): + raise ValueError("nonfinite JSON number") + return json.loads(data, parse_constant=reject) + + +def load(path): + return decode(Path(path).read_text()) + + +def summary(report): + cases = report.get("cases", []) + comparisons = sum(len(c["variants"]) for c in cases) + differences = sum(v["first_divergence"] is not None for c in cases for v in c["variants"]) + line = f"DRAFT_DIVERGENCE status={report['status']} cases={len(cases)} comparisons={comparisons} divergences={differences}" + first = next(((c, v) for c in cases for v in c["variants"] if v["first_divergence"]), None) + if first: + c, v = first + line += f" first={json.dumps(c['id'])}@{v['first_divergence']['output_index']} depth={v['requested_depth']}" + return line + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--recording", type=Path, required=True) + parser.add_argument("--profiles", type=Path, required=True) + parser.add_argument("--replay", type=Path, help="Offline observations keyed CASE:plain or CASE:requested-depth") + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--depths", default="1,4,8") + parser.add_argument("--cases", type=int, default=8) + parser.add_argument("--lookback", type=int, default=8) + parser.add_argument("--tokens", type=int, default=32) + parser.add_argument("--timeout", type=float, default=120) + args = parser.parse_args(argv) + try: + require(math.isfinite(args.timeout) and args.timeout > 0, "timeout must be finite and positive") + recording, profiles = load(args.recording), load(args.profiles) + if args.replay: + replay = load(args.replay) + + def fetch(profile, body, case_id, depth): + return replay[case_id + ":" + depth] + else: + fetch = live_fetch(args.timeout) + report = evaluate(recording, profiles, fetch, tuple(int(x) for x in args.depths.split(",")), + args.cases, args.lookback, args.tokens) + report["mode"] = "recorded-replay" if args.replay else "served-endpoint" + report["input_sha256"] = {"recording": hashlib.sha256(args.recording.read_bytes()).hexdigest(), + "profiles": hashlib.sha256(args.profiles.read_bytes()).hexdigest()} + except (ValueError, KeyError, TypeError, AttributeError, IndexError, OverflowError, OSError, + urllib.error.URLError) as error: + report = {"schema": 1, "status": "error", "passed": False, "error": str(error)} + args.output.write_text(json.dumps(report, indent=2, allow_nan=False) + "\n") + print(summary(report)) + return 0 if report["passed"] else 1 if report["status"] == "divergent" else 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/lfm3/serve_check.py b/tools/lfm3/serve_check.py index feaf54fa02f..e1a1754b11e 100644 --- a/tools/lfm3/serve_check.py +++ b/tools/lfm3/serve_check.py @@ -98,7 +98,7 @@ def request(self, item, draft=False, gate=None): headers={'Content-Type': 'application/json'}) if gate: gate.wait(timeout=30) - evidence, usage, runtime, text = Evidence(), {}, {}, [] + evidence, usage, runtime, speculative, text = Evidence(), {}, {}, {}, [] complete = False try: with urllib.request.urlopen(request, timeout=180) as response: @@ -114,11 +114,14 @@ def request(self, item, draft=False, gate=None): raise RuntimeError(str(event['error'])) usage = event.get('usage') or usage runtime = event.get('tensorfold') or runtime + speculative = event.get('speculative') or speculative for choice in event.get('choices', []): evidence.add(choice) text.append(choice.get('text') or (choice.get('delta') or {}).get('content') or '') result = evidence.finish(usage, runtime, complete) result['text'] = ''.join(text) + result['sampling'] = runtime.get('sampling') + result['accepted'], result['drafted'] = speculative.get('accepted'), speculative.get('drafted') if not complete: result['error'] = 'incomplete_stream' return result @@ -245,6 +248,8 @@ def check(name, passed, evidence=None, skip=False): result = server.request(item) baselines[name] = result check(name + '/fresh_plain', result.get('complete') and bool(result.get('token_sha256')), result) + if item.get('temperature'): # the reply names its sampler: "exact" when sampled, "greedy" otherwise + check(name + '/sampler_ran', result.get('sampling') == 'exact', result) if 'long_prefix' in baselines: check('long_prefix/length_over_256', (baselines['long_prefix'].get('prompt_tokens') or 0) > 256, baselines['long_prefix'].get('prompt_tokens')) @@ -252,9 +257,14 @@ def check(name, passed, evidence=None, skip=False): receipt['logs'].append(server.log.name) receipt['commands'].append(server.command) if not args.cancel_only: + drafts = {'accepted': 0, 'plain_drafted': 0} for name, item in items.items(): for draft in (False, True): result = server.request(item, draft=draft) + if draft: + drafts['accepted'] += result.get('accepted') or 0 + else: + drafts['plain_drafted'] += result.get('drafted') or 0 if name == 'edited_prefix' and not draft: check('edited_prefix/no_stale_prefix_reuse', result.get('cached_tokens') == 0, result) check(name + ('/drafted_equals_fresh' if draft else '/plain_equals_fresh'), @@ -266,6 +276,8 @@ def check(name, passed, evidence=None, skip=False): if name == 'edited_prefix': result = server.request(item) check('edited_prefix/matches_cache_off', token_equal(result, baselines[name]), result) + # drafted == fresh tests drafting only if a draft landed, and plain == fresh only if plain drafted none + check('drafts/exercised', drafts['accepted'] > 0 and drafts['plain_drafted'] == 0, drafts) for level in (1, 2, 4): names = ['code', 'chat'] if not args.sampled else ['code', 'chat', 'sampled_code', 'sampled_chat'] for name in names: diff --git a/tools/replay_request.py b/tools/replay_request.py new file mode 100644 index 00000000000..f8ce92e4bd3 --- /dev/null +++ b/tools/replay_request.py @@ -0,0 +1,282 @@ +"""List, clear or replay requests from a TENSORFOLD_REQUEST_JOURNAL and compare the reply with the journaled one.""" +import argparse +import base64 +import copy +import hashlib +import json +import os +import sys +import time +import urllib.error +import urllib.parse +import urllib.request +from pathlib import Path + +FILES = 4 # the current file and three rotated ones, as request_journal.zig keeps them +QUARANTINE_S = 24 * 60 * 60 # a quarantine lapses a day after its crash + + +class ReplayError(ValueError): + pass + + +def journal_files(path): + """The kept files oldest first: path.3, path.2, path.1, then path itself.""" + path = Path(path) + older = [Path(f'{path}.{n}') for n in range(FILES - 1, 0, -1)] + return [p for p in older if p.exists()] + [path] + + +def read_journal(path, now=None): + """Each request's records by id, read as the server reads them; unreadable lines are passed over.""" + entries, pending, crashes, skipped = {}, set(), {}, 0 + now = time.time() if now is None else now + for file in journal_files(path): + for line in file.read_bytes().split(b'\n')[:-1]: # the last piece is empty or a torn line + try: + record = json.loads(line) + except ValueError: + record = None + if not isinstance(record, dict) or record.get('version') != 1: + skipped += 1 + continue + kind, request_id = record.get('kind'), record.get('id') + if kind == 'stop': + pending.clear() + elif kind == 'clear' and record.get('all'): + crashes.clear() + elif kind == 'clear': + crashes.pop(record.get('fingerprint'), None) + elif kind == 'start': + entries[request_id] = {'start': record, 'prepared': None, 'finish': None, 'quarantine': []} + pending.add(request_id) + elif kind == 'quarantine' and record.get('at', 0) + QUARANTINE_S > now: + crashes[record.get('fingerprint')] = crashes.get(record.get('fingerprint'), 0) + 1 + if request_id not in entries or kind not in ('prepared', 'finish', 'quarantine'): + continue + entry = entries[request_id] + if kind == 'prepared': + entry['prepared'] = record # the last one made the reply (a compacted request has several) + continue + if kind == 'finish': + entry['finish'] = record + else: + entry['quarantine'].append(record) + pending.discard(request_id) + for entry in entries.values(): + entry['refused'] = crashes.get(entry['start'].get('fingerprint'), 0) >= 2 # in flight at two crashes + entry['in_flight'] = entry['start']['id'] in pending + return entries, skipped + + +def output_of(raw, stream): + """What the model produced, without what differs between two runs of one request (ids, times, cache hits).""" + def merge(into, delta): + for key, value in delta.items(): + if key in ('id', 'role'): + continue + if key == 'tool_calls': + calls = into.setdefault('tool_calls', {}) + for call in value: + merge(calls.setdefault(str(call.get('index', len(calls))), {}), call) + elif isinstance(value, str) and isinstance(into.get(key), str): + into[key] += value + elif isinstance(value, list) and isinstance(into.get(key), list): + into[key].extend(copy.deepcopy(value)) + elif isinstance(value, dict) and isinstance(into.get(key), dict): + merge(into[key], value) + elif value is not None or key not in into: + into[key] = copy.deepcopy(value) + + def tail(payload, out): + usage = payload.get('usage') or {} + for key in ('prompt_tokens', 'completion_tokens'): + if key in usage: + out[key] = usage[key] + for key in ('stop_sequence', 'error'): + if key in payload: + out[key] = payload[key] + runtime = payload.get('tensorfold') + if isinstance(runtime, dict) and 'token_sha256' in runtime: + out['token_sha256'] = runtime['token_sha256'] + + out, choices = {}, {} + payloads = [json.loads(line[6:]) for line in raw.split(b'\n') if line.startswith(b'data: ') and line != b'data: [DONE]'] if stream else [json.loads(raw)] + for payload in payloads: + for choice in payload.get('choices') or []: + body = {k: v for k, v in choice.items() if k not in ('delta', 'message', 'index')} + body.update(choice.get('delta') or choice.get('message') or {}) + merge(choices.setdefault(str(choice.get('index', 0)), {}), body) + tail(payload, out) + out['choices'] = choices + return json.dumps(out, ensure_ascii=False, sort_keys=True, separators=(',', ':')).encode() + + +def redacted(value): + if value == '': + return True + if isinstance(value, dict): + return any(redacted(v) for v in value.values()) + if isinstance(value, list): + return any(redacted(v) for v in value) + return False + + +def request_body(entry, replacement=None): + """The journaled body, or its restored copy, with the seed the server drew when the client sent none.""" + body = copy.deepcopy(replacement if replacement is not None else entry['start'].get('body')) + if body is None: + raise ReplayError('the body was too large to journal; supply it with --body FILE') + if not isinstance(body, dict): + raise ReplayError('the request body must be a JSON object') + if redacted(body): + raise ReplayError('the request has redacted media; supply the original with --body FILE') + prepared = entry['prepared'] + if 'seed' not in body and prepared and prepared.get('seed') is not None: + body['seed'] = prepared['seed'] + return body + + +def reference(entry): + finish = entry['finish'] + if finish is None: + return None + raw = finish.get('reply_base64') + return base64.b64decode(raw, validate=True) if raw is not None else None + + +def http_send(url, body, key=None): + headers = {'Content-Type': 'application/json'} + if key: + headers['Authorization'] = 'Bearer ' + key + request = urllib.request.Request(url, data=json.dumps(body).encode(), headers=headers, method='POST') + try: + with urllib.request.urlopen(request, timeout=900) as response: + return response.status, response.read() + except urllib.error.HTTPError as error: + return error.code, error.read() + + +def replay(entry, base, send, *, replacement=None, whole_body=False, allow_quarantined=False): + """One send of the request; equal is True, False, or None when the journal holds no reply to compare.""" + request_id = entry['start']['id'] + if entry['quarantine'] and not allow_quarantined: + raise ReplayError(f'{request_id} was in flight at a crash; pass --allow-quarantined to send it on purpose') + path = entry['start'].get('path') + if path not in ('/v1/chat/completions', '/v1/completions'): + raise ReplayError('the journal names a route replay does not send') + parsed = urllib.parse.urlsplit(base) + if parsed.scheme not in ('http', 'https') or not parsed.netloc or parsed.username or parsed.password or parsed.query or parsed.fragment or parsed.path not in ('', '/'): + raise ReplayError('--base must be an http(s) origin with no credentials, path or query') + body = request_body(entry, replacement) + status, actual = send(base.rstrip('/') + path, body) + finish, expected = entry['finish'], reference(entry) + result = {'id': request_id, 'actual_status': status, 'actual_bytes': len(actual), 'actual_sha256': hashlib.sha256(actual).hexdigest()} + if finish is None: + return dict(result, comparison='no_reference', equal=None), actual + result.update(expected_status=finish.get('status'), expected_bytes=finish.get('reply_bytes'), expected_sha256=finish.get('reply_sha256')) + stream = bool(finish.get('stream')) + if whole_body: + result['comparison'] = 'whole_body' + if expected is None: + result.update(equal=status == finish.get('status') and result['actual_sha256'] == finish.get('reply_sha256'), first_difference=None) + return result, actual + left, right = expected, actual + elif expected is None: + try: + tokens = json.loads(output_of(actual, stream)).get('token_sha256') + except ValueError: + tokens = None + result.update(comparison='tokens', equal=status == finish.get('status') and tokens is not None and tokens == finish.get('token_sha256'), first_difference=None) + return result, actual + else: + result['comparison'] = 'output' + try: + left, right = output_of(expected, stream), output_of(actual, stream) + except ValueError: + left, right = expected, actual + different = next((i for i, (x, y) in enumerate(zip(left, right)) if x != y), None) + if different is None and len(left) != len(right): + different = min(len(left), len(right)) + result.update(equal=status == finish.get('status') and left == right, first_difference=different, compared_bytes=[len(left), len(right)]) + return result, actual + + +def locked(path): + """True when a server holds the journal's lock; the lock is released when this process exits.""" + fd = os.open(f'{path}.lock', os.O_RDWR | getattr(os, 'O_NOFOLLOW', 0)) + try: + if os.name == 'nt': + import msvcrt + msvcrt.locking(fd, msvcrt.LK_NBLCK, 1) + else: + import fcntl + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + except OSError: + os.close(fd) + return True + return False + + +def clear(path, target, entries): + """Appends a clear record while no server holds the journal; the next start serves those requests again.""" + if locked(path): + raise ReplayError('a server holds this journal; stop it, clear, then start it again') + record = {'version': 1, 'kind': 'clear', 'at': int(time.time())} + if target == 'all': + record['all'] = True + else: + entry = entries.get(target) + record['fingerprint'] = entry['start']['fingerprint'] if entry else target + if len(record['fingerprint']) != 64: + raise ReplayError('name a journaled request id, a 64-character fingerprint, or all') + fd = os.open(path, os.O_WRONLY | os.O_APPEND | getattr(os, 'O_NOFOLLOW', 0)) + try: + os.write(fd, (json.dumps(record, separators=(',', ':')) + '\n').encode()) + finally: + os.close(fd) + return record + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('journal') + parser.add_argument('--list', action='store_true', help='list the journaled requests; nothing is sent') + parser.add_argument('--clear', metavar='ID|FINGERPRINT|all', help='lift a quarantine (stop the server first)') + parser.add_argument('--id', help='the request to replay') + parser.add_argument('--base', help='the server origin, such as http://127.0.0.1:8080') + parser.add_argument('--body', help='the original request JSON, when its media were redacted or it was too large') + parser.add_argument('--key-env', default='TENSORFOLD_API_KEY', help='the variable that holds the API key') + parser.add_argument('--whole-body', action='store_true', help='compare every reply byte, ids and timings included') + parser.add_argument('--allow-quarantined', action='store_true', help='send a request that was in flight at a crash') + parser.add_argument('--output', help='write the reply bytes to this file (owner-only)') + args = parser.parse_args(argv) + entries, skipped = read_journal(args.journal) + if skipped: + print(f'{skipped} unreadable record(s) passed over', file=sys.stderr) + if args.list: + rows = [{'id': key, 'at': e['start'].get('at'), 'path': e['start'].get('path'), 'fingerprint': e['start'].get('fingerprint'), + 'outcome': e['finish'].get('outcome') if e['finish'] else 'in_flight' if e['in_flight'] else 'unfinished', + 'crashes': len(e['quarantine']), 'refused': e['refused']} for key, e in entries.items()] + print(json.dumps(rows, indent=2)) + return 0 + if args.clear: + print(json.dumps(clear(args.journal, args.clear, entries))) + return 0 + if not args.id or not args.base or args.id not in entries: + parser.error('name a journaled --id and a --base, or use --list or --clear') + replacement = json.loads(Path(args.body).read_text()) if args.body else None + result, actual = replay(entries[args.id], args.base, lambda url, body: http_send(url, body, os.environ.get(args.key_env)), replacement=replacement, whole_body=args.whole_body, allow_quarantined=args.allow_quarantined) + if args.output: + fd = os.open(args.output, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + with os.fdopen(fd, 'wb') as out: + out.write(actual) + print(json.dumps(result, indent=2)) + return 2 if result['equal'] is None else 0 if result['equal'] else 1 + + +if __name__ == '__main__': + try: + raise SystemExit(main()) + except (ReplayError, OSError, ValueError) as error: + raise SystemExit(f'replay_request: {error}') diff --git a/tools/test_replay_request.py b/tools/test_replay_request.py new file mode 100644 index 00000000000..3aedfa00fc5 --- /dev/null +++ b/tools/test_replay_request.py @@ -0,0 +1,181 @@ +"""replay_request.py on journal fixtures; every send goes to a fake server, and no socket is opened.""" +import base64 +import contextlib +import hashlib +import importlib.util +import io +import json +import os +import tempfile +import time +import unittest +from pathlib import Path +from unittest.mock import patch + +spec = importlib.util.spec_from_file_location('replay_request', Path(__file__).with_name('replay_request.py')) +r = importlib.util.module_from_spec(spec) +spec.loader.exec_module(r) + +FP = 'ab' * 32 +TOKENS = 'c0' * 32 + + +def whole(content, reply_id='chatcmpl-1', created=1, tokens=TOKENS, seconds=0.5): + return json.dumps({'id': reply_id, 'object': 'chat.completion', 'created': created, 'model': 'm', + 'choices': [{'index': 0, 'message': {'role': 'assistant', 'content': content}, 'finish_reason': 'stop'}], + 'usage': {'prompt_tokens': 3, 'completion_tokens': 2, 'prompt_tokens_details': {'cached_tokens': 0}}, + 'tensorfold': {'token_sha256': tokens, 'seconds': seconds}}).encode() + + +def streamed(pieces, reply_id='chatcmpl-1', keepalive=False): + frames = [{'id': reply_id, 'choices': [{'index': 0, 'delta': {'role': 'assistant'}, 'finish_reason': None}]}] + frames += [{'id': reply_id, 'choices': [{'index': 0, 'delta': {'content': p}, 'finish_reason': None}]} for p in pieces] + frames.append({'id': reply_id, 'choices': [{'index': 0, 'delta': {}, 'finish_reason': 'stop'}], 'tensorfold': {'token_sha256': TOKENS}}) + out = b''.join(b'data: ' + json.dumps(f).encode() + b'\n\n' for f in frames) + return (b': keepalive\n\n' if keepalive else b'') + out + b'data: [DONE]\n\n' + + +class FakeServer: + def __init__(self, reply, status=200): + self.reply, self.status, self.calls = reply, status, [] + + def send(self, url, body): + self.calls.append((url, body)) + return self.status, self.reply + + +class ReplayTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.path = Path(self.tmp.name) / 'requests.jsonl' + + def write(self, records, path=None): + (path or self.path).write_text(''.join(json.dumps(dict(version=1, **x)) + '\n' for x in records)) + + def journal(self, reply=whole('ok'), stream=False, body=None, seed=42, kept=True): + start = {'kind': 'start', 'id': 'r', 'at': int(time.time()), 'path': '/v1/chat/completions', 'fingerprint': FP, 'seed': None, + 'body': {'messages': [{'role': 'user', 'content': 'hi'}], 'temperature': 1} if body is None else body} + finish = {'kind': 'finish', 'id': 'r', 'status': 200, 'stream': stream, 'outcome': 'completed', 'reply_bytes': len(reply), + 'reply_sha256': hashlib.sha256(reply).hexdigest(), 'token_sha256': TOKENS} + if kept: + finish['reply_base64'] = base64.b64encode(reply).decode() + self.write([start, {'kind': 'prepared', 'id': 'r', 'seed': seed}, finish]) + return r.read_journal(self.path)[0]['r'] + + def test_the_drawn_seed_is_sent_and_equal_output_passes_despite_new_ids_and_timings(self): + server = FakeServer(whole('ok', reply_id='chatcmpl-2', created=2, seconds=0.9)) + result, _ = r.replay(self.journal(), 'http://example.test', server.send) + self.assertTrue(result['equal']) + self.assertEqual(result['comparison'], 'output') + self.assertEqual(server.calls[0][0], 'http://example.test/v1/chat/completions') + self.assertEqual(server.calls[0][1]['seed'], 42) + own = self.journal(body={'messages': [], 'seed': 7}) + server = FakeServer(whole('ok')) + r.replay(own, 'http://example.test', server.send) + self.assertEqual(server.calls[0][1]['seed'], 7) # the client's own seed is never replaced + + def test_different_text_or_tokens_are_a_reported_mismatch(self): + result, _ = r.replay(self.journal(), 'http://example.test', FakeServer(whole('oK')).send) + self.assertFalse(result['equal']) + self.assertIsNotNone(result['first_difference']) + result, _ = r.replay(self.journal(), 'http://example.test', FakeServer(whole('ok', tokens='d1' * 32)).send) + self.assertFalse(result['equal']) + self.assertFalse(r.replay(self.journal(), 'http://example.test', FakeServer(whole('ok'), 500).send)[0]['equal']) + + def test_whole_body_compares_every_byte(self): + entry = self.journal() + self.assertTrue(r.replay(entry, 'http://example.test', FakeServer(whole('ok')).send, whole_body=True)[0]['equal']) + result, _ = r.replay(entry, 'http://example.test', FakeServer(whole('ok', reply_id='chatcmpl-2')).send, whole_body=True) + self.assertFalse(result['equal']) + self.assertEqual(result['comparison'], 'whole_body') + + def test_a_stream_compares_its_output_whatever_its_frames_and_keepalives(self): + entry = self.journal(streamed(['o', 'k']), stream=True) + self.assertTrue(r.replay(entry, 'http://example.test', FakeServer(streamed(['ok'], 'chatcmpl-9', True)).send)[0]['equal']) + self.assertFalse(r.replay(entry, 'http://example.test', FakeServer(streamed(['o', 'h'])).send)[0]['equal']) + self.assertFalse(r.replay(entry, 'http://example.test', FakeServer(streamed(['ok'], keepalive=True)).send, whole_body=True)[0]['equal']) + + def test_a_reply_too_large_to_keep_is_compared_by_its_token_hash(self): + entry = self.journal(kept=False) + result, _ = r.replay(entry, 'http://example.test', FakeServer(whole('anything')).send) + self.assertEqual(result['comparison'], 'tokens') + self.assertTrue(result['equal']) + self.assertFalse(r.replay(entry, 'http://example.test', FakeServer(whole('ok', tokens='d1' * 32)).send)[0]['equal']) + + def test_redacted_media_and_an_omitted_body_need_the_original_before_any_send(self): + for body in ({'messages': [{'content': [{'type': 'image_url', 'image_url': {'url': ''}}]}]}, None): + server = FakeServer(whole('ok')) + entry = self.journal(body=body if body else {}) + if body is None: + entry['start'].pop('body') + with self.assertRaises(r.ReplayError): + r.replay(entry, 'http://example.test', server.send) + self.assertEqual(server.calls, []) + self.assertTrue(r.replay(entry, 'http://example.test', server.send, replacement={'messages': []})[0]['equal']) + + def test_a_crashed_request_is_sent_only_on_purpose_and_has_no_reference(self): + crash = {'kind': 'quarantine', 'id': 'r', 'fingerprint': FP, 'at': int(time.time())} + self.write([{'kind': 'start', 'id': 'r', 'path': '/v1/chat/completions', 'fingerprint': FP, 'body': {'messages': []}}, crash, crash]) + entry = r.read_journal(self.path)[0]['r'] + self.assertTrue(entry['refused']) + server = FakeServer(b'{}') + with self.assertRaises(r.ReplayError): + r.replay(entry, 'http://example.test', server.send) + self.assertEqual(server.calls, []) + result, _ = r.replay(entry, 'http://example.test', server.send, allow_quarantined=True) + self.assertIsNone(result['equal']) + self.assertEqual(result['comparison'], 'no_reference') + + def test_rotated_files_are_read_oldest_first_and_torn_or_bad_lines_passed_over(self): + self.write([{'kind': 'start', 'id': 'r', 'path': '/v1/completions', 'fingerprint': FP, 'body': {}}], Path(f'{self.path}.2')) + self.path.write_bytes(b'bad\n' + json.dumps({'version': 1, 'kind': 'finish', 'id': 'r', 'status': 200}).encode() + b'\n{"kind":') + entries, skipped = r.read_journal(self.path) + self.assertEqual(skipped, 1) + self.assertEqual(entries['r']['finish']['status'], 200) + self.assertFalse(entries['r']['in_flight']) + + def test_two_recent_crashes_refuse_and_a_lapsed_one_or_a_clear_does_not(self): + old = int(time.time()) - r.QUARANTINE_S - 1 + start = {'kind': 'start', 'id': 'r', 'path': '/v1/completions', 'fingerprint': FP, 'body': {}} + lapsed, recent = ({'kind': 'quarantine', 'id': 'r', 'fingerprint': FP, 'at': at} for at in (old, int(time.time()))) + self.write([start, lapsed, recent]) + self.assertFalse(r.read_journal(self.path)[0]['r']['refused']) + self.write([start, recent, recent]) + self.assertTrue(r.read_journal(self.path)[0]['r']['refused']) + self.write([start, recent, recent, {'kind': 'clear', 'fingerprint': FP}]) + self.assertFalse(r.read_journal(self.path)[0]['r']['refused']) + + def test_route_and_origin_are_checked_before_any_send(self): + entry, server = self.journal(), FakeServer(b'{}') + for base in ('file:///tmp/a', 'http://name:secret@example.test', 'http://example.test/v1', 'http://example.test/?a=1'): + with self.assertRaises(r.ReplayError): + r.replay(entry, base, server.send) + entry['start']['path'] = '/admin' + with self.assertRaises(r.ReplayError): + r.replay(entry, 'http://example.test', server.send) + self.assertEqual(server.calls, []) + + @unittest.skipIf(os.name == 'nt', 'the lock is flock here; Windows locks a byte') + def test_cli_list_never_sends_a_mismatch_exits_one_and_clear_waits_for_the_server_to_stop(self): + import fcntl + self.journal() + quiet = contextlib.redirect_stdout(io.StringIO()) + with patch.object(r, 'http_send', side_effect=AssertionError('no send')), quiet: + self.assertEqual(r.main([str(self.path), '--list']), 0) + with patch.object(r, 'http_send', return_value=(200, whole('no'))), quiet: + self.assertEqual(r.main([str(self.path), '--id', 'r', '--base', 'http://example.test']), 1) + lock = os.open(f'{self.path}.lock', os.O_RDWR | os.O_CREAT, 0o600) + self.addCleanup(os.close, lock) + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) # as a running server holds it + with self.assertRaises(r.ReplayError): + r.clear(self.path, 'r', r.read_journal(self.path)[0]) + fcntl.flock(lock, fcntl.LOCK_UN) + with quiet: + self.assertEqual(r.main([str(self.path), '--clear', 'r']), 0) + last = json.loads(self.path.read_text().splitlines()[-1]) + self.assertEqual((last['kind'], last['fingerprint']), ('clear', FP)) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/tests/fake_served_api.py b/tools/tests/fake_served_api.py index c94105eb6d4..19fc1b64267 100644 --- a/tools/tests/fake_served_api.py +++ b/tools/tests/fake_served_api.py @@ -12,12 +12,26 @@ - cancel_reply: the request a client left answers differently the next time it arrives. - cancel_health: a server a client left answers ``/health`` with an error. - evict: a chat turn pushed out of the prompt cache reports it (0 cached) but answers from the stale state. +- undrafted: no request drafts, so a drafted reply runs the plain path. +- plain_drafts: a ``"draft": false`` request drafts anyway, so both arms run the same drafted path. +- sampled_drafts: a sampled request drafts nothing, so drafting is exercised only greedy. +- unsampled: temperature and seed never reach the sampler; a sampled request gets the greedy reply. +- serial: the server takes one request at a time, so requests sent together never overlap in it. +- empty: every reply is empty (no tokens), so every pair of replies hashes the same. ``running(..., warm=S)`` keeps the server busy (one running, more waiting) for ``S`` seconds after each reply, as a server that prefills the chat's next turn in the background; ``lanes_free=False`` leaves ``capacity.lanes_free`` out of ``GET /v1/load``, as a server without lanes. -The cached server reports five cached tokens for a later chat turn (more than one message). It keeps the prompts it +A request is counted in ``GET /v1/load``'s running and active chat requests while open. One that finds another in +flight within ``PARTNER_WINDOW`` stays open ``HOLD`` seconds more; a request alone leaves after the window. While a +client polls the census (two reads within ``WATCHED`` seconds, the last that recent), a request waits +``WATCHED_WINDOW`` for a partner, as threads sent together can start a scheduler tick apart (about 16 ms on Windows), +and a pair stays open until a census counts two open at once (at most ``COUNTED`` seconds), so however slow a census +read is, one taken meanwhile sees them. + +The cached server reports five cached tokens for a later chat turn (more than one message), and for a one-message +prompt it answered before. It keeps the prompts it answered in an LRU of ``CAPACITY`` entries; a prompt pushed out reports 0 until it is asked again. ``GET /v1/load``, ``/metrics`` and ``/health`` show the lanes open streams hold, the disconnects counted and the server's health. @@ -42,20 +56,26 @@ import time FAULTS = ("drafted", "repeat", "concurrent", "resumed", "refusals", "cancel_lane", "cancel_free", "cancel_reply", - "cancel_health", "evict") + "cancel_health", "evict", "undrafted", "plain_drafts", "sampled_drafts", "unsampled", "serial", "empty") BATCH_WINDOW = 0.15 # seconds a lone request waits for a partner under the concurrent fault DONE = b"data: [DONE]\n\n" HASHES = {"token_sha": "d" * 12, "token_sha256": "d" * 64} CAPACITY = 4 # prompt cache entries the cached server keeps LANES = 8 TOKEN_GAP = 0.0002 # seconds between streamed events +PARTNER_WINDOW = 0.01 # seconds a request waits for another to share the server with +HOLD = 0.025 # seconds a request that shares the server stays open, when no census is being read +WATCHED_WINDOW = 0.06 # seconds a request waits for a partner while a census is read +WATCHED = 0.1 # a census read this recent, after one this close before it, is a client polling +COUNTED = 0.5 # most seconds a pair waits for a census to count it, while watched -def doc(sha="a" * 64, cached=0, accepted=2, drafted=3, text="hi"): +def doc(sha="a" * 64, cached=0, accepted=2, drafted=3, text="hi", tokens=4, sampling="greedy", prompt=9): """A chat completion body carrying the fields the kit reads.""" - return {"choices": [{"message": {"content": text}}], "tensorfold": {"token_sha256": sha}, - "speculative": {"accepted": accepted, "drafted": drafted}, - "usage": {"prompt_tokens": 9, "completion_tokens": 4, "prompt_tokens_details": {"cached_tokens": cached}}} + return {"choices": [{"message": {"content": text}}], "tensorfold": {"token_sha256": sha, "sampling": sampling}, + "speculative": {"rounds": int(drafted > 0), "accepted": accepted, "drafted": drafted}, + "usage": {"prompt_tokens": prompt, "completion_tokens": tokens, + "prompt_tokens_details": {"cached_tokens": cached}}} def refusal(body, fault=None): @@ -71,8 +91,13 @@ def refusal(body, fault=None): return None +def messages_of(body) -> list: + """A chat request's messages; a completion request's prompt as one user message.""" + return body.get("messages") or [{"role": "user", "content": body.get("prompt", "")}] + + def text_of(body) -> str: - return " ".join(m.get("content", "") for m in body.get("messages", [])) + return " ".join(m.get("content", "") for m in messages_of(body)) def event(chunk: dict) -> bytes: @@ -144,7 +169,11 @@ def do_GET(self): server = self.server if self.path == "/v1/load": with server.lock: - busy, warming = server.streams + server.leaked, time.monotonic() < server.warm_until + busy, warming = server.streams + server.leaked + server.inflight, time.monotonic() < server.warm_until + server.census_gap, server.census_at = time.monotonic() - server.census_at, time.monotonic() + if busy > 1: + server.overlaps += 1 + server.cond.notify_all() capacity = {"mode": "window", "lanes_free": LANES - busy - server.lost} if server.lanes_free else {} return self.reply(200, {"lanes": LANES, "running": busy + warming, "waiting": 19 * warming, "http_active": {"chat_completions": busy}, "capacity": capacity}) @@ -164,6 +193,20 @@ def do_POST(self): if error: return self.reply(400, {"error": {"message": error, "type": "invalid_request_error"}}) key = json.dumps({k: v for k, v in body.items() if k not in ("stream", "stream_options")}, sort_keys=True) + with server.one if server.fault == "serial" else contextlib.nullcontext(): + payload = self.answer(body, key) + # Out of flight before the reply is written: the client's next request must not find this one counted. + if body.get("stream"): + self.play(streamed(payload, body.get("max_tokens", 16), TOKEN_GAP), key) + else: + self.reply(200, payload) + with server.lock: + server.warm_until = time.monotonic() + server.warm + time.sleep(server.linger) + + def answer(self, body, key) -> dict: + """The reply's body, computed while the request is counted in flight.""" + server, messages = self.server, messages_of(body) with server.lock: server.seen[key] = server.seen.get(key, 0) + 1 arrival = server.seen[key] @@ -171,34 +214,38 @@ def do_POST(self): after_cut = key in server.cut server.cut.discard(key) try: - batched = self.batched() if server.fault == "concurrent" else False - seed = body["seed"] if body.get("temperature") else None - cached, stale = self.lookup(body["messages"]) + watched = time.monotonic() - server.census_at < WATCHED and server.census_gap < WATCHED # a poller + window = WATCHED_WINDOW if watched else PARTNER_WINDOW + batched = self.batched(BATCH_WINDOW if server.fault == "concurrent" else window) + if batched: + self.counted() if watched else time.sleep(HOLD) + sampled = bool(body.get("temperature")) and server.fault != "unsampled" + cached, stale = self.lookup(messages) salt = "stale" if stale else "after a cut" if after_cut and server.fault == "cancel_reply" else None - salt = salt or self.salt(body, arrival, batched) - sha = hashlib.sha256(json.dumps([body["messages"], seed, salt]).encode()).hexdigest() - self.keep(body["messages"]) - accepted = 2 if body.get("draft", True) else 0 - payload = doc(sha=sha, cached=cached, accepted=accepted, drafted=accepted, text="r" + sha[:6]) + salt = salt or self.salt(body, arrival, batched and server.fault == "concurrent") + seed = body.get("seed") if sampled else None + sha = hashlib.sha256(json.dumps([messages, seed, salt]).encode()).hexdigest() + self.keep(messages) + drafts = (body.get("draft", True) or server.fault == "plain_drafts") and server.fault != "undrafted" + accepted = 2 if drafts and not (sampled and server.fault == "sampled_drafts") else 0 + if server.fault == "empty": + return doc(sha=hashlib.sha256(b"").hexdigest(), cached=cached, accepted=accepted, drafted=accepted, + text="", tokens=0) + return doc(sha=sha, cached=cached, accepted=accepted, drafted=accepted, text="r" + sha[:6], + sampling="exact" if sampled else "greedy", prompt=max(9, len(text_of(body)) // 4)) finally: with server.lock: server.inflight -= 1 - # Out of flight before the reply is written: the client's next request must not find this one still counted. - if body.get("stream"): - self.play(streamed(payload, body.get("max_tokens", 16), TOKEN_GAP), key) - else: - self.reply(200, payload) - with server.lock: - server.warm_until = time.monotonic() + server.warm - time.sleep(server.linger) def lookup(self, messages): """Cached tokens for the prompt, and whether the evict fault answers from an evicted prompt.""" server = self.server - if not server.cache or len(messages) < 2: + if not server.cache: return 0, False with server.lock: whole = json.dumps(messages) + if len(messages) < 2: + return (5 if whole in server.kept else 0), False if whole in server.evicted: return 0, server.fault == "evict" return (0 if server.fault == "resumed" and whole not in server.kept else 5), False @@ -216,12 +263,19 @@ def keep(self, messages): while len(server.kept) > CAPACITY: server.evicted.add(server.kept.popitem(last=False)[0]) - def batched(self) -> bool: - """True when another request shares the server with this one within the batch window.""" + def batched(self, window: float) -> bool: + """True when another request shares the server with this one within ``window`` seconds.""" server = self.server with server.cond: server.cond.notify_all() - return server.cond.wait_for(lambda: server.inflight > 1, timeout=BATCH_WINDOW) + return server.cond.wait_for(lambda: server.inflight > 1, timeout=window) + + def counted(self): + """Wait, at most ``COUNTED`` seconds, for a ``GET /v1/load`` that counts two chat requests open at once.""" + server = self.server + with server.cond: + mark = server.overlaps + server.cond.wait_for(lambda: server.overlaps > mark, timeout=COUNTED) def salt(self, body, arrival, batched): """A planted fault changes the reply by adding a salt to its hash; None leaves it correct.""" @@ -275,9 +329,10 @@ def running(cache=False, fault=None, linger=0.0, steps=None, warm=0.0, lanes_fre server = FixtureHTTPServer(("127.0.0.1", 0), FakeEngine) server.cache, server.fault, server.seen, server.inflight, server.linger = cache, fault, {}, 0, linger server.steps, server.kept, server.evicted, server.cut = steps, collections.OrderedDict(), set(), set() - server.streams = server.leaked = server.lost = server.disconnects = 0 + server.streams = server.leaked = server.lost = server.disconnects = server.overlaps = 0 server.warm, server.warm_until, server.lanes_free = warm, 0.0, lanes_free - server.lock = threading.Lock() + server.census_at, server.census_gap = -1e9, 1e9 # no census read yet + server.lock, server.one = threading.Lock(), threading.Lock() server.cond = threading.Condition(server.lock) thread = threading.Thread(target=server.serve_forever, kwargs={"poll_interval": 0.01}, daemon=True) thread.start() diff --git a/tools/tests/fixtures/draft_divergence/README.md b/tools/tests/fixtures/draft_divergence/README.md new file mode 100644 index 00000000000..0e3b7d5bf2c --- /dev/null +++ b/tools/tests/fixtures/draft_divergence/README.md @@ -0,0 +1,9 @@ +These JSON files are synthetic recorded-format unit fixtures, authored for the +harness. They are not captures from any model or hardware. `recording.json` has +eight greedy tokens and a BF16-near tie at generated index 2. `profiles.json` +contains three placeholder endpoints with configured caps 1, 4 and 8. + +`equal.json` records identical serial/drafted token streams. `divergent.json` +changes only the depth-4 token at index 2 from 12 to 99, reversing the two +synthetic contenders in that run's raw-logit capture. Both margins are within +one BF16 spacing, but exact token equality must fail. diff --git a/tools/tests/fixtures/draft_divergence/divergent.json b/tools/tests/fixtures/draft_divergence/divergent.json new file mode 100644 index 00000000000..a04b04d060c --- /dev/null +++ b/tools/tests/fixtures/draft_divergence/divergent.json @@ -0,0 +1,486 @@ +{ + "fixture:2:plain": { + "response": { + "model": "fixture-model", + "choices": [ + { + "index": 0, + "text": "fixture only", + "finish_reason": "length" + } + ], + "tensorfold": { + "token_ids": [ + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17 + ], + "drafts": false + }, + "usage": { + "completion_tokens": 8 + }, + "speculative": { + "drafted": 0 + } + }, + "top2": [ + { + "ids": [ + 10, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 2 + }, + { + "ids": [ + 11, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 3 + }, + { + "ids": [ + 12, + 99 + ], + "logits": [ + 16.0, + 15.9375 + ], + "position": 4 + }, + { + "ids": [ + 13, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 5 + }, + { + "ids": [ + 14, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 6 + }, + { + "ids": [ + 15, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 7 + }, + { + "ids": [ + 16, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 8 + }, + { + "ids": [ + 17, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 9 + } + ] + }, + "fixture:2:1": { + "response": { + "model": "fixture-model", + "choices": [ + { + "index": 0, + "text": "fixture only", + "finish_reason": "length" + } + ], + "tensorfold": { + "token_ids": [ + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17 + ], + "drafts": true + }, + "usage": { + "completion_tokens": 8 + }, + "speculative": { + "drafted": 7 + } + }, + "top2": [ + { + "ids": [ + 10, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 2 + }, + { + "ids": [ + 11, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 3 + }, + { + "ids": [ + 12, + 99 + ], + "logits": [ + 16.0, + 15.9375 + ], + "position": 4 + }, + { + "ids": [ + 13, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 5 + }, + { + "ids": [ + 14, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 6 + }, + { + "ids": [ + 15, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 7 + }, + { + "ids": [ + 16, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 8 + }, + { + "ids": [ + 17, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 9 + } + ] + }, + "fixture:2:4": { + "response": { + "model": "fixture-model", + "choices": [ + { + "index": 0, + "text": "fixture only", + "finish_reason": "length" + } + ], + "tensorfold": { + "token_ids": [ + 10, + 11, + 99, + 13, + 14, + 15, + 16, + 17 + ], + "drafts": true + }, + "usage": { + "completion_tokens": 8 + }, + "speculative": { + "drafted": 7 + } + }, + "top2": [ + { + "ids": [ + 10, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 2 + }, + { + "ids": [ + 11, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 3 + }, + { + "ids": [ + 99, + 12 + ], + "logits": [ + 16.0, + 15.9375 + ], + "position": 4 + }, + { + "ids": [ + 13, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 5 + }, + { + "ids": [ + 14, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 6 + }, + { + "ids": [ + 15, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 7 + }, + { + "ids": [ + 16, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 8 + }, + { + "ids": [ + 17, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 9 + } + ] + }, + "fixture:2:8": { + "response": { + "model": "fixture-model", + "choices": [ + { + "index": 0, + "text": "fixture only", + "finish_reason": "length" + } + ], + "tensorfold": { + "token_ids": [ + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17 + ], + "drafts": true + }, + "usage": { + "completion_tokens": 8 + }, + "speculative": { + "drafted": 7 + } + }, + "top2": [ + { + "ids": [ + 10, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 2 + }, + { + "ids": [ + 11, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 3 + }, + { + "ids": [ + 12, + 99 + ], + "logits": [ + 16.0, + 15.9375 + ], + "position": 4 + }, + { + "ids": [ + 13, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 5 + }, + { + "ids": [ + 14, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 6 + }, + { + "ids": [ + 15, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 7 + }, + { + "ids": [ + 16, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 8 + }, + { + "ids": [ + 17, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 9 + } + ] + } +} diff --git a/tools/tests/fixtures/draft_divergence/equal.json b/tools/tests/fixtures/draft_divergence/equal.json new file mode 100644 index 00000000000..9aa0944680e --- /dev/null +++ b/tools/tests/fixtures/draft_divergence/equal.json @@ -0,0 +1,486 @@ +{ + "fixture:2:plain": { + "response": { + "model": "fixture-model", + "choices": [ + { + "index": 0, + "text": "fixture only", + "finish_reason": "length" + } + ], + "tensorfold": { + "token_ids": [ + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17 + ], + "drafts": false + }, + "usage": { + "completion_tokens": 8 + }, + "speculative": { + "drafted": 0 + } + }, + "top2": [ + { + "ids": [ + 10, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 2 + }, + { + "ids": [ + 11, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 3 + }, + { + "ids": [ + 12, + 99 + ], + "logits": [ + 16.0, + 15.9375 + ], + "position": 4 + }, + { + "ids": [ + 13, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 5 + }, + { + "ids": [ + 14, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 6 + }, + { + "ids": [ + 15, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 7 + }, + { + "ids": [ + 16, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 8 + }, + { + "ids": [ + 17, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 9 + } + ] + }, + "fixture:2:1": { + "response": { + "model": "fixture-model", + "choices": [ + { + "index": 0, + "text": "fixture only", + "finish_reason": "length" + } + ], + "tensorfold": { + "token_ids": [ + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17 + ], + "drafts": true + }, + "usage": { + "completion_tokens": 8 + }, + "speculative": { + "drafted": 7 + } + }, + "top2": [ + { + "ids": [ + 10, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 2 + }, + { + "ids": [ + 11, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 3 + }, + { + "ids": [ + 12, + 99 + ], + "logits": [ + 16.0, + 15.9375 + ], + "position": 4 + }, + { + "ids": [ + 13, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 5 + }, + { + "ids": [ + 14, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 6 + }, + { + "ids": [ + 15, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 7 + }, + { + "ids": [ + 16, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 8 + }, + { + "ids": [ + 17, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 9 + } + ] + }, + "fixture:2:4": { + "response": { + "model": "fixture-model", + "choices": [ + { + "index": 0, + "text": "fixture only", + "finish_reason": "length" + } + ], + "tensorfold": { + "token_ids": [ + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17 + ], + "drafts": true + }, + "usage": { + "completion_tokens": 8 + }, + "speculative": { + "drafted": 7 + } + }, + "top2": [ + { + "ids": [ + 10, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 2 + }, + { + "ids": [ + 11, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 3 + }, + { + "ids": [ + 12, + 99 + ], + "logits": [ + 16.0, + 15.9375 + ], + "position": 4 + }, + { + "ids": [ + 13, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 5 + }, + { + "ids": [ + 14, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 6 + }, + { + "ids": [ + 15, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 7 + }, + { + "ids": [ + 16, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 8 + }, + { + "ids": [ + 17, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 9 + } + ] + }, + "fixture:2:8": { + "response": { + "model": "fixture-model", + "choices": [ + { + "index": 0, + "text": "fixture only", + "finish_reason": "length" + } + ], + "tensorfold": { + "token_ids": [ + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17 + ], + "drafts": true + }, + "usage": { + "completion_tokens": 8 + }, + "speculative": { + "drafted": 7 + } + }, + "top2": [ + { + "ids": [ + 10, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 2 + }, + { + "ids": [ + 11, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 3 + }, + { + "ids": [ + 12, + 99 + ], + "logits": [ + 16.0, + 15.9375 + ], + "position": 4 + }, + { + "ids": [ + 13, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 5 + }, + { + "ids": [ + 14, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 6 + }, + { + "ids": [ + 15, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 7 + }, + { + "ids": [ + 16, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 8 + }, + { + "ids": [ + 17, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 9 + } + ] + } +} diff --git a/tools/tests/fixtures/draft_divergence/profiles.json b/tools/tests/fixtures/draft_divergence/profiles.json new file mode 100644 index 00000000000..0a268983213 --- /dev/null +++ b/tools/tests/fixtures/draft_divergence/profiles.json @@ -0,0 +1,32 @@ +[ + { + "depth": 1, + "url": "http://fixture.invalid:8001", + "model": "fixture-model", + "identity": { + "checkpoint": "Org/RecordedFixture@0000000000000000000000000000000000000000", + "tokenizer": "fixture-tokenizer", + "backend": "recorded-unit-fixture" + } + }, + { + "depth": 4, + "url": "http://fixture.invalid:8004", + "model": "fixture-model", + "identity": { + "checkpoint": "Org/RecordedFixture@0000000000000000000000000000000000000000", + "tokenizer": "fixture-tokenizer", + "backend": "recorded-unit-fixture" + } + }, + { + "depth": 8, + "url": "http://fixture.invalid:8008", + "model": "fixture-model", + "identity": { + "checkpoint": "Org/RecordedFixture@0000000000000000000000000000000000000000", + "tokenizer": "fixture-tokenizer", + "backend": "recorded-unit-fixture" + } + } +] diff --git a/tools/tests/fixtures/draft_divergence/recording.json b/tools/tests/fixtures/draft_divergence/recording.json new file mode 100644 index 00000000000..016ab31d4ff --- /dev/null +++ b/tools/tests/fixtures/draft_divergence/recording.json @@ -0,0 +1,117 @@ +{ + "schema": 1, + "identity": { + "checkpoint": "Org/RecordedFixture@0000000000000000000000000000000000000000", + "tokenizer": "fixture-tokenizer", + "backend": "recorded-unit-fixture" + }, + "traces": [ + { + "name": "fixture", + "prompt": [ + 1, + 2 + ], + "tokens": [ + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17 + ], + "top2": [ + { + "ids": [ + 10, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 2 + }, + { + "ids": [ + 11, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 3 + }, + { + "ids": [ + 12, + 99 + ], + "logits": [ + 16.0, + 15.9375 + ], + "position": 4 + }, + { + "ids": [ + 13, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 5 + }, + { + "ids": [ + 14, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 6 + }, + { + "ids": [ + 15, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 7 + }, + { + "ids": [ + 16, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 8 + }, + { + "ids": [ + 17, + 99 + ], + "logits": [ + 16.0, + 14.0 + ], + "position": 9 + } + ] + } + ] +} diff --git a/tools/tests/test_bench_conformance.py b/tools/tests/test_bench_conformance.py index 45daa86425b..2f685b10484 100644 --- a/tools/tests/test_bench_conformance.py +++ b/tools/tests/test_bench_conformance.py @@ -45,6 +45,12 @@ def test_same_needs_two_full_hashes(self): self.assertIsNone(same(a, {**a, "error": "x"})) self.assertEqual(tally([(a, a), (a, b), (a, {})]), {"equal": 1, "unequal": 1, "unverified": 1}) + def test_empty_replies_are_unverified(self): + # Two empty replies hash the same: equal without a token is no evidence. + empty = reply_row(200, doc(tokens=0, text="")) + self.assertIsNone(same(empty, empty)) + self.assertIsNone(same(reply_row(200, doc()), {**reply_row(200, doc()), "tokens": None})) + def test_equality_gate_fails_on_unequal_unverified_or_empty(self): a, b = reply_row(200, doc()), reply_row(200, doc(sha="b" * 64)) self.assertTrue(equality_gate("g", [(a, a)])["passed"]) @@ -54,10 +60,29 @@ def test_equality_gate_fails_on_unequal_unverified_or_empty(self): def test_drafted_gate_is_vacuous_without_an_accepted_draft(self): plain, drafted = reply_row(200, doc(accepted=0, drafted=0)), reply_row(200, doc(accepted=0, drafted=7)) - gate = drafted_gate([(plain, drafted)]) + gate = drafted_gate({"greedy": [(plain, drafted)]}) self.assertFalse(gate["passed"]) self.assertIn("vacuous", gate["line"]) - self.assertTrue(drafted_gate([(plain, reply_row(200, doc()))])["passed"]) + self.assertTrue(drafted_gate({"greedy": [(plain, reply_row(200, doc()))]})["passed"]) + + def test_drafted_gate_needs_drafts_in_each_mode_and_none_in_plain(self): + plain, good, idle = (reply_row(200, doc(accepted=a, drafted=d)) for a, d in ((0, 0), (2, 3), (0, 3))) + sampled_idle = drafted_gate({"greedy": [(plain, good)], "sampled": [(plain, idle)]}) + self.assertFalse(sampled_idle["passed"]) + self.assertIn("no draft accepted sampled", sampled_idle["line"]) + both_drafted = drafted_gate({"greedy": [(good, good)]}) + self.assertFalse(both_drafted["passed"]) + self.assertIn("plain replies drafted 3 tokens", both_drafted["line"]) + + def test_seeded_and_overlap_problems(self): + a, b = reply_row(200, doc()), reply_row(200, doc(sha="b" * 64)) + self.assertIsNone(conformance.seeded_problem([(a, a), (a, b)])) + self.assertIn("never reached sampling", conformance.seeded_problem([(a, a)])) + self.assertIsNone(conformance.overlap_problem([2, 8])) + self.assertIn("2 of 3 batches", conformance.overlap_problem([2, 1, None])) + self.assertIsNone(conformance.batch_drafts_problem({2: [5, 0], "mixed": [1, 0]})) + self.assertIn("accepted no draft at [2]; plain rows drafted at {'mixed': 3}", + conformance.batch_drafts_problem({2: [0, 0], "mixed": [1, 3]})) def test_resumed_gate_asserts_both_cache_counts(self): def turns(fresh_cached, resumed_cached): @@ -134,7 +159,10 @@ class GateRunTests(unittest.TestCase): NAMES = {"drafted": "drafted == plain", "repeat": "repeat == first", "concurrent": "concurrent == solo", "resumed": "resumed == fresh", "refusals": "refusals", "cancel": "cancel", "evict": "evict", - "cancel_lane": "cancel", "cancel_free": "cancel", "cancel_reply": "cancel", "cancel_health": "cancel"} + "cancel_lane": "cancel", "cancel_free": "cancel", "cancel_reply": "cancel", "cancel_health": "cancel", + "undrafted": "drafted == plain", "plain_drafts": "drafted == plain", "sampled_drafts": "drafted == plain", + "unsampled": "repeat == first", "serial": "concurrent == solo", "empty": "drafted == plain"} + JSON_ONLY = ("undrafted", "sampled_drafts", "unsampled", "serial") # faults the stream test leaves out GATE_OF = {fault: name.split()[0] for fault, name in NAMES.items() if fault in FAULTS} # the gate a fault turns red def run_kit(self, *extra, fault=None, shape=None, **changes): @@ -180,6 +208,30 @@ def test_fault_resumed_reports_no_cached_tokens(self): def test_fault_listed_refusal_accepted(self): self.assert_only_red("refusals") + def test_fault_no_draft_lands(self): + # Batched drafted rows accept no draft either, so concurrency fails as unproven drafting too. + self.assert_only_red("undrafted", also=("concurrent == solo",)) + + def test_fault_plain_arm_drafts(self): + self.assert_only_red("plain_drafts", also=("concurrent == solo",)) + + def test_fault_sampled_arm_drafts_nothing(self): + self.assert_only_red("sampled_drafts") + + def test_fault_seed_never_reaches_sampling(self): + # Only the cached fake carries the fault, so its sampled chat also differs from the clean cache-off fake's. + self.assert_only_red("unsampled", also=("resumed == fresh",)) + + def test_fault_requests_never_overlap(self): + self.assert_only_red("serial") + + def test_fault_empty_replies_fail_every_exactness_gate(self): + code, lines = self.run_kit("--gates", "drafted,repeat,concurrent,resumed", fault="empty") + self.assertEqual(code, 1, lines) + self.assertEqual(len(lines), 4, lines) + self.assertTrue(all(line.startswith("FAIL") and " unverified" in line for line in lines), lines) + self.assertTrue(all(" 0 unverified" not in line for line in lines), lines) + def test_fault_cancel_keeps_a_lane(self): # A request left running keeps the server from ever going idle, so evict has no idle census either. self.assert_only_red("cancel_lane", also=("evict",)) @@ -257,7 +309,8 @@ def test_streamed_replies_pass_clean_and_each_fault_turns_its_gate_red(self): self.assertEqual(code, 0, lines) self.assertEqual(len(lines), len(conformance.GATES)) self.assertTrue(all(line.startswith("PASS") for line in lines), lines) - for fault, gate in self.GATE_OF.items(): + # the streamed reader's draft and token counts: two faults suffice; the others change nothing it reads + for fault, gate in ((f, g) for f, g in self.GATE_OF.items() if f not in self.JSON_ONLY): with self.subTest(fault=fault): code, lines = self.run_kit("--stream", "--gates", gate, fault=fault) self.assertEqual(code, 1, lines) diff --git a/tools/tests/test_bench_lfm3_serve_check.py b/tools/tests/test_bench_lfm3_serve_check.py new file mode 100644 index 00000000000..3bc31164b77 --- /dev/null +++ b/tools/tests/test_bench_lfm3_serve_check.py @@ -0,0 +1,68 @@ +"""tools/lfm3/serve_check.py on the fake served API: clean it passes; unexercised drafts or sampling fail by name.""" +import contextlib +import importlib.util +import io +import json +from pathlib import Path +import sys +import tempfile +import unittest +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from fake_served_api import fake + +SPEC = importlib.util.spec_from_file_location("lfm3_serve_check", Path(__file__).resolve().parents[1] / "lfm3" / + "serve_check.py") +check = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(check) + + +def fake_server(fault): + """``serve_check.Server`` with a fake served API (with ``fault``) in place of the native binary.""" + + class Fake(check.Server): + def __enter__(self): + self.command = ["fake", str(self.cache)] + self.log = tempfile.NamedTemporaryFile(mode="w+b", dir=self.log_directory, delete=False) + self.running = fake(self.cache > 0, fault) + self.base = self.running.__enter__() + return self + + def __exit__(self, *exc): + self.running.__exit__(*exc) + self.log.close() + return Fake + + +def run(fault=None): + """The exit code and the failed checks' names of one ``--sampled`` run against the fake.""" + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + (root / "config.json").write_text(json.dumps({"model_type": "lfm3"})) + (root / "binary").write_bytes(b"fake") + argv = ["serve_check.py", "--binary", str(root / "binary"), "--model-dir", str(root), "--output", + str(root / "out.json"), "--sampled"] + with mock.patch.object(check, "Server", fake_server(fault)), mock.patch.object(sys, "argv", argv), \ + mock.patch.object(check.tempfile, "mkdtemp", lambda prefix: tmp), \ + contextlib.redirect_stdout(io.StringIO()): + code = check.main() + receipt = json.loads((root / "out.json").read_text()) + return code, [t["name"] for t in receipt["tests"] if t["status"] == "failed"] + + +class Lfm3ServeCheckTests(unittest.TestCase): + def test_clean_fake_passes(self): + self.assertEqual(run(), (0, [])) + + def test_unexercised_drafts_fail(self): + for fault in ("undrafted", "plain_drafts"): + with self.subTest(fault=fault): + self.assertEqual(run(fault), (1, ["drafts/exercised"])) + + def test_a_sampler_that_never_ran_fails(self): + self.assertEqual(run("unsampled"), (1, ["sampled_code/sampler_ran", "sampled_chat/sampler_ran"])) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_bench_qwen27_http_gate.py b/tools/tests/test_bench_qwen27_http_gate.py new file mode 100644 index 00000000000..b6260139f2a --- /dev/null +++ b/tools/tests/test_bench_qwen27_http_gate.py @@ -0,0 +1,43 @@ +"""tools/zig/qwen27_http_gate.py's reply check on fake served replies: a drafted reply must propose and accept.""" +import json +from pathlib import Path +import sys +import unittest +import urllib.request + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "zig")) +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import qwen27_http_gate +from fake_served_api import fake + +TOKENS = [11, 22, 33] + + +def reply(fault, draft): + """The fake's reply to one request, its runtime fields set as the CLI receipt's tokens give them.""" + with fake(False, fault) as url: + body = {"messages": [{"role": "user", "content": "hi"}], "max_tokens": len(TOKENS), "draft": draft} + request = urllib.request.Request(url + "/v1/chat/completions", json.dumps(body).encode(), + {"Content-Type": "application/json"}) + with urllib.request.urlopen(request, timeout=10) as answer: + doc = json.load(answer) + digest = qwen27_http_gate.hashlib.sha256(",".join(map(str, TOKENS)).encode()).hexdigest()[:12] + doc["tensorfold"].update(token_sha=digest, drafts=draft) + doc["usage"].update(prompt_tokens=2, completion_tokens=len(TOKENS)) + return doc + + +class DraftCheckTests(unittest.TestCase): + def test_drafted_and_plain_replies_pass(self): + for draft in (True, False): + self.assertEqual(qwen27_http_gate.check(reply(None, draft), [1, 2], TOKENS, draft)["drafts"], draft) + + def test_a_drafted_reply_that_accepted_nothing_fails(self): + doc = reply("undrafted", True) + doc["speculative"].update(rounds=4, drafted=12) # verified rounds whose drafts all missed + with self.assertRaisesRegex(ValueError, "did not exercise draft verification"): + qwen27_http_gate.check(doc, [1, 2], TOKENS, True) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_bench_serve_check.py b/tools/tests/test_bench_serve_check.py new file mode 100644 index 00000000000..a2820410ef6 --- /dev/null +++ b/tools/tests/test_bench_serve_check.py @@ -0,0 +1,52 @@ +"""zig/tests/qwen35/serve_check.py against the fake served API: clean it passes, and each planted fault fails by name.""" +import subprocess +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from fake_served_api import fake + +SCRIPT = Path(__file__).resolve().parents[2] / "zig" / "tests" / "qwen35" / "serve_check.py" + + +def run(fault=None): + """The script's exit code and its FAIL lines, against a cached fake with ``fault`` and a cache-off fake.""" + with fake(True, fault) as url, fake(False) as fresh: + done = subprocess.run([sys.executable, str(SCRIPT), url, "fake", "8", fresh], capture_output=True, text=True, + timeout=120) + return done.returncode, [line for line in done.stdout.splitlines() if line.startswith("FAIL")] + + +class ServeCheckTests(unittest.TestCase): + def test_clean_fake_passes(self): + self.assertEqual(run(), (0, [])) + + def test_a_resume_that_resumed_nothing_fails(self): + # The vacuous pass of #2460: a later turn that resumed no tokens compared two fresh replies. + code, failed = run("resumed") + self.assertEqual(code, 1) + self.assertEqual([line.split(":")[0] for line in failed], ["FAIL resumed == fresh"], failed) + self.assertIn("resumed no tokens", failed[0]) + + def test_unexercised_drafts_fail(self): + for fault, labels in (("plain_drafts", ["greedy", "t0.8"]), ("sampled_drafts", ["t0.8"])): + with self.subTest(fault=fault): + code, failed = run(fault) + self.assertEqual(code, 1) + self.assertEqual([line.split(":")[0] for line in failed], [f"FAIL {x}" for x in labels], failed) + self.assertTrue(all("drafted == serial" in line for line in failed), failed) + + def test_a_sampler_that_never_ran_fails(self): + code, failed = run("unsampled") + self.assertEqual(code, 1) + self.assertEqual(failed, ["FAIL t0.8: the same twice, unlike greedy"]) + + def test_empty_replies_are_never_equal(self): + code, failed = run("empty") + self.assertEqual(code, 1) + self.assertGreaterEqual(len(failed), 10, failed) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_draft_divergence.py b/tools/tests/test_draft_divergence.py new file mode 100644 index 00000000000..25629b36fb0 --- /dev/null +++ b/tools/tests/test_draft_divergence.py @@ -0,0 +1,293 @@ +"""Recorded synthetic fixtures exercise strict IDs, BF16 diagnostics and served/replay request contracts.""" +import contextlib +import copy +import io +import json +from pathlib import Path +import sys +import tempfile +import unittest +from unittest.mock import patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import draft_divergence as harness + +FIXTURES = Path(__file__).parent / "fixtures" / "draft_divergence" + + +class DraftDivergenceTests(unittest.TestCase): + def setUp(self): + self.recording = harness.load(FIXTURES / "recording.json") + self.profiles = harness.load(FIXTURES / "profiles.json") + self.equal = harness.load(FIXTURES / "equal.json") + self.calls = [] + + def evaluate(self, observations=None, **kwargs): + observations = self.equal if observations is None else observations + + def fetch(profile, body, case_id, depth): + self.calls.append((copy.deepcopy(profile), copy.deepcopy(body), case_id, depth)) + return copy.deepcopy(observations[case_id + ":" + depth]) + + return harness.evaluate(self.recording, self.profiles, fetch, lookback=2, tokens=8, **kwargs) + + def test_equal_runs_and_exact_request_contract(self): + report = self.evaluate() + self.assertTrue(report["passed"]) + self.assertEqual(report["status"], "pass") + case, = report["cases"] + self.assertEqual(case["near_tie_offset"], 2) + self.assertTrue(case["source_reproduced"]) + self.assertEqual([v["configured_depth"] for v in case["variants"]], [1, 4, 8]) + self.assertTrue(all(v["token_equal"] for v in case["variants"])) + self.assertEqual(len(self.calls), 4) + for index, (profile, body, name, depth) in enumerate(self.calls): + self.assertEqual(body["prompt"], [1, 2]) + self.assertEqual(body["max_tokens"], 8) + self.assertEqual(body["temperature"], 0) + self.assertIs(body["draft"], index > 0) + self.assertIs(body["return_token_ids"], True) + self.assertIs(body["ignore_eos"], True) + self.assertIs(body["stream"], False) + self.assertEqual(body["model"], profile["model"]) + self.assertNotIn("draft_depth", body) + self.assertEqual(name, "fixture:2") + self.assertEqual(depth, ["plain", "1", "4", "8"][index]) + self.assertEqual(harness.summary(report), + "DRAFT_DIVERGENCE status=pass cases=1 comparisons=3 divergences=0") + + def test_divergence_at_token_n_reports_both_raw_captures(self): + report = self.evaluate(harness.load(FIXTURES / "divergent.json")) + self.assertFalse(report["passed"]) + self.assertEqual(report["status"], "divergent") + difference = report["cases"][0]["variants"][1]["first_divergence"] + self.assertEqual((difference["output_index"], difference["absolute_position"]), (2, 4)) + self.assertEqual((difference["plain_token_id"], difference["drafted_token_id"]), (12, 99)) + self.assertEqual(difference["plain_top2"]["ids"], [12, 99]) + self.assertEqual(difference["drafted_top2"]["ids"], [99, 12]) + self.assertEqual(difference["plain_top2"]["logits"], [16.0, 15.9375]) + self.assertEqual(difference["drafted_top2"]["logits"], [16.0, 15.9375]) + self.assertEqual(difference["label"], "near-tie") + self.assertIs(difference["strict_equal"], False) + self.assertIn('first="fixture:2"@2 depth=4', harness.summary(report)) + + def test_bf16_boundary_is_inclusive_and_uses_absolute_raw_logits(self): + row = self.recording["traces"][0]["top2"][2] + row["logits"] = [16, 15.875] + case, = harness.select_prompts(self.recording, lookback=1, tokens=8) + self.assertEqual(case["bf16_spacing"], 0.125) + self.assertEqual(case["prompt"], [1, 2, 10]) + self.assertEqual(case["near_tie_offset"], 1) + row["logits"][1] = 15.874 + with self.assertRaisesRegex(ValueError, "no recorded BF16 near-ties"): + harness.select_prompts(self.recording) + self.assertTrue(harness.near({"logits": [16, 15.9375]})) + self.assertFalse(harness.near({"logits": [-0.68, -0.7425]})) + + def test_nearest_supported_caps_are_reported(self): + for profile, depth in zip(self.profiles, [1, 3, 6]): + profile["depth"] = depth + report = self.evaluate() + self.assertTrue(report["passed"]) + variants = report["cases"][0]["variants"] + self.assertEqual([(v["requested_depth"], v["configured_depth"]) for v in variants], + [(1, 1), (4, 3), (8, 6)]) + self.assertIn("not per-request", variants[0]["depth_control"]) + + def test_no_draft_work_never_passes(self): + for value in (0, None): + observations = copy.deepcopy(self.equal) + observations["fixture:2:4"]["response"]["speculative"]["drafted"] = value + with self.subTest(value=value): + report = self.evaluate(observations) + self.assertEqual(report["status"], "incomplete") + self.assertFalse(report["passed"]) + + def test_equal_early_stops_do_not_pass(self): + observations = copy.deepcopy(self.equal) + for observation in observations.values(): + response = observation["response"] + response["tensorfold"]["token_ids"] = response["tensorfold"]["token_ids"][:2] + response["usage"]["completion_tokens"] = 2 + response["choices"][0]["finish_reason"] = "stop" + observation["top2"] = observation["top2"][:2] + report = self.evaluate(observations) + self.assertEqual(report["status"], "incomplete") + self.assertFalse(report["passed"]) + + def test_length_difference_has_missing_id_and_fails(self): + observations = copy.deepcopy(self.equal) + observation = observations["fixture:2:4"] + observation["response"]["tensorfold"]["token_ids"].pop() + observation["response"]["usage"]["completion_tokens"] -= 1 + observation["response"]["choices"][0]["finish_reason"] = "stop" + observation["top2"].pop() + report = self.evaluate(observations) + self.assertEqual(report["status"], "divergent") + difference = report["cases"][0]["variants"][1]["first_divergence"] + self.assertEqual(difference["output_index"], 7) + self.assertEqual(difference["plain_token_id"], 17) + self.assertIsNone(difference["drafted_token_id"]) + + def test_live_shape_without_raw_captures_labels_historical_logits(self): + observations = harness.load(FIXTURES / "divergent.json") + for observation in observations.values(): + observation.pop("top2") + report = self.evaluate(observations) + difference = report["cases"][0]["variants"][1]["first_divergence"] + self.assertFalse(report["passed"]) + self.assertEqual(difference["label"], "recorded-near-tie") + self.assertIsNone(difference["plain_top2"]) + self.assertIsNone(difference["drafted_top2"]) + self.assertEqual(difference["recorded_logits_for_tokens"], {"plain": 16.0, "drafted": 15.9375}) + self.assertIn("recorded source", difference["logit_source"]) + + def test_changed_plain_history_does_not_reuse_source_logits(self): + observations = harness.load(FIXTURES / "divergent.json") + for observation in observations.values(): + observation.pop("top2") + observation["response"]["tensorfold"]["token_ids"][0] = 77 + report = self.evaluate(observations) + difference = report["cases"][0]["variants"][1]["first_divergence"] + self.assertFalse(difference["recorded_history_matches"]) + self.assertEqual(difference["recorded_logits_for_tokens"], {"plain": None, "drafted": None}) + self.assertEqual(difference["label"], "divergence") + + def test_nonreproduced_source_never_passes_even_when_modes_agree(self): + observations = copy.deepcopy(self.equal) + for observation in observations.values(): + observation.pop("top2") + observation["response"]["tensorfold"]["token_ids"][0] = 77 + report = self.evaluate(observations) + self.assertEqual(report["status"], "incomplete") + self.assertFalse(report["cases"][0]["source_reproduced"]) + + def test_malformed_responses_refused(self): + mutations = [ + lambda r: r["tensorfold"].pop("token_ids"), + lambda r: r["tensorfold"]["token_ids"].__setitem__(0, True), + lambda r: r["tensorfold"].__setitem__("drafts", True), + lambda r: r["usage"].__setitem__("completion_tokens", 7), + lambda r: r.__setitem__("model", "wrong"), + lambda r: r["choices"][0].__setitem__("finish_reason", "error"), + lambda r: r.__setitem__("error", "failure"), + lambda r: r["speculative"].__setitem__("drafted", 2), + ] + for index, mutate in enumerate(mutations): + observations = copy.deepcopy(self.equal) + mutate(observations["fixture:2:plain"]["response"]) + with self.subTest(mutation=index), self.assertRaises(ValueError): + self.evaluate(observations) + + def test_bad_recorded_logits_refused(self): + mutations = [ + lambda r: r.__setitem__("logits", [15, 16]), + lambda r: r.__setitem__("logits", [float("nan"), 15]), + lambda r: r.__setitem__("logits", [float("inf"), 15]), + lambda r: r.__setitem__("ids", [12, 12]), + lambda r: r.__setitem__("ids", [13, 99]), + lambda r: r.__setitem__("position", 999), + ] + for index, mutate in enumerate(mutations): + recording = copy.deepcopy(self.recording) + mutate(recording["traces"][0]["top2"][2]) + with self.subTest(mutation=index), self.assertRaises(ValueError): + harness.select_prompts(recording) + + def test_bad_profiles_refused(self): + mutations = [ + lambda p: p[1]["identity"].__setitem__("tokenizer", "different"), + lambda p: p[1].__setitem__("depth", 1), + lambda p: p[1].__setitem__("url", p[0]["url"] + "/"), + lambda p: p[1].__setitem__("url", p[0]["url"] + "/v1/completions"), + lambda p: p[1].__setitem__("url", "http://secret@fixture.invalid"), + lambda p: p[1].__setitem__("url", "http://fixture.invalid?key=secret"), + ] + for index, mutate in enumerate(mutations): + profiles = copy.deepcopy(self.profiles) + mutate(profiles) + with self.subTest(mutation=index), self.assertRaises(ValueError): + harness.profiles_for(profiles, self.recording["identity"], (1, 4, 8)) + + def test_distinct_prefix_selection_is_bounded(self): + trace = self.recording["traces"][0] + trace["top2"][3]["logits"] = [16, 15.99] + cases = harness.select_prompts(self.recording, limit=1, lookback=0, tokens=4) + self.assertEqual(len(cases), 1) + self.assertEqual(cases[0]["id"], "fixture:3") + self.assertEqual(cases[0]["prompt"], [1, 2, 10, 11, 12]) + self.assertEqual(cases[0]["tokens"], [13, 14, 15, 16]) + + def test_bad_per_run_capture_refused(self): + observations = copy.deepcopy(self.equal) + observations["fixture:2:4"]["top2"][2]["ids"] = [99, 12] + with self.assertRaisesRegex(ValueError, "argmax disagree"): + self.evaluate(observations) + + def test_redirect_is_refused(self): + with self.assertRaisesRegex(ValueError, "redirect refused"): + harness.NoRedirect().redirect_request(None, None, 302, "found", {}, "http://fixture.invalid") + + def test_cli_replay_is_offline_and_exit_codes_are_strict(self): + with tempfile.TemporaryDirectory() as directory: + output = Path(directory) / "result.json" + for filename, code, status in [("equal.json", 0, "pass"), ("divergent.json", 1, "divergent")]: + stdout = io.StringIO() + with patch.object(harness, "live_fetch", side_effect=AssertionError("unexpected HTTP")): + with contextlib.redirect_stdout(stdout): + actual = harness.main(["--recording", str(FIXTURES / "recording.json"), "--profiles", + str(FIXTURES / "profiles.json"), "--replay", str(FIXTURES / filename), + "--lookback", "2", "--tokens", "8", "--output", str(output)]) + self.assertEqual(actual, code) + report = json.loads(output.read_text()) + self.assertEqual(report["status"], status) + self.assertEqual(report["mode"], "recorded-replay") + self.assertEqual(len(stdout.getvalue().splitlines()), 1) + self.assertIn("input_sha256", report) + + def test_cli_errors_are_json_and_one_summary_line(self): + with tempfile.TemporaryDirectory() as directory: + output = Path(directory) / "result.json" + stdout = io.StringIO() + with contextlib.redirect_stdout(stdout): + code = harness.main(["--recording", str(FIXTURES / "recording.json"), "--profiles", + str(FIXTURES / "profiles.json"), "--depths", "1,1", "--replay", + str(FIXTURES / "equal.json"), "--output", str(output)]) + self.assertEqual(code, 2) + self.assertEqual(json.loads(output.read_text())["status"], "error") + self.assertEqual(len(stdout.getvalue().splitlines()), 1) + + def test_nonfinite_json_refused(self): + with tempfile.TemporaryDirectory() as directory: + source = Path(directory) / "nonfinite.json" + source.write_text('{"logit": NaN}') + with self.assertRaisesRegex(ValueError, "nonfinite"): + harness.load(source) + + def test_served_client_posts_exact_ids_without_network(self): + class Reply: + def __enter__(self): + return self + + def __exit__(self, *args): + return False + + def read(self, size): + return json.dumps(self_response).encode() + + self_response = self.equal["fixture:2:plain"]["response"] + case, = harness.select_prompts(self.recording, lookback=2, tokens=8) + body = harness.request(case, self.profiles[0], False) + with patch.object(harness.urllib.request, "build_opener") as build: + build.return_value.open.return_value = Reply() + observation = harness.live_fetch(12)(self.profiles[0], body, case["id"], "plain") + (request,), kwargs = build.return_value.open.call_args + self.assertEqual(request.full_url, "http://fixture.invalid:8001/v1/completions") + self.assertEqual(request.get_method(), "POST") + self.assertEqual(json.loads(request.data), body) + self.assertEqual(kwargs, {"timeout": 12}) + self.assertEqual(observation["response"], self_response) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/zig/host_tests_test.py b/tools/zig/host_tests_test.py index 7d6bd0d8610..010e6e46665 100644 --- a/tools/zig/host_tests_test.py +++ b/tools/zig/host_tests_test.py @@ -15,10 +15,6 @@ "check-release-paths", "test-startup-states-timing", "test-imprint-ops-timing", - "test-metal-residency-owners-host", - "test-qwen35-draft-frame-host", - "test-qwen35-frame-invalidation-host", - "test-gradient-serving", ) diff --git a/tools/zig/idol_case.py b/tools/zig/idol_case.py new file mode 100644 index 00000000000..9f356ff0472 --- /dev/null +++ b/tools/zig/idol_case.py @@ -0,0 +1,257 @@ +#!/usr/bin/env python3 +"""Idol reference cases for tf-idol from the publisher's idol-sdk (torch): the denoiser's schedule and its blocks.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import sys +import time +from pathlib import Path + +USAGE = """\ + case WEIGHTS SDK OUT --features F [F] noise, each step's input and both velocities, the final sample + case WEIGHTS SDK OUT --synthetic-conditioning --cond-seed N + the same, on feature1 and feature2 drawn N(0, 1) from seed N (no encoders) + blocks WEIGHTS SDK CASE [--step S] every block's rows at step S, and each block in float32 on its input + exact WEIGHTS SDK CASE [--steps N] both velocities in float32 on the case's first N inputs (the ruler) +WEIGHTS is a speridlabs/idol snapshot; SDK an idol-sdk checkout at the pinned commit. F holds feature1 (DINOv3 rows +[1, 4101, 1280]) and feature2 (FLUX.2 VAE rows [1, 4101, 128]), in one file or two, as the SDK's ImageEncoder returns. +""" + +SDK_COMMIT = "4702a7f00850e34b6e83a2170cc123c3e9570744" +SDK_SHA256 = { + "idol/models/dit.py": "fbe725cc478b0acd245d9404ac8d9df327ebfbf79fe51c954d94b005c5bd6af4", + "idol/models/layers.py": "2dbf24107396194636c9a2e89e7acee1bcf91b14dba1b4cde0318cb85b3f482f", + "idol/sampler.py": "532987b5599be678361c2fcf566335bb3e1b0171696f985818d10b7460bfc8b0", +} +WEIGHTS_REVISION = "2731c2291fc65a797c5cb627a5e5526fc1490902" +DENOISER_ARGS = {"q_token_length": 8192, "in_channels": 16, "cam_channels": 5, "model_channels": 1024, + "cond_channels": 1280, "cond2_channels": 128, "num_blocks": 24, "num_refiner_blocks": 2, + "num_heads": 16, "mlp_ratio": 4} + + +def sdk(path: str): + """The SDK's denoiser and sampler, imported once each file used has the pinned commit's sha256.""" + root = Path(path) + for name, want in SDK_SHA256.items(): + digest = hashlib.sha256((root / name).read_bytes()).hexdigest() + if digest != want: + sys.exit(f"{root / name} has sha256 {digest}; this tool runs only idol-sdk {SDK_COMMIT[:12]}'s ({want})") + sys.path.insert(0, str(root)) + from idol.models.dit import LatentSeqMMFlowModel + from idol.sampler import sample_flow + return LatentSeqMMFlowModel, sample_flow + + +def denoiser(weights: str, sdk_dir: str, device: str): + """The SDK's denoiser with the snapshot's weights, strictly loaded, as IdolPipeline builds it.""" + import torch + from safetensors.torch import load_file + + model_cls, _ = sdk(sdk_dir) + config = json.loads((Path(weights) / "config.json").read_text()) + args = config["denoiser"]["args"] + if config["denoiser"]["name"] != "LatentSeqMMFlowModel" or args != DENOISER_ARGS: + sys.exit(f"{weights}/config.json is not speridlabs/idol {WEIGHTS_REVISION[:12]}'s denoiser") + model = model_cls(**args) + model.load_state_dict(load_file(str(Path(weights) / "denoiser.safetensors")), strict=True) + return model.eval().requires_grad_(False).to(torch.device(device)) + + +def features(paths: list[str]): + """feature1 and feature2 [1, 4101, C] float32 from one or two safetensors files.""" + from safetensors.torch import load_file + + found = {} + for path in paths: + found.update(load_file(path)) + for key, width in (("feature1", 1280), ("feature2", 128)): + if key not in found or tuple(found[key].shape) != (1, 4101, width): + sys.exit(f"the features need {key} [1, 4101, {width}]") + return found["feature1"].float(), found["feature2"].float() + + +def synthetic(seed: int): + """feature1 and feature2 [1, 4101, C] float32 drawn N(0, 1) from `seed`, in that order, in place of the encoders.""" + import torch + + gen = torch.Generator("cpu").manual_seed(seed) + return tuple(torch.randn((1, 4101, width), generator=gen, dtype=torch.float32) for width in (1280, 128)) + + +def condition(f1, f2, device: str): + """The sampler's cond and neg_cond (both streams zeroed), as IdolPipeline passes them.""" + from tensordict import TensorDict + + cond = TensorDict({"feature1": f1, "feature2": f2}, batch_size=1, device=device) + return cond, cond.apply(lambda x: x * 0) + + +def sample(latent, camera, device: str): + """The sampler's TensorDict for one latent [8192, 16] and camera [5].""" + from tensordict import TensorDict + + return TensorDict({"latent": latent[None].to(device), "camera": camera.view(1, 1, 5).to(device)}, batch_size=1, + device=device) + + +def flush(device: str) -> None: + import torch + + if device == "mps": + torch.mps.synchronize() + + +def case(args) -> int: + import torch + from safetensors.torch import save_file + + out = Path(args.out_dir) + out.mkdir(parents=True, exist_ok=True) + model = denoiser(args.weights, args.sdk, args.device) + _, sample_flow = sdk(args.sdk) + f1, f2 = synthetic(args.cond_seed) if args.synthetic_conditioning else features(args.features) + cond, neg = condition(f1, f2, args.device) + gen = torch.Generator("cpu").manual_seed(args.seed) + latent = torch.randn((8192, 16), generator=gen, dtype=torch.float32) + camera = torch.randn((5,), generator=gen, dtype=torch.float32) + calls = [] + forward = model.forward + + def recorded(x, t, c): + mark = time.perf_counter() + v = forward(x, t, c) + flush(args.device) + calls.append({"latent": x["latent"][0].float().cpu(), "camera": x["camera"][0, 0].float().cpu(), + "t": float(t[0]), "negative": bool(c["feature1"].abs().max() == 0), + "v": v["latent"][0].float().cpu(), "v_camera": v["camera"][0, 0].float().cpu(), + "s": time.perf_counter() - mark}) + return v + + model.forward = recorded + with torch.no_grad(): + final = sample_flow(model, sample(latent, camera, args.device), cond=cond, neg_cond=neg, steps=args.steps, + rescale_t=args.rescale_t, cfg_strength=args.cfg, verbose=False, batch_cfg=False) + model.forward = forward + pos, negs = calls[0::2], calls[1::2] + if args.cfg <= 0 or any(c["negative"] for c in pos) or not all(c["negative"] for c in negs): + sys.exit("the sampler's calls are not (conditional, negative) pairs") + stack = lambda rows, key: torch.stack([r[key] for r in rows]).contiguous() + tensors = {"feature1": f1[0].contiguous(), "feature2": f2[0].contiguous(), "latent": latent, "camera": camera, + "timesteps": torch.tensor([c["t"] for c in pos], dtype=torch.float32), + "inputs": stack(pos, "latent"), "inputs_camera": stack(pos, "camera"), + "velocity": stack(pos, "v"), "velocity_camera": stack(pos, "v_camera"), + "velocity_negative": stack(negs, "v"), "velocity_negative_camera": stack(negs, "v_camera"), + "sample": final["latent"][0].float().cpu().contiguous(), + "sample_camera": final["camera"][0, 0].float().cpu().contiguous()} + save_file(tensors, str(out / "case.safetensors")) + meta = {"seed": args.seed, "steps": args.steps, "cfg": args.cfg, "rescale_t": args.rescale_t, + "device": args.device, "torch": torch.__version__, "sdk": SDK_COMMIT, "weights": WEIGHTS_REVISION, + "conditioning": {"synthetic": True, "cond_seed": args.cond_seed} if args.synthetic_conditioning else + {"synthetic": False}, "torch_forward_s": [round(c["s"], 3) for c in calls]} + (out / "reference.json").write_text(json.dumps(meta, indent=1) + "\n") + times = sorted(meta["torch_forward_s"]) + print(json.dumps({k: v for k, v in meta.items() if k != "torch_forward_s"} | {"median_forward_s": times[len(times) // 2]})) + return 0 + + +def blocks(args) -> int: + """Each block's rows in the conditional forward at one step, and each block again in float32 on the same input.""" + import copy + + import torch + from safetensors.torch import load_file, save_file + + case_dir = Path(args.case_dir) + data = load_file(str(case_dir / "case.safetensors")) + model = denoiser(args.weights, args.sdk, args.device) + cond, _ = condition(data["feature1"][None], data["feature2"][None], args.device) + seen = {} + + def keep(name): + def hook(_module, _inputs, output): + seen[name] = output.detach().contiguous() + return hook + + stages = [("noise_refiner", model.noise_refiner), ("context_refiner", model.context_refiner), ("block", model.blocks)] + hooks = [m.register_forward_hook(keep(f"{name}.{i}")) for name, layers in stages for i, m in enumerate(layers)] + x = sample(data["inputs"][args.step], data["inputs_camera"][args.step], args.device) + t = data["timesteps"][args.step : args.step + 1].to(args.device) + with torch.no_grad(): + v = model(x, t, cond) + for h in hooks: + h.remove() + # the ruler: each joint block in float32 on the fp16 rows the SDK fed it, with an unrounded modulation + t_emb = model.t_embedder(t) + t_mod = model.adaLN_modulation(t_emb).float() + exact = {} + for i in range(1, len(model.blocks)): + block = copy.deepcopy(model.blocks[i]).float() + h = seen[f"block.{i - 1}"].float() + exact[f"block.{i}"] = block(h, mod=t_mod, rotary_emb=model.repo_layers[i](h))[0].cpu().contiguous() + del block + tensors = {k: x[0].cpu().contiguous() for k, x in seen.items()} + tensors["velocity"] = v["latent"][0].float().cpu().contiguous() + tensors["velocity_camera"] = v["camera"][0, 0].float().cpu().contiguous() + save_file(tensors, str(case_dir / f"blocks{args.step}.safetensors")) + save_file(exact, str(case_dir / f"blocks{args.step}_f32.safetensors")) + drift = (tensors["velocity"] - data["velocity"][args.step]).abs().max().item() + print(json.dumps({"step": args.step, "tensors": len(tensors), "velocity_max_abs_vs_case": drift})) + return 0 + + +def exact(args) -> int: + """Both branches in float32 throughout on the case's own inputs: the fp16 reference's distance from exact.""" + import torch + from safetensors.torch import load_file, save_file + + case_dir = Path(args.case_dir) + data = load_file(str(case_dir / "case.safetensors")) + model = denoiser(args.weights, args.sdk, args.device).float() + model.dtype = torch.float32 + cond, neg = condition(data["feature1"][None], data["feature2"][None], args.device) + keys = ("velocity", "velocity_camera", "velocity_negative", "velocity_negative_camera") + rows = {k: [] for k in keys} + with torch.no_grad(): + for s in range(min(args.steps, data["inputs"].shape[0])): + x = sample(data["inputs"][s], data["inputs_camera"][s], args.device) + t = data["timesteps"][s : s + 1].to(args.device) + for prefix, c in (("velocity", cond), ("velocity_negative", neg)): + v = model(x, t, c) + rows[prefix].append(v["latent"][0].float().cpu()) + rows[prefix + "_camera"].append(v["camera"][0, 0].float().cpu()) + save_file({k + "_f32": torch.stack(v).contiguous() for k, v in rows.items()}, str(case_dir / "exact.safetensors")) + print(json.dumps({"steps": len(rows["velocity"])})) + return 0 + + +def main(argv: list[str]) -> int: + ap = argparse.ArgumentParser(description=__doc__, epilog=USAGE, formatter_class=argparse.RawDescriptionHelpFormatter) + sub = ap.add_subparsers(dest="cmd", required=True) + for name in ("case", "blocks", "exact"): + p = sub.add_parser(name) + p.add_argument("weights") + p.add_argument("sdk") + p.add_argument("out_dir" if name == "case" else "case_dir") + p.add_argument("--device", default="mps", choices=("mps", "cpu", "cuda")) + if name == "case": + given = p.add_mutually_exclusive_group(required=True) + given.add_argument("--features", nargs="+") + given.add_argument("--synthetic-conditioning", action="store_true") + p.add_argument("--cond-seed", type=int, default=0) + p.add_argument("--seed", type=int, default=42) + p.add_argument("--steps", type=int, default=50) + p.add_argument("--cfg", type=float, default=3.0) + p.add_argument("--rescale-t", type=float, default=3.0) + elif name == "blocks": + p.add_argument("--step", type=int, default=0) + else: + p.add_argument("--steps", type=int, default=50) + args = ap.parse_args(argv) + return {"case": case, "blocks": blocks, "exact": exact}[args.cmd](args) + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/tools/zig/qwen27_http_gate.py b/tools/zig/qwen27_http_gate.py index 9c80e3b5ef6..3d7e08f2c22 100644 --- a/tools/zig/qwen27_http_gate.py +++ b/tools/zig/qwen27_http_gate.py @@ -21,8 +21,8 @@ def check(reply, ids, tokens, drafted): if runtime["token_sha"] != digest or runtime["drafts"] is not drafted: raise ValueError("served token SHA or draft mode differs from CLI") speculative = reply["speculative"] - if drafted and (speculative["rounds"] <= 0 or speculative["drafted"] <= 0): - raise ValueError("drafted server request did not exercise draft verification") + if drafted and (speculative["rounds"] <= 0 or speculative["drafted"] <= 0 or speculative["accepted"] <= 0): + raise ValueError("drafted server request did not exercise draft verification (no draft proposed or accepted)") return {"token_sha": digest, "drafts": drafted, "usage": usage, "runtime": runtime, "speculative": speculative} diff --git a/tools/zig/zig_cache_restat_test.py b/tools/zig/zig_cache_restat_test.py index 4c46a9b9b3f..da557cf4bf9 100644 --- a/tools/zig/zig_cache_restat_test.py +++ b/tools/zig/zig_cache_restat_test.py @@ -1,4 +1,5 @@ """A restored build cache stays cached when only file ids changed, and still misses when contents changed.""" +import ast import os import re from pathlib import Path @@ -50,9 +51,11 @@ def setUp(self): (self.root / "build.zig").write_text(BUILD, newline="\n") for path, text in SOURCES.items(): (self.root / path).write_text(text, newline="\n") - lib = Path(self.zig).resolve().parent / "lib" + info = self.run_zig([self.zig, "env"]) + lib = re.search(r'^\s*\.lib_dir = ("(?:[^"\\]|\\.)*"),$', info, re.MULTILINE) + self.assertIsNotNone(lib, "zig env did not report .lib_dir") self.restat_command = [self.zig, "run", "-OReleaseFast", "-mcpu=baseline", str(TOOL), "--", str(self.cache), - str(lib)] + ast.literal_eval(lib[1])] def run_zig(self, command): result = subprocess.run(command, cwd=self.root, env=self.env, capture_output=True, text=True, timeout=300) diff --git a/web/tensorfold_web/engine.py b/web/tensorfold_web/engine.py index 3cdd0828256..3ec69d3e17b 100644 --- a/web/tensorfold_web/engine.py +++ b/web/tensorfold_web/engine.py @@ -287,7 +287,7 @@ def target(self) -> tuple[int, str, str | None]: """The generation, address and key, read together.""" with self.target_lock: - return self.generation, self.settings.engine_url.rstrip("/"), self.key_in_use() + return self.generation, settings_mod.engine_root(self.settings.engine_url), self.key_in_use() def retargeted(self) -> None: """The address or the key changed (the caller holds ``target_lock``): readings begun before are not used.""" diff --git a/web/tensorfold_web/engines.py b/web/tensorfold_web/engines.py index a9186c3dad7..1fbbf73f946 100644 --- a/web/tensorfold_web/engines.py +++ b/web/tensorfold_web/engines.py @@ -7,7 +7,7 @@ import httpx from . import native -from .settings import Settings +from .settings import Settings, engine_root @dataclass @@ -108,7 +108,7 @@ def _json(client: httpx.Client, url: str, headers: dict) -> dict | None: def identify(url: str, *, key: str | None = None, client: httpx.Client | None = None) -> Endpoint: - base = url.rstrip("/").removesuffix("/v1") + base = engine_root(url) headers = {"Authorization": f"Bearer {key}"} if key else {} own = client or httpx.Client(trust_env=False, timeout=3.0) try: diff --git a/web/tensorfold_web/replay.py b/web/tensorfold_web/replay.py index d238a334934..5461a5cac95 100644 --- a/web/tensorfold_web/replay.py +++ b/web/tensorfold_web/replay.py @@ -52,7 +52,7 @@ def _start(self, cid: str, target: dict) -> dict: if not isinstance(target.get("url"), str) or not target.get("model"): raise ValueError("another engine needs its address and a model") # a user or password in the address would be kept in the replay's title, settings and exports - url = settings_mod._engine_url(target["url"]).removesuffix("/v1") + url = settings_mod.engine_root(settings_mod._engine_url(target["url"])) target = {**target, "url": url} base, key, model, engine = url, target.get("key") or None, target["model"], target.get("label") or url else: diff --git a/web/tensorfold_web/server.py b/web/tensorfold_web/server.py index 32129cc4f42..edf669eafec 100644 --- a/web/tensorfold_web/server.py +++ b/web/tensorfold_web/server.py @@ -96,7 +96,7 @@ def create_app(*, settings: settings_mod.Settings | None = None, engine: Engine dl = Downloads() - proxy = Proxy(lambda: s.engine_url, eng.key_in_use, target=lambda: eng.target()[1:]) + proxy = Proxy(lambda: settings_mod.engine_root(s.engine_url), eng.key_in_use, target=lambda: eng.target()[1:]) def bench_target() -> tuple[str, str | None, str | None]: h = eng.status() @@ -104,7 +104,7 @@ def bench_target() -> tuple[str, str | None, str | None]: if h.status == "running": # a bare /health behind a key names no model: /v1/models does model = h.model or next(iter(engines.identify(s.engine_url, key=eng.key_in_use()).models), None) - return s.engine_url.rstrip("/").removesuffix("/v1"), eng.key_in_use(), model + return settings_mod.engine_root(s.engine_url), eng.key_in_use(), model runner = bench.Bench(bench_store or bench.Store(settings_mod.config_dir() / "bench.sqlite"), bench_target) @@ -410,7 +410,7 @@ def lesson_target() -> living.Target: h = eng.status() if h.status != "running" or not served_copy(): raise RuntimeError("serve a living copy first (Teach, then Serve)") - base = s.engine_url.rstrip("/").removesuffix("/v1") + base = settings_mod.engine_root(s.engine_url) return living.Target(base, eng.key_in_use(), h.model or eng.model or "") # left halfway by a stopped TensorFold Web @@ -470,7 +470,7 @@ def settled(name: str) -> None: def engine_get(path: str) -> httpx.Response: key = eng.key_in_use() - return httpx.get(trust_env=False, url=s.engine_url.rstrip("/").removesuffix("/v1") + path, timeout=10.0, + return httpx.get(trust_env=False, url=settings_mod.engine_root(s.engine_url) + path, timeout=10.0, headers={"Authorization": f"Bearer {key}"} if key else {}) def no_store(resp: Response) -> Response: diff --git a/web/tensorfold_web/server_connect.py b/web/tensorfold_web/server_connect.py index 6b64f6f4c04..be96ef2b60a 100644 --- a/web/tensorfold_web/server_connect.py +++ b/web/tensorfold_web/server_connect.py @@ -20,6 +20,7 @@ connect_ctx, lan_hostname, ) +from .settings import engine_root def install(app, eng, s, token) -> None: @@ -27,7 +28,8 @@ def install(app, eng, s, token) -> None: def connect(where: str = "here", relay: str = ""): h = eng.last_health or eng.health() - c = connect_ctx(s.engine_url, h.model if h else None, share=s.share, api_key=eng.key_in_use()) + root = engine_root(s.engine_url) + c = connect_ctx(root, h.model if h else None, share=s.share, api_key=eng.key_in_use()) if where == "away": u = urlsplit(relay) # a name or address and a port, nothing else: the recipes paste it into a shell @@ -38,10 +40,10 @@ def connect(where: str = "here", relay: str = ""): c = recipes.Ctx(base=base, key=s.api_key or eng.key_in_use() or "YOUR-KEY", model=c.model, docker_base=base, away=True) # asked of the engine itself (on its own address): a coding agent needs a long window, and its recipe says so - window = recipes.served_window(recipes.Ctx(base=s.engine_url.rstrip("/").removesuffix("/v1"), + window = recipes.served_window(recipes.Ctx(base=root, key=eng.key_in_use() or "local", model=c.model)) \ if h and h.status == "running" else None - return {"engine_url": s.engine_url, "share": s.share, + return {"engine_url": root, "share": s.share, "lan_url": f"http://{lan_hostname()}:{s.engine_port()}" if s.share else None, # the key that opens the engine now; a new one waiting for the restart is not copied before it works "api_key": eng.key_in_use(), "key_pending_restart": eng.key_pending_restart(), @@ -62,13 +64,13 @@ def connect_test(body: dict[str, Any]): if h.status != "running": raise HTTPException(409, "no model is being served; start one from Models") model = h.model or next(iter(engines.identify(s.engine_url, key=eng.key_in_use()).models), None) - c = recipes.Ctx(base=s.engine_url.rstrip("/").removesuffix("/v1"), key=eng.key_in_use() or "local", + c = recipes.Ctx(base=engine_root(s.engine_url), key=eng.key_in_use() or "local", model=model or "") return recipes.test(rec, c) @app.get("/api/connect/compose/open-webui") def connect_compose(): h = eng.last_health or eng.health() - c = connect_ctx(s.engine_url, h.model if h else None, share=s.share, api_key=eng.key_in_use()) + c = connect_ctx(engine_root(s.engine_url), h.model if h else None, share=s.share, api_key=eng.key_in_use()) return Response(recipes.compose(c), media_type="text/yaml", headers={"Content-Disposition": 'attachment; filename="docker-compose.yml"'}) diff --git a/web/tensorfold_web/server_engine.py b/web/tensorfold_web/server_engine.py index 8f1ece2e637..155adb80954 100644 --- a/web/tensorfold_web/server_engine.py +++ b/web/tensorfold_web/server_engine.py @@ -87,7 +87,7 @@ def access(request: Request): open_without_key = None if not engine_local: # does the engine answer anyone, without its key? try: - r = httpx.get(trust_env=False, url=s.engine_url.rstrip("/") + "/v1/models", timeout=2.0) + r = httpx.get(trust_env=False, url=settings_mod.engine_root(s.engine_url) + "/v1/models", timeout=2.0) open_without_key = r.status_code == 200 except httpx.HTTPError: open_without_key = None diff --git a/web/tensorfold_web/server_lessons.py b/web/tensorfold_web/server_lessons.py index 292d6aab35e..020e67e4b5a 100644 --- a/web/tensorfold_web/server_lessons.py +++ b/web/tensorfold_web/server_lessons.py @@ -16,6 +16,7 @@ living_versions, ) from .gate import Busy +from .settings import engine_root def install(app, cat, chore, chore_cancel, chore_lock, copy_name, creating, eng, gate, launch, lesson_target, run_chore, s, served_copy, teacher, wait_running) -> None: @@ -241,7 +242,7 @@ def living_facts(name: str): graph: dict = {} if served_copy() == name: try: - r = httpx.get(trust_env=False, url=s.engine_url.rstrip("/").removesuffix("/v1") + "/v1/slide/graph", timeout=5.0, + r = httpx.get(trust_env=False, url=engine_root(s.engine_url) + "/v1/slide/graph", timeout=5.0, headers={"Authorization": f"Bearer {eng.key_in_use()}"} if eng.key_in_use() else {}) graph = r.json() if r.status_code == 200 else {} except (httpx.HTTPError, ValueError): diff --git a/web/tensorfold_web/settings.py b/web/tensorfold_web/settings.py index 979185d6cbc..9024acc9eb0 100644 --- a/web/tensorfold_web/settings.py +++ b/web/tensorfold_web/settings.py @@ -23,6 +23,17 @@ def config_dir() -> Path: return Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / "tensorfold-web" +def engine_root(url: str) -> str: + """Accept an OpenAI API base URL while keeping the server's reverse-proxy prefix.""" + + with contextlib.suppress(ValueError): + parts = urlsplit(url) + path = parts.path.rstrip("/") + if parts.scheme in ("http", "https") and parts.netloc and path.endswith("/v1"): + return parts._replace(path=path.removesuffix("/v1")).geturl() + return url.rstrip("/") + + @dataclass class Settings: engine_url: str = DEFAULT_ENGINE diff --git a/web/tests/test_engine_base_url.py b/web/tests/test_engine_base_url.py new file mode 100644 index 00000000000..c83d9093301 --- /dev/null +++ b/web/tests/test_engine_base_url.py @@ -0,0 +1,61 @@ +import json + +import httpx +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient + +from tensorfold_web import engine, gate, recipes, server_connect, server_settings, settings + + +@pytest.mark.parametrize("source", ["settings-api", "saved-on-disk"]) +@pytest.mark.parametrize(("address", "prefix"), [ + ("http://fixture.test/proxy", "/proxy"), + ("http://fixture.test/proxy/v1/", "/proxy"), + ("http://fixture.test/proxy/v1/v1", "/proxy/v1"), +]) +def test_compatible_engine_address_may_end_in_v1(tmp_path, monkeypatch, source, address, prefix): + def respond(request): + if request.url.path == prefix + "/health": + return httpx.Response(200, json={"status": "ok"}) + if request.url.path == prefix + "/v1/models": + return httpx.Response(200, json={"data": [{"id": "fixture"}]}) + return httpx.Response(404) + + monkeypatch.setattr(settings, "config_dir", lambda: tmp_path) + if source == "saved-on-disk": + settings.path().write_text(json.dumps({"engine_url": address, "remote": True})) + cfg = settings.load() + eng = engine.Engine(cfg) + eng._client.close() + eng._client = httpx.Client(transport=httpx.MockTransport(respond)) + try: + monkeypatch.setattr(recipes, "served_window", lambda _: None) + app = FastAPI() + server_settings.install(app, eng, gate.Gate(), cfg, lambda: settings.save(cfg), cfg.to_dict) + server_connect.install(app, eng, cfg, None) + with TestClient(app) as client: + if source == "settings-api": + saved = client.put("/api/settings", json={"engine_url": address, "remote": True}) + assert saved.status_code == 200 + assert settings.load().engine_url == (address.rstrip("/") if source == "settings-api" else address) + health = eng.health() + connect = client.get("/api/connect").json() + root = "http://fixture.test" + prefix + assert connect["engine_url"] == root + jan = next(r for r in connect["snippets"] if r["id"] == "jan") + assert (health.status, health.model, jan["snippet"].splitlines()[1]) == ( + "running", "fixture", "Base URL " + root + "/v1" + ) + finally: + eng._client.close() + + +@pytest.mark.parametrize(("address", "expected"), [ + ("http://v1", "http://v1"), + ("http://v1/v1/", "http://v1"), + ("https://fixture.test/proxy/v10", "https://fixture.test/proxy/v10"), + ("https://[::1]:8080/proxy/v1", "https://[::1]:8080/proxy"), +]) +def test_engine_url_normalizes_the_api_path_without_changing_the_authority(address, expected): + assert settings.engine_root(address) == expected diff --git a/zig/build/checkpoint_io_host.zig b/zig/build/checkpoint_io_host.zig index 583d42f9b1e..4bba10bb4e9 100644 --- a/zig/build/checkpoint_io_host.zig +++ b/zig/build/checkpoint_io_host.zig @@ -13,6 +13,8 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget) void { .dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = core, .filters = &.{"part:"} })).step); if (mode == .debug) b.step("test-fp8-block-host", "The shared block-FP8 reader and exact scale widening (core/quant/fp8.zig)") .dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = core, .filters = &.{"fp8 block:"} })).step); + if (mode == .debug) b.step("test-gptq-reader-host", "The shared GPTQ reader on a synthetic checkpoint, against binary64 (core/quant/gptq.zig)") + .dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = core, .filters = &.{"gptq:"} })).step); const qwen = b.createModule(.{ .root_source_file = b.path("zig/src/families/qwen3_5/loader.zig"), .target = target, .optimize = mode, .link_libc = true, .imports = &.{.{ .name = "core", .module = core }} }); step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = qwen, .filters = &.{"Qwen shard integrity:"} })).step); } diff --git a/zig/build/cluster_host.zig b/zig/build/cluster_host.zig index a68cdf5f000..338029250c3 100644 --- a/zig/build/cluster_host.zig +++ b/zig/build/cluster_host.zig @@ -1,4 +1,4 @@ -//! The cluster's membership and bring-up over fake links, on the build host with no GPU. +//! Cluster membership, bring-up, and config validate on the build host with no GPU. const std = @import("std"); pub fn steps(b: *std.Build) void { @@ -8,5 +8,14 @@ pub fn steps(b: *std.Build) void { const canon = @import("cuda_engines.zig").canonModule(b, host, .debug); const bringup = b.createModule(.{ .root_source_file = b.path("zig/src/cluster/bringup.zig"), .target = host, .link_libc = true, .imports = &.{ .{ .name = "fabric", .module = fabric }, .{ .name = "canon", .module = canon } } }); const run = b.addRunArtifact(b.addTest(.{ .root_module = bringup })); - b.step("test-cluster-membership-host", "Cluster membership and bring-up over fake links, without a GPU").dependOn(&run.step); + const core = b.createModule(.{ .root_source_file = b.path("zig/src/core/root.zig"), .target = host, .link_libc = true }); + core.addImport("gpu_memory", @import("gpu_memory.zig").module(b, host)); + core.addImport("tokenizer", b.createModule(.{ .root_source_file = b.path("zig/src/core/tokenizer/tokenizer.zig"), .target = host, .link_libc = true })); + const validate = b.createModule(.{ .root_source_file = b.path("zig/src/cluster/validate.zig"), .target = host, .link_libc = true, .imports = &.{ .{ .name = "fabric", .module = fabric }, .{ .name = "canon", .module = canon }, .{ .name = "core", .module = core } } }); + const validate_run = b.addRunArtifact(b.addTest(.{ .root_module = validate, .filters = &.{"config validate:"} })); + const step = b.step("test-cluster-membership-host", "Cluster membership, bring-up, and config validate, without a GPU"); + step.dependOn(&run.step); + step.dependOn(&validate_run.step); + const exe = b.addExecutable(.{ .name = "tf-config-validate", .root_module = b.createModule(.{ .root_source_file = b.path("zig/src/cluster/validate_main.zig"), .target = host, .link_libc = true, .imports = &.{ .{ .name = "fabric", .module = fabric }, .{ .name = "canon", .module = canon }, .{ .name = "core", .module = core } } }) }); + b.step("tf-config-validate", "Validate a cluster.json without planning or probes").dependOn(&b.addInstallArtifact(exe, .{}).step); } diff --git a/zig/build/cuda_server_host.zig b/zig/build/cuda_server_host.zig index 7eb27628359..42986c3230d 100644 --- a/zig/build/cuda_server_host.zig +++ b/zig/build/cuda_server_host.zig @@ -68,6 +68,7 @@ pub fn steps(b: *std.Build, host: std.Build.ResolvedTarget, cuda: *std.Build.Mod media_gate.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = mods.core, .filters = &.{ "qwen_vl", "video" } })).step); b.step("test-http-limits-host", "Total HTTP read deadlines and connection admission without shaders").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{"HTTP limits:"} })).step); b.step("test-server-recovery-host", "Incomplete replies, token allocation and bounded SSE storage without shaders").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{"Server recovery:"} })).step); + b.step("test-request-journal-host", "The request journal's records, rotation and crash quarantine on a fake engine").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{"request journal:"} })).step); b.step("test-prompt-interior-host", "Last-user metadata excludes later messages without shaders").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{"interior prompt:"} })).step); b.step("test-cors-template-host", "Exact CORS and special-preserving template route regressions").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{ "CORS", "apply-template:" } })).step); b.step("test-ocr-host", "OCR route readers, shared page steps and dialects without a GPU").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{"ocr "} })).step); diff --git a/zig/build/drama3_host.zig b/zig/build/drama3_host.zig index 6a3f3a3dbeb..89b98e98176 100644 --- a/zig/build/drama3_host.zig +++ b/zig/build/drama3_host.zig @@ -26,7 +26,7 @@ pub fn native(b: *std.Build, step: *std.Build.Step, family: *std.Build.Module, c if (family.import_table.get("metal")) |runtime| mod.addImport("metal", runtime); if (cuda) |c| mod.addImport("cuda", c); step.dependOn(&b.addObject(.{ .name = name, .root_module = mod }).step); - const tests = b.addTest(.{ .root_module = mod, .filters = &.{ "native silence guard:", "drama reference cache:" } }); + const tests = b.addTest(.{ .root_module = mod, .filters = &.{ "native silence guard:", "drama reference cache:", "drama voice encode:" } }); step.dependOn(&b.addRunArtifact(tests).step); } diff --git a/zig/build/hip.zig b/zig/build/hip.zig index 7d0da890b63..558f908831a 100644 --- a/zig/build/hip.zig +++ b/zig/build/hip.zig @@ -168,6 +168,7 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil native_ocr.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host.native.import_table.get("glm_ocr").?, .filters = &.{"GLM-OCR native admission:"} })).step); b.step("test-hip-family-offers-host", "HIP optional native family metadata without device execution").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host.native, .filters = &.{"HIP optional family offers:"} })).step); b.step("test-hip-native-options-host", "Shared HIP native open settings without device execution").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host.serve, .filters = &.{"HIP native options:"} })).step); + @import("hip_followers.zig").steps(b, &.{ host.serve, host.flashnext, host.nemotron }); @import("dots_mocr.zig").hipTests(b, host.hip, test_step); b.step("test-dots-native-host", "dots.mocr registry, reasoning, and unsupported flags without GPU execution").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host.native, .filters = &.{ "dots refuses", "every registered family", "a HIP family declares replies without reasoning" } })).step); @import("lighton_hip.zig").host(b, host.lighton, test_step); @@ -543,7 +544,6 @@ pub fn kernelObjects(b: *std.Build, hipcc: []const u8, hipcc_resolved: []const u } return b.createModule(.{ .root_source_file = files.add("kernels.zig", b.fmt("pub const arch = \"{s}\";\n{s}pub const images = [_][]align(8) const u8{{ {s}}};\n", .{ arch, decls, refs })) }); } - /// The HIP compiler as the build found it, the device bitcode it links, and whether gfx1100 relaxes branches earlier. pub const Hipcc = struct { name: []const u8, resolved: []const u8, device_lib: ?[]const u8, relax_branches: bool = false }; diff --git a/zig/build/hip_followers.zig b/zig/build/hip_followers.zig new file mode 100644 index 00000000000..df1cf2cef1a --- /dev/null +++ b/zig/build/hip_followers.zig @@ -0,0 +1,17 @@ +//! The HIP followers' step parsers: what rank 0 sends a rank above it, taken or refused (#3042, #3081), no device. +const std = @import("std"); + +/// Tests by name: the shared loop's and each family worker's step parsers, and the sender they pair with. +pub const parsers = [_][]const u8{ + "security: a step from the link", // protocol.zig and flashnext/hip/worker.zig (#3042) + "security: rank 0's page and slot", // protocol.zig's bounds the Nemotron and Qwen workers use (#3081) + "security: a begin's cache slot", // flashnext/hip/worker.zig (#3081) + "a sender ", // protocol.zig: what rank 0's Sender puts in a message + "the words of a prefill message", // nemotron/hip/worker.zig +}; + +/// `test-hip-followers-host` over the host modules (hip_serve, Flash Next HIP, Nemotron HIP) with inert kernels. +pub fn steps(b: *std.Build, modules: []const *std.Build.Module) void { + const step = b.step("test-hip-followers-host", "HIP follower step parsers and their refusals without device execution"); + for (modules) |m| step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = m, .filters = &parsers })).step); +} diff --git a/zig/build/host_ci.zig b/zig/build/host_ci.zig index 194972e9a2d..e0b17c692ac 100644 --- a/zig/build/host_ci.zig +++ b/zig/build/host_ci.zig @@ -114,6 +114,7 @@ const linux_hip = [_][]const u8{ "test-hip-blas-host", "test-hip-contract-select-host", "test-hip-family-offers-host", + "test-hip-followers-host", "test-hip-native-options-host", "test-hip-pair-contract-host", "test-lighton-hip-contract-host", diff --git a/zig/build/host_tests.zig b/zig/build/host_tests.zig index 8af5c5dd4b5..ce4b8b73f44 100644 --- a/zig/build/host_tests.zig +++ b/zig/build/host_tests.zig @@ -21,10 +21,6 @@ const exclusions = [_]Exclusion{ .{ .name = "check-release-paths", .reason = "The release-paths CI job checks the separately built release server" }, .{ .name = "test-startup-states-timing", .reason = "Manual disk startup timing seeds up to 100,000 states" }, .{ .name = "test-imprint-ops-timing", .reason = "Manual Imprint timing seeds up to 100,000 learned states" }, - .{ .name = "test-metal-residency-owners-host", .reason = "red on main, #2031 (Qwen27 recording fixture leaves Runner.kv unset)" }, - .{ .name = "test-qwen35-draft-frame-host", .reason = "red on main, #2031 (recording fixture leaves seg_fn uninitialized)" }, - .{ .name = "test-qwen35-frame-invalidation-host", .reason = "red on main, #2031 (same recording fixture as test-qwen35-draft-frame-host)" }, - .{ .name = "test-gradient-serving", .reason = "red on main, #2031 (Flash Next hyper-connection source pin drifted)" }, }; // A holds the long execution suites; B holds the compile-heavy and the remaining standalone suites. diff --git a/zig/build/kernel_contract.zig b/zig/build/kernel_contract.zig index 3a270c4cf47..1e0a4dee504 100644 --- a/zig/build/kernel_contract.zig +++ b/zig/build/kernel_contract.zig @@ -29,6 +29,17 @@ pub fn hostTests(b: *std.Build, family: *std.Build.Step) void { }) })); b.step("test-llama-controls-host", "Llama's source controls plant one fault without a device or shader compiler").dependOn(&llama_controls.step); step.dependOn(&llama_controls.step); + const ling_mla_controls = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/contract/metal_ling_mla_controls.zig"), + .target = b.graph.host, + .optimize = .debug, + .imports = &.{ + .{ .name = "contract", .module = module(b, b.graph.host, .debug) }, + .{ .name = "ling_metal", .module = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/ling/sources.zig") }) }, + }, + }) })); + b.step("test-ling-mla-controls-host", "Ling MLA source controls plant one fault without a device or shader compiler").dependOn(&ling_mla_controls.step); + step.dependOn(&ling_mla_controls.step); const mapping_tf = b.createModule(.{ .root_source_file = b.path("zig/lfm2_mapping_tf.zig"), .imports = &.{ .{ .name = "metal", .module = mapping_stub }, .{ .name = "kernel_sources", .module = mapping_stub }, @@ -156,6 +167,19 @@ pub fn metal(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil }, }) }); b.step("test-ling-kda-gpu", "Ling KDA mixer on this GPU against kda.zig, using k3_kda").dependOn(&b.addRunArtifact(ling_kda_gpu).step); + const ling_mla_gpu = b.addTest(.{ .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/ling_mla_gpu.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .imports = &.{ + .{ .name = "metal", .module = metal_mod }, + .{ .name = "mla", .module = b.createModule(.{ .root_source_file = b.path("zig/src/families/ling/mla.zig") }) }, + .{ .name = "kimi_metallib", .module = kimi_metallib }, + .{ .name = "ling_metal", .module = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/ling/sources.zig") }) }, + }, + }) }); + b.step("test-ling-mla-gpu", "Ling MLA mixer on this GPU around k3_mla, against mla.zig").dependOn(&b.addRunArtifact(ling_mla_gpu).step); } /// Linux: `kernel-contract` runs tf-cuda-test's kernel-contract command (kernels from -Dnvcc or -Dfatbins). diff --git a/zig/build/ling_host.zig b/zig/build/ling_host.zig index b802cbd518a..5706cc8e41c 100644 --- a/zig/build/ling_host.zig +++ b/zig/build/ling_host.zig @@ -7,6 +7,6 @@ pub fn tests(b: *std.Build, target: std.Build.ResolvedTarget, test_step: *std.Bu .target = target, }); const run = b.addRunArtifact(b.addTest(.{ .root_module = root })); - b.step("test-ling-host", "Ling family package: config, names, tiny fixtures, synth JSON, grouped routing, KDA mixer").dependOn(&run.step); + b.step("test-ling-host", "Ling family package: config, names, tiny fixtures, synth JSON, grouped routing, KDA mixer, MLA RoPE and mixer").dependOn(&run.step); test_step.dependOn(&run.step); } diff --git a/zig/build/metal_image_programs.zig b/zig/build/metal_image_programs.zig new file mode 100644 index 00000000000..27530a26948 --- /dev/null +++ b/zig/build/metal_image_programs.zig @@ -0,0 +1,18 @@ +//! The image families' Metal programs (tf-qwen-image, tf-moss-image*, tf-idol, tf-uocr-*) for metal_targets.zig. + +/// One engine program: its executable name, root file, step description and optional C source. +pub const Program = struct { name: []const u8, path: []const u8, about: []const u8, c_source: ?[]const u8 = null }; + +/// Their rows, in their place between tf-qwen-vision and tf-glm-attn-probe. +pub const rows = [_]Program{ + .{ .name = "tf-qwen-image", .path = "zig/tests/qwen_image.zig", .about = "Qwen-Image-2.1's transformer on a reference case: each step compared, then the schedule timed" }, + .{ .name = "tf-moss-image", .path = "zig/tests/moss_image.zig", .about = "MOSS-Image on a reference case: each step's two branches compared, then the guided schedule timed and decoded" }, + .{ .name = "tf-moss-image-encoder", .path = "zig/tests/moss_image_encoder.zig", .about = "MOSS-Image's prompt encoder on a reference case: the ids checked, each step gated against float32, then timed" }, + .{ .name = "tf-moss-image-decoder", .path = "zig/tests/moss_image_decoder.zig", .about = "MOSS-Image's image decoder on latents, gated against float64 beside torch float32, then timed" }, + .{ .name = "tf-moss-image-blocks", .path = "zig/tests/moss_image_blocks.zig", .about = "MOSS-Image's transformer on one step, each block alone gated against float32, repeated byte for byte" }, + .{ .name = "tf-moss-image-generate", .path = "zig/tests/moss_image_generate.zig", .about = "MOSS-Image from options alone: prompts, schedule and noise, then the decoder's picture" }, + .{ .name = "tf-idol", .path = "zig/tests/idol.zig", .about = "Idol's denoiser on a reference case: each step's two branches compared, then the guided schedule timed" }, + .{ .name = "tf-uocr-decode", .path = "zig/tests/uocr/decode.zig", .about = "Unlimited-OCR-2 end to end on a page against a reference dump: prompt, layers, logits, greedy reply" }, + .{ .name = "tf-uocr-vision", .path = "zig/tests/uocr/vision.zig", .about = "Unlimited-OCR-2's image encoder on a reference dump's pixels: SAM gated against float32, CLIP and the projector reported" }, + .{ .name = "tf-uocr-blocks", .path = "zig/tests/uocr/blocks.zig", .about = "Unlimited-OCR-2's image encoder step by step: each SAM block, the neck, CLIP's front, each CLIP layer and the projector alone against float32" }, +}; diff --git a/zig/build/metal_targets.zig b/zig/build/metal_targets.zig index 8ea472b4874..b00995dcff3 100644 --- a/zig/build/metal_targets.zig +++ b/zig/build/metal_targets.zig @@ -11,6 +11,7 @@ const exlr8_build = @import("exlr8.zig"); const server_build = @import("server.zig"); const golden_build = @import("golden.zig"); const contract_build = @import("kernel_contract.zig"); +const image_programs = @import("metal_image_programs.zig"); const metal_lists = @import("metal_source_lists.zig"); const kernels = metal_lists.kernels; const generated = metal_lists.generated; @@ -321,7 +322,7 @@ pub fn metalTargets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: s const pack_cache_run = b.addRunArtifact(pack_cache_cases); b.step("test-flashnext-pack-cache", "CPU-only atomic Flash Next pack cache lifecycle").dependOn(&pack_cache_run.step); test_step.dependOn(&pack_cache_run.step); - const engine_programs = [_]struct { name: []const u8, path: []const u8, about: []const u8, c_source: ?[]const u8 = null }{ + const engine_programs = [_]image_programs.Program{ .{ .name = "tf-qwen35-check", .path = "zig/tests/qwen35_check.zig", .about = "Qwen3.5-2B checkpoint and native operations" }, .{ .name = "tf-qwen35-forward", .path = "zig/tests/qwen35_forward.zig", .about = "Qwen3.5-2B native teacher-forced logits" }, .{ .name = "tf-qwen35-exact", .path = "zig/tests/qwen35_exact.zig", .about = "Qwen3.5-2B forward and committed-state exactness" }, @@ -357,15 +358,7 @@ pub fn metalTargets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: s .{ .name = "tf-glm-vision", .path = "zig/tests/glm_vision.zig", .about = "GLM-5.3-Flash's image tower on an image or a reference dump's patches, compared with the dump" }, .{ .name = "tf-glm-video", .path = "zig/tests/glm_video.zig", .about = "GLM-5.3-Flash's video preparation on a clip (libtfvideo), written for tools/zig/glm_video_fixtures.py" }, .{ .name = "tf-qwen-vision", .path = "zig/tests/qwen_vision.zig", .about = "The Qwen-VL tower on picture files: patches, grids and merged rows written for a float32 reference" }, - .{ .name = "tf-qwen-image", .path = "zig/tests/qwen_image.zig", .about = "Qwen-Image-2.1's transformer on a reference case: each step compared, then the schedule timed" }, - .{ .name = "tf-moss-image", .path = "zig/tests/moss_image.zig", .about = "MOSS-Image on a reference case: each step's two branches compared, then the guided schedule timed and decoded" }, - .{ .name = "tf-moss-image-encoder", .path = "zig/tests/moss_image_encoder.zig", .about = "MOSS-Image's prompt encoder on a reference case: the ids checked, each step gated against float32, then timed" }, - .{ .name = "tf-moss-image-decoder", .path = "zig/tests/moss_image_decoder.zig", .about = "MOSS-Image's image decoder on latents, gated against float64 beside torch float32, then timed" }, - .{ .name = "tf-moss-image-blocks", .path = "zig/tests/moss_image_blocks.zig", .about = "MOSS-Image's transformer on one step, each block alone gated against float32, repeated byte for byte" }, - .{ .name = "tf-moss-image-generate", .path = "zig/tests/moss_image_generate.zig", .about = "MOSS-Image from options alone: prompts, schedule and noise, then the decoder's picture" }, - .{ .name = "tf-uocr-decode", .path = "zig/tests/uocr/decode.zig", .about = "Unlimited-OCR-2 end to end on a page against a reference dump: prompt, layers, logits, greedy reply" }, - .{ .name = "tf-uocr-vision", .path = "zig/tests/uocr/vision.zig", .about = "Unlimited-OCR-2's image encoder on a reference dump's pixels: SAM gated against float32, CLIP and the projector reported" }, - .{ .name = "tf-uocr-blocks", .path = "zig/tests/uocr/blocks.zig", .about = "Unlimited-OCR-2's image encoder step by step: each SAM block, the neck, CLIP's front, each CLIP layer and the projector alone against float32" }, + } ++ image_programs.rows ++ [_]image_programs.Program{ .{ .name = "tf-glm-attn-probe", .path = "zig/tests/glm_attn_probe.zig", .about = "GLM-5.3-Flash's dense latent attention kernels on given inputs (scores, probabilities, outputs)" }, .{ .name = "tf-moe-bench", .path = "zig/tests/moe_bench.zig", .about = "Routed-expert prompt kernels from .metal files on a skewed routing: chained speed, bits against the first" }, .{ .name = "tf-mm-bench", .path = "zig/tests/mm_bench.zig", .about = "Prompt matmul kernels from .metal files: chained speed at one shape, bits against the first, error against fp64" }, diff --git a/zig/build/qwen27.zig b/zig/build/qwen27.zig index 53a9cb00f17..1a18977d336 100644 --- a/zig/build/qwen27.zig +++ b/zig/build/qwen27.zig @@ -62,6 +62,7 @@ fn program(b: *std.Build, name: []const u8, about: []const u8, path: []const u8, /// The core lane, shared-context and 27B programs and host tests; the 27B's module takes `core` from qwen27_core.zig. pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, metal: *std.Build.Module, sources: *std.Build.Module, engine: *std.Build.Module, lanes: *std.Build.Module, s: Shared, test_step: *std.Build.Step) void { + b.step("test-qwen27-metal4", "Metal 4 queue feedback and resource retirement").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = metal, .filters = &.{"a Metal 4 context runs"} })).step); const core_row = b.createModule(.{ .root_source_file = b.path("zig/src/core/row_projection.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "kernel_sources", .module = sources } } }); test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = core_row })).step); const core_lane = b.createModule(.{ .root_source_file = b.path("zig/src/core/lane_projection.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "kernel_sources", .module = sources } } }); @@ -131,6 +132,10 @@ pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu _ = program(b, "tf-qwen27-lanes-check", "Build synthetic lane-core versus plain greedy token and state check", "zig/tests/qwen27/lanes_check.zig", target, false, served); _ = program(b, "tf-qwen27-lanes-run", "Build the real-weight serial versus lane-core A/B", "zig/tests/qwen27/lanes_run.zig", target, false, served); _ = program(b, "tf-qwen27-bench", "Build the projection-split, one-row floor and shared-round timing bench on real weights", "zig/tests/qwen27/bench.zig", target, false, served); + _ = program(b, "tf-qwen27-qk-ab", "Build tf_lane_reg against qk, interleaved on real weights", "zig/tests/qwen27/qk_ab.zig", target, false, served); + _ = program(b, "tf-qwen27-glue-ab", "Build the general glue against the flat kernels, interleaved on real weights", "zig/tests/qwen27/glue_ab.zig", target, false, served); + _ = program(b, "tf-qwen27-metal4-ab", "Build Metal 3 against Metal 4 verify passes, interleaved on real weights", "zig/tests/qwen27/metal4_ab.zig", target, false, served); + _ = program(b, "tf-qwen27-stack-ab", "Build stock kernels on Metal 3 against qk, flat glue and Metal 4, interleaved on real weights", "zig/tests/qwen27/stack_ab.zig", target, false, served); _ = program(b, "tf-qwen27-classes", "Build the per-class projection GPU time against the weight-bytes roofline on real weights", "zig/tests/qwen27/classes.zig", target, false, served); _ = program(b, "tf-qwen27-streams", "Build the real-weight check that shared rounds keep each stream's logits alone", "zig/tests/qwen27/streams.zig", target, false, served); _ = program(b, "tf-qwen27-reuse", "Qwen27 prompt reuse through the served host against fresh prompt passes: states and replies", "zig/tests/qwen27/reuse.zig", target, false, served); diff --git a/zig/build/xpu.zig b/zig/build/xpu.zig index 85a9f272760..6195dc84e04 100644 --- a/zig/build/xpu.zig +++ b/zig/build/xpu.zig @@ -25,6 +25,7 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil .{ "gemm128", "zig/kernels/xpu/qwen27/gemm.cl", " -DGSZ=128" }, .{ "gdn", "zig/kernels/xpu/qwen27/gdn_chunk.cl", "" }, .{ "drafter", "zig/kernels/xpu/qwen27/drafter.cl", "" }, + .{ "tp", "zig/kernels/xpu/tp.cl", "" }, .{ "glue_g4s", "zig/kernels/xpu/gemma4/glue_g4.cl", " -I zig/kernels/xpu/gemma4" }, .{ "glue_g4g", "zig/kernels/xpu/gemma4/glue_g4.cl", " -DHD=512 -I zig/kernels/xpu/gemma4" }, .{ "rows_g4s", "zig/kernels/xpu/gemma4/glue_g4.cl", " -I zig/kernels/xpu/gemma4" }, @@ -94,9 +95,22 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil \\ ) }); const ze_mod = zeModule(b, target, optimize); + const tp_mod = b.createModule(.{ .root_source_file = b.path("zig/src/xpu/tp.zig"), .target = target, .optimize = optimize, .link_libc = true }); + tp_mod.addImport("ze", ze_mod); // one `core` for these trees: the Gemma 4 config, the safetensors readers, Nemotron, the CLI and server const core = b.createModule(.{ .root_source_file = b.path("zig/src/core/root.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true }); core.addImport("gpu_memory", @import("gpu_memory.zig").module(b, target)); + { + const embedded_tp = b.createModule(.{ .root_source_file = files.add("xpu_tp_kernels.zig", + \\pub const tp align(8) = @embedFile("tp.bin").*; + \\ + ) }); + const tpb = b.createModule(.{ .root_source_file = b.path("zig/src/xpu/tp_bench.zig"), .target = target, .optimize = optimize, .link_libc = true }); + tpb.addImport("xpu_tp_kernels", embedded_tp); + tpb.addImport("ze", ze_mod); + const tpb_exe = b.addExecutable(.{ .name = "tf-xpu-tp-bench", .root_module = tpb }); + b.step("xpu-tp-bench", "Build the multi-GPU Level Zero P2P TP=2/4 collective benchmark").dependOn(&b.addInstallArtifact(tpb_exe, .{}).step); + } { const g4 = b.createModule(.{ .root_source_file = b.path("zig/src/families/gemma4/xpu_main.zig"), .target = target, .optimize = optimize, .link_libc = true }); g4.addImport("xpu_gemma4_kernels", embedded_g4); diff --git a/zig/build/xpu_contract.zig b/zig/build/xpu_contract.zig index c2c336df7a4..87e7389a606 100644 --- a/zig/build/xpu_contract.zig +++ b/zig/build/xpu_contract.zig @@ -24,6 +24,12 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil for ([_][]const u8{ "glue_attn.cl", "glue_quant.cl" }) |part| glue.addFileInput(b.path(b.fmt("zig/kernels/xpu/qwen27/{s}", .{part}))); const glue_dir = glue.addOutputDirectoryArg("ocloc-glue"); _ = files.addCopyFile(glue_dir.path(b, "glue.bin"), b.fmt("{s}/glue.bin", .{device})); + const tp_obj = b.addSystemCommand(&.{ ocloc, "compile", "-q", "-file" }); + tp_obj.addFileArg(b.path("zig/kernels/xpu/tp.cl")); + tp_obj.addArgs(&.{ "-device", device, "-options", opts, "-output_no_suffix", "-output", "tp", "-out_dir" }); + tp_obj.setCwd(b.path(".")); + const tp_dir = tp_obj.addOutputDirectoryArg("ocloc-tp"); + _ = files.addCopyFile(tp_dir.path(b, "tp.bin"), b.fmt("{s}/tp.bin", .{device})); const ctl = b.addSystemCommand(&.{ ocloc, "compile", "-q", "-file" }); ctl.addFileArg(b.path("zig/kernels/xpu/contract_controls.cl")); ctl.addArgs(&.{ "-device", device, "-options", opts, "-output_no_suffix", "-output", "contract_controls", "-out_dir" }); @@ -58,7 +64,7 @@ pub fn runner(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bui const files = b.addWriteFiles(); if (prebuilt) |dir| { - for ([_][]const u8{ "glue", "contract_controls", "contract_gate_controls" }) |name| { + for ([_][]const u8{ "glue", "tp", "contract_controls", "contract_gate_controls" }) |name| { _ = files.addCopyFile(.{ .cwd_relative = b.fmt("{s}/{s}.bin", .{ dir, name }) }, b.fmt("{s}.bin", .{name})); } } else { @@ -70,17 +76,22 @@ pub fn runner(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bui for ([_][]const u8{ "glue_attn.cl", "glue_quant.cl" }) |part| glue.addFileInput(b.path(b.fmt("zig/kernels/xpu/qwen27/{s}", .{part}))); const glue_dir = glue.addOutputDirectoryArg("ocloc-glue-run"); _ = files.addCopyFile(glue_dir.path(b, "glue.bin"), "glue.bin"); - for ([_][]const u8{ "contract_controls", "contract_gate_controls" }) |name| { + for ([_][2][]const u8{ + .{ "tp", "zig/kernels/xpu/tp.cl" }, + .{ "contract_controls", "zig/kernels/xpu/contract_controls.cl" }, + .{ "contract_gate_controls", "zig/kernels/xpu/contract_gate_controls.cl" }, + }) |pair| { const run = b.addSystemCommand(&.{ ocloc, "compile", "-q", "-file" }); - run.addFileArg(b.path(b.fmt("zig/kernels/xpu/{s}.cl", .{name}))); - run.addArgs(&.{ "-device", device, "-options", opts, "-output_no_suffix", "-output", name, "-out_dir" }); + run.addFileArg(b.path(pair[1])); + run.addArgs(&.{ "-device", device, "-options", opts, "-output_no_suffix", "-output", pair[0], "-out_dir" }); run.setCwd(b.path(".")); - const dir = run.addOutputDirectoryArg(b.fmt("ocloc-{s}-run", .{name})); - _ = files.addCopyFile(dir.path(b, b.fmt("{s}.bin", .{name})), b.fmt("{s}.bin", .{name})); + const dir = run.addOutputDirectoryArg(b.fmt("ocloc-{s}-run", .{pair[0]})); + _ = files.addCopyFile(dir.path(b, b.fmt("{s}.bin", .{pair[0]})), b.fmt("{s}.bin", .{pair[0]})); } } const images = b.createModule(.{ .root_source_file = files.add("xpu_contract_images.zig", \\pub const glue align(8) = @embedFile("glue.bin").*; + \\pub const tp align(8) = @embedFile("tp.bin").*; \\pub const controls align(8) = @embedFile("contract_controls.bin").*; \\pub const gate_controls align(8) = @embedFile("contract_gate_controls.bin").*; ), .target = target, .optimize = optimize }); diff --git a/zig/cuda_checkpoint_cache_host.zig b/zig/cuda_checkpoint_cache_host.zig index 816caa056cb..dd95787a1e6 100644 --- a/zig/cuda_checkpoint_cache_host.zig +++ b/zig/cuda_checkpoint_cache_host.zig @@ -109,10 +109,11 @@ test "CUDA load cache: DeepSeek finishes backbone and DSpark before the pack swe test "CUDA load cache: Flash Next sweep follows MTP and retains live PLE files" { const s = @embedFile("src/families/flashnext/cuda_lanes_load.zig"); - const drop = std.mem.indexOf(u8, s, ".dropPageCache(io, dir, e.ngram.files.items)") orelse return error.NoPleExclusion; + const drop = std.mem.indexOf(u8, s, ".dropPageCache(gpa, io, dir, e.ngram.files.items)") orelse return error.NoPleExclusion; try t.expect(std.mem.indexOf(u8, s, "mtp.Head.init").? < drop); const owner = @embedFile("src/families/flashnext/cuda_prompt_wt.zig"); - try t.expect(std.mem.indexOf(u8, owner, "if (!runtimePages(self.f.names.keys())) self.f.release(std.heap.page_allocator)") != null); + try t.expect(std.mem.indexOf(u8, owner, "if (runtimePage(name)) keep.append(scratch, self.f.get(name).?.bytes) catch return;") != null); + try t.expect(std.mem.indexOf(u8, owner, "self.f.releaseExcept(keep.items, scratch)") != null); } test "CUDA load cache: LFM2 decision model releases its direct-read fallback" { @@ -137,7 +138,7 @@ test "CUDA load cache: every TP load scope defers file advice through all-rank r const read = std.mem.indexOfPos(u8, source, start, last) orelse return error.NoLastLoad; try t.expect(start < read and read < ready); if (std.mem.eql(u8, path, "flashnext/cuda_lanes_load.zig")) { - const drop = std.mem.indexOf(u8, source, "dropPageCache(io,") orelse return error.NoSweep; + const drop = std.mem.indexOf(u8, source, "dropPageCache(gpa, io,") orelse return error.NoSweep; try t.expect(drop < ready); } } diff --git a/zig/exl3_prompt_host.zig b/zig/exl3_prompt_host.zig index 82a2735f5f4..655ac1983cb 100644 --- a/zig/exl3_prompt_host.zig +++ b/zig/exl3_prompt_host.zig @@ -5,23 +5,25 @@ const glm = @import("glm"); const lanes = @import("lanes"); const ex = cuda.exl3_experts; const Capture = struct { - const Call = struct { id: usize, grid: [3]u32, block: u32, args: [20]u64 = @splat(0) }; + const Call = struct { id: usize, grid: [3]u32, block: u32, args: [24]u64 = @splat(0) }; var calls: [256]Call = undefined; var count: usize = 0; var copies: [16]cuda.abi.Memcpy2D = undefined; var copied: usize = 0; fn launch(f: cuda.abi.Function, gx: c_uint, gy: c_uint, gz: c_uint, bx: c_uint, _: c_uint, _: c_uint, _: c_uint, _: cuda.abi.Stream, args: ?[*]?*anyopaque, _: ?[*]?*anyopaque) callconv(.c) cuda.abi.Result { calls[count] = .{ .id = @intFromPtr(f), .grid = .{ gx, gy, gz }, .block = bx }; - if (@intFromPtr(f) >= 11 and @intFromPtr(f) <= 13) { - const sizes: []const u8 = switch (@intFromPtr(f)) { - 11 => &.{ 8, 4, 8, 8, 4 }, - 12 => &.{ 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 4, 4, 4, 4, 4, 4 }, - else => &.{ 8, 8, 8, 8, 8, 8, 8, 4, 4, 4 }, - }; - for (sizes, 0..) |size, i| { - const bytes: [*]const u8 = @ptrCast(args.?[i].?); - calls[count].args[i] = if (size == 8) std.mem.readInt(u64, bytes[0..8], .little) else std.mem.readInt(u32, bytes[0..4], .little); - } + const sizes: []const u8 = switch (@intFromPtr(f)) { + 2 => &.{ 8, 4, 4, 8, 8, 8, 8, 8, 4, 4, 4 }, + 3 => &.{ 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 }, + 5 => &.{ 8, 8, 8, 8, 8, 8, 4, 4, 4, 4, 4 }, + 11 => &.{ 8, 4, 8, 8, 4 }, + 12 => &.{ 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 4, 4, 4, 4, 4, 4 }, + 13 => &.{ 8, 8, 8, 8, 8, 8, 8, 4, 4, 4 }, + else => &.{}, + }; + for (sizes, 0..) |size, j| { + const bytes: [*]const u8 = @ptrCast(args.?[j].?); + calls[count].args[j] = if (size == 8) std.mem.readInt(u64, bytes[0..8], .little) else std.mem.readInt(u32, bytes[0..4], .little); } count += 1; return cuda.abi.success; @@ -120,19 +122,49 @@ test "exl3 prompt: 4096-row calls keep input and output offsets on both sides of try std.testing.expectEqual(@as(usize, 2), outputs); } -test "exl3 prompt: decode retains the existing split-K launches" { - try run(4, false, true); - try std.testing.expectEqual(@as(usize, 0), Capture.by(12).len); - try std.testing.expect(Capture.by(1).len > 0 and Capture.by(2).len > 0 and Capture.by(3).len > 0); - try run(1030, false, true); - try std.testing.expectEqual(@as(usize, 4), Capture.copied); - try std.testing.expectEqual(@as(usize, 1024), Capture.copies[0].height); - try std.testing.expectEqual(@as(usize, 6), Capture.copies[2].height); - try std.testing.expectEqual(@as(u64, 0x300000000 + 1024 * 9 * 4), Capture.copies[2].src); - try std.testing.expectEqual(@as(u64, 0x400000000 + 1024 * 9 * 512 * 4), Capture.copies[3].dst); - try std.testing.expectEqual(@as(usize, 8 * 4), Capture.copies[0].width); - try std.testing.expectEqual(@as(usize, 9 * 4), Capture.copies[0].src_pitch); - try std.testing.expectEqual(@as(usize, 9 * 512 * 4), Capture.copies[1].dst_pitch); +test "exl3 prompt: decode uses item plans and keeps slot and input offsets across chunks" { + for ([_]usize{ 4, 1030 }) |rows| { + try run(rows, false, true); + try std.testing.expectEqual(@as(usize, 0), Capture.copied); + try std.testing.expectEqual(@as(usize, 0), Capture.by(1).len); + try std.testing.expectEqual(@as(usize, 0), Capture.by(12).len); + var rotations: usize = 0; + var projections: usize = 0; + var outputs: usize = 0; + for (Capture.calls[0..Capture.count]) |call| { + if (call.id == 2) { + const at = rotations * 1024; + const n: usize = @min(rows - at, 1024); + try std.testing.expectEqual(@as(u64, 0x200000000 + at * 520 * 2), call.args[0]); + try std.testing.expectEqual(@as(u64, 0x300000000 + at * 9 * 4), call.args[3]); + try std.testing.expectEqual(@as(u32, @intCast(n * 9)), call.grid[0]); + rotations += 1; + } + if (call.id == 3) { + try std.testing.expectEqual(@as(u64, 10000), call.args[6]); + try std.testing.expectEqual(@as(u64, 30000), call.args[7]); + try std.testing.expectEqual(@as(u64, 20000), call.args[8]); + try std.testing.expectEqual(@as(u64, 16), call.args[14]); + try std.testing.expectEqual(@as(u64, 9), call.args[15]); + try std.testing.expectEqual(@as(u64, 1), call.args[19]); + try std.testing.expectEqual(@as(u64, 9), call.args[20]); + projections += 1; + } + if (call.id == 5) { + const at = outputs * 1024; + const n: usize = @min(rows - at, 1024); + try std.testing.expectEqual(@as(u64, 0x300000000 + at * 9 * 4), call.args[1]); + try std.testing.expectEqual(@as(u64, 0x400000000 + at * 9 * 512 * 4), call.args[3]); + try std.testing.expectEqual(@as(u64, n * 9), call.args[6]); + try std.testing.expectEqual(@as(u64, 9), call.args[10]); + outputs += 1; + } + } + const chunks = (rows + 1023) / 1024; + try std.testing.expectEqual(chunks, rotations); + try std.testing.expectEqual(chunks * 2, projections); + try std.testing.expectEqual(chunks, outputs); + } } test "exl3 prompt: the common dispatch requires verified mcg4 geometry and keeps every fallback" { diff --git a/zig/glm_exl3_prompt_host.zig b/zig/glm_exl3_prompt_host.zig index f53075680e2..f0d067fab49 100644 --- a/zig/glm_exl3_prompt_host.zig +++ b/zig/glm_exl3_prompt_host.zig @@ -16,6 +16,10 @@ const Record = struct { var outputs: [16]u64 = undefined; var skip: [16]i32 = undefined; var routes: usize = 0; + var item_calls: usize = 0; + var item_outputs: [16]u64 = undefined; + var item_picks: [16]u64 = undefined; + var item_pairs: [16]i32 = undefined; fn reset() void { copies = 0; @@ -23,6 +27,7 @@ const Record = struct { down = 0; decode = 0; routes = 0; + item_calls = 0; } fn arg(comptime T: type, args: ?[*]?*anyopaque, index: usize) T { return @as(*const T, @ptrCast(@alignCast(args.?[index].?))).*; @@ -47,6 +52,17 @@ const Record = struct { skip[down] = arg(i32, args, 9); down += 1; }, + 10 => { + t.expectEqual(@as(i32, 16), arg(i32, args, 14)) catch return 1; + t.expectEqual(@as(i32, 1), arg(i32, args, 19)) catch return 1; + t.expectEqual(@as(i32, 288), arg(i32, args, 20)) catch return 1; + }, + 14 => { + item_outputs[item_calls] = arg(u64, args, 3); + item_picks[item_calls] = arg(u64, args, 1); + item_pairs[item_calls] = arg(i32, args, 6); + item_calls += 1; + }, 9 => decode += 1, else => {}, } @@ -94,12 +110,24 @@ test "GLM EXL3 prompt: a whole pass makes one expert call and no 2D copies" { }; } -test "GLM EXL3 prompt: decode retains compact 1024-row calls" { - try run(2048, false, false, 288); - try t.expectEqual(@as(usize, 4), Record.copies); - try t.expectEqual(@as(usize, 2), Record.decode); - try t.expectEqual(@as(usize, 0), Record.up); - try t.expectEqual(@as(usize, 0), Record.down); +test "GLM EXL3 prompt: decode item calls keep the shared slot and chunk offsets without copies" { + for ([_]usize{ 4, 1030 }) |rows| { + try run(rows, false, false, 288); + try t.expectEqual(@as(usize, 0), Record.copies); + try t.expectEqual(@as(usize, 0), Record.decode); + try t.expectEqual(@as(usize, 0), Record.up); + try t.expectEqual(@as(usize, 0), Record.down); + const calls = (rows + 1023) / 1024; + try t.expectEqual(calls, Record.routes); + try t.expectEqual(calls, Record.item_calls); + for (0..calls) |j| { + const at = j * 1024; + const n: usize = @min(rows - at, 1024); + try t.expectEqual(@as(i32, @intCast(n * 9)), Record.item_pairs[j]); + try t.expectEqual(@as(u64, 0x300000000 + at * 9 * 4), Record.item_picks[j]); + try t.expectEqual(@as(u64, 0x400000000 + at * 9 * 512 * 4), Record.item_outputs[j]); + } + } } test "GLM EXL3 prompt: the direct shared-id route refuses an overflowing expert table before launch" { @@ -121,6 +149,13 @@ test "GLM EXL3 prompt: scratch names the rank width and rotation layout" { try t.expectEqual(@as(usize, 360 * MiB * scale), glm.exl3.scratchBytes(rows, D, W_tp1, true, false)[0]); } try t.expectEqual(glm.exl3.scratchBytes(4096, D, W_tp2, true, true), glm.exl3.scratchBytes(4102, D, W_tp2, true, true)); + const l: cuda.exl3_experts.Layer = .{ .gate = 0, .up = 0, .down = 0, .gate_k2 = 0, .up_k2 = 0, .down_k2 = 0, .suh_g = 0, .suh_u = 0, .svh_g = 0, .svh_u = 0, .suh_d = 0, .svh_d = 0, .experts = cuda.grouped.max_experts, .dims = D, .width = W_tp2, .codebook = .mcg }; + for ([_]usize{ 1, 4, 64, 1024, 1030 }) |rows| { + const n: usize = @min(rows, 1024); + const picks = std.mem.alignForward(usize, n * 8 * 4, 256); + const need = @max(try cuda.exl3_experts.scratchBytes(l, n, 8), try cuda.exl3_experts.fusedBytes(l, n, 9)); + try t.expectEqual(picks + need, glm.exl3.scratchBytes(rows, D, W_tp2, false, false)[0]); + } } fn guarded(text: []const u8, name: []const u8, payload: []const u8) bool { diff --git a/zig/kernels/cuda/nvfp4_experts.cu b/zig/kernels/cuda/nvfp4_experts.cu index 27a7cfaba9c..5a360758b93 100644 --- a/zig/kernels/cuda/nvfp4_experts.cu +++ b/zig/kernels/cuda/nvfp4_experts.cu @@ -11,37 +11,18 @@ namespace tf_nvfp4_experts { constexpr int BLOCK4 = 36; -__device__ __forceinline__ uint4 ld_nc(const uint4* p) { return tf_common::ld_nc(p); } - using tf_common::fp4pair; using tf_common::e4m3f; -template +// A k32 group's stage: the lane's words (Word = uint2 for half a unit's two n8 tiles), its scales and inputs. +template struct Stage { - uint4 w[M]; + Word w[M]; uint4 s[M]; uint2 xa[2], xb[2]; }; -template -__device__ __forceinline__ void load_stage(Stage& st, const uint4* blk, int g, int lane, int t, - const __nv_bfloat16* x0, const __nv_bfloat16* x1, bool v0, bool v1) { - const uint4* b = blk + (size_t)g * (M * BLOCK4); -#pragma unroll - for (int m = 0; m < M; ++m) { - st.w[m] = ld_nc(b + m * BLOCK4 + lane); - st.s[m] = ld_nc(b + m * BLOCK4 + 32 + t); - } - const uint2 zero = make_uint2(0u, 0u); - const int k0 = g * 32 + 4 * t; -#pragma unroll - for (int h = 0; h < 2; ++h) { - st.xa[h] = v0 ? __ldg(reinterpret_cast(x0 + k0 + 16 * h)) : zero; - st.xb[h] = v1 ? __ldg(reinterpret_cast(x1 + k0 + 16 * h)) : zero; - } -} - template __device__ __forceinline__ void compute_stage(float (&acc)[M][1][NTW][4], const Stage& st, bool hi) { #pragma unroll @@ -68,33 +49,124 @@ __device__ __forceinline__ void compute_stage(float (&acc)[M][1][NTW][4], const } } -template -__device__ __forceinline__ void k_loop(float (&acc)[M][1][NTW][4], const uint4* blk, int KG, int lane, int t, +#if __CUDA_ARCH__ == 1210 +// GB10's register form of Ring: two k32 stages held in registers, each refilled as soon as it has been summed. +#define TF_RING_STORAGE +template +struct Ring { + __device__ __forceinline__ void load(Stage& st, int g, int lane, int t, int jh, const uint4* blk, const __nv_bfloat16* x0, const __nv_bfloat16* x1, bool v0, bool v1) { - constexpr int D = 2; - Stage st[D]; -#pragma unroll - for (int d = 0; d < D; ++d) - if (d < KG) load_stage(st[d], blk, d, lane, t, x0, x1, v0, v1); - for (int g0 = 0; g0 < KG; g0 += D) { -#pragma unroll - for (int d = 0; d < D; ++d) { - const int g = g0 + d; - if (g < KG) { - compute_stage(acc, st[d], v1); - if (g + D < KG) load_stage(st[d], blk, g + D, lane, t, x0, x1, v0, v1); + const uint4* b = blk + (size_t)g * (M * BLOCK4); +#pragma unroll + for (int m = 0; m < M; ++m) { + if constexpr (sizeof(Word) == 16) + st.w[m] = tf_common::ld_nc(b + m * BLOCK4 + lane); + else + st.w[m] = tf_common::ld_nc2(reinterpret_cast(b + m * BLOCK4 + lane) + jh); + st.s[m] = tf_common::ld_nc(b + m * BLOCK4 + 32 + t); + } + const uint2 zero = make_uint2(0u, 0u); + const int k0 = g * 32 + 4 * t; +#pragma unroll + for (int h = 0; h < 2; ++h) { + st.xa[h] = v0 ? __ldg(reinterpret_cast(x0 + k0 + 16 * h)) : zero; + st.xb[h] = v1 ? __ldg(reinterpret_cast(x1 + k0 + 16 * h)) : zero; + } + } + + // All KG groups in k order: `sum` takes each group's stage. + template + __device__ __forceinline__ void run(int KG, int, int lane, int t, int jh, const uint4* blk, const __nv_bfloat16* x0, + const __nv_bfloat16* x1, bool v0, bool v1, Sum sum) { + constexpr int D = 2; + Stage st[D]; +#pragma unroll + for (int d = 0; d < D; ++d) + if (d < KG) load(st[d], d, lane, t, jh, blk, x0, x1, v0, v1); + for (int g0 = 0; g0 < KG; g0 += D) { +#pragma unroll + for (int d = 0; d < D; ++d) { + const int g = g0 + d; + if (g < KG) { + sum(st[d]); + if (g + D < KG) load(st[d], g + D, lane, t, jh, blk, x0, x1, v0, v1); + } } } } -} +}; +#else +#define TF_RING_STORAGE __shared__ +// A warp's ring of D shared k32 stages, filled by cp.async: the next D - 1 groups load while one group sums. +template +struct Ring { + static constexpr int D = 4; + Word w[WARPS][D][M][32]; // a lane's words + uint4 s[WARPS][D][M][4]; // the group's scales, read by t + uint2 x[WARPS][D][4][32]; // a lane's x0 then x1 inputs, h = 0 and 1 + + // Group g into stage g % D: words (half jh of each lane's uint4 when Word is uint2), scales, the rows' inputs. + __device__ __forceinline__ void issue(int g, int wi, int lane, int t, int jh, const uint4* blk, + const __nv_bfloat16* x0, const __nv_bfloat16* x1, bool v0, bool v1) { + const uint4* b = blk + (size_t)g * (M * BLOCK4); + const int d = g % D, k0 = g * 32 + 4 * t; +#pragma unroll + for (int m = 0; m < M; ++m) { + if constexpr (sizeof(Word) == 16) + tf_common::cp16(&w[wi][d][m][lane], b + m * BLOCK4 + lane); + else + tf_common::cp8(&w[wi][d][m][lane], reinterpret_cast(b + m * BLOCK4 + lane) + jh); + if (lane < 4) tf_common::cp16(&s[wi][d][m][lane], b + m * BLOCK4 + 32 + lane); + } +#pragma unroll + for (int h = 0; h < 2; ++h) { + if (v0) tf_common::cp8(&x[wi][d][h][lane], x0 + k0 + 16 * h); + if (v1) tf_common::cp8(&x[wi][d][2 + h][lane], x1 + k0 + 16 * h); + } + } + + // All KG groups in k order: `sum` takes each group's stage once its loads land. + template + __device__ __forceinline__ void run(int KG, int wi, int lane, int t, int jh, const uint4* blk, + const __nv_bfloat16* x0, const __nv_bfloat16* x1, bool v0, bool v1, Sum sum) { +#pragma unroll + for (int d = 0; d < D - 1; ++d) { + if (d < KG) issue(d, wi, lane, t, jh, blk, x0, x1, v0, v1); + tf_common::cp_commit(); + } + const uint2 zero = make_uint2(0u, 0u); + for (int g = 0; g < KG; ++g) { + if (g + D - 1 < KG) issue(g + D - 1, wi, lane, t, jh, blk, x0, x1, v0, v1); + tf_common::cp_commit(); + tf_common::cp_wait(); + __syncwarp(); + const int d = g % D; + Stage st; +#pragma unroll + for (int m = 0; m < M; ++m) { + st.w[m] = w[wi][d][m][lane]; + st.s[m] = s[wi][d][m][t]; + } +#pragma unroll + for (int h = 0; h < 2; ++h) { + st.xa[h] = v0 ? x[wi][d][h][lane] : zero; + st.xb[h] = v1 ? x[wi][d][2 + h][lane] : zero; + } + sum(st); + __syncwarp(); // every lane has read stage d before the next issue refills it + } + } +}; +#endif // One unit of the decode form: a warp's 32 columns of item `unit / NB` over all K, then the epilogue. -template -__device__ __forceinline__ void unit_full(int unit, int lane, int gq, int t, const __nv_bfloat16* __restrict__ X, - int x_stride, int slots, const uint4* __restrict__ W, - const float* __restrict__ scale, int KG, int NB, const int* __restrict__ items, - const int* __restrict__ members, void* __restrict__ out, int N, float limit, - int skip) { +template +__device__ __forceinline__ void unit_full(int unit, int lane, int gq, int t, int wi, + const __nv_bfloat16* __restrict__ X, int x_stride, int slots, + const uint4* __restrict__ W, const float* __restrict__ scale, int KG, int NB, + const int* __restrict__ items, const int* __restrict__ members, + void* __restrict__ out, int N, float limit, int skip) { + TF_RING_STORAGE Ring ring; const int it = unit / NB, cb = unit - it * NB; const int e = __ldg(items + 3 * it), first = __ldg(items + 3 * it + 1), cnt = __ldg(items + 3 * it + 2); if (e == skip) return; @@ -111,7 +183,7 @@ __device__ __forceinline__ void unit_full(int unit, int lane, int gq, int t, con for (int m = 0; m < M; ++m) #pragma unroll for (int j = 0; j < NTW; ++j) acc[m][0][j][0] = acc[m][0][j][1] = acc[m][0][j][2] = acc[m][0][j][3] = 0.f; - k_loop(acc, blk, KG, lane, t, x0, x1, v0, v1); + ring.run(KG, wi, lane, t, 0, blk, x0, x1, v0, v1, [&](const Stage& st) { compute_stage(acc, st, v1); }); #pragma unroll for (int m = 0; m < M; ++m) { const float g = __ldg(scale + e * M + m); @@ -133,7 +205,8 @@ __global__ void __launch_bounds__(WARPS * 32) const int lane = threadIdx.x & 31, gq = lane >> 2, t = lane & 3; const int units = __ldg(counts) * NB; for (int unit = blockIdx.x * WARPS + (threadIdx.x >> 5); unit < units; unit += gridDim.x * WARPS) - unit_full(unit, lane, gq, t, X, x_stride, slots, W, scale, KG, NB, items, members, out, N, limit, skip); + unit_full(unit, lane, gq, t, threadIdx.x >> 5, X, x_stride, slots, W, scale, KG, NB, items, + members, out, N, limit, skip); } // The decode form's units dealt in equal waves: ceil(units / waves) warps run, the others leave at once. @@ -150,36 +223,13 @@ __global__ void __launch_bounds__(WARPS * 32) const int run = (units + waves - 1) / waves, w = blockIdx.x * WARPS + (threadIdx.x >> 5); if (w >= run) return; for (int unit = w; unit < units; unit += run) - unit_full(unit, lane, gq, t, X, x_stride, slots, W, scale, KG, NB, items, members, out, N, limit, skip); + unit_full(unit, lane, gq, t, threadIdx.x >> 5, X, x_stride, slots, W, scale, KG, NB, items, + members, out, N, limit, skip); } // Half a unit's stage: the lane's words of n8 tiles 2jh and 2jh + 1, all its scales, its inputs. template -struct Half { - uint2 w[M]; - uint4 s[M]; - uint2 xa[2], xb[2]; -}; - -__device__ __forceinline__ uint2 ld_nc2(const void* p) { return tf_common::ld_nc2(p); } - -template -__device__ __forceinline__ void load_half(Half& st, const uint4* blk, int g, int lane, int t, int jh, - const __nv_bfloat16* x0, const __nv_bfloat16* x1, bool v0, bool v1) { - const uint4* b = blk + (size_t)g * (M * BLOCK4); -#pragma unroll - for (int m = 0; m < M; ++m) { - st.w[m] = ld_nc2(reinterpret_cast(b + m * BLOCK4 + lane) + jh); - st.s[m] = ld_nc(b + m * BLOCK4 + 32 + t); - } - const uint2 zero = make_uint2(0u, 0u); - const int k0 = g * 32 + 4 * t; -#pragma unroll - for (int h = 0; h < 2; ++h) { - st.xa[h] = v0 ? __ldg(reinterpret_cast(x0 + k0 + 16 * h)) : zero; - st.xb[h] = v1 ? __ldg(reinterpret_cast(x1 + k0 + 16 * h)) : zero; - } -} +using Half = Stage; // compute_stage's sums for tiles j = 2jh + jj: scale word 2h + jh, byte pair jj * 16. template @@ -248,10 +298,10 @@ __global__ void __launch_bounds__(WARPS * 32) const float* __restrict__ scale, int KG, int NB, const int* __restrict__ items, const int* __restrict__ counts, const int* __restrict__ members, void* __restrict__ out, int N, float limit, int skip) { - constexpr int D = 2; - const int lane = threadIdx.x & 31, gq = lane >> 2, t = lane & 3; + TF_RING_STORAGE Ring ring; + const int lane = threadIdx.x & 31, gq = lane >> 2, t = lane & 3, wi = threadIdx.x >> 5; const int units = __ldg(counts) * NB * 2; - for (int unit = blockIdx.x * WARPS + (threadIdx.x >> 5); unit < units; unit += gridDim.x * WARPS) { + for (int unit = blockIdx.x * WARPS + wi; unit < units; unit += gridDim.x * WARPS) { const int it = unit / (NB * 2), rest = unit - it * NB * 2, cb = rest >> 1, jh = rest & 1; const int e = __ldg(items + 3 * it), first = __ldg(items + 3 * it + 1), cnt = __ldg(items + 3 * it + 2); if (e == skip) continue; @@ -268,20 +318,7 @@ __global__ void __launch_bounds__(WARPS * 32) for (int m = 0; m < M; ++m) #pragma unroll for (int j = 0; j < 2; ++j) acc[m][j][0] = acc[m][j][1] = acc[m][j][2] = acc[m][j][3] = 0.f; - Half st[D]; -#pragma unroll - for (int d = 0; d < D; ++d) - if (d < KG) load_half(st[d], blk, d, lane, t, jh, x0, x1, v0, v1); - for (int g0 = 0; g0 < KG; g0 += D) { -#pragma unroll - for (int d = 0; d < D; ++d) { - const int g = g0 + d; - if (g < KG) { - compute_half(acc, st[d], v1, jh); - if (g + D < KG) load_half(st[d], blk, g + D, lane, t, jh, x0, x1, v0, v1); - } - } - } + ring.run(KG, wi, lane, t, jh, blk, x0, x1, v0, v1, [&](const Half& st) { compute_half(acc, st, v1, jh); }); #pragma unroll for (int m = 0; m < M; ++m) { const float g = __ldg(scale + e * M + m); diff --git a/zig/kernels/metal/core/affine_mm.metal b/zig/kernels/metal/core/affine_mm.metal index 833756dc2c4..6e3cfe99307 100644 --- a/zig/kernels/metal/core/affine_mm.metal +++ b/zig/kernels/metal/core/affine_mm.metal @@ -152,6 +152,47 @@ inline void am_codes(thread const Codes& c, threadgroup bfloat* out) { #endif } +#if defined(TF_GLM_M3_FAST) && defined(TF_SIMD_FRAGS) +// GLM pre-M5: codes in [K=64][N=64] layout so frag_get reads transposed weights with zero bank conflict. +inline void am_codes_kn(thread const Codes& c, threadgroup bfloat* tile, int w_n, int w_kh) { +#if TF_BITS == 2 + TF_UNROLL + for (short i = 0; i < 2; i++) { + const uint w = c.v[i]; + TF_UNROLL + for (short j = 0; j < 16; j++) tile[(w_kh * 32 + i * 16 + j) * PAD + w_n] = bfloat(float((w >> (2 * j)) & 3u)); + } +#elif TF_BITS % 4 != 0 + TF_UNROLL + for (short j = 0; j < 32; j++) { + const short at = TF_BITS * j, word = at / 32, shift = at % 32; + uint v = c.v[word] >> shift; + if (shift + TF_BITS > 32) v |= c.v[word + 1] << (32 - shift); + tile[(w_kh * 32 + j) * PAD + w_n] = bfloat(float(v & ((1u << TF_BITS) - 1u))); + } +#elif TF_BITS == 4 + TF_UNROLL + for (short i = 0; i < 4; i++) { + const uint w = c.v[0][i]; + TF_UNROLL + for (short j = 0; j < 8; j++) { + tile[(w_kh * 32 + i * 8 + j) * PAD + w_n] = as_type(ushort(0x4300u | ((w >> (4 * j)) & 0xfu))); + } + } +#else + TF_UNROLL + for (short i = 0; i < 8; i++) { + const uchar4 f = as_type(c.v[i / 4][i % 4]); + const int b = w_kh * 32 + i * 4; + tile[b * PAD + w_n] = bfloat(float(f.x)); + tile[(b + 1) * PAD + w_n] = bfloat(float(f.y)); + tile[(b + 2) * PAD + w_n] = bfloat(float(f.z)); + tile[(b + 3) * PAD + w_n] = bfloat(float(f.w)); + } +#endif +} +#endif + // A block of the code tile as the transposed right operand: 8-byte loads on M5 (PAD rows, 16-column blocks). #ifndef TF_SIMD_FRAGS #define am_tile_frag frag_get_tg @@ -188,8 +229,13 @@ inline void am_step(thread frag (&acc)[TM][2], thread const AmRows& r TF_UNROLL for (short q = 0; q < 4; q++) { // the step's four 16-deep slices, every row fragment's chain interleaved frag b0, b1, a[TL]; +#if defined(TF_GLM_M3_FAST) && defined(TF_SIMD_FRAGS) + frag_get(b0, tile, PAD, 16 * q, tn, home); + frag_get(b1, tile, PAD, 16 * q, tn + 16, home); +#else am_tile_frag(b0, tile, PAD, tn, 16 * q, home); am_tile_frag(b1, tile, PAD, tn + 16, 16 * q, home); +#endif TF_UNROLL for (short m = 0; m < TL; m++) { a[m] = am_frag(rows.x[m][0], rows.x[m][1], k + 16 * q, home); @@ -231,8 +277,13 @@ inline void am_step128(thread frag (&acc)[TM][2], thread frag (&pa TF_UNROLL for (short q = 0; q < 4; q++) { frag b0, b1, a[TL]; +#if defined(TF_GLM_M3_FAST) && defined(TF_SIMD_FRAGS) + frag_get(b0, tile, PAD, 16 * q, tn, home); + frag_get(b1, tile, PAD, 16 * q, tn + 16, home); +#else frag_get_t(b0, tile, PAD, tn, 16 * q, home); frag_get_t(b1, tile, PAD, tn + 16, 16 * q, home); +#endif TF_UNROLL for (short m = 0; m < TL; m++) { a[m] = am_frag(rows.x[m][0], rows.x[m][1], k + 16 * q, home); @@ -268,7 +319,11 @@ template inline void am_k_loop(thread frag (&acc)[TM][2], thread const AmRows& rows, int K, int live, const device uchar* wq, const device bfloat* scales, const device bfloat* biases, threadgroup bfloat* tile, threadgroup float* sb, int tn, uint t, short2 home) { +#if defined(TF_GLM_M3_FAST) && defined(TF_SIMD_FRAGS) + const int w_n = int(t / 2), w_kh = int(t % 2); +#else threadgroup bfloat* mine = tile + (t / 2) * PAD + 32 * (t % 2); +#endif const int g_mine = TF_GROUP == 32 ? int(t % 2) : 0; // at g32 each thread of a pair takes one group's scale and bias #if TF_GROUP == 128 frag part[TM][2]; // a group's sums across its two steps @@ -280,7 +335,11 @@ inline void am_k_loop(thread frag (&acc)[TM][2], thread const AmRows& } for (int k = 0; k < K; k += 64) { threadgroup_barrier(mem_flags::mem_threadgroup); +#if defined(TF_GLM_M3_FAST) && defined(TF_SIMD_FRAGS) + am_codes_kn(am_load(wq), tile, w_n, w_kh); +#else am_codes(am_load(wq), mine); +#endif if (TF_GROUP == 32 || t % 2 == 0) { const float s = float(scales[g_mine]); sb[g_mine * 128 + t / 2] = s; @@ -417,9 +476,14 @@ inline void am_block(const device bfloat* x, int ldx, const device float* xs, in uint3 tg [[threadgroup_position_in_grid]]) { threadgroup bfloat tile[64 * PAD]; threadgroup float sb[NG * 128]; - const int row = int(tg.y) * 64, col = int(tg.x) * 64, b = int(tg.z); - am_block<64>(X + long(b) * st.x_batch, st.x_row, XS + long(b) * st.sums_batch * (a.k / TF_GROUP), - st.sums_row * (a.k / TF_GROUP), row, min(64, a.rows - row), a.k, st.y_row, col, +#if defined(TF_GLM_M3_FAST) && defined(TF_SIMD_FRAGS) + constexpr int BM = 32; +#else + constexpr int BM = 64; +#endif + const int row = int(tg.y) * BM, col = int(tg.x) * 64, b = int(tg.z); + am_block(X + long(b) * st.x_batch, st.x_row, XS + long(b) * st.sums_batch * (a.k / TF_GROUP), + st.sums_row * (a.k / TF_GROUP), row, min(BM, a.rows - row), a.k, st.y_row, col, long(b) * st.w_batch + col, W, S, B, Y + long(b) * st.y_batch, tile, sb, sg, lane); } diff --git a/zig/kernels/metal/core/deltanet_slots.metal b/zig/kernels/metal/core/deltanet_slots.metal index a6106bdc4b3..565c7bed51d 100644 --- a/zig/kernels/metal/core/deltanet_slots.metal +++ b/zig/kernels/metal/core/deltanet_slots.metal @@ -53,3 +53,139 @@ TF_TREE_SLOTS(2) TF_TREE_SLOTS(4) TF_TREE_SLOTS(8) TF_TREE_SLOTS(16) + +// The slot scan for 128-wide heads, 4 value columns a simdgroup; a flow word holds a row and slots to restore and save. +template +[[max_total_threads_per_threadgroup(32)]] +kernel void tf_delta_gdn_columns(device const vec* query [[buffer(0)]], + device const vec* key [[buffer(1)]], + device const bfloat* value [[buffer(2)]], + device const float* decay [[buffer(3)]], + device const bfloat* mixing [[buffer(4)]], + device const float4* committed [[buffer(5)]], + device const TfDeltaSegment* segments [[buffer(6)]], + constant TfDeltaParams& p [[buffer(7)]], + device bfloat* output [[buffer(8)]], + device const uint* flows [[buffer(9)]], + uint3 group [[threadgroup_position_in_grid]], + ushort lane [[thread_index_in_simdgroup]]) { + threadgroup float4 kept[SLOTS][4][32]; + const uint head = group.z % p.nv, first = group.y * 4, key_head = head / (p.nv / p.nk); + const TfDeltaSegment span = segments[group.z / p.nv]; + float4 s[4]; + _Pragma("clang loop unroll(full)") + for (uint k = 0; k < 4; k++) s[k] = committed[(span.state_slot * p.nv * p.dv + head * p.dv + first + k) * 32 + lane]; + for (uint at = 0; at < span.rows; at++) { + const uint flow = flows[span.first + at], row = flow & 0xffffu; + if (SLOTS > 1) { + const uint restore = (flow >> 16) & 0xffu; + if (restore != 0) { + _Pragma("clang loop unroll(full)") + for (uint k = 0; k < 4; k++) s[k] = kept[restore - 1][k][lane]; + } + } + const uint cell = row * p.nv + head, key_at = (row * p.nk + key_head) * 32 + lane; + const float forget = decay[cell], mix = float(mixing[cell]); + const float4 ki = float4(key[key_at]), qi = float4(query[key_at]); + const float4 incoming = float4(*(device const vec*)(value + cell * p.dv + first)); + float4 results; + _Pragma("clang loop unroll(full)") + for (uint k = 0; k < 4; k++) { + float4 t = s[k]; + float remembered = 0.0f; + _Pragma("clang loop unroll(full)") + for (uint part = 0; part < 4; part++) { + t[part] = t[part] * forget; + remembered += t[part] * ki[part]; + } + remembered = simd_sum(remembered); + const float correction = (incoming[k] - remembered) * mix; + float result = 0.0f; + _Pragma("clang loop unroll(full)") + for (uint part = 0; part < 4; part++) { + t[part] = t[part] + ki[part] * correction; + result += t[part] * qi[part]; + } + s[k] = t; + results[k] = simd_sum(result); + } + if (lane == 0) *(device vec*)(output + cell * p.dv + first) = vec(results); + if (SLOTS > 1) { + const uint save = flow >> 24; + if (save != 0) { + _Pragma("clang loop unroll(full)") + for (uint k = 0; k < 4; k++) kept[save - 1][k][lane] = s[k]; + } + } + } +} +#define TF_COLUMNS(N) template [[host_name("tf_delta_gdn_columns_" #N)]] kernel void tf_delta_gdn_columns(device const vec*, device const vec*, device const bfloat*, device const float*, device const bfloat*, device const float4*, device const TfDeltaSegment*, constant TfDeltaParams&, device bfloat*, device const uint*, uint3, ushort); +TF_COLUMNS(1) +TF_COLUMNS(2) +TF_COLUMNS(4) + +// tf_delta_gdn_pre for 128-wide heads, four taps and bf16 weights: a lane's channels load together, and no tails. +[[max_total_threads_per_threadgroup(32)]] +kernel void tf_delta_gdn_pre_vectors(device const vec* projection [[buffer(0)]], + device const bfloat* a [[buffer(1)]], + device const bfloat* b [[buffer(2)]], + device const vec* history [[buffer(3)]], + device const packed_ushort4* weights [[buffer(4)]], + device const bfloat* decay_weight [[buffer(5)]], + device const bfloat* time_bias [[buffer(6)]], + device const packed_uint4* windows [[buffer(7)]], + device const uint* row_slot [[buffer(8)]], + constant TfDeltaParams& p [[buffer(9)]], + device vec* query [[buffer(10)]], + device vec* key [[buffer(11)]], + device vec* value [[buffer(12)]], + device float* decay [[buffer(13)]], + device bfloat* mixing [[buffer(14)]], + uint3 group [[threadgroup_position_in_grid]], + ushort lane [[thread_index_in_simdgroup]]) { + const uint row = group.z, head = group.y, keep = p.taps - 1; + const uint channels = (2 * p.nk * p.dk + p.nv * p.dv) / 4, at = head * 32 + lane; + const uint4 sources = uint4(windows[row]); + float4 taps[4]; + _Pragma("clang loop unroll(full)") + for (uint tap = 0; tap < 4; tap++) { + const uint source = sources[tap]; + device const vec* from = source < keep ? history + (row_slot[row] * keep + source) * channels : projection + (source - keep) * channels; + taps[tap] = float4(from[at]); + } + float activated[4]; + _Pragma("clang loop unroll(full)") + for (uint part = 0; part < 4; part++) { + const float4 w = as_type(uint4(ushort4(weights[head * p.dk + lane * 4 + part])) << 16); + float result = 0.0f; + _Pragma("clang loop unroll(full)") + for (uint tap = 0; tap < 4; tap++) result += w[tap] * taps[tap][part]; + const float rounded = float(bfloat(result)); + const float sigmoid = float(bfloat(1.0f / (1.0f + metal::exp(-rounded)))); + activated[part] = float(bfloat(rounded * sigmoid)); + } + if (head < 2 * p.nk) { + float square = 0.0f; + _Pragma("clang loop unroll(full)") + for (uint part = 0; part < 4; part++) square += activated[part] * activated[part]; + square = simd_sum(square); + const float inverse = metal::rsqrt(square / float(p.dk) + 1e-6f); + const float scale = head < p.nk ? float(bfloat(1.0f / float(p.dk))) : float(bfloat(metal::rsqrt(float(p.dk)))); + float4 out; + _Pragma("clang loop unroll(full)") + for (uint part = 0; part < 4; part++) out[part] = scale * float(bfloat(activated[part] * inverse)); + const uint position = (row * p.nk + head % p.nk) * 32 + lane; + if (head < p.nk) query[position] = vec(out); + else key[position] = vec(out); + return; + } + const uint output_head = head - 2 * p.nk; + value[(row * p.nv + output_head) * 32 + lane] = vec(float4(activated[0], activated[1], activated[2], activated[3])); + if (lane == 0) { + const uint cell = row * p.nv + output_head, gate_at = p.zba_stride ? row * p.zba_stride + output_head : cell; + const float shifted = float(bfloat(float(a[gate_at]) + float(time_bias[output_head]))); + const float softplus = float(bfloat(metal::max(shifted, 0.0f) + metal::log(1.0f + metal::exp(-metal::abs(shifted))))); + decay[cell] = metal::exp(-metal::exp(float(decay_weight[output_head])) * softplus); + mixing[cell] = bfloat(1.0f / (1.0f + metal::exp(-float(b[gate_at])))); + } +} diff --git a/zig/kernels/metal/core/qk.metal b/zig/kernels/metal/core/qk.metal new file mode 100644 index 00000000000..1d615097d16 --- /dev/null +++ b/zig/kernels/metal/core/qk.metal @@ -0,0 +1,129 @@ +// qk: y = sum over groups of scale * (x . codes) + bias * sum(x), the op reading packed codes; tf_lane_reg's words. +#include +#include +using namespace metal; +using namespace mpp::tensor_ops; +// TF_SK: simdgroups a tile on slices of the groups (the K split, which sets the bits); TF_ROWS: rows a threadgroup. +#define TF_QK_EACH _Pragma("clang loop unroll(full)") + +constant constexpr int QK_NT = 32; // columns in a tile +constant constexpr int QK_GS = 64; // codes in a group +constant constexpr int QK_CODES = QK_NT * QK_GS / 2; // bytes of codes in one block: a tile's group +constant constexpr int QK_SETS = QK_NT / 16; // column sets one lane holds: columns c0 + 16 s, four each +constant constexpr int QK_RUNS = TF_ROWS / 8; // row runs one lane holds: rows r0 + 8 k +constant constexpr int QK_VALUES = QK_RUNS * QK_SETS * 4; // values one lane keeps for a tile + +struct tf_qk_args { + int rows; // rows of x and y, all threadgroups together + int k; // columns of x + int n; // columns of y, a multiple of 32 + int groups; // k / 64 + int stride; // rows between one group's sums and the next's +}; + +// Where one op puts a lane's values: column sets, then the two runs of its 16 rows. +inline int tf_qk_place(int k, int s, int j) { return (s * 2 + k) * 4 + j; } +// Where this kernel keeps them. +inline int tf_qk_kept(int k, int s, int j) { return (k * QK_SETS + s) * 4 + j; } + +kernel void tf_qk(const device bfloat* X [[buffer(0)]], + const device uchar* W [[buffer(1)]], // weight_layout: [tile][group][column][32 bytes] + const device uint* SB [[buffer(2)]], // metadata_layout words: [group][column] scale | bias << 16 + const device float* SUMS [[buffer(3)]], // x summed over each group: [group * stride + row] + device bfloat* Y [[buffer(4)]], + constant tf_qk_args& p [[buffer(5)]], + uint2 tg [[threadgroup_position_in_grid]], + uint slice [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + const int tile = int(tg.x); + const int first_row = int(tg.y) * TF_ROWS; + const int end_row = min(first_row + TF_ROWS, p.rows); + const int last_row = p.rows - 1; // sums past it are read here, never used + const int first = p.groups * int(slice) / TF_SK, last = p.groups * (int(slice) + 1) / TF_SK; + const device uchar* blocks = W + (size_t)tile * p.groups * QK_CODES; + + constexpr auto desc = matmul2d_descriptor(TF_ROWS < 16 ? TF_ROWS : 16, QK_NT, QK_GS, false, true, false, matmul2d_descriptor::mode::multiply); + matmul2d op; + tensor, tensor_inline> xs((device bfloat*)X, dextents(p.k, end_row)); + // Metal refuses static extents on packed codes, whose implied stride must be 64 bytes. + tensor, tensor_inline> b0((device uchar*)blocks, dextents(QK_GS, QK_NT)); + auto LX = op.template get_left_input_cooperative_tensor(); + auto P = op.template get_destination_cooperative_tensor, decltype(b0), float>(); + + const auto home = P.get_multidimensional_index(ushort(0)); + const int c0 = home[0], r0 = home[1]; + const device uint* columns = SB + (size_t)tile * QK_NT + c0; + + float C[QK_VALUES]; + TF_QK_EACH for (int i = 0; i < QK_VALUES; i++) C[i] = 0.0f; + + // A lane's scales and biases for each column set. The next group's are on their way while this group's ops run. + uint4 next[QK_SETS]; + TF_QK_EACH for (int s = 0; s < QK_SETS; s++) next[s] = *(const device uint4*)(columns + (size_t)first * p.n + 16 * s); + + // Each group: 16 rows of x into registers, one op against the group's codes in place, scale and bias folded after. + for (int g = first; g < last; g++) { + float scale[QK_SETS][4]; + float bias[QK_SETS][4]; + const int ahead = g + 1 < last ? g + 1 : g; + TF_QK_EACH for (int s = 0; s < QK_SETS; s++) { + TF_QK_EACH for (int j = 0; j < 4; j++) { + scale[s][j] = as_type(next[s][j] << 16); + bias[s][j] = as_type(next[s][j] & 0xFFFF0000u); + } + next[s] = *(const device uint4*)(columns + (size_t)ahead * p.n + 16 * s); + } + tensor, tensor_inline> b((device uchar*)blocks + (size_t)g * QK_CODES, dextents(QK_GS, QK_NT)); + const device float* group_sums = SUMS + (size_t)g * p.stride; + // The compiler has to unroll this, or the running sums leave registers. An odd run stays out of it for that reason. + TF_QK_EACH for (int part = 0; part < QK_RUNS / 2; part++) { + auto a = xs.slice(g * QK_GS, first_row + part * 16); + LX.load(a); + op.run(LX, b, P); + const int row = first_row + part * 16 + r0; + const float x0 = group_sums[min(row, last_row)], x1 = group_sums[min(row + 8, last_row)]; + TF_QK_EACH for (int s = 0; s < QK_SETS; s++) { + TF_QK_EACH for (int j = 0; j < 4; j++) { + C[tf_qk_kept(part * 2, s, j)] = fma(scale[s][j], P[tf_qk_place(0, s, j)], fma(bias[s][j], x0, C[tf_qk_kept(part * 2, s, j)])); + C[tf_qk_kept(part * 2 + 1, s, j)] = fma(scale[s][j], P[tf_qk_place(1, s, j)], fma(bias[s][j], x1, C[tf_qk_kept(part * 2 + 1, s, j)])); + } + } + } +#if (TF_ROWS / 8) % 2 == 1 + { + auto a = xs.slice(g * QK_GS, first_row + QK_RUNS / 2 * 16); + LX.load(a); + op.run(LX, b, P); + const float x0 = group_sums[min(first_row + QK_RUNS / 2 * 16 + r0, last_row)]; + TF_QK_EACH for (int s = 0; s < QK_SETS; s++) { + TF_QK_EACH for (int j = 0; j < 4; j++) C[tf_qk_kept(QK_RUNS - 1, s, j)] = fma(scale[s][j], P[tf_qk_place(0, s, j)], fma(bias[s][j], x0, C[tf_qk_kept(QK_RUNS - 1, s, j)])); + } + } +#endif + } + +#if TF_SK > 1 + // Slices add up through threadgroup memory in slice order, as tf_lane_reg's do: no partial reaches device memory. + threadgroup float part_sums[(TF_SK - 1) * QK_VALUES * 32]; + if (slice > 0) { + TF_QK_EACH for (int i = 0; i < QK_VALUES; i++) part_sums[((slice - 1) * QK_VALUES + i) * 32 + lane] = C[i]; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (slice > 0) return; + TF_QK_EACH for (int s = 0; s < TF_SK - 1; s++) { + TF_QK_EACH for (int i = 0; i < QK_VALUES; i++) C[i] += part_sums[(s * QK_VALUES + i) * 32 + lane]; + } +#endif + + const int n0 = tile * QK_NT + c0; + TF_QK_EACH for (int k = 0; k < QK_RUNS; k++) { + const int m = first_row + r0 + 8 * k; + if (m < end_row) { + device bfloat* out = Y + (size_t)m * p.n; + TF_QK_EACH for (int s = 0; s < QK_SETS; s++) { + const vec four = vec(float4(C[tf_qk_kept(k, s, 0)], C[tf_qk_kept(k, s, 1)], C[tf_qk_kept(k, s, 2)], C[tf_qk_kept(k, s, 3)])); + *(device vec*)(out + n0 + 16 * s) = four; + } + } + } +} diff --git a/zig/kernels/metal/core/tree_round.metal b/zig/kernels/metal/core/tree_round.metal index a7995249793..b08e15c0449 100644 --- a/zig/kernels/metal/core/tree_round.metal +++ b/zig/kernels/metal/core/tree_round.metal @@ -44,6 +44,53 @@ kernel void tf_round_bf16_argmax(const device ushort* logits [[buffer(0)]], } if (lane == 0) picks[row] = { masks[0] != 0 ? 0xffffffffu : ids[0], masks[0] }; } +// tf_round_bf16_argmax with a row on every core: the largest finite value, then the lowest token, chunk by chunk. +struct ChunkBest { float value; uint token, mask; }; +constant constexpr uint CHUNK_STEPS = 32, CHUNK_TOKENS = 32 * CHUNK_STEPS; +kernel void tf_round_pick_chunks(const device ushort* logits [[buffer(0)]], + device ChunkBest* out [[buffer(1)]], + constant Argmax& p [[buffer(2)]], + uint2 place [[threadgroup_position_in_grid]], + ushort lane [[thread_index_in_simdgroup]]) { + const uint chunk = place.x, row = place.y, chunks = (p.vocab + CHUNK_TOKENS - 1) / CHUNK_TOKENS; + float best = -INFINITY; + uint id = 0xffffffffu, mask = 0; + for (uint step = 0; step < CHUNK_STEPS; step++) { + const uint token = chunk * CHUNK_TOKENS + step * 32 + lane; + if (token >= p.vocab) break; + const float value = as_type(uint(logits[ulong(row) * p.stride + token]) << 16); + if (!isfinite(value)) mask |= isnan(value) ? 1u : value > 0 ? 2u : 4u; + else if (id == 0xffffffffu || value > best) { + best = value; + id = token; + } + } + const float top = simd_max(best); + const uint who = simd_min(best == top && id != 0xffffffffu ? id : 0xffffffffu); + const uint masks = simd_or(mask); + if (lane == 0) out[row * chunks + chunk] = {top, who, masks}; +} +kernel void tf_round_pick_rows(const device ChunkBest* chunks_best [[buffer(0)]], + device Pick* picks [[buffer(1)]], + constant Argmax& p [[buffer(2)]], + uint row [[threadgroup_position_in_grid]], + ushort lane [[thread_index_in_simdgroup]]) { + const uint chunks = (p.vocab + CHUNK_TOKENS - 1) / CHUNK_TOKENS; + float best = -INFINITY; + uint id = 0xffffffffu, mask = 0; + for (uint chunk = lane; chunk < chunks; chunk += 32) { + const ChunkBest other = chunks_best[row * chunks + chunk]; + mask |= other.mask; + if (other.token != 0xffffffffu && (id == 0xffffffffu || other.value > best || (other.value == best && other.token < id))) { + best = other.value; + id = other.token; + } + } + const float top = simd_max(best); + const uint who = simd_min(best == top && id != 0xffffffffu ? id : 0xffffffffu); + const uint masks = simd_or(mask); + if (lane == 0) picks[row] = { masks != 0 ? 0xffffffffu : who, masks }; +} kernel void tf_tree_round_match(const device uint* tokens [[buffer(0)]], const device int* parents [[buffer(1)]], const device Pick* picks [[buffer(2)]], diff --git a/zig/kernels/metal/glm_index_nax.metal b/zig/kernels/metal/glm_index_nax.metal index 1f55031f96a..9f7905544d2 100644 --- a/zig/kernels/metal/glm_index_nax.metal +++ b/zig/kernels/metal/glm_index_nax.metal @@ -10,10 +10,16 @@ struct GlmScoreArgs { uint p0, q_stride, w_stride, s_stride, rows; }; -// A fragment of q at column c from a lane's two row starts (8-byte loads on M5). +// A fragment of q at column c from a lane's two row starts (8-byte loads on M5, 4-byte on pre-M5 GLM). inline frag ix_frag(const device bfloat* r0, const device bfloat* r1, int c, short2 home) { #ifndef TF_SIMD_FRAGS return frag(*(const device bfloat4*)(r0 + c + home.x), *(const device bfloat4*)(r1 + c + home.x)); +#elif defined(TF_GLM_M3_FAST) + const bfloat2 a0 = *(const device bfloat2*)(r0 + c + home.x); + const bfloat2 a1 = *(const device bfloat2*)(r0 + c + home.x + 8); + const bfloat2 b0 = *(const device bfloat2*)(r1 + c + home.x); + const bfloat2 b1 = *(const device bfloat2*)(r1 + c + home.x + 8); + return frag(a0.x, a0.y, a1.x, a1.y, b0.x, b0.y, b1.x, b1.y); #else frag f; TF_UNROLL @@ -24,11 +30,69 @@ inline frag ix_frag(const device bfloat* r0, const device bfloat* r1, in #endif } -// Grid: 64-block, 64-row tiles; 4 simdgroups, 32 rows x 32 blocks; only read blocks stored, whole tiles beyond skipped. +// Grid: 64-block, 64-row (32-row under TF_GLM_M3_FAST) tiles; only read blocks stored, whole tiles beyond skipped. [[kernel]] void glm_index_scores_nax(const device bfloat* iq [[buffer(0)]], const device bfloat* iw [[buffer(1)]], const device bfloat* pool [[buffer(2)]], device float* scores [[buffer(3)]], constant GlmScoreArgs& a [[buffer(4)]], uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], uint3 tg [[threadgroup_position_in_grid]]) { +#if defined(TF_GLM_M3_FAST) && defined(TF_SIMD_FRAGS) + constexpr int TPAD = 64 + 8; + threadgroup bfloat tileT[DI * TPAD]; + const int b0 = int(tg.x) * 64, r0 = int(tg.y) * 32; + const int rows = min(32, int(a.rows) - r0); + if (rows <= 0 || b0 >= (int(a.p0) + r0 + rows) / 4) return; + const uint t = sg * 32 + lane; + for (uint i = t; i < 64 * (DI / 8); i += 128) { + const uint rr = i / (DI / 8), cc = (i % (DI / 8)) * 8; + const int b = min(b0 + int(rr), int(a.s_stride) - 1); + const uint4 v = *(const device uint4*)(pool + size_t(b) * DI + cc); + const bfloat2 p0 = as_type(v.x), p1 = as_type(v.y); + const bfloat2 p2 = as_type(v.z), p3 = as_type(v.w); + tileT[(cc + 0) * TPAD + rr] = p0.x; tileT[(cc + 1) * TPAD + rr] = p0.y; + tileT[(cc + 2) * TPAD + rr] = p1.x; tileT[(cc + 3) * TPAD + rr] = p1.y; + tileT[(cc + 4) * TPAD + rr] = p2.x; tileT[(cc + 5) * TPAD + rr] = p2.y; + tileT[(cc + 6) * TPAD + rr] = p3.x; tileT[(cc + 7) * TPAD + rr] = p3.y; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + const short2 home = frag_home(ushort(lane)); + const int tm = 16 * int(sg / 2), tn = 32 * int(sg % 2); + const device bfloat* qr[2]; + const device bfloat* wr[2]; + TF_UNROLL + for (short h = 0; h < 2; h++) { + const int r = tm + home.y + 8 * h; + const long at = long(r0 + (r < rows ? r : 0)); + qr[h] = iq + at * a.q_stride; + wr[h] = iw + at * a.w_stride; + } + frag total[2] = {frag(0), frag(0)}; + for (int hd = 0; hd < HI; hd++) { + frag s[2] = {frag(0), frag(0)}; + TF_UNROLL + for (short q = 0; q < DI / 16; q++) { + frag k0, k1; + frag_get(k0, tileT, TPAD, 16 * q, tn, home); + frag_get(k1, tileT, TPAD, 16 * q, tn + 16, home); + const frag qa = ix_frag(qr[0] + hd * DI, qr[1] + hd * DI, 16 * q, home); + mma_16x32(s[0], s[1], qa, k0, k1); + } + const float w0 = float(wr[0][hd]), w1 = float(wr[1][hd]); + TF_UNROLL + for (short j = 0; j < 2; j++) { + TF_UNROLL + for (short e = 0; e < 8; e++) total[j][e] = fma(e < 4 ? w0 : w1, metal::max(s[j][e], 0.0f), total[j][e]); + } + } + TF_UNROLL + for (short j = 0; j < 2; j++) { + TF_UNROLL + for (short e = 0; e < 8; e++) { + const int r = tm + home.y + (e >> 2) * 8; + const int b = b0 + tn + 16 * j + home.x + TF_COL(e); + if (r < rows && b < (int(a.p0) + r0 + r + 1) / 4) scores[size_t(r0 + r) * a.s_stride + b] = total[j][e]; + } + } +#else threadgroup bfloat tile[64 * PAD]; const int b0 = int(tg.x) * 64, r0 = int(tg.y) * 64; const int rows = min(64, int(a.rows) - r0); @@ -102,6 +166,7 @@ inline frag ix_frag(const device bfloat* r0, const device bfloat* r1, in } } } +#endif } // A transposed right operand's element e: key (a block, the op's column), dim (on M5 the op loads it as any operand). @@ -113,11 +178,69 @@ inline short ix_key(short e, short2 home) { return home.x + TF_COL(e); } inline short ix_dim(short e, short2 home) { return home.y + (e >> 2) * 8; } #endif -// Decode index scores, grid (128-tile blocks, rows) of 4 simdgroups: 32 heads, bf16 products, relu, weights, head sum. +// Decode index scores, grid (128-tile or 64-tile under TF_GLM_M3_FAST, rows) of 4 simdgroups: 32 heads, head sum. [[kernel]] void glm_index_decode(const device bfloat* iq [[buffer(0)]], const device bfloat* iw [[buffer(1)]], const device bfloat* pool [[buffer(2)]], device float* scores [[buffer(3)]], constant GlmScoreArgs& a [[buffer(4)]], uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], uint3 tg [[threadgroup_position_in_grid]]) { +#if defined(TF_GLM_M3_FAST) && defined(TF_SIMD_FRAGS) + constexpr int TPAD = 64 + 8; + threadgroup bfloat tileT[64 * TPAD]; + const int row = int(tg.y), blk0 = int(tg.x) * 64; + const int blocks = (int(a.p0) + row + 1) / 4; + if (blk0 >= blocks) return; + const uint t = sg * 32 + lane; + const short2 home = frag_home(ushort(lane)); + const int bs = blk0 + 16 * int(sg); + const device bfloat* q = iq + long(row) * a.q_stride; + frag s[2] = {frag(0), frag(0)}; + for (int kd = 0; kd < DI; kd += 64) { + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint i = t; i < 64u * 8u; i += 128u) { + const uint rr = i >> 3, cc = (i & 7u) * 8u; + const int bk = min(blk0 + int(rr), blocks - 1); + const uint4 v = *(const device uint4*)(pool + long(bk) * DI + kd + cc); + const bfloat2 p0 = as_type(v.x), p1 = as_type(v.y); + const bfloat2 p2 = as_type(v.z), p3 = as_type(v.w); + tileT[(cc + 0) * TPAD + rr] = p0.x; tileT[(cc + 1) * TPAD + rr] = p0.y; + tileT[(cc + 2) * TPAD + rr] = p1.x; tileT[(cc + 3) * TPAD + rr] = p1.y; + tileT[(cc + 4) * TPAD + rr] = p2.x; tileT[(cc + 5) * TPAD + rr] = p2.y; + tileT[(cc + 6) * TPAD + rr] = p3.x; tileT[(cc + 7) * TPAD + rr] = p3.y; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (bs < blocks) { + TF_UNROLL + for (short sub = 0; sub < 4; sub++) { + const int kq = (kd / 16) + sub; + frag k0; + frag_get(k0, tileT, TPAD, 16 * sub, 16 * int(sg), home); + const frag qa0 = ix_frag(q + home.y * DI, q + (home.y + 8) * DI, 16 * kq, home); + const frag qa1 = ix_frag(q + (16 + home.y) * DI, q + (24 + home.y) * DI, 16 * kq, home); + mma_16x16(s[0], qa0, k0); + mma_16x16(s[1], qa1, k0); + } + } + } + if (bs >= blocks) return; + float w[2][2]; + TF_UNROLL + for (short m = 0; m < 2; m++) { + w[m][0] = float(iw[long(row) * a.w_stride + 16 * m + home.y]); + w[m][1] = float(iw[long(row) * a.w_stride + 16 * m + home.y + 8]); + } + TF_UNROLL + for (short c = 0; c < 4; c++) { + float tv = w[0][0] * metal::max(s[0][c], 0.0f); + tv = fma(w[0][1], metal::max(s[0][4 + c], 0.0f), tv); + tv = fma(w[1][0], metal::max(s[1][c], 0.0f), tv); + tv = fma(w[1][1], metal::max(s[1][4 + c], 0.0f), tv); + tv += simd_shuffle_xor(tv, ushort(2)); + tv += simd_shuffle_xor(tv, ushort(4)); + tv += simd_shuffle_xor(tv, ushort(16)); + const int b = bs + home.x + TF_COL(c); + if (home.y == 0 && b < blocks) scores[long(row) * a.s_stride + b] = tv; + } +#else const int row = int(tg.y), b0 = int(tg.x) * 128 + 32 * int(sg); const int blocks = (int(a.p0) + row + 1) / 4; if (b0 >= blocks) return; @@ -171,4 +294,5 @@ inline short ix_dim(short e, short2 home) { return home.y + (e >> 2) * 8; } if (home.y == 0 && b < blocks) scores[long(row) * a.s_stride + b] = t; } } +#endif } diff --git a/zig/kernels/metal/glm_kda_prompt.metal b/zig/kernels/metal/glm_kda_prompt.metal index 79ced70bf9d..910fe908391 100644 --- a/zig/kernels/metal/glm_kda_prompt.metal +++ b/zig/kernels/metal/glm_kda_prompt.metal @@ -19,6 +19,50 @@ template const uint h = tg.y * (uint)HB + sg; const uint PS = (uint)P_shape[1]; const size_t at = (size_t)rl * W + h * (uint)D; +#ifdef TF_GLM_M3_FAST + const uint d = 4u * lane; + float4 sq = float4(0.0f), sk = float4(0.0f); + for (uint part = 0; part < 3u; ++part) { + const uint c = part * W + h * (uint)D + d; + float4 acc = float4(0.0f); + for (int j = 0; j < TAPS; ++j) { + const int e = r + j; + const bfloat4 xv = e < TAPS - 1 + ? *(const device bfloat4*)(CS + (size_t)e * C3 + c) + : *(const device bfloat4*)(P + (size_t)(e - (TAPS - 1)) * PS + c); + const float4 cw = *(const device float4*)(CW + (size_t)j * C3 + c); + const float4 term = float4(xv) * cw; + acc = j == 0 ? term : (acc + term); + } + const bfloat4 xb = bfloat4(acc); + bfloat4 sl; + sl.x = xb.x * mlx_sigmoid_precise(xb.x); + sl.y = xb.y * mlx_sigmoid_precise(xb.y); + sl.z = xb.z * mlx_sigmoid_precise(xb.z); + sl.w = xb.w * mlx_sigmoid_precise(xb.w); + if (part == 0u) sq = float4(sl); + else if (part == 1u) sk = float4(sl); + else *(device bfloat4*)(VO + at + d) = sl; + } + const float a_h = A[h], lb = LB[0]; + const float4 av = float4(*(const device bfloat4*)(FB + at + d)) + *(const device float4*)(DTB + h * (uint)D + d); + float4 go; + go.x = metal::precise::exp(lb * mlx_sigmoid_precise(a_h * av.x)); + go.y = metal::precise::exp(lb * mlx_sigmoid_precise(a_h * av.y)); + go.z = metal::precise::exp(lb * mlx_sigmoid_precise(a_h * av.z)); + go.w = metal::precise::exp(lb * mlx_sigmoid_precise(a_h * av.w)); + *(device float4*)(GO + at + d) = go; + if (lane == 0u) BETA[(size_t)rl * H + h] = float(mlx_sigmoid_precise(P[(size_t)r * PS + BO + h])); + float pq = 0.0f, pk = 0.0f; + pq = sq_acc(pq, sq.x); pq = sq_acc(pq, sq.y); pq = sq_acc(pq, sq.z); pq = sq_acc(pq, sq.w); + pk = sq_acc(pk, sk.x); pk = sq_acc(pk, sk.y); pk = sq_acc(pk, sk.z); pk = sq_acc(pk, sk.w); + pq = simd_sum(pq); + pk = simd_sum(pk); + const float rq = metal::precise::rsqrt(pq + 1.0e-6f), rk = metal::precise::rsqrt(pk + 1.0e-6f); + const float qscale = metal::precise::rsqrt(float(D)); + *(device bfloat4*)(QO + at + d) = bfloat4((sq * rq) * qscale); + *(device bfloat4*)(KO + at + d) = bfloat4(sk * rk); +#else float sq[NDK], sk[NDK]; for (uint part = 0; part < 3u; ++part) { for (int i = 0; i < NDK; ++i) { @@ -60,6 +104,7 @@ template QO[at + d] = bfloat((sq[i] * rq) * qscale); KO[at + d] = bfloat(sk[i] * rk); } +#endif } // Recurrence over R rows: 8 lanes a value column (16 key dims each, 8-way xor-shuffle sums), rows staged B at a time. @@ -81,6 +126,73 @@ template const int c = int(sg) * 4 + int(lane >> 3); // this lane's value column in the threadgroup const uint dv = tg.x * (uint)VC + (uint)c; const int k0 = NK * int(lane & 7u); +#ifdef TF_GLM_M3_FAST + const device float4* si4 = (const device float4*)(ST + ((size_t)h * D + dv) * D + k0); + float4 st4[4]; + for (int i = 0; i < 4; ++i) st4[i] = si4[i]; + for (int r0 = 0; r0 < R; r0 += B) { + const int n = min(B, R - r0); + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int idx = int(tid); idx < n * (D / 8); idx += NT) { + const int b = idx / (D / 8), d8 = (idx % (D / 8)) * 8; + const size_t at = (size_t)(r0 + b) * W + h * (uint)D + (uint)d8; + *(threadgroup uint4*)(sqs + b * D + d8) = *(const device uint4*)(QO + at); + *(threadgroup uint4*)(sks + b * D + d8) = *(const device uint4*)(KO + at); + *(threadgroup float4*)(sgs + b * D + d8) = *(const device float4*)(GO + at); + *(threadgroup float4*)(sgs + b * D + d8 + 4) = *(const device float4*)(GO + at + 4); + } + for (int idx = int(tid); idx < n * (VC / 8); idx += NT) { + const int b = idx / (VC / 8), cc = (idx % (VC / 8)) * 8; + *(threadgroup uint4*)(svs + b * VC + cc) = *(const device uint4*)(VO + (size_t)(r0 + b) * W + h * (uint)D + tg.x * (uint)VC + (uint)cc); + } + if (int(tid) < n) sbs[tid] = BETA[(size_t)(r0 + int(tid)) * H + h]; + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int b = 0; b < n; ++b) { + const threadgroup uint4* qv = (const threadgroup uint4*)(sqs + b * D + k0); + const threadgroup uint4* kv4 = (const threadgroup uint4*)(sks + b * D + k0); + const threadgroup float4* gv = (const threadgroup float4*)(sgs + b * D + k0); + const uint4 k_lo = kv4[0], k_hi = kv4[1]; + const uint4 q_lo = qv[0], q_hi = qv[1]; + float kv = 0.0f; + float4 kf[4]; + _Pragma("clang loop unroll(full)") + for (int j = 0; j < 4; ++j) { + const uint w0 = j < 2 ? k_lo[2 * j] : k_hi[2 * (j - 2)]; + const uint w1 = j < 2 ? k_lo[2 * j + 1] : k_hi[2 * (j - 2) + 1]; + const bfloat2 b0 = as_type(w0), b1 = as_type(w1); + kf[j] = float4(float(b0.x), float(b0.y), float(b1.x), float(b1.y)); + st4[j] = st4[j] * gv[j]; + kv += st4[j].x * kf[j].x; + kv += st4[j].y * kf[j].y; + kv += st4[j].z * kf[j].z; + kv += st4[j].w * kf[j].w; + } + kv += simd_shuffle_xor(kv, ushort(1)); + kv += simd_shuffle_xor(kv, ushort(2)); + kv += simd_shuffle_xor(kv, ushort(4)); + const float delta = (float(svs[b * VC + c]) - kv) * sbs[b]; + float o = 0.0f; + _Pragma("clang loop unroll(full)") + for (int j = 0; j < 4; ++j) { + const uint w0 = j < 2 ? q_lo[2 * j] : q_hi[2 * (j - 2)]; + const uint w1 = j < 2 ? q_lo[2 * j + 1] : q_hi[2 * (j - 2) + 1]; + const bfloat2 b0 = as_type(w0), b1 = as_type(w1); + const float4 qf = float4(float(b0.x), float(b0.y), float(b1.x), float(b1.y)); + st4[j] = st4[j] + kf[j] * delta; + o += st4[j].x * qf.x; + o += st4[j].y * qf.y; + o += st4[j].z * qf.z; + o += st4[j].w * qf.w; + } + o += simd_shuffle_xor(o, ushort(1)); + o += simd_shuffle_xor(o, ushort(2)); + o += simd_shuffle_xor(o, ushort(4)); + if ((lane & 7u) == 0u) SY[(size_t)(r0 + b) * W + h * (uint)D + dv] = bfloat(o); + } + } + device float4* so4 = (device float4*)(ST_OUT + ((size_t)h * D + dv) * D + k0); + for (int i = 0; i < 4; ++i) so4[i] = st4[i]; +#else device const float* si = ST + ((size_t)h * D + dv) * D + k0; float st[NK]; _Pragma("clang loop unroll(full)") @@ -130,6 +242,7 @@ template device float* so = ST_OUT + ((size_t)h * D + dv) * D + k0; _Pragma("clang loop unroll(full)") for (int i = 0; i < NK; ++i) so[i] = st[i]; +#endif } template @@ -137,10 +250,15 @@ template const device float* ONW [[buffer(2)]], const constant float* EPS [[buffer(3)]], device bfloat16_t* Y [[buffer(4)]], const device bfloat16_t* P [[buffer(5)]], const constant int* P_shape [[buffer(6)]], const device bfloat16_t* CS [[buffer(7)]], - device bfloat16_t* CS_OUT [[buffer(8)]], uint lane [[thread_index_in_simdgroup]], + device bfloat16_t* CS_OUT [[buffer(8)]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]], uint3 threadgroup_position_in_grid [[threadgroup_position_in_grid]]) { const int r = int(threadgroup_position_in_grid.x); +#ifdef TF_GLM_M3_FAST + const uint h = threadgroup_position_in_grid.y * 4u + sg; +#else const uint h = threadgroup_position_in_grid.y; +#endif constexpr int RBLK = D / 128; constexpr int REXTRA = D - RBLK * 128; constexpr uint W = (uint)(H * D); @@ -149,6 +267,25 @@ template const uint PS = (uint)P_shape[1]; const float eps = EPS[0]; const size_t at = (size_t)r * W + h * (uint)D; +#ifdef TF_GLM_M3_FAST + const uint base = 4u * lane; + const float4 sy4 = float4(*(const device bfloat4*)(SY + at + base)); + float po = 0.0f; + po = sq_acc(po, sy4.x); + po = sq_acc(po, sy4.y); + po = sq_acc(po, sy4.z); + po = sq_acc(po, sy4.w); + po = simd_sum(po); + const float rn = metal::precise::rsqrt(po / (float)D + eps); + const float4 onw = *(const device float4*)(ONW + base); + const float4 g4 = float4(*(const device bfloat4*)(GATE + at + base)); + float4 y4 = (sy4 * rn) * onw; + y4.x *= mlx_sigmoid_precise(g4.x); + y4.y *= mlx_sigmoid_precise(g4.y); + y4.z *= mlx_sigmoid_precise(g4.z); + y4.w *= mlx_sigmoid_precise(g4.w); + *(device bfloat4*)(Y + at + base) = bfloat4(y4); +#else float po = 0.0f; for (int blk = 0; blk < RBLK; ++blk) { const uint base = (uint)(blk * 128) + 4u * lane; @@ -164,6 +301,7 @@ template x = x * mlx_sigmoid_precise(float(GATE[at + d])); Y[at + d] = bfloat(x); } +#endif if (r != 0) return; for (uint idx = lane; idx < 3u * (uint)D * (uint)(TAPS - 1); idx += 32u) { // the next chunk's window: the last rows const uint m = idx / (3u * (uint)D); @@ -177,9 +315,17 @@ template } template [[host_name("glm_kda_prep")]] [[kernel]] decltype(glm_kda_prep<64, 128, 4, 4>) glm_kda_prep<64, 128, 4, 4>; +#ifdef TF_GLM_M3_FAST +template [[host_name("glm_kda_scan")]] [[kernel]] decltype(glm_kda_scan<64, 128, 4, 24>) glm_kda_scan<64, 128, 4, 24>; +#else template [[host_name("glm_kda_scan")]] [[kernel]] decltype(glm_kda_scan<64, 128, 16, 16>) glm_kda_scan<64, 128, 16, 16>; +#endif template [[host_name("glm_kda_post")]] [[kernel]] decltype(glm_kda_post<64, 128, 4, 32, 4, 4>) glm_kda_post<64, 128, 4, 32, 4, 4>; // TP2: one Mac's 32 heads template [[host_name("glm_kda_prep_tp")]] [[kernel]] decltype(glm_kda_prep<32, 128, 4, 4>) glm_kda_prep<32, 128, 4, 4>; +#ifdef TF_GLM_M3_FAST +template [[host_name("glm_kda_scan_tp")]] [[kernel]] decltype(glm_kda_scan<32, 128, 4, 24>) glm_kda_scan<32, 128, 4, 24>; +#else template [[host_name("glm_kda_scan_tp")]] [[kernel]] decltype(glm_kda_scan<32, 128, 16, 16>) glm_kda_scan<32, 128, 16, 16>; +#endif template [[host_name("glm_kda_post_tp")]] [[kernel]] decltype(glm_kda_post<32, 128, 4, 32, 4, 4>) glm_kda_post<32, 128, 4, 32, 4, 4>; diff --git a/zig/kernels/metal/idol.metal b/zig/kernels/metal/idol.metal new file mode 100644 index 00000000000..f687b50e5a7 --- /dev/null +++ b/zig/kernels/metal/idol.metal @@ -0,0 +1,331 @@ +// Idol's denoiser steps after gemm_nax.metal: fp16 rows rounded where idol-sdk's torch code rounds them. + +inline float id_h(float x) { return float(half(x)); } + +// One threadgroup's sum of every thread's `v` (at most 1,024 threads), returned to all of them. +inline float id_sum(float v, threadgroup float* part, uint n, uint lane, uint sg) { + v = simd_sum(v); + if (lane == 0) part[sg] = v; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg == 0) { + float s = lane < (n + 31) / 32 ? part[lane] : 0.0f; + s = simd_sum(s); + if (lane == 0) part[32] = s; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + const float out = part[32]; + threadgroup_barrier(mem_flags::mem_threadgroup); + return out; +} + +// torch's tanh GELU of an fp16 value, computed in fp32. +inline float id_gelu(float x) { + const float inner = 0.7978845608028654f * (x + 0.044715f * x * x * x); + return 0.5f * x * (1.0f + metal::precise::tanh(inner)); +} + +// ---- y [M, N] = fp16(x w^T + b) (EPI 1: then GELU, rounded again): tfp::gemm_nax's block, fp32 sums ---- +template +inline void id_linear(const device half* A, const device half* B, const device half* bias, device half* D, + const device int* P, uint3 tg, uint sg, uint lane) { + constexpr int BM = 64, BN = 128, BK = 256, WN = 4; + const int tx = int(tg.x), ty = int(tg.y); + if (tx >= P[6] || ty >= P[7]) return; + const int lda = P[3], ldb = P[4], ldd = P[5]; + const int row = ty * BM + 32 * int(sg / WN), col = tx * BN + 32 * int(sg % WN); + A += long(row) * lda; + B += long(col) * ldb; + D += long(row) * ldd + col; + const int rows = AM ? 32 : min(32, P[0] - row), cols = AN ? 32 : min(32, P[1] - col); + const bool full = (AM || rows == 32) && (AN || cols == 32); + const short2 home = tfp::frag_home(ushort(lane)); + tfp::frag acc[2][2]; + if (full) { + tfp::gemm_block(acc, A, B, lda, ldb, P[2], P[9], rows, cols, home); + } else { + tfp::gemm_block(acc, A, B, lda, ldb, P[2], P[9], rows, cols, home); + } + TF_UNROLL + for (short j = 0; j < 2; j++) { + TF_UNROLL + for (short e = 0; e < 8; e++) { + const int c = col + 16 * j + home.x + TF_COL(e); + const float b = c < P[1] ? float(bias[c]) : 0.0f; + TF_UNROLL + for (short i = 0; i < 2; i++) { + const float v = id_h(acc[i][j][e] + b); + acc[i][j][e] = EPI == 1 ? id_gelu(v) : v; + } + } + } + if (full) { + tfp::gemm_store(acc, D, ldd, rows, cols, home); + } else if (rows > 0 && cols > 0) { + tfp::gemm_store(acc, D, ldd, rows, cols, home); + } +} + +#define ID_LINEAR(NAME, EPI, AM, AN) \ + [[max_total_threads_per_threadgroup(256)]] [[kernel]] void NAME( \ + const device half* A [[buffer(0)]], const device half* B [[buffer(1)]], const device int32_t* P [[buffer(2)]], \ + device half* D [[buffer(3)]], const device half* bias [[buffer(4)]], uint sg [[simdgroup_index_in_threadgroup]], \ + uint lane [[thread_index_in_simdgroup]], uint3 tg [[threadgroup_position_in_grid]]) { \ + id_linear(A, B, bias, D, P, tg, sg, lane); \ + } +ID_LINEAR(id_linear_00, 0, false, false) +ID_LINEAR(id_linear_01, 0, false, true) +ID_LINEAR(id_linear_10, 0, true, false) +ID_LINEAR(id_linear_11, 0, true, true) +ID_LINEAR(id_linear_gelu_00, 1, false, false) +ID_LINEAR(id_linear_gelu_01, 1, false, true) +ID_LINEAR(id_linear_gelu_10, 1, true, false) +ID_LINEAR(id_linear_gelu_11, 1, true, true) + +struct IdGemm32 { + uint M, N, K, ldy; +}; + +// y [M, N] (rows ldy apart) = x [M, K] w^T, fp32 FMA on 8x8 simdgroup matrices; K % 32, N % 64 (or N < 64, % 8) = 0. +[[max_total_threads_per_threadgroup(128)]] [[kernel]] void id_gemm32( + const device float* x [[buffer(0)]], const device float* w [[buffer(1)]], device float* y [[buffer(2)]], + constant IdGemm32& p [[buffer(3)]], uint2 tg [[threadgroup_position_in_grid]], uint t [[thread_index_in_threadgroup]], + uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]]) { + constexpr uint BK = 32, LD = BK + 4; + threadgroup float ta[64 * LD]; + threadgroup float tb[64 * LD]; + threadgroup float stage[4][64]; + const uint row0 = tg.y * 64, col0 = tg.x * 64; + const uint r0 = (sg / 2) * 32, c0 = (sg % 2) * 32; + const uint cols = min(64u, p.N - col0); + simdgroup_float8x8 acc[4][4]; + for (uint i = 0; i < 4; i++) + for (uint j = 0; j < 4; j++) acc[i][j] = make_filled_simdgroup_matrix(0.0f); + for (uint k = 0; k < p.K; k += BK) { + // 64 x 32 of x and of w: 2,048 values each, 16 a thread as float4s; rows past M or N read as zeros + for (uint e = t; e < 64 * BK / 4; e += 128) { + const uint r = e / (BK / 4), c = (e % (BK / 4)) * 4; + const float4 va = row0 + r < p.M ? *(const device float4*)(x + ulong(row0 + r) * p.K + k + c) : float4(0.0f); + const float4 vb = r < cols ? *(const device float4*)(w + ulong(col0 + r) * p.K + k + c) : float4(0.0f); + *(threadgroup float4*)(ta + r * LD + c) = va; + *(threadgroup float4*)(tb + r * LD + c) = vb; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint kk = 0; kk < BK; kk += 8) { + simdgroup_float8x8 a[4], b[4]; + for (uint i = 0; i < 4; i++) simdgroup_load(a[i], ta + (r0 + 8 * i) * LD + kk, LD); + for (uint j = 0; j < 4; j++) simdgroup_load(b[j], tb + (c0 + 8 * j) * LD + kk, LD, ulong2(0, 0), true); + for (uint i = 0; i < 4; i++) + for (uint j = 0; j < 4; j++) simdgroup_multiply_accumulate(acc[i][j], a[i], b[j], acc[i][j]); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + for (uint i = 0; i < 4; i++) { + for (uint j = 0; j < 4; j++) { + const uint r = row0 + r0 + 8 * i, c = c0 + 8 * j; + if (r >= p.M || c >= cols) continue; + if (r + 8 <= p.M) { + simdgroup_store(acc[i][j], y + ulong(r) * p.ldy + col0 + c, p.ldy); + } else { + simdgroup_store(acc[i][j], stage[sg], 8); + simdgroup_barrier(mem_flags::mem_threadgroup); + for (uint e = lane; e < 64; e += 32) + if (r + e / 8 < p.M) y[ulong(r + e / 8) * p.ldy + col0 + c + e % 8] = stage[sg][e]; + simdgroup_barrier(mem_flags::mem_threadgroup); + } + } + } +} + +// c [M, N] fp32 = a [M, K] b^T over fp16 operands, tfp::gemm_splitk_nax's one partition (fp32 sums). +#define ID_SPLIT(NAME, AM) \ + [[max_total_threads_per_threadgroup(128)]] [[kernel]] void NAME( \ + const device half* A [[buffer(0)]], const device half* B [[buffer(1)]], const device int32_t* P [[buffer(2)]], \ + device float* C [[buffer(3)]], uint sg [[simdgroup_index_in_threadgroup]], \ + uint lane [[thread_index_in_simdgroup]], uint3 tg [[threadgroup_position_in_grid]]) { \ + tfp::gemm_splitk_nax(A, B, C, P, tg, sg, lane); \ + } +ID_SPLIT(id_split_0, false) +ID_SPLIT(id_split_1, true) + +struct IdNorm { + uint width; + float eps; + uint mode; // 0 plain, 1 affine (fp32 w, b), 2 modulated (fp16 1 + scale, shift) +}; + +// LayerNorm32 of an fp16 row in fp32, rounded to fp16; then affine in fp32, or modulated in fp16. A threadgroup a row. +[[max_total_threads_per_threadgroup(256)]] [[kernel]] void id_norm( + const device half* x [[buffer(0)]], const device float* w [[buffer(1)]], const device float* b [[buffer(2)]], + const device half* s1 [[buffer(3)]], const device half* sh [[buffer(4)]], device half* y [[buffer(5)]], + constant IdNorm& p [[buffer(6)]], uint row [[threadgroup_position_in_grid]], uint t [[thread_position_in_threadgroup]], + uint n [[threads_per_threadgroup]], uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]]) { + threadgroup float part[33]; + const device half* xr = x + ulong(row) * p.width; + device half* yr = y + ulong(row) * p.width; + float a = 0.0f; + for (uint i = t; i < p.width; i += n) a += float(xr[i]); + const float mean = id_sum(a, part, n, lane, sg) / float(p.width); + float q = 0.0f; + for (uint i = t; i < p.width; i += n) q += (float(xr[i]) - mean) * (float(xr[i]) - mean); + const float inv = metal::precise::rsqrt(id_sum(q, part, n, lane, sg) / float(p.width) + p.eps); + for (uint i = t; i < p.width; i += n) { + float v = (float(xr[i]) - mean) * inv; + if (p.mode == 1) v = v * w[i] + b[i]; + v = id_h(v); + if (p.mode == 2) v = id_h(id_h(v * float(s1[i])) + float(sh[i])); + yr[i] = half(v); + } +} + +// Affine LayerNorm32 of an fp16 row as fp16 [hi | hi | lo] of 3 * width: times [w_hi | w_lo | w_hi], near-fp32 sums. +[[max_total_threads_per_threadgroup(256)]] [[kernel]] void id_norm_split( + const device half* x [[buffer(0)]], const device float* w [[buffer(1)]], const device float* b [[buffer(2)]], + device half* y [[buffer(3)]], constant IdNorm& p [[buffer(4)]], uint row [[threadgroup_position_in_grid]], + uint t [[thread_position_in_threadgroup]], uint n [[threads_per_threadgroup]], + uint lane [[thread_index_in_simdgroup]], uint sg [[simdgroup_index_in_threadgroup]]) { + threadgroup float part[33]; + const device half* xr = x + ulong(row) * p.width; + device half* yr = y + ulong(row) * 3 * p.width; + float a = 0.0f; + for (uint i = t; i < p.width; i += n) a += float(xr[i]); + const float mean = id_sum(a, part, n, lane, sg) / float(p.width); + float q = 0.0f; + for (uint i = t; i < p.width; i += n) q += (float(xr[i]) - mean) * (float(xr[i]) - mean); + const float inv = metal::precise::rsqrt(id_sum(q, part, n, lane, sg) / float(p.width) + p.eps); + for (uint i = t; i < p.width; i += n) { + const float v = (float(xr[i]) - mean) * inv * w[i] + b[i]; + const half hi = half(v); + yr[i] = hi; + yr[p.width + i] = hi; + yr[2 * p.width + i] = half(v - float(hi)); + } +} + +// LayerNorm of an fp16 row in fp32 kept in fp32: affine (w, b) when given, else times (1 + scale) plus shift (mode 2). +[[max_total_threads_per_threadgroup(256)]] [[kernel]] void id_norm32( + const device half* x [[buffer(0)]], const device float* w [[buffer(1)]], const device float* b [[buffer(2)]], + device float* y [[buffer(3)]], constant IdNorm& p [[buffer(4)]], uint row [[threadgroup_position_in_grid]], + uint t [[thread_position_in_threadgroup]], uint n [[threads_per_threadgroup]], + uint lane [[thread_index_in_simdgroup]], uint sg [[simdgroup_index_in_threadgroup]]) { + threadgroup float part[33]; + const device half* xr = x + ulong(row) * p.width; + device float* yr = y + ulong(row) * p.width; + float a = 0.0f; + for (uint i = t; i < p.width; i += n) a += float(xr[i]); + const float mean = id_sum(a, part, n, lane, sg) / float(p.width); + float q = 0.0f; + for (uint i = t; i < p.width; i += n) q += (float(xr[i]) - mean) * (float(xr[i]) - mean); + const float inv = metal::precise::rsqrt(id_sum(q, part, n, lane, sg) / float(p.width) + p.eps); + for (uint i = t; i < p.width; i += n) { + const float v = (float(xr[i]) - mean) * inv; + yr[i] = p.mode == 2 ? v * (1.0f + w[i]) + b[i] : v * w[i] + b[i]; + } +} + +struct IdRepo { + uint rows; + uint stride; // fp32 values from one row's gate sums to the next; content sums follow gate's 128 + float inv; // the maps' power-of-two scale undone, exactly +}; + +// RePo: d = final_map(silu(gate) * content), 3 per head; angles clamp_mul(d, freqs) * pi as cos, sin [rows, 16, 32]. +[[max_total_threads_per_threadgroup(64)]] [[kernel]] void id_repo( + const device float* gc [[buffer(0)]], const device float* wf [[buffer(1)]], const device float* f [[buffer(2)]], + device float* cs [[buffer(3)]], device float* sn [[buffer(4)]], constant IdRepo& p [[buffer(5)]], + uint row [[threadgroup_position_in_grid]], uint t [[thread_position_in_threadgroup]]) { + threadgroup float u[128]; + threadgroup float d[48]; + const device float* g = gc + ulong(row) * p.stride; + for (uint i = t; i < 128; i += 64) { + const float a = g[i] * p.inv; + u[i] = (a / (1.0f + metal::precise::exp(-a))) * (g[128 + i] * p.inv); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t < 48) { + float s = 0.0f; + for (uint k = 0; k < 128; k++) s = fma(u[k], wf[t * 128 + k], s); + d[t] = s; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + // freqs: 10 x, 10 y, 12 z; each pair of the 32 takes its axis's offset + for (uint i = t; i < 512; i += 64) { + const uint h = i / 32, j = i % 32; + const uint axis = j < 10 ? 0 : (j < 20 ? 1 : 2); + const float x = d[h * 3 + axis], fr = f[j]; + const float ft = metal::precise::tanh(fr); + const float ang = (x * ft + x * (fr - ft)) * 3.14159265358979323846f; + cs[ulong(row) * 512 + i] = metal::precise::cos(ang); + sn[ulong(row) * 512 + i] = metal::precise::sin(ang); + } +} + +struct IdHeads { + uint rows; + float scale; // sqrt(head width): MultiHeadRMSNorm's +}; + +// q, k of qkv rows: pairs turned by the row and head's cos, sin; F.normalize * gamma * scale; out [16, rows, 64]. +[[max_total_threads_per_threadgroup(256)]] [[kernel]] void id_qk( + const device half* qkv [[buffer(0)]], const device float* gq [[buffer(1)]], const device float* gk [[buffer(2)]], + const device float* cs [[buffer(3)]], const device float* sn [[buffer(4)]], device half* Q [[buffer(5)]], + device half* K [[buffer(6)]], device half* V [[buffer(7)]], constant IdHeads& p [[buffer(8)]], + uint2 tg [[threadgroup_position_in_grid]], uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]]) { + const uint r = tg.x, h = tg.y * 8 + sg; + if (h >= 16) return; + const ulong from = ulong(r) * 3072 + h * 64 + lane * 2; + const ulong at = ulong(r) * 512 + h * 32 + lane; + const float c = cs[at], s = sn[at]; + const float q0 = float(qkv[from]), q1 = float(qkv[from + 1]); + const float k0 = float(qkv[from + 1024]), k1 = float(qkv[from + 1025]); + const float rq0 = id_h(q0 * c - q1 * s), rq1 = id_h(q0 * s + q1 * c); + const float rk0 = id_h(k0 * c - k1 * s), rk1 = id_h(k0 * s + k1 * c); + // F.normalize's clamp_min keeps a NaN norm, where Metal's max would drop it + const float sq = metal::precise::sqrt(simd_sum(rq0 * rq0 + rq1 * rq1)); + const float sk = metal::precise::sqrt(simd_sum(rk0 * rk0 + rk1 * rk1)); + const float qn = isnan(sq) ? sq : max(sq, 1e-12f), kn = isnan(sk) ? sk : max(sk, 1e-12f); + const uint g = h * 64 + lane * 2; + const ulong to = (ulong(h) * p.rows + r) * 64 + lane * 2; + Q[to] = half(rq0 / qn * gq[g] * p.scale); + Q[to + 1] = half(rq1 / qn * gq[g + 1] * p.scale); + K[to] = half(rk0 / kn * gk[g] * p.scale); + K[to + 1] = half(rk1 / kn * gk[g + 1] * p.scale); + V[to] = qkv[from + 2048]; + V[to + 1] = qkv[from + 2049]; +} + +// x = fp16(x + fp16(g * y)) by column; g is a modulation gate, or ones for an ungated residual. +[[max_total_threads_per_threadgroup(256)]] [[kernel]] void id_gate_add( + device half* x [[buffer(0)]], const device half* y [[buffer(1)]], const device half* g [[buffer(2)]], + constant uint& width [[buffer(3)]], uint2 at [[thread_position_in_grid]]) { + const ulong i = ulong(at.y) * width + at.x; + x[i] = half(float(x[i]) + id_h(float(g[at.x]) * float(y[i]))); +} + +// x = fp16(fp16(z w^T + b) + pe): the latent's input projection (16 inputs, fp32) and its fp16 position embedding. +[[max_total_threads_per_threadgroup(256)]] [[kernel]] void id_embed( + const device float* z [[buffer(0)]], const device float* w [[buffer(1)]], const device float* b [[buffer(2)]], + const device half* pe [[buffer(3)]], device half* x [[buffer(4)]], uint2 at [[thread_position_in_grid]]) { + const uint c = at.x, r = at.y; + float s = 0.0f; + for (uint k = 0; k < 16; k++) s = fma(z[r * 16 + k], w[c * 16 + k], s); + const ulong i = ulong(r) * 1024 + c; + x[i] = half(float(half(s + b[c])) + float(pe[i])); +} + +// y = fp16(a + ba + c + bc) by column: the two condition projections' fp32 sums and biases (each torch Linear). +[[max_total_threads_per_threadgroup(256)]] [[kernel]] void id_cond( + const device float* a [[buffer(0)]], const device float* ba [[buffer(1)]], const device float* c [[buffer(2)]], + const device float* bc [[buffer(3)]], device half* y [[buffer(4)]], constant uint& width [[buffer(5)]], + uint2 at [[thread_position_in_grid]]) { + const ulong i = ulong(at.y) * width + at.x; + y[i] = half((a[i] + ba[at.x]) + (c[i] + bc[at.x])); +} + +// y = x + b by column in fp32 (an fp32 Linear's bias), in place. +[[max_total_threads_per_threadgroup(256)]] [[kernel]] void id_bias32( + device float* y [[buffer(0)]], const device float* b [[buffer(1)]], constant uint& width [[buffer(2)]], + uint2 at [[thread_position_in_grid]]) { + y[ulong(at.y) * width + at.x] += b[at.x]; +} diff --git a/zig/kernels/metal/idol_attention.metal b/zig/kernels/metal/idol_attention.metal new file mode 100644 index 00000000000..8cc6919b338 --- /dev/null +++ b/zig/kernels/metal/idol_attention.metal @@ -0,0 +1,150 @@ +// Idol's attention: tfp::attention_nax's online softmax at head width 64, every query row to every key row. + +constant constexpr float kIdMasked = -3.402823466e+38f; +constant constexpr int kIdAnyCols = 1 << 30; + +// Fold one fragment's rows into r[2] (rows home.y, home.y + 8): pairs, then lanes 1 and 8 apart, then into r. +template +inline void id_fold(thread const tfp::frag& f, thread float (&r)[2]) { + TF_UNROLL + for (short h = 0; h < 2; h++) { + const short b = 4 * h; + float t = MAX ? max(max(f[b], f[b + 1]), max(f[b + 2], f[b + 3])) : (f[b] + f[b + 1]) + (f[b + 2] + f[b + 3]); + const float u = simd_shuffle_xor(t, ushort(1)); + t = MAX ? max(t, u) : t + u; + const float w = simd_shuffle_xor(t, ushort(8)); + t = MAX ? max(t, w) : t + w; + r[h] = MAX ? max(r[h], t) : r[h] + t; + } +} + +// One 64-query block of one head over 32-key blocks; P and F as Kernels.attention sets them (kernels.zig). +template +inline void id_attention(const device T* Q, const device T* K, const device T* V, device T* O, const device int* P, + const device float* F, uint3 tg, uint sg, uint lane) { + constexpr int BQ = 64, BK = 32, D = 64; + const int h = int(tg.y), lq = P[1], lk = P[2]; + Q += (long(h) * lq + long(tg.x) * BQ) * D; + K += long(h) * lk * D; + V += long(h) * lk * D; + const int os = P[0] * D; + O += long(tg.x) * BQ * os + h * D; + const float scale2 = F[0] * 1.44269504089f; + const short tm = 16 * short(sg); + Q += tm * D; + const short2 home = tfp::frag_home(ushort(lane)); + + tfp::frag acc[4]; + TF_UNROLL + for (short i = 0; i < 4; i++) acc[i] = tfp::frag(0); + float top[2] = {kIdMasked, kIdMasked}, total[2] = {0.0f, 0.0f}; + const bool last_q = int(tg.x) == P[4]; + const short q_rows = short(P[6] - tm), k_rows = short(P[7]); + + for (int kb = 0; kb < P[3]; kb++) { + const bool last_k = kb == P[5]; + tfp::frag s[2] = {tfp::frag(0), tfp::frag(0)}; + TF_UNROLL + for (short d = 0; d < 4; d++) { + tfp::frag q, k0, k1; + if (!AQ && last_q) { + tfp::frag_get_in(q, Q, D, 0, 16 * d, home, q_rows, kIdAnyCols); + } else { + tfp::frag_get(q, Q, D, 0, 16 * d, home); + } + if (!AK && last_k) { + tfp::frag_get_t_in(k0, K, D, 0, 16 * d, home, k_rows, kIdAnyCols); + tfp::frag_get_t_in(k1, K, D, 16, 16 * d, home, k_rows, kIdAnyCols); + } else { + tfp::frag_get_t(k0, K, D, 0, 16 * d, home); + tfp::frag_get_t(k1, K, D, 16, 16 * d, home); + } + tfp::mma_16x32(s[0], s[1], q, k0, k1); + } + TF_UNROLL + for (short f = 0; f < 2; f++) { + TF_UNROLL + for (short e = 0; e < 8; e++) s[f][e] *= scale2; + } + if (!AK && last_k) { + TF_UNROLL + for (short f = 0; f < 2; f++) { + TF_UNROLL + for (short e = 0; e < 8; e++) s[f][e] = (16 * f + home.x + TF_COL(e)) < k_rows ? s[f][e] : kIdMasked; + } + } + float top_new[2] = {top[0], top[1]}; + id_fold(s[0], top_new); + id_fold(s[1], top_new); + TF_UNROLL + for (short f = 0; f < 2; f++) { + TF_UNROLL + // the units take an fp32 P short: round it to fp16 here, so the denominator sums the values P V multiplies + for (short e = 0; e < 8; e++) s[f][e] = float(half(fast::exp2(s[f][e] - top_new[e >> 2]))); + } + float scale_old[2]; + TF_UNROLL + for (short r = 0; r < 2; r++) { + scale_old[r] = fast::exp2(top[r] - top_new[r]); + top[r] = top_new[r]; + total[r] = total[r] * scale_old[r]; + } + id_fold(s[0], total); + id_fold(s[1], total); + TF_UNROLL + for (short i = 0; i < 4; i++) { + TF_UNROLL + for (short e = 0; e < 8; e++) acc[i][e] = acc[i][e] * scale_old[e >> 2]; + } + simdgroup_barrier(mem_flags::mem_none); + TF_UNROLL + for (short d = 0; d < 4; d += 2) { + TF_UNROLL + for (short k = 0; k < 2; k++) { + tfp::frag v0, v1; + if (!AK && last_k) { + tfp::frag_get_in(v0, V, D, 16 * k, 16 * d, home, k_rows, kIdAnyCols); + tfp::frag_get_in(v1, V, D, 16 * k, 16 * d + 16, home, k_rows, kIdAnyCols); + } else { + tfp::frag_get(v0, V, D, 16 * k, 16 * d, home); + tfp::frag_get(v1, V, D, 16 * k, 16 * d + 16, home); + } + tfp::mma_16x32(acc[d], acc[d + 1], s[k], v0, v1); + } + } + K += BK * D; + V += BK * D; + } + + threadgroup_barrier(mem_flags::mem_none); + float inv[2]; + TF_UNROLL + for (short r = 0; r < 2; r++) inv[r] = 1.f / total[r]; + TF_UNROLL + for (short i = 0; i < 4; i++) { + TF_UNROLL + for (short e = 0; e < 8; e++) acc[i][e] = acc[i][e] * inv[e >> 2]; + } + O += tm * os; + if (!AQ && last_q) { + if (q_rows <= 0) return; + TF_UNROLL + for (short i = 0; i < 4; i++) tfp::frag_put_in(acc[i], O, os, 0, 16 * i, home, q_rows, kIdAnyCols); + } else { + TF_UNROLL + for (short i = 0; i < 4; i++) tfp::frag_put(acc[i], O, os, 0, 16 * i, home); + } +} + +#define ID_ATTENTION(NAME, T, AQ, AK) \ + [[max_total_threads_per_threadgroup(128)]] [[kernel]] void NAME( \ + const device T* Q [[buffer(0)]], const device T* K [[buffer(1)]], const device T* V [[buffer(2)]], \ + const device int32_t* P [[buffer(3)]], const device float* F [[buffer(4)]], device T* O [[buffer(5)]], \ + uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], \ + uint3 tg [[threadgroup_position_in_grid]]) { \ + id_attention(Q, K, V, O, P, F, tg, sg, lane); \ + } +ID_ATTENTION(id_attention_00, half, false, false) +ID_ATTENTION(id_attention_01, half, false, true) +ID_ATTENTION(id_attention_10, half, true, false) +ID_ATTENTION(id_attention_11, half, true, true) diff --git a/zig/kernels/metal/ling/mla.metal b/zig/kernels/metal/ling/mla.metal new file mode 100644 index 00000000000..fcd813af9d5 --- /dev/null +++ b/zig/kernels/metal/ling/mla.metal @@ -0,0 +1,72 @@ +// Ling MLA extras around k3: RoPE (GPT-J pairs then halves) and per-head gate expand. + +// k3_mla_* kernels are unchanged. Layout matches ling_forward.py rot() and HF apply_rotary_pos_emb_interleave. + +// Pair (z[2i], z[2i+1]) rotates to (out[i], out[32+i]). +#include +using namespace metal; + +constant constexpr uint LAT = 512, ROPE = 64, KEY = LAT + ROPE, NOPE = 128, VD = 128, QD = NOPE + ROPE; + +struct MlaRow { + uint slot, pos; +}; + +struct MlaArgs { + device bfloat* cache; + uint slot_keys, heads, head0, rows, q_stride, kv_stride, gate_stride, out_stride; + float eps, scale; +}; + +// cs is (rows, 32, 2) f32: host f64 cos/sin of pos*inv, rounded to f32. Kernels apply only. +inline float2 ling_apply(float x0, float x1, const device float* cs, uint row, uint i) { + const uint at = (row * (ROPE / 2) + i) * 2; + const float c = cs[at], s = cs[at + 1]; + return float2(fma(x0, c, -(x1 * s)), fma(x1, c, x0 * s)); +} + +inline device bfloat* ling_keys(constant MlaArgs& a, MlaRow r) { + return a.cache + ulong(r.slot) * a.slot_keys * KEY; +} + +// In-place GPT-J rotate of the 64 rope columns k3_mla_cache just copied. + +// 32 threads, no early return: the threadgroup temp needs every lane at the barrier. + +// Cache address is rows[row].pos. +kernel void tf_ling_mla_rope_cache(device const MlaRow* rows [[buffer(0)]], constant MlaArgs& a [[buffer(1)]], + device const float* cs [[buffer(2)]], + uint row [[threadgroup_position_in_grid]], + uint t [[thread_index_in_threadgroup]]) { + threadgroup float tmp[ROPE]; + device bfloat* dst = ling_keys(a, rows[row]) + ulong(rows[row].pos) * KEY + LAT; + const float2 o = ling_apply(float(dst[2 * t]), float(dst[2 * t + 1]), cs, row, t); + tmp[t] = o.x; + tmp[t + ROPE / 2] = o.y; + threadgroup_barrier(mem_flags::mem_threadgroup); + dst[t] = bfloat(tmp[t]); + dst[t + ROPE / 2] = bfloat(tmp[t + ROPE / 2]); +} + +// Same rotate on q's rope region (offset NOPE in each head) in place. Angles from cs[row]. +kernel void tf_ling_mla_rope_q(device bfloat* q [[buffer(0)]], constant MlaArgs& a [[buffer(1)]], + device const float* cs [[buffer(2)]], + uint2 tg [[threadgroup_position_in_grid]], uint t [[thread_index_in_threadgroup]]) { + threadgroup float tmp[ROPE]; + const uint hl = tg.x, row = tg.y; + device bfloat* z = q + ulong(row) * a.q_stride + hl * QD + NOPE; + const float2 o = ling_apply(float(z[2 * t]), float(z[2 * t + 1]), cs, row, t); + tmp[t] = o.x; + tmp[t + ROPE / 2] = o.y; + threadgroup_barrier(mem_flags::mem_threadgroup); + z[t] = bfloat(tmp[t]); + z[t + ROPE / 2] = bfloat(tmp[t + ROPE / 2]); +} + +// Broadcast each per-head gate to 128 value columns so k3_mla_uv keeps Kimi's stride. +kernel void tf_ling_mla_gate_expand(device const bfloat* g [[buffer(0)]], device bfloat* g2 [[buffer(1)]], + constant MlaArgs& a [[buffer(2)]], uint2 gid [[thread_position_in_grid]]) { + const uint col = gid.x, row = gid.y; + if (row >= a.rows || col >= a.heads * VD) return; + g2[row * a.gate_stride + col] = g[row * a.heads + col / VD]; +} diff --git a/zig/kernels/metal/ling/sources.zig b/zig/kernels/metal/ling/sources.zig index 5fac014e986..6863a6cae5c 100644 --- a/zig/kernels/metal/ling/sources.zig +++ b/zig/kernels/metal/ling/sources.zig @@ -1,2 +1,3 @@ //! Ling Metal kernel sources. pub const route = @embedFile("route.metal"); +pub const mla = @embedFile("mla.metal"); diff --git a/zig/kernels/metal/nax.h b/zig/kernels/metal/nax.h index 210c6aaa4c0..341859f2cb7 100644 --- a/zig/kernels/metal/nax.h +++ b/zig/kernels/metal/nax.h @@ -1,6 +1,9 @@ // M5 tensor-unit fragments shared by every NAX kernel (ops and prefill): layout, loads, stores and the 16x32x16 op. #include #include +#if defined(TF_SIMD_FRAGS) && defined(TF_GLM_M3_FAST) +#include +#endif namespace tfp { using namespace metal; @@ -107,10 +110,15 @@ inline short2 frag_home(ushort l) { template inline void frag_get(thread frag& f, P p, int ld, int r, int c, short2 home) { const P q = p + (r + home.y) * ld + (c + home.x); +#ifdef TF_GLM_M3_FAST + f[0] = T(q[0]); f[1] = T(q[1]); f[2] = T(q[8]); f[3] = T(q[9]); + f[4] = T(q[8 * ld]); f[5] = T(q[8 * ld + 1]); f[6] = T(q[8 * ld + 8]); f[7] = T(q[8 * ld + 9]); +#else TF_UNROLL for (short e = 0; e < 8; e++) { f[e] = T(q[(e >> 2) * 8 * ld + TF_COL(e)]); } +#endif } template @@ -164,6 +172,55 @@ inline void frag_put_in(thread const frag& f, device O* p, int ld, int r, template inline void mma_16x32(thread frag& lo, thread frag& hi, thread const frag& a, thread const frag& b0, thread const frag& b1) { +#ifdef TF_GLM_M3_FAST + simdgroup_matrix a00, a01, a10, a11; + simdgroup_matrix b00, b01, b10, b11, c00, c01, c10, c11; + simdgroup_matrix d00, d01, d10, d11, e00, e01, e10, e11; + a00.thread_elements()[0] = a[0]; a00.thread_elements()[1] = a[1]; + a01.thread_elements()[0] = a[2]; a01.thread_elements()[1] = a[3]; + a10.thread_elements()[0] = a[4]; a10.thread_elements()[1] = a[5]; + a11.thread_elements()[0] = a[6]; a11.thread_elements()[1] = a[7]; + b00.thread_elements()[0] = b0[0]; b00.thread_elements()[1] = b0[1]; + b01.thread_elements()[0] = b0[2]; b01.thread_elements()[1] = b0[3]; + b10.thread_elements()[0] = b0[4]; b10.thread_elements()[1] = b0[5]; + b11.thread_elements()[0] = b0[6]; b11.thread_elements()[1] = b0[7]; + c00.thread_elements()[0] = b1[0]; c00.thread_elements()[1] = b1[1]; + c01.thread_elements()[0] = b1[2]; c01.thread_elements()[1] = b1[3]; + c10.thread_elements()[0] = b1[4]; c10.thread_elements()[1] = b1[5]; + c11.thread_elements()[0] = b1[6]; c11.thread_elements()[1] = b1[7]; + d00.thread_elements()[0] = lo[0]; d00.thread_elements()[1] = lo[1]; + d01.thread_elements()[0] = lo[2]; d01.thread_elements()[1] = lo[3]; + d10.thread_elements()[0] = lo[4]; d10.thread_elements()[1] = lo[5]; + d11.thread_elements()[0] = lo[6]; d11.thread_elements()[1] = lo[7]; + e00.thread_elements()[0] = hi[0]; e00.thread_elements()[1] = hi[1]; + e01.thread_elements()[0] = hi[2]; e01.thread_elements()[1] = hi[3]; + e10.thread_elements()[0] = hi[4]; e10.thread_elements()[1] = hi[5]; + e11.thread_elements()[0] = hi[6]; e11.thread_elements()[1] = hi[7]; + simdgroup_multiply_accumulate(d00, a00, b00, d00); + simdgroup_multiply_accumulate(d01, a00, b01, d01); + simdgroup_multiply_accumulate(d10, a10, b00, d10); + simdgroup_multiply_accumulate(d11, a10, b01, d11); + simdgroup_multiply_accumulate(e00, a00, c00, e00); + simdgroup_multiply_accumulate(e01, a00, c01, e01); + simdgroup_multiply_accumulate(e10, a10, c00, e10); + simdgroup_multiply_accumulate(e11, a10, c01, e11); + simdgroup_multiply_accumulate(d00, a01, b10, d00); + simdgroup_multiply_accumulate(d01, a01, b11, d01); + simdgroup_multiply_accumulate(d10, a11, b10, d10); + simdgroup_multiply_accumulate(d11, a11, b11, d11); + simdgroup_multiply_accumulate(e00, a01, c10, e00); + simdgroup_multiply_accumulate(e01, a01, c11, e01); + simdgroup_multiply_accumulate(e10, a11, c10, e10); + simdgroup_multiply_accumulate(e11, a11, c11, e11); + lo[0] = d00.thread_elements()[0]; lo[1] = d00.thread_elements()[1]; + lo[2] = d01.thread_elements()[0]; lo[3] = d01.thread_elements()[1]; + lo[4] = d10.thread_elements()[0]; lo[5] = d10.thread_elements()[1]; + lo[6] = d11.thread_elements()[0]; lo[7] = d11.thread_elements()[1]; + hi[0] = e00.thread_elements()[0]; hi[1] = e00.thread_elements()[1]; + hi[2] = e01.thread_elements()[0]; hi[3] = e01.thread_elements()[1]; + hi[4] = e10.thread_elements()[0]; hi[5] = e10.thread_elements()[1]; + hi[6] = e11.thread_elements()[0]; hi[7] = e11.thread_elements()[1]; +#else using namespace mpp::tensor_ops; constexpr auto shape = matmul2d_descriptor(16, 32, 16, TA, TB, true, matmul2d_descriptor::mode::multiply_accumulate); matmul2d op; @@ -187,8 +244,43 @@ inline void mma_16x32(thread frag& lo, thread frag& hi, thread const frag< lo[e] = acc[j]; hi[e] = acc[j + 4]; } +#endif +} + +#ifdef TF_GLM_M3_FAST +// Half-width 16x16 multiply-accumulate used by GLM's decode index kernel when TF_GLM_M3_FAST is active. +template +inline void mma_16x16(thread frag& d, thread const frag& a, thread const frag& b) { + simdgroup_matrix a00, a01, a10, a11; + simdgroup_matrix b00, b01, b10, b11; + simdgroup_matrix d00, d01, d10, d11; + a00.thread_elements()[0] = a[0]; a00.thread_elements()[1] = a[1]; + a01.thread_elements()[0] = a[2]; a01.thread_elements()[1] = a[3]; + a10.thread_elements()[0] = a[4]; a10.thread_elements()[1] = a[5]; + a11.thread_elements()[0] = a[6]; a11.thread_elements()[1] = a[7]; + b00.thread_elements()[0] = b[0]; b00.thread_elements()[1] = b[1]; + b01.thread_elements()[0] = b[2]; b01.thread_elements()[1] = b[3]; + b10.thread_elements()[0] = b[4]; b10.thread_elements()[1] = b[5]; + b11.thread_elements()[0] = b[6]; b11.thread_elements()[1] = b[7]; + d00.thread_elements()[0] = d[0]; d00.thread_elements()[1] = d[1]; + d01.thread_elements()[0] = d[2]; d01.thread_elements()[1] = d[3]; + d10.thread_elements()[0] = d[4]; d10.thread_elements()[1] = d[5]; + d11.thread_elements()[0] = d[6]; d11.thread_elements()[1] = d[7]; + simdgroup_multiply_accumulate(d00, a00, b00, d00); + simdgroup_multiply_accumulate(d01, a00, b01, d01); + simdgroup_multiply_accumulate(d10, a10, b00, d10); + simdgroup_multiply_accumulate(d11, a10, b01, d11); + simdgroup_multiply_accumulate(d00, a01, b10, d00); + simdgroup_multiply_accumulate(d01, a01, b11, d01); + simdgroup_multiply_accumulate(d10, a11, b10, d10); + simdgroup_multiply_accumulate(d11, a11, b11, d11); + d[0] = d00.thread_elements()[0]; d[1] = d00.thread_elements()[1]; + d[2] = d01.thread_elements()[0]; d[3] = d01.thread_elements()[1]; + d[4] = d10.thread_elements()[0]; d[5] = d10.thread_elements()[1]; + d[6] = d11.thread_elements()[0]; d[7] = d11.thread_elements()[1]; } #endif +#endif // frag_get from a block whose rows home.y and home.y + 8 start at r0 and r1; an unflagged row reads as zero. template diff --git a/zig/kernels/metal/qwen27/mlp_xs.metal b/zig/kernels/metal/qwen27/mlp_xs.metal index ab26d52c3df..13d4a38f4e5 100644 --- a/zig/kernels/metal/qwen27/mlp_xs.metal +++ b/zig/kernels/metal/qwen27/mlp_xs.metal @@ -39,3 +39,45 @@ Q27_SPECIALIZE } #endif } + +// The same activation and sums with 16 rows of a group in a threadgroup: one simdgroup runs their sums side by side. +[[max_total_threads_per_threadgroup(256)]] +[[kernel]] void q27_mlp_rows( + const device vec* FUSED [[buffer(0)]], + const device int32_t* dims [[buffer(2)]], + device vec* HOUT [[buffer(3)]], + device float* XS [[buffer(4)]], + constant uint& width [[buffer(5)]], + uint2 place [[threadgroup_position_in_grid]], + ushort t [[thread_index_in_threadgroup]], + ushort sg [[simdgroup_index_in_threadgroup]], + ushort lane [[thread_index_in_simdgroup]]) { + threadgroup vec values[256]; + const int M = dims[0], MP = dims[1]; + const uint g = place.x, first_row = place.y * 16, m = first_row + (t >> 4), four = g * 16 + (t & 15); + if (int(m) < M) { + const float4 gate = float4(FUSED[m * (width / 2) + four]); + const float4 up = float4(FUSED[m * (width / 2) + width / 4 + four]); + float4 h; + _Pragma("clang loop unroll(full)") + for (uint part = 0; part < 4; part++) h[part] = gate[part] / (1.0f + metal::exp(-gate[part])) * up[part]; + const vec rounded = vec(h); + HOUT[m * (width / 4) + four] = rounded; + values[t] = rounded; + } + #if Q27_XS + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg == 0 && lane < 16) { + const uint row = first_row + lane; + float acc = 0.0f; + if (int(row) < M) { + for (uint i = 0; i < 16; i++) { + const float4 x = float4(values[uint(lane) * 16 + i]); + _Pragma("clang loop unroll(full)") + for (uint part = 0; part < 4; part++) acc += x[part]; + } + } + XS[g * MP + row] = acc; + } + #endif +} diff --git a/zig/kernels/metal/sources.zig b/zig/kernels/metal/sources.zig index 5f178dd7400..3e0f292897e 100644 --- a/zig/kernels/metal/sources.zig +++ b/zig/kernels/metal/sources.zig @@ -148,6 +148,8 @@ pub const glm_vision = vision_glue ++ @embedFile("glm_vision.metal"); pub const core_qwen_vision = vision_glue ++ @embedFile("core/qwen_vision.metal"); /// Qwen-Image-2.1's transformer: the prefill attention template, then its own steps (projections: core_qwen_vision). pub const qwen_image = @embedFile("prefill/attention_nax.metal") ++ @embedFile("qwen_image.metal"); +/// Idol's denoiser: the prefill GEMM template, then its own steps and head-64 attention. +pub const idol = @embedFile("prefill/gemm_nax.metal") ++ @embedFile("idol.metal") ++ @embedFile("idol_attention.metal"); /// MOSS-Image: the prefill attention template, then its transformer's and encoder's steps (gemms: core_qwen_vision). pub const moss_image = @embedFile("prefill/attention_nax.metal") ++ @embedFile("moss_image.metal") ++ @embedFile("moss_image_encoder.metal"); /// Unlimited-OCR-2: its image encoder's and decoder's own steps (projections: core_qwen_vision). @@ -167,6 +169,7 @@ pub const glm_index_nax = @embedFile("glm_index_nax.metal"); pub const glm_absorb_nax = @embedFile("glm_absorb_nax.metal"); /// A MoE layer's route in two launches (core/moe_route.zig): router logits, then the top-k and the expert groups. pub const core_moe_route = @embedFile("core/moe_route.metal"); +pub const core_tree_round = @embedFile("core/tree_round.metal"); pub const core_affine_mm = @embedFile("core/affine_mm.metal"); /// A hyper-connection block boundary in two launches (core/hc.zig). pub const core_hc_boundary = @embedFile("core/hc_boundary.metal"); @@ -180,6 +183,8 @@ pub const packed_metallib = @import("nemotron_packed_metallib").bytes; /// The core lane projection (tensor units): every window row's sums in one weight read, and its row order. pub const core_lane_projection = @embedFile("core/lane_projection.metal"); pub const core_lane_order = @embedFile("core/lane_order.metal"); +/// qk: the M5's 4-bit g64 products on the lane layout as load leaves it, tf_lane_reg's words (core/qk_projection.zig). +pub const core_qk = @embedFile("core/qk.metal"); /// Lane rows attending a shared context through an explicit mask (core/shared_attention.zig). pub const core_shared_attention = @embedFile("core/shared_attention.metal"); /// The core DeltaNet kernels (core/deltanet_kernels.zig). @@ -256,3 +261,6 @@ pub const lfm2_prompt_masked = @import("lfm2/prompt_masked.zig"); /// Qwen3 embeddings' projected-head RMS norm (128-wide Q and K, V unchanged). pub const qwen3_heads = @embedFile("qwen3/heads.metal"); + +/// Qwen27 flat activation shares the production specialization with its contract. +pub const q27_mlp_xs = @embedFile("qwen27/mlp_xs.metal"); diff --git a/zig/kernels/xpu/tp.cl b/zig/kernels/xpu/tp.cl new file mode 100644 index 00000000000..724f7378226 --- /dev/null +++ b/zig/kernels/xpu/tp.cl @@ -0,0 +1,154 @@ +// Level Zero P2P collectives for Intel Xe2: rank-ordered FP32 sums (#pragma OPENCL FP_CONTRACT OFF) for exact bits. +#pragma OPENCL FP_CONTRACT OFF +#pragma OPENCL EXTENSION cl_khr_fp16 : enable + +#define KERNEL(N) __attribute__((intel_reqd_sub_group_size(16))) __attribute__((reqd_work_group_size(N, 1, 1))) kernel + +static inline float bf2f(ushort h) { return as_float((uint)h << 16); } +static inline ushort f2bf(float f) { return intel_convert_bfloat16_as_ushort(f); } + +// 1-shot P2P AllReduce (FP16): out[i] = fp16_rte(p0[i] + p1[i]) +KERNEL(256) void tp2_allreduce_f16( + global const half *p0, + global const half *p1, + global half *out, + int n4) +{ + const int idx = get_global_id(0); + if (idx >= n4) return; + const float4 s = convert_float4(vload4(idx, p0)) + convert_float4(vload4(idx, p1)); + vstore4(convert_half4_rte(s), idx, out); +} + +// 1-shot P2P AllReduce (FP16): out[i] = fp16_rte(((p0[i] + p1[i]) + p2[i]) + p3[i]) +KERNEL(256) void tp4_allreduce_f16( + global const half *p0, + global const half *p1, + global const half *p2, + global const half *p3, + global half *out, + int n4) +{ + const int idx = get_global_id(0); + if (idx >= n4) return; + float4 s = convert_float4(vload4(idx, p0)) + convert_float4(vload4(idx, p1)); + s = s + convert_float4(vload4(idx, p2)); + s = s + convert_float4(vload4(idx, p3)); + vstore4(convert_half4_rte(s), idx, out); +} + +// 2-shot P2P ReduceScatter (FP16): sums slice [off4 .. off4 + slice_n4) into rs_out[0 .. slice_n4) +KERNEL(256) void tp2_rs_f16( + global const half *p0, + global const half *p1, + global half *rs_out, + int off4, + int slice_n4) +{ + const int idx = get_global_id(0); + if (idx >= slice_n4) return; + const int src = off4 + idx; + const float4 s = convert_float4(vload4(src, p0)) + convert_float4(vload4(src, p1)); + vstore4(convert_half4_rte(s), idx, rs_out); +} + +KERNEL(256) void tp4_rs_f16( + global const half *p0, + global const half *p1, + global const half *p2, + global const half *p3, + global half *rs_out, + int off4, + int slice_n4) +{ + const int idx = get_global_id(0); + if (idx >= slice_n4) return; + const int src = off4 + idx; + float4 s = convert_float4(vload4(src, p0)) + convert_float4(vload4(src, p1)); + s = s + convert_float4(vload4(src, p2)); + s = s + convert_float4(vload4(src, p3)); + vstore4(convert_half4_rte(s), idx, rs_out); +} + +// 1-shot P2P AllReduce (BF16) for BF16/FlashNext activations +KERNEL(256) void tp2_allreduce_bf16( + global const ushort *p0, + global const ushort *p1, + global ushort *out, + int n4) +{ + const int idx = get_global_id(0); + if (idx >= n4) return; + const ushort4 a0 = vload4(idx, p0), a1 = vload4(idx, p1); + ushort4 r; + r.s0 = f2bf(bf2f(a0.s0) + bf2f(a1.s0)); + r.s1 = f2bf(bf2f(a0.s1) + bf2f(a1.s1)); + r.s2 = f2bf(bf2f(a0.s2) + bf2f(a1.s2)); + r.s3 = f2bf(bf2f(a0.s3) + bf2f(a1.s3)); + vstore4(r, idx, out); +} + +KERNEL(256) void tp4_allreduce_bf16( + global const ushort *p0, + global const ushort *p1, + global const ushort *p2, + global const ushort *p3, + global ushort *out, + int n4) +{ + const int idx = get_global_id(0); + if (idx >= n4) return; + const ushort4 a0 = vload4(idx, p0), a1 = vload4(idx, p1), a2 = vload4(idx, p2), a3 = vload4(idx, p3); + ushort4 r; + r.s0 = f2bf(((bf2f(a0.s0) + bf2f(a1.s0)) + bf2f(a2.s0)) + bf2f(a3.s0)); + r.s1 = f2bf(((bf2f(a0.s1) + bf2f(a1.s1)) + bf2f(a2.s1)) + bf2f(a3.s1)); + r.s2 = f2bf(((bf2f(a0.s2) + bf2f(a1.s2)) + bf2f(a2.s2)) + bf2f(a3.s2)); + r.s3 = f2bf(((bf2f(a0.s3) + bf2f(a1.s3)) + bf2f(a2.s3)) + bf2f(a3.s3)); + vstore4(r, idx, out); +} + +// 1-shot P2P AllReduce (FP32) for FlashNext routed MoE / FP32 partials +KERNEL(256) void tp2_allreduce_f32( + global const float *p0, + global const float *p1, + global float *out, + int n4) +{ + const int idx = get_global_id(0); + if (idx >= n4) return; + vstore4(vload4(idx, p0) + vload4(idx, p1), idx, out); +} + +KERNEL(256) void tp4_allreduce_f32( + global const float *p0, + global const float *p1, + global const float *p2, + global const float *p3, + global float *out, + int n4) +{ + const int idx = get_global_id(0); + if (idx >= n4) return; + float4 s = vload4(idx, p0) + vload4(idx, p1); + s = s + vload4(idx, p2); + s = s + vload4(idx, p3); + vstore4(s, idx, out); +} + +KERNEL(256) void tp4_rs_f32( + global const float *p0, + global const float *p1, + global const float *p2, + global const float *p3, + global float *rs_out, + int off4, + int slice_n4) +{ + const int idx = get_global_id(0); + if (idx >= slice_n4) return; + const int src = off4 + idx; + float4 s = vload4(src, p0) + vload4(src, p1); + s = s + vload4(src, p2); + s = s + vload4(src, p3); + vstore4(s, idx, rs_out); +} diff --git a/zig/qwen27_quant_test.zig b/zig/qwen27_quant_test.zig index a5b361c5d0a..e0ee43ba0c5 100644 --- a/zig/qwen27_quant_test.zig +++ b/zig/qwen27_quant_test.zig @@ -331,24 +331,31 @@ test "qwen27 quant: mixed raw columns remain unordered until the caller barrier" } test "qwen27 quant: norm and MLP compile XS only on tensor units and pad only its grid" { + const glue = @import("core_delta"); + defer glue.flat_glue = true; var r: mtl.Record = .{}; var k = quant.Kernels{ .allocator = a, .device = r.device(), .raw_tiles = false }; defer k.deinit(); const ref = quant.Ref{ .buffer = r.virtual() }; - for ([_]bool{ false, true, false }) |units| { - r.tensor_units = units; - for ([_]u32{ 1, 7, 16, 17 }) |rows| { - r.count = 0; - try k.norm(r.encoder(), ref, null, ref, ref, ref, ref, ref, ref, 512, rows); - try k.norm(r.encoder(), ref, ref, ref, ref, ref, ref, ref, ref, 512, rows); - try k.mlp(r.encoder(), ref, ref, ref, ref, ref, 1024, rows); - try t.expectEqual(@as(usize, 3), r.count); - for (r.launches[0..r.count]) |l| { - try t.expectEqual(@as(?bool, units), l.xs); - try t.expectEqual(@as(usize, if (units) quant.padded(rows) else rows), l.grid.height); + // The flat glue's row-side MLP takes 16 rows a threadgroup, so its grid is padded rows over 16 on every chip. + for ([_]bool{ false, true }) |flat| { + glue.flat_glue = flat; + for ([_]bool{ false, true, false }) |units| { + r.tensor_units = units; + for ([_]u32{ 1, 7, 16, 17 }) |rows| { + r.count = 0; + try k.norm(r.encoder(), ref, null, ref, ref, ref, ref, ref, ref, 512, rows); + try k.norm(r.encoder(), ref, ref, ref, ref, ref, ref, ref, ref, 512, rows); + try k.mlp(r.encoder(), ref, ref, ref, ref, ref, 1024, rows); + try t.expectEqual(@as(usize, 3), r.count); + for (r.launches[0..r.count], 0..) |l, i| { + try t.expectEqual(@as(?bool, units), l.xs); + const height: usize = if (flat and i == 2) quant.padded(rows) / 16 else if (units) quant.padded(rows) else rows; + try t.expectEqual(height, l.grid.height); + } } } } - try t.expectEqual(@as(u32, 6), k.cache.count()); - try t.expectEqual(@as(usize, 6), r.libraries); + try t.expectEqual(@as(u32, 8), k.cache.count()); + try t.expectEqual(@as(usize, 8), r.libraries); } diff --git a/zig/qwen35_draft_frame_host.zig b/zig/qwen35_draft_frame_host.zig index b2dd9be15cf..c3f042015df 100644 --- a/zig/qwen35_draft_frame_host.zig +++ b/zig/qwen35_draft_frame_host.zig @@ -155,13 +155,26 @@ fn actualFrame(block: usize) !void { e.embed_w = 1; e.embed_s = 2; e.embed_b = 3; - e.affine.mlp128 = false; - e.affine.prefill_fn = function(&driver, 11); - e.affine.group_fn = function(&driver, 10); - e.affine.gemv_fn = function(&driver, 7); - e.affine.split = null; - e.affine.pdl = false; - e.affine.wide_verify = false; + e.affine = .{ + .group_fn = function(&driver, 10), + .mlp128_fn = function(&driver, 10), + .gemv_fn = function(&driver, 7), + .verify_fn = function(&driver, 10), + .verify64_fn = function(&driver, 10), + .verify128_fn = function(&driver, 10), + .split_fn = function(&driver, 10), + .seg_fn = function(&driver, 10), + .many_fn = function(&driver, 10), + .prefill_fn = function(&driver, 11), + .prefill22_fn = function(&driver, 10), + .prefill_many_fn = function(&driver, 10), + .words_fn = function(&driver, 10), + .scales_fn = function(&driver, 10), + .gemv_blocks = 0, + .split = null, + .pdl = false, + .wide_verify = false, + }; e.fns.norm = function(&driver, 13); e.head = .{ .a4 = weight() }; e.draws.logprob_rows_fn = function(&driver, 9); diff --git a/zig/residency_qwen27_tests.zig b/zig/residency_qwen27_tests.zig index f1080223744..f0509758952 100644 --- a/zig/residency_qwen27_tests.zig +++ b/zig/residency_qwen27_tests.zig @@ -173,18 +173,24 @@ test "residency owner Qwen27: native inventory and lazy owners match every alloc try model.kernels.lanes.put(a, .{ .kind = .projection, .k = 128 }, cached); model.frame = try @import("src/families/qwen27/gpu_frame.zig").Frame.init(device, model.config, 16); defer model.frame.deinit(); - var r: round_mod.Runner = undefined; - r.model = &model; - r.slots = 1; - r.ready = 1; - r.caches = &.{}; - r.owned = .empty; - r.residency = null; - r.failed = false; - r.active = null; - r.reading = @splat(null); var offsets = [_]u32{1}; - r.offsets = &offsets; + var r: round_mod.Runner = .{ + .allocator = a, + .model = &model, + .gdn = undefined, + .attention = undefined, + .scratch = undefined, + .bindings = &.{}, + .caches = &.{}, + .linear_index = &.{}, + .attention_index = &.{}, + .offsets = &offsets, + .owned = .empty, + .taps = undefined, + .slots = 1, + .ready = 1, + .capacity = 16, + }; const budget = try Budget.init(try abi.Shape.init(model.config), 1, 1, 16); r.gdn = .{ .budget = budget, .buffers = try bank.Pool.allocateBuffers(device, budget), .kernels = undefined }; defer for (r.gdn.buffers) |b| b.deinit(); diff --git a/zig/src/cli/cuda_main.zig b/zig/src/cli/cuda_main.zig index a646fdecb1c..4921afa79b9 100644 --- a/zig/src/cli/cuda_main.zig +++ b/zig/src/cli/cuda_main.zig @@ -51,6 +51,7 @@ const usage = \\ tensorfold rm REPO[@REVISION] [--yes] [--dry-run] \\ tensorfold lanes MODEL PROMPTS.json [--solo] [--max-tokens N] [--no-drafts] [sampling as run] [--report PATH] \\ (every prompt through the lane core at once, or one at a time with --solo) + \\ tensorfold config validate FILE \\ tensorfold cluster init|check|status \\ tensorfold serve [MODEL] --cluster FILE \\ tensorfold node --name NAME --cluster FILE @@ -71,6 +72,7 @@ pub fn main(init: std.process.Init) !u8 { } // Cluster commands must work without a model load. node joins over MCDMA, through the library each node names. if (args.len >= 2 and cluster.cli.wants(@ptrCast(args[1..]))) return cluster.cli.main(init, args[1..]); + if (args.len >= 2 and cluster.validate.wants(@ptrCast(args[1..]))) return cluster.validate.main(init, args[1..]); // The checkpoint commands must work without a model, driver or GPU too. if (args.len >= 2 and checkpoint_cli.wants(@ptrCast(args[1..]))) return checkpoint_cli.main(init, args[1..]); // A leading flag is not a command: the usage covers it, without touching the GPU. diff --git a/zig/src/cli/pull_http_test.zig b/zig/src/cli/pull_http_test.zig index 8d4c743d51c..de456b86f80 100644 --- a/zig/src/cli/pull_http_test.zig +++ b/zig/src/cli/pull_http_test.zig @@ -176,7 +176,10 @@ test "pull connect: a pending attempt observes real I/O cancellation and closes }; Pending.entered.store(false, .monotonic); Pending.closes.store(0, .monotonic); - const io = std.testing.io; + var client_io: @import("pull_test_client.zig").Client = undefined; + client_io.init(); + defer client_io.deinit(); + const io = client_io.io(); var future = try io.concurrent(Pending.run, .{io}); while (!Pending.entered.load(.acquire)) try Io.sleep(io, .fromMilliseconds(1), .awake); try std.testing.expectError(error.Canceled, future.cancel(io)); diff --git a/zig/src/cli/pull_test.zig b/zig/src/cli/pull_test.zig index 020f2684571..087d806a3a1 100644 --- a/zig/src/cli/pull_test.zig +++ b/zig/src/cli/pull_test.zig @@ -5,9 +5,11 @@ const pull = @import("pull.zig"); const ranged = @import("pull_parts.zig"); const single = @import("pull_file.zig"); const exlr8_pull = @import("pull_exlr8.zig"); +const TestClient = @import("pull_test_client.zig").Client; /// A fake hub on 127.0.0.1: revision and tree APIs, ranged resolve endpoints, a body cut once, a repo ignoring ranges. const FakeHub = struct { + allocator: Allocator = std.heap.page_allocator, // the fake server owns its worker allocations server: std.Io.net.Server, io: std.Io, threaded: *std.Io.Threaded, @@ -37,9 +39,11 @@ const FakeHub = struct { const nested_body: []const u8 = &nested_body_storage; fn open() !FakeHub { - const threaded = try std.testing.allocator.create(std.Io.Threaded); - threaded.* = std.Io.Threaded.init(std.testing.allocator, .{}); - errdefer std.testing.allocator.destroy(threaded); + const a = std.heap.page_allocator; + const threaded = try a.create(std.Io.Threaded); + errdefer a.destroy(threaded); + threaded.* = std.Io.Threaded.init(a, .{}); + errdefer threaded.deinit(); const io = threaded.io(); const loopback: std.Io.net.IpAddress = .{ .ip4 = .loopback(0) }; var server = try loopback.listen(io, .{}); @@ -52,15 +56,20 @@ const FakeHub = struct { nested_hash.update(nested_body); var nested_digest: [32]u8 = undefined; nested_hash.final(&nested_digest); + const weights_sha_hex = try std.fmt.allocPrint(a, "{s}", .{std.fmt.bytesToHex(digest, .lower)}); + errdefer a.free(weights_sha_hex); + const nested_sha_hex = try std.fmt.allocPrint(a, "{s}", .{std.fmt.bytesToHex(nested_digest, .lower)}); + errdefer a.free(nested_sha_hex); return .{ + .allocator = a, .server = server, .io = io, .threaded = threaded, .weights = weights_body, .config = config_body, .nested = nested_body, - .weights_sha_hex = try std.fmt.allocPrint(std.testing.allocator, "{s}", .{std.fmt.bytesToHex(digest, .lower)}), - .nested_sha_hex = try std.fmt.allocPrint(std.testing.allocator, "{s}", .{std.fmt.bytesToHex(nested_digest, .lower)}), + .weights_sha_hex = weights_sha_hex, + .nested_sha_hex = nested_sha_hex, .config_git_hex = gitHex(config_body), .flaky_git_hex = gitHex(flaky_body), .port = server.socket.address.getPort(), @@ -94,7 +103,7 @@ const FakeHub = struct { continue; } fake.live_lock.lockUncancelable(fake.io); - fake.live.append(std.testing.allocator, conn) catch {}; + fake.live.append(fake.allocator, conn) catch {}; fake.live_lock.unlock(fake.io); conns[n] = std.Thread.spawn(.{}, handle, .{ fake, conn }) catch { fake.forget(conn); @@ -184,8 +193,8 @@ const FakeHub = struct { fake.respond(conn, config_body); } else if (std.mem.eql(u8, path, "/api/models/Org/Flash/tree/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1") or std.mem.eql(u8, path, "/api/models/Org/Whole/tree/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb2")) { // The hub's tree sends LFS oids as bare hex. - const tree = std.fmt.allocPrint(std.testing.allocator, "[{{\"type\": \"file\", \"oid\": \"{s}\", \"path\": \"config.json\", \"size\": {d}}}, {{\"type\": \"file\", \"oid\": \"1111111111111111111111111111111111111111\", \"path\": \"weights.safetensors\", \"size\": {d}, \"lfs\": {{\"oid\": \"{s}\", \"size\": {d}}}}}, {{\"type\": \"file\", \"oid\": \"{s}\", \"path\": \"flaky.json\", \"size\": {d}}}, {{\"type\": \"file\", \"oid\": \"3333333333333333333333333333333333333333\", \"path\": \"tensors/model-00001-of-00001.safetensors\", \"size\": {d}, \"lfs\": {{\"oid\": \"{s}\", \"size\": {d}}}}}]", .{ &fake.config_git_hex, fake.config.len, fake.weights.len, fake.weights_sha_hex, fake.weights.len, &fake.flaky_git_hex, flaky_body.len, fake.nested.len, fake.nested_sha_hex, fake.nested.len }) catch return false; - defer std.testing.allocator.free(tree); + const tree = std.fmt.allocPrint(fake.allocator, "[{{\"type\": \"file\", \"oid\": \"{s}\", \"path\": \"config.json\", \"size\": {d}}}, {{\"type\": \"file\", \"oid\": \"1111111111111111111111111111111111111111\", \"path\": \"weights.safetensors\", \"size\": {d}, \"lfs\": {{\"oid\": \"{s}\", \"size\": {d}}}}}, {{\"type\": \"file\", \"oid\": \"{s}\", \"path\": \"flaky.json\", \"size\": {d}}}, {{\"type\": \"file\", \"oid\": \"3333333333333333333333333333333333333333\", \"path\": \"tensors/model-00001-of-00001.safetensors\", \"size\": {d}, \"lfs\": {{\"oid\": \"{s}\", \"size\": {d}}}}}]", .{ &fake.config_git_hex, fake.config.len, fake.weights.len, fake.weights_sha_hex, fake.weights.len, &fake.flaky_git_hex, flaky_body.len, fake.nested.len, fake.nested_sha_hex, fake.nested.len }) catch return false; + defer fake.allocator.free(tree); fake.respond(conn, tree); } else if (std.mem.eql(u8, path, config_path) or std.mem.eql(u8, path, "/Org/Whole/resolve/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb2/config.json")) { fake.respond(conn, fake.config); @@ -277,11 +286,11 @@ const FakeHub = struct { if (fake.server.socket.address.connect(fake.io, .{ .mode = .stream }) catch null) |wake| wake.close(fake.io); if (fake.thread) |t| t.join(); fake.server.deinit(fake.io); - fake.live.deinit(std.testing.allocator); + fake.live.deinit(fake.allocator); fake.threaded.deinit(); - std.testing.allocator.destroy(fake.threaded); - std.testing.allocator.free(fake.weights_sha_hex); - std.testing.allocator.free(fake.nested_sha_hex); + fake.allocator.destroy(fake.threaded); + fake.allocator.free(fake.weights_sha_hex); + fake.allocator.free(fake.nested_sha_hex); } }; @@ -292,10 +301,13 @@ fn testEnv(a: Allocator, endpoint_url: []const u8) !std.process.Environ.Map { } test "pull downloads, verifies, retries a cut body, resumes and refuses a family Zig cannot serve" { - var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + var client_io: TestClient = undefined; + client_io.init(); + defer client_io.deinit(); + var arena_state = std.heap.ArenaAllocator.init(client_io.allocator()); defer arena_state.deinit(); const a = arena_state.allocator(); - const io = std.testing.io; + const io = client_io.io(); var fake_hub = FakeHub.open() catch { return error.SkipZigTest; }; @@ -371,10 +383,13 @@ test "pull downloads, verifies, retries a cut body, resumes and refuses a family } test "large files come down as shared pieces, and whole files when the hub ignores ranges" { - var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + var client_io: TestClient = undefined; + client_io.init(); + defer client_io.deinit(); + var arena_state = std.heap.ArenaAllocator.init(client_io.allocator()); defer arena_state.deinit(); const a = arena_state.allocator(); - const io = std.testing.io; + const io = client_io.io(); var fake_hub = FakeHub.open() catch return error.SkipZigTest; fake_hub.start(); defer fake_hub.stopServer(); @@ -403,10 +418,13 @@ test "large files come down as shared pieces, and whole files when the hub ignor } test "shared pieces fill every byte across files, restart only unmarked pieces and refuse a server without ranges" { - var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + var client_io: TestClient = undefined; + client_io.init(); + defer client_io.deinit(); + var arena_state = std.heap.ArenaAllocator.init(client_io.allocator()); defer arena_state.deinit(); const a = arena_state.allocator(); - const io = std.testing.io; + const io = client_io.io(); var fake_hub = FakeHub.open() catch return error.SkipZigTest; fake_hub.start(); defer fake_hub.stopServer(); @@ -445,10 +463,13 @@ fn hexBytes(text: []const u8) ![32]u8 { } test "an EXLR8 node's whole files land in a relative directory, small files and LFS pieces alike" { - var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + var client_io: TestClient = undefined; + client_io.init(); + defer client_io.deinit(); + var arena_state = std.heap.ArenaAllocator.init(client_io.allocator()); defer arena_state.deinit(); const a = arena_state.allocator(); - const io = std.testing.io; + const io = client_io.io(); var fake_hub = FakeHub.open() catch return error.SkipZigTest; fake_hub.start(); defer fake_hub.stopServer(); @@ -473,10 +494,13 @@ test "an EXLR8 node's whole files land in a relative directory, small files and } test "security: a hub response cannot write beyond the manifest file size" { - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + var client_io: TestClient = undefined; + client_io.init(); + defer client_io.deinit(); + var arena = std.heap.ArenaAllocator.init(client_io.allocator()); defer arena.deinit(); const a = arena.allocator(); - const io = std.testing.io; + const io = client_io.io(); var fake = try FakeHub.open(); fake.start(); defer fake.stopServer(); @@ -500,10 +524,13 @@ test "security: a hub response cannot write beyond the manifest file size" { } test "security: a shard in a folder inside the model folder lands inside the snapshot" { - var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + var client_io: TestClient = undefined; + client_io.init(); + defer client_io.deinit(); + var arena_state = std.heap.ArenaAllocator.init(client_io.allocator()); defer arena_state.deinit(); const a = arena_state.allocator(); - const io = std.testing.io; + const io = client_io.io(); var fake_hub = FakeHub.open() catch return error.SkipZigTest; fake_hub.start(); defer fake_hub.stopServer(); @@ -522,10 +549,13 @@ test "security: a shard in a folder inside the model folder lands inside the sna } test "security: a hub tree path TensorFold reserves is refused, naming the path and why" { - var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + var client_io: TestClient = undefined; + client_io.init(); + defer client_io.deinit(); + var arena_state = std.heap.ArenaAllocator.init(client_io.allocator()); defer arena_state.deinit(); const a = arena_state.allocator(); - const io = std.testing.io; + const io = client_io.io(); var fake_hub = FakeHub.open() catch return error.SkipZigTest; fake_hub.start(); defer fake_hub.stopServer(); @@ -546,10 +576,13 @@ test "security: a hub tree path TensorFold reserves is refused, naming the path } test "pull refuses cache mutation while rm holds the cache directory" { - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + var client_io: TestClient = undefined; + client_io.init(); + defer client_io.deinit(); + var arena = std.heap.ArenaAllocator.init(client_io.allocator()); defer arena.deinit(); const a = arena.allocator(); - const io = std.testing.io; + const io = client_io.io(); var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); const root = try tmp.dir.realPathFileAlloc(io, ".", a); diff --git a/zig/src/cli/pull_test_client.zig b/zig/src/cli/pull_test_client.zig new file mode 100644 index 00000000000..25dd35a5cec --- /dev/null +++ b/zig/src/cli/pull_test_client.zig @@ -0,0 +1,50 @@ +//! Pull tests own their client I/O and leak-checking allocator without stack unwinds on worker frees. +const std = @import("std"); + +pub const Client = struct { + heap: std.heap.SafeAllocator = undefined, + threaded: std.Io.Threaded = undefined, + + pub fn init(c: *Client) void { + c.heap = .init(std.heap.page_allocator, .{ .stack_trace_frames = 0 }); + c.threaded = .init(c.heap.allocator(), .{}); + } + + pub fn allocator(c: *Client) std.mem.Allocator { + return c.heap.allocator(); + } + + pub fn io(c: *Client) std.Io { + return c.threaded.io(); + } + + pub fn deinit(c: *Client) void { + c.threaded.deinit(); + const leaks = c.heap.deinit(); + if (leaks != 0) std.log.err("pull client test leaked {d} allocations", .{leaks}); + } +}; + +test "pull client I/O: cancelled futures and completed worker groups release their allocations" { + var client: Client = undefined; + client.init(); + defer client.deinit(); + const io = client.io(); + const Work = struct { + fn wait(i: std.Io, entered: *std.Io.Event, finish: *std.Io.Event) std.Io.Cancelable!void { + entered.set(i); + try finish.wait(i); + } + }; + var entered: std.Io.Event = .unset; + var finish: std.Io.Event = .unset; + var future = try io.concurrent(Work.wait, .{ io, &entered, &finish }); + entered.waitUncancelable(io); + try std.testing.expectError(error.Canceled, future.cancel(io)); + entered = .unset; + var group: std.Io.Group = .init; + try group.concurrent(io, Work.wait, .{ io, &entered, &finish }); + entered.waitUncancelable(io); + finish.set(io); + try group.await(io); +} diff --git a/zig/src/cluster/cli.zig b/zig/src/cluster/cli.zig index dc7a6e1f5f1..f300a4ed925 100644 --- a/zig/src/cluster/cli.zig +++ b/zig/src/cluster/cli.zig @@ -22,7 +22,8 @@ pub const Env = struct { }; pub const usage = - \\usage: tensorfold cluster init --node NAME=ADDRESS[@VIA]... [--cuda NAME]... [--ssh-user U] [--ssh-key FILE] [--name CLUSTER] [--probes DIR] + \\usage: tensorfold config validate FILE + \\ tensorfold cluster init --node NAME=ADDRESS[@VIA]... [--cuda NAME]... [--ssh-user U] [--ssh-key FILE] [--name CLUSTER] [--probes DIR] \\ tensorfold cluster check --cluster FILE [--model ID] [--model-config FILE [--model-files FILE]] [--probe | --probes DIR] \\ tensorfold cluster status --cluster FILE [--model ID] [--probe | --probes DIR] \\ tensorfold serve [MODEL] --cluster FILE [--leader NAME] [--dry-run] [--hold SECONDS] [--model-config FILE [--model-files FILE]] [--probe | --probes DIR] diff --git a/zig/src/cluster/cluster.zig b/zig/src/cluster/cluster.zig index 09a70313b94..4ae327fa6a6 100644 --- a/zig/src/cluster/cluster.zig +++ b/zig/src/cluster/cluster.zig @@ -32,6 +32,7 @@ pub const status = @import("status.zig"); pub const cli = @import("cli.zig"); pub const cli_model = @import("cli_model.zig"); pub const bringup = @import("bringup.zig"); +pub const validate = @import("validate.zig"); test { std.testing.refAllDecls(@This()); diff --git a/zig/src/cluster/main.zig b/zig/src/cluster/main.zig index 73e8d2a8c3b..3129ef3fcb2 100644 --- a/zig/src/cluster/main.zig +++ b/zig/src/cluster/main.zig @@ -4,5 +4,6 @@ const cluster = @import("cluster"); pub fn main(init: std.process.Init) !u8 { const argv = try init.minimal.args.toSlice(init.arena.allocator()); + if (cluster.validate.wants(@ptrCast(argv[1..]))) return cluster.validate.main(init, argv[1..]); return cluster.cli.main(init, argv[1..]); } diff --git a/zig/src/cluster/validate.zig b/zig/src/cluster/validate.zig new file mode 100644 index 00000000000..6fbef1ac434 --- /dev/null +++ b/zig/src/cluster/validate.zig @@ -0,0 +1,65 @@ +//! `tensorfold config validate FILE`: parse a cluster file, print every problem, no planning or probes. +const std = @import("std"); +const config = @import("config.zig"); + +const Allocator = std.mem.Allocator; +const W = std.Io.Writer; + +pub const Env = struct { + io: std.Io, + a: Allocator, + out: *W, + err: *W, +}; + +pub const usage = + \\usage: tensorfold config validate FILE + \\ +; + +/// True when argv starts with the config command. +pub fn wants(args: []const []const u8) bool { + return args.len > 0 and std.mem.eql(u8, args[0], "config"); +} + +/// Exit: 0 valid, 1 unreadable or invalid, 2 usage. +pub fn run(env: Env, args: []const []const u8) !u8 { + if (args.len != 3 or !std.mem.eql(u8, args[0], "config") or !std.mem.eql(u8, args[1], "validate")) return bad(env); + const path = args[2]; + if (std.mem.startsWith(u8, path, "-")) return bad(env); + const json = std.Io.Dir.cwd().readFileAlloc(env.io, path, env.a, .limited(16 << 20)) catch |err| { + try env.err.print("{s}: {s}\n", .{ path, @errorName(err) }); + return 1; + }; + var probs: config.Problems = .{ .a = env.a }; + const c = config.parse(env.a, json, &probs) catch { + for (probs.list.items) |p| try env.err.print("{s}\n", .{p}); + return 1; + }; + try env.out.print("{s}: {d} nodes, {d} models\n", .{ path, c.nodes.len, c.models.len }); + return 0; +} + +fn bad(env: Env) !u8 { + try env.err.writeAll(usage); + return 2; +} + +/// The entry both binaries share: argv after the program name, stdout and stderr. +pub fn main(init: std.process.Init, argv: []const [:0]const u8) !u8 { + const a = init.arena.allocator(); + var out_buf: [64 << 10]u8 = undefined; + var err_buf: [4 << 10]u8 = undefined; + var out = std.Io.File.stdout().writerStreaming(init.io, &out_buf); + var err = std.Io.File.stderr().writerStreaming(init.io, &err_buf); + const args = try a.alloc([]const u8, argv.len); + for (args, argv) |*x, y| x.* = y; + const code = try run(.{ .io = init.io, .a = a, .out = &out.interface, .err = &err.interface }, args); + try out.interface.flush(); + try err.interface.flush(); + return code; +} + +test { + _ = @import("validate_test.zig"); +} diff --git a/zig/src/cluster/validate_main.zig b/zig/src/cluster/validate_main.zig new file mode 100644 index 00000000000..fb473ed89c6 --- /dev/null +++ b/zig/src/cluster/validate_main.zig @@ -0,0 +1,8 @@ +//! Host-only `tensorfold config validate`: the same argv as the product CLI, no GPU, no CUDA, no probes. +const std = @import("std"); +const validate = @import("validate.zig"); + +pub fn main(init: std.process.Init) !u8 { + const argv = try init.minimal.args.toSlice(init.arena.allocator()); + return validate.main(init, argv[1..]); +} diff --git a/zig/src/cluster/validate_test.zig b/zig/src/cluster/validate_test.zig new file mode 100644 index 00000000000..8bad2fdf838 --- /dev/null +++ b/zig/src/cluster/validate_test.zig @@ -0,0 +1,125 @@ +//! `tensorfold config validate FILE` on the host: valid, invalid, missing, and usage, with no probes or planning. +const std = @import("std"); +const validate = @import("validate.zig"); +const config_test = @import("config_test.zig"); + +const io = std.testing.io; + +const Run = struct { out: []const u8, err: []const u8, code: u8 }; + +fn run(a: std.mem.Allocator, args: []const []const u8) !Run { + var out: std.Io.Writer.Allocating = .init(a); + var err: std.Io.Writer.Allocating = .init(a); + const code = try validate.run(.{ .io = io, .a = a, .out = &out.writer, .err = &err.writer }, args); + return .{ .out = out.written(), .err = err.written(), .code = code }; +} + +fn has(text: []const u8, needle: []const u8) bool { + if (std.mem.indexOf(u8, text, needle) != null) return true; + std.debug.print("missing \"{s}\" in:\n{s}\n", .{ needle, text }); + return false; +} + +fn writeCluster(a: std.mem.Allocator, tmp: std.testing.TmpDir, data: []const u8) ![]const u8 { + try tmp.dir.writeFile(io, .{ .sub_path = "cluster.json", .data = data }); + return std.fmt.allocPrint(a, ".zig-cache/tmp/{s}/cluster.json", .{tmp.sub_path}); +} + +test "config validate: only the config command belongs to this entry" { + try std.testing.expect(validate.wants(&.{"config"}) and validate.wants(&.{ "config", "validate", "c.json" })); + try std.testing.expect(!validate.wants(&.{ "cluster", "check" }) and !validate.wants(&.{"serve"}) and !validate.wants(&.{})); +} + +test "config validate: the worked example exits 0 and names the path and counts" { + var arena: std.heap.ArenaAllocator = .init(std.heap.page_allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const file = try writeCluster(a, tmp, config_test.example); + const got = try run(a, &.{ "config", "validate", file }); + try std.testing.expectEqual(@as(u8, 0), got.code); + try std.testing.expect(has(got.out, file)); + try std.testing.expect(has(got.out, "6 nodes")); + try std.testing.expect(has(got.out, "3 models")); + try std.testing.expectEqualStrings("", got.err); +} + +test "config validate: an unknown backend exits 1 and names it" { + var arena: std.heap.ArenaAllocator = .init(std.heap.page_allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const file = try writeCluster(a, tmp, "{\"schema\":\"tensorfold-cluster/1\",\"cluster\":\"x\",\"nodes\":[{\"name\":\"a\",\"address\":\"h\",\"backend\":\"rocm\"}]}"); + const got = try run(a, &.{ "config", "validate", file }); + try std.testing.expectEqual(@as(u8, 1), got.code); + try std.testing.expect(has(got.err, "backend")); + try std.testing.expectEqualStrings("", got.out); +} + +test "config validate: a wrong type exits 1 and names the field" { + var arena: std.heap.ArenaAllocator = .init(std.heap.page_allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const file = try writeCluster(a, tmp, "{\"schema\":\"tensorfold-cluster/1\",\"cluster\":\"x\",\"nodes\":\"nope\"}"); + const got = try run(a, &.{ "config", "validate", file }); + try std.testing.expectEqual(@as(u8, 1), got.code); + try std.testing.expect(has(got.err, "nodes: must be an array")); + try std.testing.expectEqualStrings("", got.out); +} + +test "config validate: a conflicting layout exits 1 and names the problem" { + var arena: std.heap.ArenaAllocator = .init(std.heap.page_allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const text = + \\{"schema":"tensorfold-cluster/1","cluster":"x", + \\"nodes":[{"name":"m1","address":"h","backend":"metal"},{"name":"m2","address":"h","backend":"metal"}, + \\{"name":"c1","address":"h","backend":"cuda"},{"name":"c2","address":"h","backend":"cuda"}], + \\"models":{"k":{"path":"/m","nodes":["m1","m2","c1","c2"],"parallel":{"tensor":3}}}} + ; + const file = try writeCluster(a, tmp, text); + const got = try run(a, &.{ "config", "validate", file }); + try std.testing.expectEqual(@as(u8, 1), got.code); + try std.testing.expect(has(got.err, "does not divide")); + try std.testing.expectEqualStrings("", got.out); +} + +test "config validate: a missing path exits 1 and includes the path tried" { + var arena: std.heap.ArenaAllocator = .init(std.heap.page_allocator); + defer arena.deinit(); + const a = arena.allocator(); + const path = "no-such-cluster-9f3a.json"; + const got = try run(a, &.{ "config", "validate", path }); + try std.testing.expectEqual(@as(u8, 1), got.code); + try std.testing.expect(has(got.err, path)); + try std.testing.expect(has(got.err, "FileNotFound")); + try std.testing.expectEqualStrings("", got.out); +} + +test "config validate: bad usage exits 2" { + var arena: std.heap.ArenaAllocator = .init(std.heap.page_allocator); + defer arena.deinit(); + const a = arena.allocator(); + const Case = struct { args: []const []const u8 }; + const cases = [_]Case{ + .{ .args = &.{"config"} }, + .{ .args = &.{ "config", "validate" } }, + .{ .args = &.{ "config", "check", "c.json" } }, + .{ .args = &.{ "config", "validate", "a.json", "b.json" } }, + .{ .args = &.{ "config", "validate", "--cluster", "c.json" } }, + .{ .args = &.{ "config", "validate", "--help" } }, + }; + for (cases) |k| { + const got = try run(a, k.args); + if (got.code != 2) std.debug.print("usage: exit {d}\n{s}{s}", .{ got.code, got.out, got.err }); + try std.testing.expectEqual(@as(u8, 2), got.code); + try std.testing.expect(has(got.err, "usage: tensorfold config validate FILE")); + try std.testing.expectEqualStrings("", got.out); + } +} diff --git a/zig/src/core/affine_mm.zig b/zig/src/core/affine_mm.zig index b633469e5a1..c38560a2a63 100644 --- a/zig/src/core/affine_mm.zig +++ b/zig/src/core/affine_mm.zig @@ -9,7 +9,7 @@ const bf16_round = @import("bf16_round"); pub const Glu = enum { clipped, plain }; /// The weights' bits (2-6 or 8) and group (32, 64 or 128), the output's type and the GLU epilogue. -pub const Format = struct { bits: u8 = 4, group: u16 = 64, out_f32: bool = false, glu: Glu = .clipped }; +pub const Format = struct { bits: u8 = 4, group: u16 = 64, out_f32: bool = false, glu: Glu = .clipped, glm_m3_fast: bool = false }; /// The kernel source for `f` (nax.h inlined for this GPU). pub fn source(device: mtl.Device, a: std.mem.Allocator, f: Format) ![]u8 { @@ -18,9 +18,10 @@ pub fn source(device: mtl.Device, a: std.mem.Allocator, f: Format) ![]u8 { const body = try frags.source(device, a, ks.core_affine_mm); defer a.free(body); const glu = if (f.glu == .plain) "#define TF_GLU_PLAIN 1\n" else ""; + const m3 = if (f.glm_m3_fast and !device.tensorUnits()) "#define TF_GLM_M3_FAST 1\n" else ""; const out = if (f.out_f32) "float" else "bfloat"; - const head = "#define TF_BITS {d}\n#define TF_GROUP {d}\n#define TF_OUT_T {s}\n{s}{s}"; - return std.fmt.allocPrint(a, head, .{ f.bits, f.group, out, glu, body }); + const head = "#define TF_BITS {d}\n#define TF_GROUP {d}\n#define TF_OUT_T {s}\n{s}{s}{s}"; + return std.fmt.allocPrint(a, head, .{ f.bits, f.group, out, glu, m3, body }); } /// Entry points: row sums, dense matmul, tiled and scattering gathers, ordered expert gate/up into SwiGLU. @@ -54,12 +55,22 @@ pub fn rowSumsAt(e: mtl.ComputeEncoder, p: Pipes, group: u32, x: anytype, sums: /// y = x W^T using group `sums`; x is [rows, q.k], y is [rows, n], n = q.n rounded up to 64 (padded weights). pub fn dense(e: mtl.ComputeEncoder, p: Pipes, x: anytype, sums: anytype, q: anytype, y: anytype, rows: u32) void { + denseBm(e, p, x, sums, q, y, rows, 64); +} + +/// `dense` with an explicit row-tile height `bm` (32 when compiled with TF_GLM_M3_FAST, 64 otherwise). +pub fn denseBm(e: mtl.ComputeEncoder, p: Pipes, x: anytype, sums: anytype, q: anytype, y: anytype, rows: u32, bm: u32) void { const n = std.mem.alignForward(u32, q.n, 64); - denseBatch(e, p, x, sums, q, y, rows, 1, .{ .x_row = @intCast(q.k), .y_row = @intCast(n) }); + denseBatchBm(e, p, x, sums, q, y, rows, 1, .{ .x_row = @intCast(q.k), .y_row = @intCast(n) }, bm); } /// `batch` dense products over per-batch weight rows with strides `s`; q.n is a multiple of 64 (e.g. heads). pub fn denseBatch(e: mtl.ComputeEncoder, p: Pipes, x: anytype, sums: anytype, q: anytype, y: anytype, rows: u32, batch: u32, s: Strides) void { + denseBatchBm(e, p, x, sums, q, y, rows, batch, s, 64); +} + +/// `denseBatch` with an explicit row-tile height `bm` (32 when compiled with TF_GLM_M3_FAST, 64 otherwise). +pub fn denseBatchBm(e: mtl.ComputeEncoder, p: Pipes, x: anytype, sums: anytype, q: anytype, y: anytype, rows: u32, batch: u32, s: Strides, bm: u32) void { const n = std.mem.alignForward(u32, q.n, 64); e.setPipeline(p[1]); bind(e, 0, x); @@ -70,7 +81,7 @@ pub fn denseBatch(e: mtl.ComputeEncoder, p: Pipes, x: anytype, sums: anytype, q: e.setValue(Args{ .rows = @intCast(rows), .n = @intCast(n), .k = @intCast(q.k), .experts = 0 }, 5); bind(e, 6, y); e.setValue(s, 7); - e.dispatchGroups(mtl.Size.of(n / 64, (rows + 63) / 64, batch), mtl.Size.of(32, 2, 2)); + e.dispatchGroups(mtl.Size.of(n / 64, (rows + bm - 1) / bm, batch), mtl.Size.of(32, 2, 2)); } /// y [rows, q.n]: x times its row expert's W^T, rows expert-sorted (`offsets`: experts' first rows); q [experts, n, k]. diff --git a/zig/src/core/checkpoint_cache.zig b/zig/src/core/checkpoint_cache.zig index 4c829a0b41e..d31f6d5d771 100644 --- a/zig/src/core/checkpoint_cache.zig +++ b/zig/src/core/checkpoint_cache.zig @@ -32,19 +32,15 @@ fn visit(io: Io, dir: []const u8, names: []const []const u8, comptime advise: an } /// Flash Next also closes shards while loading; its live PLE mappings must be excluded from the final sweep. -pub fn directory(io: Io, dir: []const u8, keep: anytype) void { +pub fn shards(io: Io, paths: []const [:0]u8, keep: anytype) void { if (@import("builtin").os.tag != .linux) return; - walk(io, dir, keep, drop); + walk(io, paths, keep, drop); } -fn walk(io: Io, dir: []const u8, keep: anytype, comptime advise: anytype) void { - var d = Io.Dir.cwd().openDir(io, dir, .{ .iterate = true }) catch return; - defer d.close(io); - var it = d.iterate(); - entries: while (it.next(io) catch null) |e| { - if (e.kind != .file and e.kind != .sym_link) continue; - if (!std.mem.endsWith(u8, e.name, ".safetensors")) continue; - const f = d.openFile(io, e.name, .{}) catch continue; +/// `paths` from the index (checkpoint.shardFiles), so shards nested under tensors/ are reached; held inodes skipped. +fn walk(io: Io, paths: []const [:0]u8, keep: anytype, comptime advise: anytype) void { + entries: for (paths) |path| { + const f = Io.Dir.cwd().openFile(io, path, .{}) catch continue; defer f.close(io); const stat = f.stat(io) catch continue; for (keep) |k| { @@ -89,30 +85,33 @@ test "checkpoint cache: last read precedes release and close on success and refu } } -test "checkpoint cache: final sweep excludes live PLE, subdirectories and unrelated files" { +test "checkpoint cache: final sweep reaches the index's nested shards and excludes live PLE and aliases" { var tmp = t.tmpDir(.{}); defer tmp.cleanup(); - for ([_][]const u8{ "model.safetensors", "mtp.safetensors", "ple.safetensors", "config.json" }) |name| + try tmp.dir.createDirPath(t.io, "tensors"); + for ([_][]const u8{ "tensors/model-1.safetensors", "tensors/model-2.safetensors", "tensors/ple.safetensors" }) |name| try tmp.dir.writeFile(t.io, .{ .sub_path = name, .data = name }); - try tmp.dir.createDirPath(t.io, "ssd.safetensors"); - try tmp.dir.writeFile(t.io, .{ .sub_path = "ssd.safetensors/expert.safetensors", .data = "runtime" }); - if (@import("builtin").os.tag != .windows) try tmp.dir.symLink(t.io, "ple.safetensors", "alias.safetensors", .{}); - const ple = try tmp.dir.openFile(t.io, "ple.safetensors", .{}); + if (@import("builtin").os.tag != .windows) try tmp.dir.symLink(t.io, "ple.safetensors", "tensors/alias.safetensors", .{}); + const ple = try tmp.dir.openFile(t.io, "tensors/ple.safetensors", .{}); defer ple.close(t.io); const keep = [_]struct { file: struct { file: Io.File } }{.{ .file = .{ .file = ple } }}; - const path = try tmp.dir.realPathFileAlloc(t.io, ".", t.allocator); - defer t.allocator.free(path); + const root = try tmp.dir.realPathFileAlloc(t.io, ".", t.allocator); + defer t.allocator.free(root); + var paths: [5][:0]u8 = undefined; + for (&paths, [_][]const u8{ "model-1", "model-2", "ple", "alias", "missing" }) |*p, name| + p.* = try std.fmt.allocPrintSentinel(t.allocator, "{s}/tensors/{s}.safetensors", .{ root, name }, 0); + defer for (paths) |p| t.allocator.free(p); const Spy = struct { var count: usize = 0; fn advise(f: Io.File) void { var buf: [64]u8 = undefined; const n = f.readPositionalAll(t.io, &buf, 0) catch unreachable; - std.debug.assert(std.mem.eql(u8, buf[0..n], "model.safetensors") or std.mem.eql(u8, buf[0..n], "mtp.safetensors")); + std.debug.assert(std.mem.startsWith(u8, buf[0..n], "tensors/model-")); count += 1; } }; Spy.count = 0; - walk(t.io, path, &keep, Spy.advise); + walk(t.io, &paths, &keep, Spy.advise); try t.expectEqual(@as(usize, 2), Spy.count); } diff --git a/zig/src/core/contract.zig b/zig/src/core/contract.zig index 24449e7175d..c5d71faab98 100644 --- a/zig/src/core/contract.zig +++ b/zig/src/core/contract.zig @@ -38,6 +38,7 @@ test { test { _ = @import("contract/qwen_served_records.zig"); _ = @import("contract/delta_slots_records.zig"); + _ = @import("contract/q27_stack_records.zig"); _ = @import("contract/vit_records.zig"); _ = @import("contract/simd_pairs_records.zig"); _ = @import("contract/simd_half_records.zig"); @@ -45,9 +46,11 @@ test { _ = @import("contract/row_wide_records.zig"); _ = @import("contract/nemotron_experts_records.zig"); _ = @import("contract/moss_image_records.zig"); + _ = @import("contract/idol_records.zig"); _ = @import("contract/metal_pair_records.zig"); _ = @import("contract/affine_gather_records.zig"); _ = @import("contract/flint_records.zig"); + _ = @import("contract/ling_mla_records.zig"); _ = spec; _ = gates; _ = rows; @@ -68,3 +71,8 @@ test { test { _ = @import("contract/seed_test.zig"); } + +pub const q27_stack_sums = @import("contract/q27_stack_sums.zig"); +test { + _ = q27_stack_sums; +} diff --git a/zig/src/core/contract/delta_slots_records.zig b/zig/src/core/contract/delta_slots_records.zig index 699bcbdee3d..416637cba7c 100644 --- a/zig/src/core/contract/delta_slots_records.zig +++ b/zig/src/core/contract/delta_slots_records.zig @@ -21,3 +21,21 @@ test "all five DeltaNet register-slot pipelines are in the live and offline coll try std.testing.expectEqual(@as(usize, 0), try registry.checkMetal(std.testing.allocator, &.{record}, true)); } } + +/// Column launches reserve their SIMD group in source; offline compile receipts remain device work. +pub const columns = [_]limits.MetalLaunch{ + .{ .name = "core deltanet tf_delta_gdn_columns_1", .threads = 32, .tg_memory = 2048, .reserved = 32 }, + .{ .name = "core deltanet tf_delta_gdn_columns_2", .threads = 32, .tg_memory = 4096, .reserved = 32 }, + .{ .name = "core deltanet tf_delta_gdn_columns_4", .threads = 32, .tg_memory = 8192, .reserved = 32 }, +}; + +test "q27 stack: all column replacements are active exactly once" { + for (columns) |record| { + var count: usize = 0; + for (registry.all_metal) |active| if (std.mem.eql(u8, record.name, active.name)) { + try std.testing.expectEqualDeep(record, active); + count += 1; + }; + try std.testing.expectEqual(@as(usize, 1), count); + } +} diff --git a/zig/src/core/contract/delta_slots_ref.zig b/zig/src/core/contract/delta_slots_ref.zig index 302aeac0fbc..9c65153df65 100644 --- a/zig/src/core/contract/delta_slots_ref.zig +++ b/zig/src/core/contract/delta_slots_ref.zig @@ -80,15 +80,17 @@ pub fn make(comptime Planner: type, a: std.mem.Allocator, limit: usize, n: usize const first = stream * n; const parents = f.parents[first..][0..n]; for (parents, 0..) |*p, row| p.* = if (row == 0) -1 else @intCast(if (limit == 1 or stream == 1) row - 1 else if (limit == 2) 0 else (row - 1) / 2); - comptime std.debug.assert(@sizeOf(Step) == @sizeOf(Planner.Step) and @alignOf(Step) == @alignOf(Planner.Step)); - const typed_steps: []Planner.Step = @ptrCast(f.steps[first..][0..n]); - _ = try Planner.build(a, parents, typed_steps, @intCast(first), limit); - // Exercise high register indices as well as the planner's normal dense slot numbering. - if (stream == 1) for (f.steps[first..][0..n]) |*step| { - if (step.read_slot >= 0) step.read_slot = @as(i32, @intCast(limit - 1)) - step.read_slot; - step.write_slot = @as(i32, @intCast(limit - 1)) - step.write_slot; - }; - try Planner.validate(parents, typed_steps, @intCast(first), limit); + if (Planner != void) { + comptime std.debug.assert(@sizeOf(Step) == @sizeOf(Planner.Step) and @alignOf(Step) == @alignOf(Planner.Step)); + const typed_steps: []Planner.Step = @ptrCast(f.steps[first..][0..n]); + _ = try Planner.build(a, parents, typed_steps, @intCast(first), limit); + // Exercise high register indices as well as the planner's normal dense slot numbering. + if (stream == 1) for (f.steps[first..][0..n]) |*step| { + if (step.read_slot >= 0) step.read_slot = @as(i32, @intCast(limit - 1)) - step.read_slot; + step.write_slot = @as(i32, @intCast(limit - 1)) - step.write_slot; + }; + try Planner.validate(parents, typed_steps, @intCast(first), limit); + } } try reference(a, &f, n); return f; @@ -152,3 +154,16 @@ pub fn reference(a: std.mem.Allocator, f: *Fixture, n: usize) !void { } }; } + +/// An exact-integer read: unchanged state, unit queries, no key or mixing contribution. +pub fn exactRead(f: *Fixture) void { + const sums = @import("q27_stack_sums.zig"); + @memset(f.query, c.toBf16(1)); + @memset(f.key, 0); + @memset(f.value, 0); + @memset(f.decay, 1); + @memset(f.mixing, 0); + for (f.state, 0..) |*entry, i| entry.* = @floatCast(sums.term(.columns, i % 128)); + @memset(f.output, sums.output(.columns, 0, .none, .sequential)); + @memset(f.bound, 0); +} diff --git a/zig/src/core/contract/idol_records.zig b/zig/src/core/contract/idol_records.zig new file mode 100644 index 00000000000..ae395491641 --- /dev/null +++ b/zig/src/core/contract/idol_records.zig @@ -0,0 +1,34 @@ +//! Idol's denoiser launches (idol.metal and idol_attention.metal after gemm_nax.metal), each source-reserved. +const std = @import("std"); +const M = @import("limits.zig").MetalLaunch; +pub const records = [_]M{ + .{ .name = "idol id_linear_00", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "idol id_linear_01", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "idol id_linear_10", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "idol id_linear_11", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "idol id_linear_gelu_00", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "idol id_linear_gelu_01", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "idol id_linear_gelu_10", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "idol id_linear_gelu_11", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "idol id_split_0", .threads = 128, .tg_memory = 0, .reserved = 128 }, + .{ .name = "idol id_split_1", .threads = 128, .tg_memory = 0, .reserved = 128 }, + .{ .name = "idol id_gemm32", .threads = 128, .tg_memory = 19456, .reserved = 128 }, + .{ .name = "idol id_norm", .threads = 256, .tg_memory = 144, .reserved = 256 }, + .{ .name = "idol id_norm32", .threads = 256, .tg_memory = 144, .reserved = 256 }, + .{ .name = "idol id_norm_split", .threads = 256, .tg_memory = 144, .reserved = 256 }, + .{ .name = "idol id_repo", .threads = 64, .tg_memory = 704, .reserved = 64 }, + .{ .name = "idol id_qk", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "idol id_gate_add", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "idol id_embed", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "idol id_cond", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "idol id_bias32", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "idol id_attention_00", .threads = 128, .tg_memory = 0, .reserved = 128 }, + .{ .name = "idol id_attention_01", .threads = 128, .tg_memory = 0, .reserved = 128 }, + .{ .name = "idol id_attention_10", .threads = 128, .tg_memory = 0, .reserved = 128 }, + .{ .name = "idol id_attention_11", .threads = 128, .tg_memory = 0, .reserved = 128 }, +}; + +test "the Idol launches fit every Apple family, one record a pipeline" { + try std.testing.expectEqual(@as(usize, 0), try @import("registry.zig").checkMetal(std.testing.allocator, &records, true)); + try std.testing.expectEqual(@as(usize, 24), records.len); +} diff --git a/zig/src/core/contract/ling_mla_records.zig b/zig/src/core/contract/ling_mla_records.zig new file mode 100644 index 00000000000..ef706fa8efd --- /dev/null +++ b/zig/src/core/contract/ling_mla_records.zig @@ -0,0 +1,12 @@ +//! Ling MLA extras (tf_ling_mla_rope_cache, tf_ling_mla_rope_q, tf_ling_mla_gate_expand). +const std = @import("std"); +const M = @import("limits.zig").MetalLaunch; +pub const records = [_]M{ + .{ .name = "metal ling mla tf_ling_mla_rope_cache", .threads = 32, .tg_memory = 256, .m1 = 1024, .m2 = 1024 }, + .{ .name = "metal ling mla tf_ling_mla_rope_q", .threads = 32, .tg_memory = 256, .m1 = 1024, .m2 = 1024 }, + .{ .name = "metal ling mla tf_ling_mla_gate_expand", .threads = 128, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, +}; + +test "the Ling MLA launches fit every Apple family" { + try std.testing.expectEqual(@as(usize, 0), try @import("registry.zig").checkMetal(std.testing.allocator, &records, true)); +} diff --git a/zig/src/core/contract/nvfp4_fact_records.zig b/zig/src/core/contract/nvfp4_fact_records.zig index 353e49ef4ee..642e4bf9b9f 100644 --- a/zig/src/core/contract/nvfp4_fact_records.zig +++ b/zig/src/core/contract/nvfp4_fact_records.zig @@ -1,27 +1,29 @@ -//! tf_nvfp4_fact_*, decode waves and 1-warp decode CTAs (nvfp4_experts.cu): nvcc 13.0.88 cubins, sm_80/86/89/120a/121a. +//! tf_nvfp4_fact_* and the decode CTAs (nvfp4_experts.cu): nvcc 13.0.88 cubins, sm_80/86/89/120a/121a. const CudaRecord = @import("registry.zig").CudaRecord; pub const cuda = [_]CudaRecord{ .{ .launch = .{ .name = "nvfp4_experts tf_nvfp4_fact_swiglu", .symbol = "tf_nvfp4_fact_swiglu", .image = "nvfp4_experts", .threads = 128, .dynamic = 34816 }, .usage = .{ .{ .regs = 249, .static = 0, .bound = 128 }, .{ .regs = 249, .static = 0, .bound = 128 }, .{ .regs = 255, .static = 0, .bound = 128 }, .{ .regs = 255, .static = 0, .bound = 128 }, .{ .regs = 255, .static = 0, .bound = 128 } } }, .{ .launch = .{ .name = "nvfp4_experts tf_nvfp4_fact_down_f32", .symbol = "tf_nvfp4_fact_down_f32", .image = "nvfp4_experts", .threads = 256, .dynamic = 34816 }, .usage = .{ .{ .regs = 185, .static = 0, .bound = 256 }, .{ .regs = 186, .static = 0, .bound = 256 }, .{ .regs = 178, .static = 0, .bound = 256 }, .{ .regs = 141, .static = 0, .bound = 256 }, .{ .regs = 141, .static = 0, .bound = 256 } } }, - .{ .launch = .{ .name = "nvfp4_experts decode waves gate-up", .symbol = "_ZN16tf_nvfp4_experts18nvfp4_expert_wavesILi2ELi2ELi4EEEvPK13__nv_bfloat16iiPK5uint4PKfiiPKiSA_SA_Pvifi", .image = "nvfp4_experts", .threads = 128, .dynamic = 0 }, .usage = .{ .{ .regs = 117, .static = 0, .bound = 128 }, .{ .regs = 117, .static = 0, .bound = 128 }, .{ .regs = 121, .static = 0, .bound = 128 }, .{ .regs = 126, .static = 0, .bound = 128 }, .{ .regs = 126, .static = 0, .bound = 128 } } }, - .{ .launch = .{ .name = "nvfp4_experts decode waves down f32", .symbol = "_ZN16tf_nvfp4_experts18nvfp4_expert_wavesILi1ELi0ELi4EEEvPK13__nv_bfloat16iiPK5uint4PKfiiPKiSA_SA_Pvifi", .image = "nvfp4_experts", .threads = 128, .dynamic = 0 }, .usage = .{ .{ .regs = 80, .static = 0, .bound = 128 }, .{ .regs = 80, .static = 0, .bound = 128 }, .{ .regs = 89, .static = 0, .bound = 128 }, .{ .regs = 96, .static = 0, .bound = 128 }, .{ .regs = 96, .static = 0, .bound = 128 } } }, - .{ .launch = .{ .name = "nvfp4_experts decode half gate-up", .symbol = "_ZN16tf_nvfp4_experts17nvfp4_expert_halfILi2ELi2ELi4EEEvPK13__nv_bfloat16iiPK5uint4PKfiiPKiSA_SA_Pvifi", .image = "nvfp4_experts", .threads = 128, .dynamic = 0 }, .usage = .{ .{ .regs = 91, .static = 0, .bound = 128 }, .{ .regs = 91, .static = 0, .bound = 128 }, .{ .regs = 95, .static = 0, .bound = 128 }, .{ .regs = 126, .static = 0, .bound = 128 }, .{ .regs = 126, .static = 0, .bound = 128 } } }, - .{ .launch = .{ .name = "nvfp4_experts decode gate-up, 1 warp", .symbol = "_ZN16tf_nvfp4_experts19nvfp4_expert_kernelILi2ELi2ELi1EEEvPK13__nv_bfloat16iiPK5uint4PKfiiPKiSA_SA_Pvifi", .image = "nvfp4_experts", .threads = 32, .dynamic = 0 }, .usage = .{ .{ .regs = 118, .static = 0, .bound = 32 }, .{ .regs = 118, .static = 0, .bound = 32 }, .{ .regs = 122, .static = 0, .bound = 32 }, .{ .regs = 127, .static = 0, .bound = 32 }, .{ .regs = 127, .static = 0, .bound = 32 } } }, - .{ .launch = .{ .name = "nvfp4_experts decode down f32, 1 warp", .symbol = "_ZN16tf_nvfp4_experts19nvfp4_expert_kernelILi1ELi0ELi1EEEvPK13__nv_bfloat16iiPK5uint4PKfiiPKiSA_SA_Pvifi", .image = "nvfp4_experts", .threads = 32, .dynamic = 0 }, .usage = .{ .{ .regs = 81, .static = 0, .bound = 32 }, .{ .regs = 83, .static = 0, .bound = 32 }, .{ .regs = 92, .static = 0, .bound = 32 }, .{ .regs = 80, .static = 0, .bound = 32 }, .{ .regs = 80, .static = 0, .bound = 32 } } }, - .{ .launch = .{ .name = "nvfp4_experts decode down bf16, 1 warp", .symbol = "_ZN16tf_nvfp4_experts19nvfp4_expert_kernelILi1ELi3ELi1EEEvPK13__nv_bfloat16iiPK5uint4PKfiiPKiSA_SA_Pvifi", .image = "nvfp4_experts", .threads = 32, .dynamic = 0 }, .usage = .{ .{ .regs = 81, .static = 0, .bound = 32 }, .{ .regs = 83, .static = 0, .bound = 32 }, .{ .regs = 92, .static = 0, .bound = 32 }, .{ .regs = 80, .static = 0, .bound = 32 }, .{ .regs = 80, .static = 0, .bound = 32 } } }, - .{ .launch = .{ .name = "nvfp4_experts decode up relu2, 1 warp", .symbol = "_ZN16tf_nvfp4_experts19nvfp4_expert_kernelILi1ELi1ELi1EEEvPK13__nv_bfloat16iiPK5uint4PKfiiPKiSA_SA_Pvifi", .image = "nvfp4_experts", .threads = 32, .dynamic = 0 }, .usage = .{ .{ .regs = 81, .static = 0, .bound = 32 }, .{ .regs = 83, .static = 0, .bound = 32 }, .{ .regs = 92, .static = 0, .bound = 32 }, .{ .regs = 80, .static = 0, .bound = 32 }, .{ .regs = 80, .static = 0, .bound = 32 } } }, - .{ .launch = .{ .name = "nvfp4_experts decode waves gate-up, 1 warp", .symbol = "_ZN16tf_nvfp4_experts18nvfp4_expert_wavesILi2ELi2ELi1EEEvPK13__nv_bfloat16iiPK5uint4PKfiiPKiSA_SA_Pvifi", .image = "nvfp4_experts", .threads = 32, .dynamic = 0 }, .usage = .{ .{ .regs = 117, .static = 0, .bound = 32 }, .{ .regs = 117, .static = 0, .bound = 32 }, .{ .regs = 123, .static = 0, .bound = 32 }, .{ .regs = 124, .static = 0, .bound = 32 }, .{ .regs = 124, .static = 0, .bound = 32 } } }, - .{ .launch = .{ .name = "nvfp4_experts decode waves down f32, 1 warp", .symbol = "_ZN16tf_nvfp4_experts18nvfp4_expert_wavesILi1ELi0ELi1EEEvPK13__nv_bfloat16iiPK5uint4PKfiiPKiSA_SA_Pvifi", .image = "nvfp4_experts", .threads = 32, .dynamic = 0 }, .usage = .{ .{ .regs = 85, .static = 0, .bound = 32 }, .{ .regs = 84, .static = 0, .bound = 32 }, .{ .regs = 92, .static = 0, .bound = 32 }, .{ .regs = 92, .static = 0, .bound = 32 }, .{ .regs = 92, .static = 0, .bound = 32 } } }, - .{ .launch = .{ .name = "nvfp4_experts decode half gate-up, 1 warp", .symbol = "_ZN16tf_nvfp4_experts17nvfp4_expert_halfILi2ELi2ELi1EEEvPK13__nv_bfloat16iiPK5uint4PKfiiPKiSA_SA_Pvifi", .image = "nvfp4_experts", .threads = 32, .dynamic = 0 }, .usage = .{ .{ .regs = 91, .static = 0, .bound = 32 }, .{ .regs = 92, .static = 0, .bound = 32 }, .{ .regs = 94, .static = 0, .bound = 32 }, .{ .regs = 95, .static = 0, .bound = 32 }, .{ .regs = 95, .static = 0, .bound = 32 } } }, + .{ .launch = .{ .name = "nvfp4_experts decode waves gate-up", .symbol = "_ZN16tf_nvfp4_experts18nvfp4_expert_wavesILi2ELi2ELi4EEEvPK13__nv_bfloat16iiPK5uint4PKfiiPKiSA_SA_Pvifi", .image = "nvfp4_experts", .threads = 128, .dynamic = 0 }, .usage = .{ .{ .regs = 101, .static = 34816, .bound = 128 }, .{ .regs = 106, .static = 34816, .bound = 128 }, .{ .regs = 134, .static = 34816, .bound = 128 }, .{ .regs = 130, .static = 34816, .bound = 128 }, .{ .regs = 126, .static = 0, .bound = 128 } } }, + .{ .launch = .{ .name = "nvfp4_experts decode waves down f32", .symbol = "_ZN16tf_nvfp4_experts18nvfp4_expert_wavesILi1ELi0ELi4EEEvPK13__nv_bfloat16iiPK5uint4PKfiiPKiSA_SA_Pvifi", .image = "nvfp4_experts", .threads = 128, .dynamic = 0 }, .usage = .{ .{ .regs = 79, .static = 25600, .bound = 128 }, .{ .regs = 82, .static = 25600, .bound = 128 }, .{ .regs = 101, .static = 25600, .bound = 128 }, .{ .regs = 108, .static = 25600, .bound = 128 }, .{ .regs = 96, .static = 0, .bound = 128 } } }, + .{ .launch = .{ .name = "nvfp4_experts decode half gate-up", .symbol = "_ZN16tf_nvfp4_experts17nvfp4_expert_halfILi2ELi2ELi4EEEvPK13__nv_bfloat16iiPK5uint4PKfiiPKiSA_SA_Pvifi", .image = "nvfp4_experts", .threads = 128, .dynamic = 0 }, .usage = .{ .{ .regs = 85, .static = 26624, .bound = 128 }, .{ .regs = 88, .static = 26624, .bound = 128 }, .{ .regs = 96, .static = 26624, .bound = 128 }, .{ .regs = 94, .static = 26624, .bound = 128 }, .{ .regs = 126, .static = 0, .bound = 128 } } }, + .{ .launch = .{ .name = "nvfp4_experts decode gate-up, 1 warp", .symbol = "_ZN16tf_nvfp4_experts19nvfp4_expert_kernelILi2ELi2ELi1EEEvPK13__nv_bfloat16iiPK5uint4PKfiiPKiSA_SA_Pvifi", .image = "nvfp4_experts", .threads = 32, .dynamic = 0 }, .usage = .{ .{ .regs = 103, .static = 8704, .bound = 32 }, .{ .regs = 103, .static = 8704, .bound = 32 }, .{ .regs = 139, .static = 8704, .bound = 32 }, .{ .regs = 124, .static = 8704, .bound = 32 }, .{ .regs = 127, .static = 0, .bound = 32 } } }, + .{ .launch = .{ .name = "nvfp4_experts decode down f32, 1 warp", .symbol = "_ZN16tf_nvfp4_experts19nvfp4_expert_kernelILi1ELi0ELi1EEEvPK13__nv_bfloat16iiPK5uint4PKfiiPKiSA_SA_Pvifi", .image = "nvfp4_experts", .threads = 32, .dynamic = 0 }, .usage = .{ .{ .regs = 80, .static = 6400, .bound = 32 }, .{ .regs = 88, .static = 6400, .bound = 32 }, .{ .regs = 102, .static = 6400, .bound = 32 }, .{ .regs = 103, .static = 6400, .bound = 32 }, .{ .regs = 80, .static = 0, .bound = 32 } } }, + .{ .launch = .{ .name = "nvfp4_experts decode down bf16, 1 warp", .symbol = "_ZN16tf_nvfp4_experts19nvfp4_expert_kernelILi1ELi3ELi1EEEvPK13__nv_bfloat16iiPK5uint4PKfiiPKiSA_SA_Pvifi", .image = "nvfp4_experts", .threads = 32, .dynamic = 0 }, .usage = .{ .{ .regs = 80, .static = 6400, .bound = 32 }, .{ .regs = 88, .static = 6400, .bound = 32 }, .{ .regs = 102, .static = 6400, .bound = 32 }, .{ .regs = 103, .static = 6400, .bound = 32 }, .{ .regs = 80, .static = 0, .bound = 32 } } }, + .{ .launch = .{ .name = "nvfp4_experts decode up relu2, 1 warp", .symbol = "_ZN16tf_nvfp4_experts19nvfp4_expert_kernelILi1ELi1ELi1EEEvPK13__nv_bfloat16iiPK5uint4PKfiiPKiSA_SA_Pvifi", .image = "nvfp4_experts", .threads = 32, .dynamic = 0 }, .usage = .{ .{ .regs = 80, .static = 6400, .bound = 32 }, .{ .regs = 88, .static = 6400, .bound = 32 }, .{ .regs = 102, .static = 6400, .bound = 32 }, .{ .regs = 103, .static = 6400, .bound = 32 }, .{ .regs = 80, .static = 0, .bound = 32 } } }, + .{ .launch = .{ .name = "nvfp4_experts decode waves gate-up, 1 warp", .symbol = "_ZN16tf_nvfp4_experts18nvfp4_expert_wavesILi2ELi2ELi1EEEvPK13__nv_bfloat16iiPK5uint4PKfiiPKiSA_SA_Pvifi", .image = "nvfp4_experts", .threads = 32, .dynamic = 0 }, .usage = .{ .{ .regs = 103, .static = 8704, .bound = 32 }, .{ .regs = 103, .static = 8704, .bound = 32 }, .{ .regs = 140, .static = 8704, .bound = 32 }, .{ .regs = 126, .static = 8704, .bound = 32 }, .{ .regs = 124, .static = 0, .bound = 32 } } }, + .{ .launch = .{ .name = "nvfp4_experts decode waves down f32, 1 warp", .symbol = "_ZN16tf_nvfp4_experts18nvfp4_expert_wavesILi1ELi0ELi1EEEvPK13__nv_bfloat16iiPK5uint4PKfiiPKiSA_SA_Pvifi", .image = "nvfp4_experts", .threads = 32, .dynamic = 0 }, .usage = .{ .{ .regs = 80, .static = 6400, .bound = 32 }, .{ .regs = 90, .static = 6400, .bound = 32 }, .{ .regs = 103, .static = 6400, .bound = 32 }, .{ .regs = 103, .static = 6400, .bound = 32 }, .{ .regs = 92, .static = 0, .bound = 32 } } }, + .{ .launch = .{ .name = "nvfp4_experts decode half gate-up, 1 warp", .symbol = "_ZN16tf_nvfp4_experts17nvfp4_expert_halfILi2ELi2ELi1EEEvPK13__nv_bfloat16iiPK5uint4PKfiiPKiSA_SA_Pvifi", .image = "nvfp4_experts", .threads = 32, .dynamic = 0 }, .usage = .{ .{ .regs = 85, .static = 6656, .bound = 32 }, .{ .regs = 87, .static = 6656, .bound = 32 }, .{ .regs = 93, .static = 6656, .bound = 32 }, .{ .regs = 90, .static = 6656, .bound = 32 }, .{ .regs = 95, .static = 0, .bound = 32 } } }, }; -/// What nvcc 13.2 compiles differently on sm_120 and sm_121: the 1-warp decode CTAs. +/// What nvcc 13.2.78 compiles differently on the decode CTAs; nvcc 13.3.73 compiles them as 13.2 does. pub const cuda_132 = [_]@import("registry.zig").Override{ - .{ .name = "nvfp4_experts decode gate-up, 1 warp", .usage = .{ .{ .regs = 118, .static = 0, .bound = 32 }, .{ .regs = 118, .static = 0, .bound = 32 }, .{ .regs = 122, .static = 0, .bound = 32 }, .{ .regs = 126, .static = 0, .bound = 32 }, .{ .regs = 126, .static = 0, .bound = 32 } } }, - .{ .name = "nvfp4_experts decode down f32, 1 warp", .usage = .{ .{ .regs = 81, .static = 0, .bound = 32 }, .{ .regs = 83, .static = 0, .bound = 32 }, .{ .regs = 92, .static = 0, .bound = 32 }, .{ .regs = 79, .static = 0, .bound = 32 }, .{ .regs = 79, .static = 0, .bound = 32 } } }, - .{ .name = "nvfp4_experts decode down bf16, 1 warp", .usage = .{ .{ .regs = 81, .static = 0, .bound = 32 }, .{ .regs = 83, .static = 0, .bound = 32 }, .{ .regs = 92, .static = 0, .bound = 32 }, .{ .regs = 79, .static = 0, .bound = 32 }, .{ .regs = 79, .static = 0, .bound = 32 } } }, - .{ .name = "nvfp4_experts decode up relu2, 1 warp", .usage = .{ .{ .regs = 81, .static = 0, .bound = 32 }, .{ .regs = 83, .static = 0, .bound = 32 }, .{ .regs = 92, .static = 0, .bound = 32 }, .{ .regs = 79, .static = 0, .bound = 32 }, .{ .regs = 79, .static = 0, .bound = 32 } } }, - .{ .name = "nvfp4_experts decode waves gate-up, 1 warp", .usage = .{ .{ .regs = 117, .static = 0, .bound = 32 }, .{ .regs = 117, .static = 0, .bound = 32 }, .{ .regs = 123, .static = 0, .bound = 32 }, .{ .regs = 126, .static = 0, .bound = 32 }, .{ .regs = 126, .static = 0, .bound = 32 } } }, - .{ .name = "nvfp4_experts decode waves down f32, 1 warp", .usage = .{ .{ .regs = 85, .static = 0, .bound = 32 }, .{ .regs = 84, .static = 0, .bound = 32 }, .{ .regs = 92, .static = 0, .bound = 32 }, .{ .regs = 95, .static = 0, .bound = 32 }, .{ .regs = 95, .static = 0, .bound = 32 } } }, + .{ .name = "nvfp4_experts decode waves gate-up", .usage = .{ .{ .regs = 101, .static = 34816, .bound = 128 }, .{ .regs = 106, .static = 34816, .bound = 128 }, .{ .regs = 134, .static = 34816, .bound = 128 }, .{ .regs = 129, .static = 34816, .bound = 128 }, .{ .regs = 126, .static = 0, .bound = 128 } } }, + .{ .name = "nvfp4_experts decode waves down f32", .usage = .{ .{ .regs = 79, .static = 25600, .bound = 128 }, .{ .regs = 82, .static = 25600, .bound = 128 }, .{ .regs = 101, .static = 25600, .bound = 128 }, .{ .regs = 107, .static = 25600, .bound = 128 }, .{ .regs = 96, .static = 0, .bound = 128 } } }, + .{ .name = "nvfp4_experts decode waves gate-up, 1 warp", .usage = .{ .{ .regs = 103, .static = 8704, .bound = 32 }, .{ .regs = 103, .static = 8704, .bound = 32 }, .{ .regs = 140, .static = 8704, .bound = 32 }, .{ .regs = 124, .static = 8704, .bound = 32 }, .{ .regs = 126, .static = 0, .bound = 32 } } }, + .{ .name = "nvfp4_experts decode gate-up, 1 warp", .usage = .{ .{ .regs = 103, .static = 8704, .bound = 32 }, .{ .regs = 103, .static = 8704, .bound = 32 }, .{ .regs = 139, .static = 8704, .bound = 32 }, .{ .regs = 124, .static = 8704, .bound = 32 }, .{ .regs = 126, .static = 0, .bound = 32 } } }, + .{ .name = "nvfp4_experts decode down f32, 1 warp", .usage = .{ .{ .regs = 80, .static = 6400, .bound = 32 }, .{ .regs = 88, .static = 6400, .bound = 32 }, .{ .regs = 102, .static = 6400, .bound = 32 }, .{ .regs = 103, .static = 6400, .bound = 32 }, .{ .regs = 79, .static = 0, .bound = 32 } } }, + .{ .name = "nvfp4_experts decode down bf16, 1 warp", .usage = .{ .{ .regs = 80, .static = 6400, .bound = 32 }, .{ .regs = 88, .static = 6400, .bound = 32 }, .{ .regs = 102, .static = 6400, .bound = 32 }, .{ .regs = 103, .static = 6400, .bound = 32 }, .{ .regs = 79, .static = 0, .bound = 32 } } }, + .{ .name = "nvfp4_experts decode up relu2, 1 warp", .usage = .{ .{ .regs = 80, .static = 6400, .bound = 32 }, .{ .regs = 88, .static = 6400, .bound = 32 }, .{ .regs = 102, .static = 6400, .bound = 32 }, .{ .regs = 103, .static = 6400, .bound = 32 }, .{ .regs = 79, .static = 0, .bound = 32 } } }, + .{ .name = "nvfp4_experts decode waves down f32, 1 warp", .usage = .{ .{ .regs = 80, .static = 6400, .bound = 32 }, .{ .regs = 90, .static = 6400, .bound = 32 }, .{ .regs = 103, .static = 6400, .bound = 32 }, .{ .regs = 103, .static = 6400, .bound = 32 }, .{ .regs = 95, .static = 0, .bound = 32 } } }, }; diff --git a/zig/src/core/contract/q27_stack_records.zig b/zig/src/core/contract/q27_stack_records.zig new file mode 100644 index 00000000000..8e8516450ac --- /dev/null +++ b/zig/src/core/contract/q27_stack_records.zig @@ -0,0 +1,36 @@ +//! Qwen27 stack launches: source reservations for flat glue; tensor-op qk stays at at most 256 threads. +const std = @import("std"); +const M = @import("limits.zig").MetalLaunch; +pub const records = blk: { + var all: [48]M = undefined; + var at: usize = 0; + for (1..9) |sk| for ([_]usize{ 8, 16, 24, 32, 40, 48 }) |block| { + const bytes = (sk - 1) * block * 32 * 4; + if (bytes > 32768) continue; + all[at] = .{ .name = std.fmt.comptimePrint("q27 stack qk sk{d} rows{d} tf_qk", .{ sk, block }), .threads = 32 * sk, .tg_memory = 0, .dynamic = bytes, .offline = false }; + at += 1; + }; + std.debug.assert(at == 45); + const flat = [_]M{ + .{ .name = "core deltanet tf_delta_gdn_pre_vectors", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "q27 stack mlp xs0 q27_mlp_rows", .threads = 256, .tg_memory = 2048, .reserved = 256 }, + .{ .name = "q27 stack mlp xs1 q27_mlp_rows", .threads = 256, .tg_memory = 2048, .reserved = 256 }, + }; + for (flat) |record| { + all[at] = record; + at += 1; + } + break :blk all; +}; +test "q27 stack: all launch records are active once and fit source-declared limits" { + const registry = @import("registry.zig"); + for (records) |record| { + var count: usize = 0; + for (registry.all_metal) |active| if (std.mem.eql(u8, active.name, record.name)) { + try std.testing.expectEqualDeep(record, active); + count += 1; + }; + try std.testing.expectEqual(@as(usize, 1), count); + try std.testing.expectEqual(@as(usize, 0), try registry.checkMetal(std.testing.allocator, &.{record}, true)); + } +} diff --git a/zig/src/core/contract/q27_stack_sums.zig b/zig/src/core/contract/q27_stack_sums.zig new file mode 100644 index 00000000000..1344a446c63 --- /dev/null +++ b/zig/src/core/contract/q27_stack_sums.zig @@ -0,0 +1,90 @@ +//! Independent exact-integer sum panels for the flat kernels' convolution, norm and XS reductions. +const std = @import("std"); +const c = @import("contract.zig"); +const g = @import("gates.zig"); +pub const Kind = enum { conv, norm, xs, columns }; +pub fn term(kind: Kind, i: usize) f64 { + return switch (kind) { + .conv => ([_]f64{ 0x1p20, 64, 64, -0x1p20 })[i], + .columns => if (i < 64) 131072 + 1024 * @as(f64, @floatFromInt(i)) else -(131072 + 1024 * @as(f64, @floatFromInt(i - 64))) + @as(f64, if (i == 127) 1024 else 0), + .norm => if (i == 0) 40 * 40 else 32 * 32, + .xs => if (i < 32) 131072 + 1024 * @as(f64, @floatFromInt(i)) else -(131072 + 1024 * @as(f64, @floatFromInt(i - 32))) + @as(f64, if (i == 63) 1024 else 0), + }; +} +fn rounded(x: f64, acc: c.Accum) f64 { + return switch (acc) { + .f32 => @as(f32, @floatCast(x)), + .f16 => @as(f16, @floatCast(x)), + .bf16 => c.fromBf16(c.toBf16(@floatCast(x))), + .none => x, + }; +} +pub fn sum(kind: Kind, acc: c.Accum, order: g.Order) f64 { + const n: usize = switch (kind) { + .conv => 4, + .norm, .columns => 128, + .xs => 64, + }; + var values: [128]f64 = @splat(0); + for (0..n) |i| values[i] = rounded(term(kind, i), acc); + if (order == .sequential) { + var out: f64 = 0; + for (values[0..n]) |v| out = rounded(out + v, acc); + return out; + } + var width = n; + if (order == .strided) { + var lanes: [32]f64 = @splat(0); + for (values[0..n], 0..) |v, i| lanes[i % 32] = rounded(lanes[i % 32] + v, acc); + @memcpy(values[0..32], &lanes); + width = 32; + } + var stride: usize = 1; + while (stride < width) : (stride *= 2) { + var i: usize = 0; + while (i < width) : (i += 2 * stride) values[i] = rounded(values[i] + values[i + stride], acc); + } + return values[0]; +} +pub fn output(kind: Kind, i: usize, acc: c.Accum, order: g.Order) f64 { + const total = sum(kind, acc, order); + return switch (kind) { + .xs => total, + .columns => c.fromBf16(c.toBf16(@floatCast(total))), + .conv => blk: { + const x = c.fromBf16(c.toBf16(@floatCast(total))); + const sigmoid = c.fromBf16(c.toBf16(@floatCast(1 / (1 + @exp(-@as(f64, x)))))); + break :blk c.fromBf16(c.toBf16(x * sigmoid)); + }, + .norm => blk: { + const x: f64 = if (i % 128 == 0) 40 else 32; + const inv = if (acc == .f32) rounded(1 / @sqrt(rounded(total / 128 + 1e-6, .f32)), .f32) else 1 / @sqrt(total / 128 + 1e-6); + break :blk c.fromBf16(c.toBf16(@floatCast(x * inv))) / 128; + }, + }; +} + +test "q27 stack: exact sum panels reject half in every reduction order" { + for (std.enums.values(Kind)) |kind| for (std.enums.values(g.Order)) |order| { + const n: usize = if (kind == .norm) 128 else 1; + for (0..n) |i| { + const want = output(kind, i, .none, .sequential); + try std.testing.expectEqual(want, output(kind, i, .f32, order)); + const half = output(kind, i, .f16, order); + const allowance = if (kind == .xs) @abs(want) * 0x1p-24 else @abs(want) * 0x1p-8; + try std.testing.expect(!std.math.isFinite(half) or @abs(half - want) >= 100 * allowance); + if (kind == .conv) try std.testing.expect(@abs(output(kind, i, .bf16, order) - want) >= 100 * allowance); + } + }; +} + +test "q27 stack: the actual column panel agrees with the independent parent-indexed FP64 oracle" { + const ref = @import("delta_slots_ref.zig"); + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var f = try ref.make(void, a, 2, 3, false, 9); + ref.exactRead(&f); + try ref.reference(a, &f, 3); + for (f.output) |v| try std.testing.expectEqual(@as(f64, 1024), v); +} diff --git a/zig/src/core/contract/registry.zig b/zig/src/core/contract/registry.zig index 7923fd41617..4f1a4bed574 100644 --- a/zig/src/core/contract/registry.zig +++ b/zig/src/core/contract/registry.zig @@ -213,111 +213,7 @@ pub const Override = struct { name: []const u8, usage: [limits.sms.len]U }; /// A later nvcc's records: the launches it compiles differently from the release before it. pub const CudaSet = struct { release: limits.Nvcc, usage: []const Override }; /// The later releases' sets, rising by release; a tree's images are checked against the newest at or below their own. -pub const cuda_sets = [_]CudaSet{ - .{ .release = .{ .major = 13, .minor = 2 }, .usage = &(@import("registry_shared_attention.zig").nvcc132(Override) ++ [_]Override{ - .{ .name = "window_pages tf_wrows_merge_512_pg", .usage = .{ .{ .regs = 56, .static = 128, .bound = 256 }, .{ .regs = 56, .static = 128, .bound = 256 }, .{ .regs = 56, .static = 128, .bound = 256 }, .{ .regs = 60, .static = 128, .bound = 256 }, .{ .regs = 60, .static = 128, .bound = 256 } } }, - .{ .name = "moe tf_moe_topk_sigmoid_score_warp", .usage = .{ .{ .regs = 219, .static = 0, .bound = 256 }, .{ .regs = 219, .static = 0, .bound = 256 }, .{ .regs = 219, .static = 0, .bound = 256 }, .{ .regs = 203, .static = 0, .bound = 256 }, .{ .regs = 203, .static = 0, .bound = 256 } } }, - .{ .name = "norms tf_rms_rows", .usage = .{ .{ .regs = 32, .static = 132, .bound = 1024 }, .{ .regs = 46, .static = 132, .bound = 1024 }, .{ .regs = 46, .static = 132, .bound = 1024 }, .{ .regs = 43, .static = 132, .bound = 1024 }, .{ .regs = 43, .static = 132, .bound = 1024 } } }, - .{ .name = "lane_gemv", .usage = .{ .{ .regs = 64, .static = 0, .bound = 128 }, .{ .regs = 58, .static = 0, .bound = 128 }, .{ .regs = 58, .static = 0, .bound = 128 }, .{ .regs = 66, .static = 0, .bound = 128 }, .{ .regs = 66, .static = 0, .bound = 128 } } }, - .{ .name = "lane_gemv split-K", .usage = .{ .{ .regs = 62, .static = 128, .bound = 128 }, .{ .regs = 56, .static = 128, .bound = 128 }, .{ .regs = 56, .static = 128, .bound = 128 }, .{ .regs = 72, .static = 128, .bound = 128 }, .{ .regs = 72, .static = 128, .bound = 128 } } }, - .{ .name = "prompt16 FP8", .usage = .{ .{ .regs = 243, .static = 0, .bound = 128 }, .{ .regs = 243, .static = 0, .bound = 128 }, .{ .regs = 243, .static = 0, .bound = 128 }, .{ .regs = 212, .static = 0, .bound = 128 }, .{ .regs = 212, .static = 0, .bound = 128 } } }, - .{ .name = "qmmf FP4 fp32 out 32-row tile, cluster of 8", .usage = .{ .{ .regs = 64, .static = 0, .bound = 128 }, .{ .regs = 64, .static = 0, .bound = 128 }, .{ .regs = 80, .static = 0, .bound = 128 }, .{ .regs = 61, .static = 0, .bound = 128 }, .{ .regs = 61, .static = 0, .bound = 128 } } }, - .{ .name = "qmmf MXFP8 64-row tile, fused slices", .usage = .{ .{ .regs = 229, .static = 0, .bound = 128 }, .{ .regs = 229, .static = 0, .bound = 128 }, .{ .regs = 229, .static = 0, .bound = 128 }, .{ .regs = 158, .static = 0, .bound = 128 }, .{ .regs = 158, .static = 0, .bound = 128 } } }, - .{ .name = "qmmf FP8 fp32 out 64-row tile, fused slices", .usage = .{ .{ .regs = 179, .static = 0, .bound = 128 }, .{ .regs = 179, .static = 0, .bound = 128 }, .{ .regs = 179, .static = 0, .bound = 128 }, .{ .regs = 140, .static = 0, .bound = 128 }, .{ .regs = 140, .static = 0, .bound = 128 } } }, - .{ .name = "qmmf MXFP8 fp32 out 64-row tile, fused slices", .usage = .{ .{ .regs = 229, .static = 0, .bound = 128 }, .{ .regs = 229, .static = 0, .bound = 128 }, .{ .regs = 229, .static = 0, .bound = 128 }, .{ .regs = 158, .static = 0, .bound = 128 }, .{ .regs = 158, .static = 0, .bound = 128 } } }, - .{ .name = "qmmf FP8G fp32 out 32-row tile, cluster of 8", .usage = .{ .{ .regs = 72, .static = 0, .bound = 128 }, .{ .regs = 72, .static = 0, .bound = 128 }, .{ .regs = 72, .static = 0, .bound = 128 }, .{ .regs = 57, .static = 0, .bound = 128 }, .{ .regs = 57, .static = 0, .bound = 128 } } }, - .{ .name = "qmmf FP8G fp32 out 64-row tile, fused slices", .usage = .{ .{ .regs = 196, .static = 0, .bound = 128 }, .{ .regs = 196, .static = 0, .bound = 128 }, .{ .regs = 196, .static = 0, .bound = 128 }, .{ .regs = 155, .static = 0, .bound = 128 }, .{ .regs = 155, .static = 0, .bound = 128 } } }, - .{ .name = "qmmf BF16 fp32 out 64-row tile, fused slices", .usage = .{ .{ .regs = 180, .static = 0, .bound = 128 }, .{ .regs = 180, .static = 0, .bound = 128 }, .{ .regs = 180, .static = 0, .bound = 128 }, .{ .regs = 140, .static = 0, .bound = 128 }, .{ .regs = 140, .static = 0, .bound = 128 } } }, - .{ .name = "flashnext_gdn flashnext_gdn_chain", .usage = .{ .{ .regs = 51, .static = 2060, .bound = 1024 }, .{ .regs = 56, .static = 2060, .bound = 1024 }, .{ .regs = 56, .static = 2060, .bound = 1024 }, .{ .regs = 64, .static = 2060, .bound = 1024 }, .{ .regs = 64, .static = 2060, .bound = 1024 } } }, - .{ .name = "flashnext_attn fn_attn_chunks", .usage = .{ .{ .regs = 72, .static = 640, .bound = 128 }, .{ .regs = 72, .static = 640, .bound = 128 }, .{ .regs = 72, .static = 640, .bound = 128 }, .{ .regs = 72, .static = 640, .bound = 128 }, .{ .regs = 72, .static = 640, .bound = 128 } } }, - .{ .name = "flashnext_attn fn_attn_chunks_ahead", .usage = .{ .{ .regs = 70, .static = 768, .bound = 128 }, .{ .regs = 70, .static = 768, .bound = 128 }, .{ .regs = 70, .static = 768, .bound = 128 }, .{ .regs = 72, .static = 768, .bound = 128 }, .{ .regs = 72, .static = 768, .bound = 128 } } }, - .{ .name = "flashnext_attn fn_attn_merge", .usage = .{ .{ .regs = 26, .static = 0, .bound = 256 }, .{ .regs = 28, .static = 0, .bound = 256 }, .{ .regs = 28, .static = 0, .bound = 256 }, .{ .regs = 23, .static = 0, .bound = 256 }, .{ .regs = 23, .static = 0, .bound = 256 } } }, - .{ .name = "flashnext_batch fn_gdn_front", .usage = .{ .{ .regs = 26, .static = 1024, .bound = 256 }, .{ .regs = 26, .static = 1024, .bound = 256 }, .{ .regs = 26, .static = 1024, .bound = 256 }, .{ .regs = 30, .static = 1024, .bound = 256 }, .{ .regs = 30, .static = 1024, .bound = 256 } } }, - .{ .name = "flashnext_hc fn_hc_down", .usage = .{ .{ .regs = 56, .static = 64, .bound = 128 }, .{ .regs = 54, .static = 64, .bound = 128 }, .{ .regs = 54, .static = 64, .bound = 128 }, .{ .regs = 64, .static = 64, .bound = 128 }, .{ .regs = 64, .static = 64, .bound = 128 } } }, - .{ .name = "flashnext_hc fn_hc_normalize", .usage = .{ .{ .regs = 32, .static = 16, .bound = 0 }, .{ .regs = 40, .static = 16, .bound = 0 }, .{ .regs = 40, .static = 16, .bound = 0 }, .{ .regs = 40, .static = 16, .bound = 0 }, .{ .regs = 40, .static = 16, .bound = 0 } } }, - .{ .name = "flashnext_hc fn_hc_reduce_act", .usage = .{ .{ .regs = 32, .static = 4096, .bound = 1024 }, .{ .regs = 63, .static = 4096, .bound = 1024 }, .{ .regs = 63, .static = 4096, .bound = 1024 }, .{ .regs = 60, .static = 4096, .bound = 1024 }, .{ .regs = 60, .static = 4096, .bound = 1024 } } }, - .{ .name = "flashnext_hc fn_hc_upmix", .usage = .{ .{ .regs = 69, .static = 2048, .bound = 256 }, .{ .regs = 64, .static = 2048, .bound = 256 }, .{ .regs = 64, .static = 2048, .bound = 256 }, .{ .regs = 62, .static = 2048, .bound = 256 }, .{ .regs = 62, .static = 2048, .bound = 256 } } }, - .{ .name = "flashnext_hc fn_hc_writeback0", .usage = .{ .{ .regs = 30, .static = 256, .bound = 256 }, .{ .regs = 30, .static = 256, .bound = 256 }, .{ .regs = 30, .static = 256, .bound = 256 }, .{ .regs = 37, .static = 256, .bound = 256 }, .{ .regs = 37, .static = 256, .bound = 256 } } }, - .{ .name = "flashnext_hc fn_hc_writeback_moe", .usage = .{ .{ .regs = 32, .static = 256, .bound = 256 }, .{ .regs = 40, .static = 256, .bound = 256 }, .{ .regs = 40, .static = 256, .bound = 256 }, .{ .regs = 47, .static = 256, .bound = 256 }, .{ .regs = 47, .static = 256, .bound = 256 } } }, - .{ .name = "flashnext_hc fn_ple_conv", .usage = .{ .{ .regs = 23, .static = 0, .bound = 512 }, .{ .regs = 35, .static = 0, .bound = 512 }, .{ .regs = 35, .static = 0, .bound = 512 }, .{ .regs = 36, .static = 0, .bound = 512 }, .{ .regs = 36, .static = 0, .bound = 512 } } }, - .{ .name = "flashnext_hc fn_ple_gate", .usage = .{ .{ .regs = 32, .static = 128, .bound = 512 }, .{ .regs = 34, .static = 128, .bound = 512 }, .{ .regs = 34, .static = 128, .bound = 512 }, .{ .regs = 33, .static = 128, .bound = 512 }, .{ .regs = 33, .static = 128, .bound = 512 } } }, - .{ .name = "flashnext_attn fn_qsa_pool", .usage = .{ .{ .regs = 32, .static = 1152, .bound = 128 }, .{ .regs = 40, .static = 1152, .bound = 128 }, .{ .regs = 40, .static = 1152, .bound = 128 }, .{ .regs = 39, .static = 1152, .bound = 128 }, .{ .regs = 39, .static = 1152, .bound = 128 } } }, - .{ .name = "flashnext_batch fn_qsa_select", .usage = .{ .{ .regs = 32, .static = 1168, .bound = 1024 }, .{ .regs = 50, .static = 1168, .bound = 1024 }, .{ .regs = 50, .static = 1168, .bound = 1024 }, .{ .regs = 42, .static = 1168, .bound = 1024 }, .{ .regs = 42, .static = 1168, .bound = 1024 } } }, - .{ .name = "route_rows tf_route_logits", .usage = .{ .{ .regs = 32, .static = 0, .bound = 128 }, .{ .regs = 39, .static = 0, .bound = 128 }, .{ .regs = 39, .static = 0, .bound = 128 }, .{ .regs = 35, .static = 0, .bound = 128 }, .{ .regs = 35, .static = 0, .bound = 128 } } }, - .{ .name = "route_rows tf_route_logits_few", .usage = .{ .{ .regs = 31, .static = 0, .bound = 128 }, .{ .regs = 40, .static = 0, .bound = 128 }, .{ .regs = 40, .static = 0, .bound = 128 }, .{ .regs = 34, .static = 0, .bound = 128 }, .{ .regs = 34, .static = 0, .bound = 128 } } }, - .{ .name = "qwen_vision tf_qv_qkv_rope", .usage = .{ .{ .regs = 32, .static = 0, .bound = 128 }, .{ .regs = 37, .static = 0, .bound = 128 }, .{ .regs = 37, .static = 0, .bound = 128 }, .{ .regs = 40, .static = 0, .bound = 128 }, .{ .regs = 40, .static = 0, .bound = 128 } } }, - .{ .name = "qwen_vision tf_qv_attention64", .usage = .{ .{ .regs = 164, .static = 32768, .bound = 64 }, .{ .regs = 164, .static = 32768, .bound = 64 }, .{ .regs = 164, .static = 32768, .bound = 64 }, .{ .regs = 162, .static = 32768, .bound = 64 }, .{ .regs = 162, .static = 32768, .bound = 64 } } }, - .{ .name = "exl3_linear tf_exl3_linear_2_2_4", .usage = .{ .{ .regs = 168, .static = 16, .bound = 128 }, .{ .regs = 168, .static = 16, .bound = 128 }, .{ .regs = 168, .static = 16, .bound = 128 }, .{ .regs = 154, .static = 16, .bound = 128 }, .{ .regs = 154, .static = 16, .bound = 128 } } }, - .{ .name = "exl3_linear tf_exl3_linear_4_2_4", .usage = .{ .{ .regs = 168, .static = 16, .bound = 128 }, .{ .regs = 168, .static = 16, .bound = 128 }, .{ .regs = 168, .static = 16, .bound = 128 }, .{ .regs = 154, .static = 16, .bound = 128 }, .{ .regs = 154, .static = 16, .bound = 128 } } }, - .{ .name = "exl3_linear tf_exl3_linear_6_2_4", .usage = .{ .{ .regs = 164, .static = 16, .bound = 128 }, .{ .regs = 164, .static = 16, .bound = 128 }, .{ .regs = 164, .static = 16, .bound = 128 }, .{ .regs = 159, .static = 16, .bound = 128 }, .{ .regs = 159, .static = 16, .bound = 128 } } }, - .{ .name = "exl3_linear tf_exl3_linear_8_2_4", .usage = .{ .{ .regs = 168, .static = 16, .bound = 128 }, .{ .regs = 168, .static = 16, .bound = 128 }, .{ .regs = 168, .static = 16, .bound = 128 }, .{ .regs = 156, .static = 16, .bound = 128 }, .{ .regs = 156, .static = 16, .bound = 128 } } }, - .{ .name = "exl3_linear tf_exl3_linear_3_2_4", .usage = .{ .{ .regs = 164, .static = 16, .bound = 128 }, .{ .regs = 164, .static = 16, .bound = 128 }, .{ .regs = 164, .static = 16, .bound = 128 }, .{ .regs = 156, .static = 16, .bound = 128 }, .{ .regs = 156, .static = 16, .bound = 128 } } }, - .{ .name = "exl3_linear tf_exl3_linear_5_2_4", .usage = .{ .{ .regs = 164, .static = 16, .bound = 128 }, .{ .regs = 164, .static = 16, .bound = 128 }, .{ .regs = 164, .static = 16, .bound = 128 }, .{ .regs = 157, .static = 16, .bound = 128 }, .{ .regs = 157, .static = 16, .bound = 128 } } }, - .{ .name = "exl3_linear tf_exl3_linear_13_2_4", .usage = .{ .{ .regs = 168, .static = 16, .bound = 128 }, .{ .regs = 167, .static = 16, .bound = 128 }, .{ .regs = 167, .static = 16, .bound = 128 }, .{ .regs = 128, .static = 16, .bound = 128 }, .{ .regs = 128, .static = 16, .bound = 128 } } }, - .{ .name = "exl3_linear tf_exl3_linear_2_1_4", .usage = .{ .{ .regs = 168, .static = 16, .bound = 128 }, .{ .regs = 168, .static = 16, .bound = 128 }, .{ .regs = 168, .static = 16, .bound = 128 }, .{ .regs = 158, .static = 16, .bound = 128 }, .{ .regs = 158, .static = 16, .bound = 128 } } }, - .{ .name = "exl3_linear tf_exl3_linear_4_1_4", .usage = .{ .{ .regs = 168, .static = 16, .bound = 128 }, .{ .regs = 168, .static = 16, .bound = 128 }, .{ .regs = 168, .static = 16, .bound = 128 }, .{ .regs = 158, .static = 16, .bound = 128 }, .{ .regs = 158, .static = 16, .bound = 128 } } }, - .{ .name = "exl3_linear tf_exl3_linear_6_1_4", .usage = .{ .{ .regs = 164, .static = 16, .bound = 128 }, .{ .regs = 164, .static = 16, .bound = 128 }, .{ .regs = 164, .static = 16, .bound = 128 }, .{ .regs = 162, .static = 16, .bound = 128 }, .{ .regs = 162, .static = 16, .bound = 128 } } }, - .{ .name = "exl3_linear tf_exl3_linear_8_1_4", .usage = .{ .{ .regs = 168, .static = 16, .bound = 128 }, .{ .regs = 168, .static = 16, .bound = 128 }, .{ .regs = 168, .static = 16, .bound = 128 }, .{ .regs = 160, .static = 16, .bound = 128 }, .{ .regs = 160, .static = 16, .bound = 128 } } }, - .{ .name = "exl3_linear tf_exl3_linear_14_1_4", .usage = .{ .{ .regs = 168, .static = 16, .bound = 128 }, .{ .regs = 167, .static = 16, .bound = 128 }, .{ .regs = 167, .static = 16, .bound = 128 }, .{ .regs = 128, .static = 16, .bound = 128 }, .{ .regs = 128, .static = 16, .bound = 128 } } }, - .{ .name = "exl3_linear tf_exl3_linear_2_0_4", .usage = .{ .{ .regs = 255, .static = 16, .bound = 128 }, .{ .regs = 255, .static = 16, .bound = 128 }, .{ .regs = 255, .static = 16, .bound = 128 }, .{ .regs = 156, .static = 16, .bound = 128 }, .{ .regs = 156, .static = 16, .bound = 128 } } }, - .{ .name = "exl3_linear tf_exl3_linear_4_0_4", .usage = .{ .{ .regs = 255, .static = 16, .bound = 128 }, .{ .regs = 255, .static = 16, .bound = 128 }, .{ .regs = 255, .static = 16, .bound = 128 }, .{ .regs = 156, .static = 16, .bound = 128 }, .{ .regs = 156, .static = 16, .bound = 128 } } }, - .{ .name = "exl3_linear tf_exl3_linear_6_0_4", .usage = .{ .{ .regs = 168, .static = 16, .bound = 128 }, .{ .regs = 168, .static = 16, .bound = 128 }, .{ .regs = 168, .static = 16, .bound = 128 }, .{ .regs = 160, .static = 16, .bound = 128 }, .{ .regs = 160, .static = 16, .bound = 128 } } }, - .{ .name = "exl3_linear tf_exl3_linear_8_0_4", .usage = .{ .{ .regs = 254, .static = 16, .bound = 128 }, .{ .regs = 254, .static = 16, .bound = 128 }, .{ .regs = 254, .static = 16, .bound = 128 }, .{ .regs = 162, .static = 16, .bound = 128 }, .{ .regs = 162, .static = 16, .bound = 128 } } }, - .{ .name = "exl3_linear tf_exl3_linear_14_0_4", .usage = .{ .{ .regs = 168, .static = 16, .bound = 128 }, .{ .regs = 167, .static = 16, .bound = 128 }, .{ .regs = 167, .static = 16, .bound = 128 }, .{ .regs = 128, .static = 16, .bound = 128 }, .{ .regs = 128, .static = 16, .bound = 128 } } }, - .{ .name = "exl3_linear tf_exl3_linear_16_0_4", .usage = .{ .{ .regs = 128, .static = 16, .bound = 128 }, .{ .regs = 156, .static = 16, .bound = 128 }, .{ .regs = 156, .static = 16, .bound = 128 }, .{ .regs = 125, .static = 16, .bound = 128 }, .{ .regs = 125, .static = 16, .bound = 128 } } }, - .{ .name = "exl3_linear tf_exl3_linear_2_2_8", .usage = .{ .{ .regs = 192, .static = 16, .bound = 256 }, .{ .regs = 192, .static = 16, .bound = 256 }, .{ .regs = 192, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 } } }, - .{ .name = "exl3_linear tf_exl3_linear_4_2_8", .usage = .{ .{ .regs = 192, .static = 16, .bound = 256 }, .{ .regs = 192, .static = 16, .bound = 256 }, .{ .regs = 192, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 } } }, - .{ .name = "exl3_linear tf_exl3_linear_8_2_8", .usage = .{ .{ .regs = 199, .static = 16, .bound = 256 }, .{ .regs = 199, .static = 16, .bound = 256 }, .{ .regs = 199, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 } } }, - .{ .name = "exl3_linear tf_exl3_linear_10_2_8", .usage = .{ .{ .regs = 178, .static = 16, .bound = 256 }, .{ .regs = 178, .static = 16, .bound = 256 }, .{ .regs = 178, .static = 16, .bound = 256 }, .{ .regs = 228, .static = 16, .bound = 256 }, .{ .regs = 228, .static = 16, .bound = 256 } } }, - .{ .name = "exl3_linear tf_exl3_linear_12_2_8", .usage = .{ .{ .regs = 181, .static = 16, .bound = 256 }, .{ .regs = 181, .static = 16, .bound = 256 }, .{ .regs = 181, .static = 16, .bound = 256 }, .{ .regs = 226, .static = 16, .bound = 256 }, .{ .regs = 226, .static = 16, .bound = 256 } } }, - .{ .name = "exl3_linear tf_exl3_linear_14_2_8", .usage = .{ .{ .regs = 225, .static = 16, .bound = 256 }, .{ .regs = 225, .static = 16, .bound = 256 }, .{ .regs = 225, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 } } }, - .{ .name = "exl3_linear tf_exl3_linear_16_2_8", .usage = .{ .{ .regs = 214, .static = 16, .bound = 256 }, .{ .regs = 214, .static = 16, .bound = 256 }, .{ .regs = 214, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 } } }, - .{ .name = "exl3_linear tf_exl3_linear_7_2_8", .usage = .{ .{ .regs = 179, .static = 16, .bound = 256 }, .{ .regs = 179, .static = 16, .bound = 256 }, .{ .regs = 179, .static = 16, .bound = 256 }, .{ .regs = 236, .static = 16, .bound = 256 }, .{ .regs = 236, .static = 16, .bound = 256 } } }, - .{ .name = "exl3_linear tf_exl3_linear_9_2_8", .usage = .{ .{ .regs = 176, .static = 16, .bound = 256 }, .{ .regs = 177, .static = 16, .bound = 256 }, .{ .regs = 177, .static = 16, .bound = 256 }, .{ .regs = 224, .static = 16, .bound = 256 }, .{ .regs = 224, .static = 16, .bound = 256 } } }, - .{ .name = "exl3_linear tf_exl3_linear_11_2_8", .usage = .{ .{ .regs = 181, .static = 16, .bound = 256 }, .{ .regs = 181, .static = 16, .bound = 256 }, .{ .regs = 181, .static = 16, .bound = 256 }, .{ .regs = 226, .static = 16, .bound = 256 }, .{ .regs = 226, .static = 16, .bound = 256 } } }, - .{ .name = "exl3_linear tf_exl3_linear_13_2_8", .usage = .{ .{ .regs = 216, .static = 16, .bound = 256 }, .{ .regs = 216, .static = 16, .bound = 256 }, .{ .regs = 216, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 } } }, - .{ .name = "exl3_linear tf_exl3_linear_2_1_8", .usage = .{ .{ .regs = 231, .static = 16, .bound = 256 }, .{ .regs = 231, .static = 16, .bound = 256 }, .{ .regs = 231, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 } } }, - .{ .name = "exl3_linear tf_exl3_linear_4_1_8", .usage = .{ .{ .regs = 231, .static = 16, .bound = 256 }, .{ .regs = 231, .static = 16, .bound = 256 }, .{ .regs = 231, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 } } }, - .{ .name = "exl3_linear tf_exl3_linear_8_1_8", .usage = .{ .{ .regs = 233, .static = 16, .bound = 256 }, .{ .regs = 233, .static = 16, .bound = 256 }, .{ .regs = 233, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 } } }, - .{ .name = "exl3_linear tf_exl3_linear_10_1_8", .usage = .{ .{ .regs = 214, .static = 16, .bound = 256 }, .{ .regs = 214, .static = 16, .bound = 256 }, .{ .regs = 214, .static = 16, .bound = 256 }, .{ .regs = 241, .static = 16, .bound = 256 }, .{ .regs = 241, .static = 16, .bound = 256 } } }, - .{ .name = "exl3_linear tf_exl3_linear_12_1_8", .usage = .{ .{ .regs = 214, .static = 16, .bound = 256 }, .{ .regs = 214, .static = 16, .bound = 256 }, .{ .regs = 214, .static = 16, .bound = 256 }, .{ .regs = 240, .static = 16, .bound = 256 }, .{ .regs = 240, .static = 16, .bound = 256 } } }, - .{ .name = "exl3_linear tf_exl3_linear_16_1_8", .usage = .{ .{ .regs = 220, .static = 16, .bound = 256 }, .{ .regs = 220, .static = 16, .bound = 256 }, .{ .regs = 220, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 } } }, - .{ .name = "exl3_linear tf_exl3_linear_2_0_8", .usage = .{ .{ .regs = 254, .static = 16, .bound = 256 }, .{ .regs = 254, .static = 16, .bound = 256 }, .{ .regs = 254, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 } } }, - .{ .name = "exl3_linear tf_exl3_linear_4_0_8", .usage = .{ .{ .regs = 254, .static = 16, .bound = 256 }, .{ .regs = 254, .static = 16, .bound = 256 }, .{ .regs = 254, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 } } }, - .{ .name = "exl3_linear tf_exl3_linear_6_0_8", .usage = .{ .{ .regs = 174, .static = 16, .bound = 256 }, .{ .regs = 174, .static = 16, .bound = 256 }, .{ .regs = 174, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 } } }, - .{ .name = "exl3_linear tf_exl3_linear_8_0_8", .usage = .{ .{ .regs = 255, .static = 16, .bound = 256 }, .{ .regs = 255, .static = 16, .bound = 256 }, .{ .regs = 255, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 } } }, - .{ .name = "exl3_linear tf_exl3_linear_10_0_8", .usage = .{ .{ .regs = 254, .static = 16, .bound = 256 }, .{ .regs = 254, .static = 16, .bound = 256 }, .{ .regs = 254, .static = 16, .bound = 256 }, .{ .regs = 231, .static = 16, .bound = 256 }, .{ .regs = 231, .static = 16, .bound = 256 } } }, - .{ .name = "exl3_linear tf_exl3_linear_12_0_8", .usage = .{ .{ .regs = 254, .static = 16, .bound = 256 }, .{ .regs = 254, .static = 16, .bound = 256 }, .{ .regs = 254, .static = 16, .bound = 256 }, .{ .regs = 231, .static = 16, .bound = 256 }, .{ .regs = 231, .static = 16, .bound = 256 } } }, - .{ .name = "exl3_linear tf_exl3_linear_14_0_8", .usage = .{ .{ .regs = 231, .static = 16, .bound = 256 }, .{ .regs = 231, .static = 16, .bound = 256 }, .{ .regs = 231, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 } } }, - .{ .name = "exl3_linear tf_exl3_linear_16_0_8", .usage = .{ .{ .regs = 220, .static = 16, .bound = 256 }, .{ .regs = 222, .static = 16, .bound = 256 }, .{ .regs = 222, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 } } }, - .{ .name = "experts3 decode down", .usage = .{ .{ .regs = 198, .static = 0, .bound = 128 }, .{ .regs = 199, .static = 0, .bound = 128 }, .{ .regs = 199, .static = 0, .bound = 128 }, .{ .regs = 194, .static = 0, .bound = 128 }, .{ .regs = 194, .static = 0, .bound = 128 } } }, - .{ .name = "experts3_prefill pair", .usage = .{ .{ .regs = 179, .static = 0, .bound = 256 }, .{ .regs = 179, .static = 0, .bound = 256 }, .{ .regs = 179, .static = 0, .bound = 256 }, .{ .regs = 150, .static = 0, .bound = 256 }, .{ .regs = 150, .static = 0, .bound = 256 } } }, - .{ .name = "experts3 tf_experts3_widen", .usage = .{ .{ .regs = 32, .static = 0, .bound = 0 }, .{ .regs = 34, .static = 0, .bound = 0 }, .{ .regs = 34, .static = 0, .bound = 0 }, .{ .regs = 36, .static = 0, .bound = 0 }, .{ .regs = 36, .static = 0, .bound = 0 } } }, - .{ .name = "exl3_experts tf_exl3_down_combine", .usage = .{ .{ .regs = 32, .static = 16384, .bound = 0 }, .{ .regs = 40, .static = 16384, .bound = 0 }, .{ .regs = 40, .static = 16384, .bound = 0 }, .{ .regs = 42, .static = 16384, .bound = 0 }, .{ .regs = 42, .static = 16384, .bound = 0 } } }, - .{ .name = "exl3_experts tf_exl3_plan_rotate", .usage = .{ .{ .regs = 32, .static = 0, .bound = 0 }, .{ .regs = 33, .static = 0, .bound = 0 }, .{ .regs = 33, .static = 0, .bound = 0 }, .{ .regs = 32, .static = 0, .bound = 0 }, .{ .regs = 32, .static = 0, .bound = 0 } } }, - .{ .name = "exl3_candidate tf_exl3_tc_1", .usage = .{ .{ .regs = 128, .static = 8196, .bound = 256 }, .{ .regs = 127, .static = 8196, .bound = 256 }, .{ .regs = 127, .static = 8196, .bound = 256 }, .{ .regs = 128, .static = 8196, .bound = 256 }, .{ .regs = 128, .static = 8196, .bound = 256 } } }, - .{ .name = "exl3_candidate tf_exl3_prompt_1", .usage = .{ .{ .regs = 80, .static = 32768, .bound = 256 }, .{ .regs = 80, .static = 32768, .bound = 256 }, .{ .regs = 80, .static = 32768, .bound = 256 }, .{ .regs = 77, .static = 32768, .bound = 256 }, .{ .regs = 77, .static = 32768, .bound = 256 } } }, - .{ .name = "exl3_candidate tf_exl3_rotate_f", .usage = .{ .{ .regs = 28, .static = 0, .bound = 32 }, .{ .regs = 28, .static = 0, .bound = 32 }, .{ .regs = 28, .static = 0, .bound = 32 }, .{ .regs = 20, .static = 0, .bound = 32 }, .{ .regs = 20, .static = 0, .bound = 32 } } }, - .{ .name = "h3 h3_attention", .usage = .{ .{ .regs = 168, .static = 0, .bound = 128 }, .{ .regs = 168, .static = 0, .bound = 128 }, .{ .regs = 168, .static = 0, .bound = 128 }, .{ .regs = 208, .static = 0, .bound = 128 }, .{ .regs = 208, .static = 0, .bound = 128 } } }, - .{ .name = "h3 h3_topk", .usage = .{ .{ .regs = 32, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 38, .static = 0, .bound = 0 }, .{ .regs = 38, .static = 0, .bound = 0 } } }, - .{ .name = "drama3 d3_gemv", .usage = .{ .{ .regs = 54, .static = 0, .bound = 256 }, .{ .regs = 54, .static = 0, .bound = 256 }, .{ .regs = 54, .static = 0, .bound = 256 }, .{ .regs = 64, .static = 0, .bound = 256 }, .{ .regs = 64, .static = 0, .bound = 256 } } }, - .{ .name = "drama3 d3_conv_silu", .usage = .{ .{ .regs = 35, .static = 0, .bound = 0 }, .{ .regs = 35, .static = 0, .bound = 0 }, .{ .regs = 35, .static = 0, .bound = 0 }, .{ .regs = 38, .static = 0, .bound = 0 }, .{ .regs = 38, .static = 0, .bound = 0 } } }, - .{ .name = "drama3 d3_qk_rope", .usage = .{ .{ .regs = 28, .static = 1168, .bound = 0 }, .{ .regs = 28, .static = 1168, .bound = 0 }, .{ .regs = 28, .static = 1168, .bound = 0 }, .{ .regs = 26, .static = 1168, .bound = 0 }, .{ .regs = 26, .static = 1168, .bound = 0 } } }, - .{ .name = "drama3 d3_sample_main", .usage = .{ .{ .regs = 31, .static = 400, .bound = 1024 }, .{ .regs = 37, .static = 400, .bound = 1024 }, .{ .regs = 37, .static = 400, .bound = 1024 }, .{ .regs = 47, .static = 400, .bound = 1024 }, .{ .regs = 47, .static = 400, .bound = 1024 } } }, - .{ .name = "drama3 d3_sample_code_fast", .usage = .{ .{ .regs = 25, .static = 3616, .bound = 1024 }, .{ .regs = 25, .static = 3616, .bound = 1024 }, .{ .regs = 25, .static = 3616, .bound = 1024 }, .{ .regs = 25, .static = 3616, .bound = 1024 }, .{ .regs = 25, .static = 3616, .bound = 1024 } } }, - .{ .name = "drama3_codec c_vq_encode", .usage = .{ .{ .regs = 31, .static = 424, .bound = 0 }, .{ .regs = 39, .static = 424, .bound = 0 }, .{ .regs = 39, .static = 424, .bound = 0 }, .{ .regs = 39, .static = 424, .bound = 0 }, .{ .regs = 39, .static = 424, .bound = 0 } } }, - .{ .name = "drama3_codec c_attn", .usage = .{ .{ .regs = 32, .static = 0, .bound = 0 }, .{ .regs = 30, .static = 0, .bound = 0 }, .{ .regs = 30, .static = 0, .bound = 0 }, .{ .regs = 38, .static = 0, .bound = 0 }, .{ .regs = 38, .static = 0, .bound = 0 } } }, - .{ .name = "drama3_codec c_snake", .usage = .{ .{ .regs = 21, .static = 0, .bound = 0 }, .{ .regs = 21, .static = 0, .bound = 0 }, .{ .regs = 21, .static = 0, .bound = 0 }, .{ .regs = 26, .static = 0, .bound = 0 }, .{ .regs = 26, .static = 0, .bound = 0 } } }, - .{ .name = "drama3_fp8 decode gate-up", .usage = .{ .{ .regs = 157, .static = 0, .bound = 128 }, .{ .regs = 157, .static = 0, .bound = 128 }, .{ .regs = 157, .static = 0, .bound = 128 }, .{ .regs = 163, .static = 0, .bound = 128 }, .{ .regs = 163, .static = 0, .bound = 128 } } }, - .{ .name = "drama3_fp8 prompt gate-up", .usage = .{ .{ .regs = 199, .static = 32768, .bound = 128 }, .{ .regs = 199, .static = 32768, .bound = 128 }, .{ .regs = 199, .static = 32768, .bound = 128 }, .{ .regs = 214, .static = 32768, .bound = 128 }, .{ .regs = 214, .static = 32768, .bound = 128 } } }, - .{ .name = "latent tf_super_topk_few", .usage = .{ .{ .regs = 32, .static = 4352, .bound = 1024 }, .{ .regs = 38, .static = 4352, .bound = 1024 }, .{ .regs = 38, .static = 4352, .bound = 1024 }, .{ .regs = 32, .static = 4352, .bound = 1024 }, .{ .regs = 32, .static = 4352, .bound = 1024 } } }, - .{ .name = "ck tf_ck4_up_relu2_few", .usage = .{ .{ .regs = 19, .static = 0, .bound = 128 }, .{ .regs = 19, .static = 0, .bound = 128 }, .{ .regs = 19, .static = 0, .bound = 128 }, .{ .regs = 124, .static = 0, .bound = 128 }, .{ .regs = 124, .static = 0, .bound = 128 } } }, - .{ .name = "mamba tf_nemo_scan", .usage = .{ .{ .regs = 138, .static = 41088, .bound = 128 }, .{ .regs = 144, .static = 41088, .bound = 128 }, .{ .regs = 144, .static = 41088, .bound = 128 }, .{ .regs = 118, .static = 41088, .bound = 128 }, .{ .regs = 118, .static = 41088, .bound = 128 } } }, - } ++ joins.nvcc_132_after) }, - .{ .release = .{ .major = 13, .minor = 3 }, .usage = &([_]Override{ - .{ .name = "flashnext_batch fn_qsa_select", .usage = .{ .{ .regs = 32, .static = 1168, .bound = 1024 }, .{ .regs = 52, .static = 1168, .bound = 1024 }, .{ .regs = 52, .static = 1168, .bound = 1024 }, .{ .regs = 63, .static = 1168, .bound = 1024 }, .{ .regs = 63, .static = 1168, .bound = 1024 } } }, - } ++ joins.nvcc_133_after) }, -}; +pub const cuda_sets = @import("registry_cuda_sets.zig").cuda_sets; pub fn newer(x: limits.Nvcc, y: limits.Nvcc) bool { return x.major > y.major or (x.major == y.major and x.minor > y.minor); } diff --git a/zig/src/core/contract/registry_cuda_sets.zig b/zig/src/core/contract/registry_cuda_sets.zig new file mode 100644 index 00000000000..fcfc5d1ac1b --- /dev/null +++ b/zig/src/core/contract/registry_cuda_sets.zig @@ -0,0 +1,112 @@ +//! The later nvcc releases' usage records for the CUDA launches, by release (registry.zig's `cuda_sets`). +const registry = @import("registry.zig"); +const joins = @import("registry_joins.zig"); +const Override = registry.Override; +const CudaSet = registry.CudaSet; + +/// The later releases' sets, rising by release; a tree's images are checked against the newest at or below their own. +pub const cuda_sets = [_]CudaSet{ + .{ .release = .{ .major = 13, .minor = 2 }, .usage = &(@import("registry_shared_attention.zig").nvcc132(Override) ++ [_]Override{ + .{ .name = "window_pages tf_wrows_merge_512_pg", .usage = .{ .{ .regs = 56, .static = 128, .bound = 256 }, .{ .regs = 56, .static = 128, .bound = 256 }, .{ .regs = 56, .static = 128, .bound = 256 }, .{ .regs = 60, .static = 128, .bound = 256 }, .{ .regs = 60, .static = 128, .bound = 256 } } }, + .{ .name = "moe tf_moe_topk_sigmoid_score_warp", .usage = .{ .{ .regs = 219, .static = 0, .bound = 256 }, .{ .regs = 219, .static = 0, .bound = 256 }, .{ .regs = 219, .static = 0, .bound = 256 }, .{ .regs = 203, .static = 0, .bound = 256 }, .{ .regs = 203, .static = 0, .bound = 256 } } }, + .{ .name = "norms tf_rms_rows", .usage = .{ .{ .regs = 32, .static = 132, .bound = 1024 }, .{ .regs = 46, .static = 132, .bound = 1024 }, .{ .regs = 46, .static = 132, .bound = 1024 }, .{ .regs = 43, .static = 132, .bound = 1024 }, .{ .regs = 43, .static = 132, .bound = 1024 } } }, + .{ .name = "lane_gemv", .usage = .{ .{ .regs = 64, .static = 0, .bound = 128 }, .{ .regs = 58, .static = 0, .bound = 128 }, .{ .regs = 58, .static = 0, .bound = 128 }, .{ .regs = 66, .static = 0, .bound = 128 }, .{ .regs = 66, .static = 0, .bound = 128 } } }, + .{ .name = "lane_gemv split-K", .usage = .{ .{ .regs = 62, .static = 128, .bound = 128 }, .{ .regs = 56, .static = 128, .bound = 128 }, .{ .regs = 56, .static = 128, .bound = 128 }, .{ .regs = 72, .static = 128, .bound = 128 }, .{ .regs = 72, .static = 128, .bound = 128 } } }, + .{ .name = "prompt16 FP8", .usage = .{ .{ .regs = 243, .static = 0, .bound = 128 }, .{ .regs = 243, .static = 0, .bound = 128 }, .{ .regs = 243, .static = 0, .bound = 128 }, .{ .regs = 212, .static = 0, .bound = 128 }, .{ .regs = 212, .static = 0, .bound = 128 } } }, + .{ .name = "qmmf FP4 fp32 out 32-row tile, cluster of 8", .usage = .{ .{ .regs = 64, .static = 0, .bound = 128 }, .{ .regs = 64, .static = 0, .bound = 128 }, .{ .regs = 80, .static = 0, .bound = 128 }, .{ .regs = 61, .static = 0, .bound = 128 }, .{ .regs = 61, .static = 0, .bound = 128 } } }, + .{ .name = "qmmf MXFP8 64-row tile, fused slices", .usage = .{ .{ .regs = 229, .static = 0, .bound = 128 }, .{ .regs = 229, .static = 0, .bound = 128 }, .{ .regs = 229, .static = 0, .bound = 128 }, .{ .regs = 158, .static = 0, .bound = 128 }, .{ .regs = 158, .static = 0, .bound = 128 } } }, + .{ .name = "qmmf FP8 fp32 out 64-row tile, fused slices", .usage = .{ .{ .regs = 179, .static = 0, .bound = 128 }, .{ .regs = 179, .static = 0, .bound = 128 }, .{ .regs = 179, .static = 0, .bound = 128 }, .{ .regs = 140, .static = 0, .bound = 128 }, .{ .regs = 140, .static = 0, .bound = 128 } } }, + .{ .name = "qmmf MXFP8 fp32 out 64-row tile, fused slices", .usage = .{ .{ .regs = 229, .static = 0, .bound = 128 }, .{ .regs = 229, .static = 0, .bound = 128 }, .{ .regs = 229, .static = 0, .bound = 128 }, .{ .regs = 158, .static = 0, .bound = 128 }, .{ .regs = 158, .static = 0, .bound = 128 } } }, + .{ .name = "qmmf FP8G fp32 out 32-row tile, cluster of 8", .usage = .{ .{ .regs = 72, .static = 0, .bound = 128 }, .{ .regs = 72, .static = 0, .bound = 128 }, .{ .regs = 72, .static = 0, .bound = 128 }, .{ .regs = 57, .static = 0, .bound = 128 }, .{ .regs = 57, .static = 0, .bound = 128 } } }, + .{ .name = "qmmf FP8G fp32 out 64-row tile, fused slices", .usage = .{ .{ .regs = 196, .static = 0, .bound = 128 }, .{ .regs = 196, .static = 0, .bound = 128 }, .{ .regs = 196, .static = 0, .bound = 128 }, .{ .regs = 155, .static = 0, .bound = 128 }, .{ .regs = 155, .static = 0, .bound = 128 } } }, + .{ .name = "qmmf BF16 fp32 out 64-row tile, fused slices", .usage = .{ .{ .regs = 180, .static = 0, .bound = 128 }, .{ .regs = 180, .static = 0, .bound = 128 }, .{ .regs = 180, .static = 0, .bound = 128 }, .{ .regs = 140, .static = 0, .bound = 128 }, .{ .regs = 140, .static = 0, .bound = 128 } } }, + .{ .name = "flashnext_gdn flashnext_gdn_chain", .usage = .{ .{ .regs = 51, .static = 2060, .bound = 1024 }, .{ .regs = 56, .static = 2060, .bound = 1024 }, .{ .regs = 56, .static = 2060, .bound = 1024 }, .{ .regs = 64, .static = 2060, .bound = 1024 }, .{ .regs = 64, .static = 2060, .bound = 1024 } } }, + .{ .name = "flashnext_attn fn_attn_chunks", .usage = .{ .{ .regs = 72, .static = 640, .bound = 128 }, .{ .regs = 72, .static = 640, .bound = 128 }, .{ .regs = 72, .static = 640, .bound = 128 }, .{ .regs = 72, .static = 640, .bound = 128 }, .{ .regs = 72, .static = 640, .bound = 128 } } }, + .{ .name = "flashnext_attn fn_attn_chunks_ahead", .usage = .{ .{ .regs = 70, .static = 768, .bound = 128 }, .{ .regs = 70, .static = 768, .bound = 128 }, .{ .regs = 70, .static = 768, .bound = 128 }, .{ .regs = 72, .static = 768, .bound = 128 }, .{ .regs = 72, .static = 768, .bound = 128 } } }, + .{ .name = "flashnext_attn fn_attn_merge", .usage = .{ .{ .regs = 26, .static = 0, .bound = 256 }, .{ .regs = 28, .static = 0, .bound = 256 }, .{ .regs = 28, .static = 0, .bound = 256 }, .{ .regs = 23, .static = 0, .bound = 256 }, .{ .regs = 23, .static = 0, .bound = 256 } } }, + .{ .name = "flashnext_batch fn_gdn_front", .usage = .{ .{ .regs = 26, .static = 1024, .bound = 256 }, .{ .regs = 26, .static = 1024, .bound = 256 }, .{ .regs = 26, .static = 1024, .bound = 256 }, .{ .regs = 30, .static = 1024, .bound = 256 }, .{ .regs = 30, .static = 1024, .bound = 256 } } }, + .{ .name = "flashnext_hc fn_hc_down", .usage = .{ .{ .regs = 56, .static = 64, .bound = 128 }, .{ .regs = 54, .static = 64, .bound = 128 }, .{ .regs = 54, .static = 64, .bound = 128 }, .{ .regs = 64, .static = 64, .bound = 128 }, .{ .regs = 64, .static = 64, .bound = 128 } } }, + .{ .name = "flashnext_hc fn_hc_normalize", .usage = .{ .{ .regs = 32, .static = 16, .bound = 0 }, .{ .regs = 40, .static = 16, .bound = 0 }, .{ .regs = 40, .static = 16, .bound = 0 }, .{ .regs = 40, .static = 16, .bound = 0 }, .{ .regs = 40, .static = 16, .bound = 0 } } }, + .{ .name = "flashnext_hc fn_hc_reduce_act", .usage = .{ .{ .regs = 32, .static = 4096, .bound = 1024 }, .{ .regs = 63, .static = 4096, .bound = 1024 }, .{ .regs = 63, .static = 4096, .bound = 1024 }, .{ .regs = 60, .static = 4096, .bound = 1024 }, .{ .regs = 60, .static = 4096, .bound = 1024 } } }, + .{ .name = "flashnext_hc fn_hc_upmix", .usage = .{ .{ .regs = 69, .static = 2048, .bound = 256 }, .{ .regs = 64, .static = 2048, .bound = 256 }, .{ .regs = 64, .static = 2048, .bound = 256 }, .{ .regs = 62, .static = 2048, .bound = 256 }, .{ .regs = 62, .static = 2048, .bound = 256 } } }, + .{ .name = "flashnext_hc fn_hc_writeback0", .usage = .{ .{ .regs = 30, .static = 256, .bound = 256 }, .{ .regs = 30, .static = 256, .bound = 256 }, .{ .regs = 30, .static = 256, .bound = 256 }, .{ .regs = 37, .static = 256, .bound = 256 }, .{ .regs = 37, .static = 256, .bound = 256 } } }, + .{ .name = "flashnext_hc fn_hc_writeback_moe", .usage = .{ .{ .regs = 32, .static = 256, .bound = 256 }, .{ .regs = 40, .static = 256, .bound = 256 }, .{ .regs = 40, .static = 256, .bound = 256 }, .{ .regs = 47, .static = 256, .bound = 256 }, .{ .regs = 47, .static = 256, .bound = 256 } } }, + .{ .name = "flashnext_hc fn_ple_conv", .usage = .{ .{ .regs = 23, .static = 0, .bound = 512 }, .{ .regs = 35, .static = 0, .bound = 512 }, .{ .regs = 35, .static = 0, .bound = 512 }, .{ .regs = 36, .static = 0, .bound = 512 }, .{ .regs = 36, .static = 0, .bound = 512 } } }, + .{ .name = "flashnext_hc fn_ple_gate", .usage = .{ .{ .regs = 32, .static = 128, .bound = 512 }, .{ .regs = 34, .static = 128, .bound = 512 }, .{ .regs = 34, .static = 128, .bound = 512 }, .{ .regs = 33, .static = 128, .bound = 512 }, .{ .regs = 33, .static = 128, .bound = 512 } } }, + .{ .name = "flashnext_attn fn_qsa_pool", .usage = .{ .{ .regs = 32, .static = 1152, .bound = 128 }, .{ .regs = 40, .static = 1152, .bound = 128 }, .{ .regs = 40, .static = 1152, .bound = 128 }, .{ .regs = 39, .static = 1152, .bound = 128 }, .{ .regs = 39, .static = 1152, .bound = 128 } } }, + .{ .name = "flashnext_batch fn_qsa_select", .usage = .{ .{ .regs = 32, .static = 1168, .bound = 1024 }, .{ .regs = 50, .static = 1168, .bound = 1024 }, .{ .regs = 50, .static = 1168, .bound = 1024 }, .{ .regs = 42, .static = 1168, .bound = 1024 }, .{ .regs = 42, .static = 1168, .bound = 1024 } } }, + .{ .name = "route_rows tf_route_logits", .usage = .{ .{ .regs = 32, .static = 0, .bound = 128 }, .{ .regs = 39, .static = 0, .bound = 128 }, .{ .regs = 39, .static = 0, .bound = 128 }, .{ .regs = 35, .static = 0, .bound = 128 }, .{ .regs = 35, .static = 0, .bound = 128 } } }, + .{ .name = "route_rows tf_route_logits_few", .usage = .{ .{ .regs = 31, .static = 0, .bound = 128 }, .{ .regs = 40, .static = 0, .bound = 128 }, .{ .regs = 40, .static = 0, .bound = 128 }, .{ .regs = 34, .static = 0, .bound = 128 }, .{ .regs = 34, .static = 0, .bound = 128 } } }, + .{ .name = "qwen_vision tf_qv_qkv_rope", .usage = .{ .{ .regs = 32, .static = 0, .bound = 128 }, .{ .regs = 37, .static = 0, .bound = 128 }, .{ .regs = 37, .static = 0, .bound = 128 }, .{ .regs = 40, .static = 0, .bound = 128 }, .{ .regs = 40, .static = 0, .bound = 128 } } }, + .{ .name = "qwen_vision tf_qv_attention64", .usage = .{ .{ .regs = 164, .static = 32768, .bound = 64 }, .{ .regs = 164, .static = 32768, .bound = 64 }, .{ .regs = 164, .static = 32768, .bound = 64 }, .{ .regs = 162, .static = 32768, .bound = 64 }, .{ .regs = 162, .static = 32768, .bound = 64 } } }, + .{ .name = "exl3_linear tf_exl3_linear_2_2_4", .usage = .{ .{ .regs = 168, .static = 16, .bound = 128 }, .{ .regs = 168, .static = 16, .bound = 128 }, .{ .regs = 168, .static = 16, .bound = 128 }, .{ .regs = 154, .static = 16, .bound = 128 }, .{ .regs = 154, .static = 16, .bound = 128 } } }, + .{ .name = "exl3_linear tf_exl3_linear_4_2_4", .usage = .{ .{ .regs = 168, .static = 16, .bound = 128 }, .{ .regs = 168, .static = 16, .bound = 128 }, .{ .regs = 168, .static = 16, .bound = 128 }, .{ .regs = 154, .static = 16, .bound = 128 }, .{ .regs = 154, .static = 16, .bound = 128 } } }, + .{ .name = "exl3_linear tf_exl3_linear_6_2_4", .usage = .{ .{ .regs = 164, .static = 16, .bound = 128 }, .{ .regs = 164, .static = 16, .bound = 128 }, .{ .regs = 164, .static = 16, .bound = 128 }, .{ .regs = 159, .static = 16, .bound = 128 }, .{ .regs = 159, .static = 16, .bound = 128 } } }, + .{ .name = "exl3_linear tf_exl3_linear_8_2_4", .usage = .{ .{ .regs = 168, .static = 16, .bound = 128 }, .{ .regs = 168, .static = 16, .bound = 128 }, .{ .regs = 168, .static = 16, .bound = 128 }, .{ .regs = 156, .static = 16, .bound = 128 }, .{ .regs = 156, .static = 16, .bound = 128 } } }, + .{ .name = "exl3_linear tf_exl3_linear_3_2_4", .usage = .{ .{ .regs = 164, .static = 16, .bound = 128 }, .{ .regs = 164, .static = 16, .bound = 128 }, .{ .regs = 164, .static = 16, .bound = 128 }, .{ .regs = 156, .static = 16, .bound = 128 }, .{ .regs = 156, .static = 16, .bound = 128 } } }, + .{ .name = "exl3_linear tf_exl3_linear_5_2_4", .usage = .{ .{ .regs = 164, .static = 16, .bound = 128 }, .{ .regs = 164, .static = 16, .bound = 128 }, .{ .regs = 164, .static = 16, .bound = 128 }, .{ .regs = 157, .static = 16, .bound = 128 }, .{ .regs = 157, .static = 16, .bound = 128 } } }, + .{ .name = "exl3_linear tf_exl3_linear_13_2_4", .usage = .{ .{ .regs = 168, .static = 16, .bound = 128 }, .{ .regs = 167, .static = 16, .bound = 128 }, .{ .regs = 167, .static = 16, .bound = 128 }, .{ .regs = 128, .static = 16, .bound = 128 }, .{ .regs = 128, .static = 16, .bound = 128 } } }, + .{ .name = "exl3_linear tf_exl3_linear_2_1_4", .usage = .{ .{ .regs = 168, .static = 16, .bound = 128 }, .{ .regs = 168, .static = 16, .bound = 128 }, .{ .regs = 168, .static = 16, .bound = 128 }, .{ .regs = 158, .static = 16, .bound = 128 }, .{ .regs = 158, .static = 16, .bound = 128 } } }, + .{ .name = "exl3_linear tf_exl3_linear_4_1_4", .usage = .{ .{ .regs = 168, .static = 16, .bound = 128 }, .{ .regs = 168, .static = 16, .bound = 128 }, .{ .regs = 168, .static = 16, .bound = 128 }, .{ .regs = 158, .static = 16, .bound = 128 }, .{ .regs = 158, .static = 16, .bound = 128 } } }, + .{ .name = "exl3_linear tf_exl3_linear_6_1_4", .usage = .{ .{ .regs = 164, .static = 16, .bound = 128 }, .{ .regs = 164, .static = 16, .bound = 128 }, .{ .regs = 164, .static = 16, .bound = 128 }, .{ .regs = 162, .static = 16, .bound = 128 }, .{ .regs = 162, .static = 16, .bound = 128 } } }, + .{ .name = "exl3_linear tf_exl3_linear_8_1_4", .usage = .{ .{ .regs = 168, .static = 16, .bound = 128 }, .{ .regs = 168, .static = 16, .bound = 128 }, .{ .regs = 168, .static = 16, .bound = 128 }, .{ .regs = 160, .static = 16, .bound = 128 }, .{ .regs = 160, .static = 16, .bound = 128 } } }, + .{ .name = "exl3_linear tf_exl3_linear_14_1_4", .usage = .{ .{ .regs = 168, .static = 16, .bound = 128 }, .{ .regs = 167, .static = 16, .bound = 128 }, .{ .regs = 167, .static = 16, .bound = 128 }, .{ .regs = 128, .static = 16, .bound = 128 }, .{ .regs = 128, .static = 16, .bound = 128 } } }, + .{ .name = "exl3_linear tf_exl3_linear_2_0_4", .usage = .{ .{ .regs = 255, .static = 16, .bound = 128 }, .{ .regs = 255, .static = 16, .bound = 128 }, .{ .regs = 255, .static = 16, .bound = 128 }, .{ .regs = 156, .static = 16, .bound = 128 }, .{ .regs = 156, .static = 16, .bound = 128 } } }, + .{ .name = "exl3_linear tf_exl3_linear_4_0_4", .usage = .{ .{ .regs = 255, .static = 16, .bound = 128 }, .{ .regs = 255, .static = 16, .bound = 128 }, .{ .regs = 255, .static = 16, .bound = 128 }, .{ .regs = 156, .static = 16, .bound = 128 }, .{ .regs = 156, .static = 16, .bound = 128 } } }, + .{ .name = "exl3_linear tf_exl3_linear_6_0_4", .usage = .{ .{ .regs = 168, .static = 16, .bound = 128 }, .{ .regs = 168, .static = 16, .bound = 128 }, .{ .regs = 168, .static = 16, .bound = 128 }, .{ .regs = 160, .static = 16, .bound = 128 }, .{ .regs = 160, .static = 16, .bound = 128 } } }, + .{ .name = "exl3_linear tf_exl3_linear_8_0_4", .usage = .{ .{ .regs = 254, .static = 16, .bound = 128 }, .{ .regs = 254, .static = 16, .bound = 128 }, .{ .regs = 254, .static = 16, .bound = 128 }, .{ .regs = 162, .static = 16, .bound = 128 }, .{ .regs = 162, .static = 16, .bound = 128 } } }, + .{ .name = "exl3_linear tf_exl3_linear_14_0_4", .usage = .{ .{ .regs = 168, .static = 16, .bound = 128 }, .{ .regs = 167, .static = 16, .bound = 128 }, .{ .regs = 167, .static = 16, .bound = 128 }, .{ .regs = 128, .static = 16, .bound = 128 }, .{ .regs = 128, .static = 16, .bound = 128 } } }, + .{ .name = "exl3_linear tf_exl3_linear_16_0_4", .usage = .{ .{ .regs = 128, .static = 16, .bound = 128 }, .{ .regs = 156, .static = 16, .bound = 128 }, .{ .regs = 156, .static = 16, .bound = 128 }, .{ .regs = 125, .static = 16, .bound = 128 }, .{ .regs = 125, .static = 16, .bound = 128 } } }, + .{ .name = "exl3_linear tf_exl3_linear_2_2_8", .usage = .{ .{ .regs = 192, .static = 16, .bound = 256 }, .{ .regs = 192, .static = 16, .bound = 256 }, .{ .regs = 192, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 } } }, + .{ .name = "exl3_linear tf_exl3_linear_4_2_8", .usage = .{ .{ .regs = 192, .static = 16, .bound = 256 }, .{ .regs = 192, .static = 16, .bound = 256 }, .{ .regs = 192, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 } } }, + .{ .name = "exl3_linear tf_exl3_linear_8_2_8", .usage = .{ .{ .regs = 199, .static = 16, .bound = 256 }, .{ .regs = 199, .static = 16, .bound = 256 }, .{ .regs = 199, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 } } }, + .{ .name = "exl3_linear tf_exl3_linear_10_2_8", .usage = .{ .{ .regs = 178, .static = 16, .bound = 256 }, .{ .regs = 178, .static = 16, .bound = 256 }, .{ .regs = 178, .static = 16, .bound = 256 }, .{ .regs = 228, .static = 16, .bound = 256 }, .{ .regs = 228, .static = 16, .bound = 256 } } }, + .{ .name = "exl3_linear tf_exl3_linear_12_2_8", .usage = .{ .{ .regs = 181, .static = 16, .bound = 256 }, .{ .regs = 181, .static = 16, .bound = 256 }, .{ .regs = 181, .static = 16, .bound = 256 }, .{ .regs = 226, .static = 16, .bound = 256 }, .{ .regs = 226, .static = 16, .bound = 256 } } }, + .{ .name = "exl3_linear tf_exl3_linear_14_2_8", .usage = .{ .{ .regs = 225, .static = 16, .bound = 256 }, .{ .regs = 225, .static = 16, .bound = 256 }, .{ .regs = 225, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 } } }, + .{ .name = "exl3_linear tf_exl3_linear_16_2_8", .usage = .{ .{ .regs = 214, .static = 16, .bound = 256 }, .{ .regs = 214, .static = 16, .bound = 256 }, .{ .regs = 214, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 } } }, + .{ .name = "exl3_linear tf_exl3_linear_7_2_8", .usage = .{ .{ .regs = 179, .static = 16, .bound = 256 }, .{ .regs = 179, .static = 16, .bound = 256 }, .{ .regs = 179, .static = 16, .bound = 256 }, .{ .regs = 236, .static = 16, .bound = 256 }, .{ .regs = 236, .static = 16, .bound = 256 } } }, + .{ .name = "exl3_linear tf_exl3_linear_9_2_8", .usage = .{ .{ .regs = 176, .static = 16, .bound = 256 }, .{ .regs = 177, .static = 16, .bound = 256 }, .{ .regs = 177, .static = 16, .bound = 256 }, .{ .regs = 224, .static = 16, .bound = 256 }, .{ .regs = 224, .static = 16, .bound = 256 } } }, + .{ .name = "exl3_linear tf_exl3_linear_11_2_8", .usage = .{ .{ .regs = 181, .static = 16, .bound = 256 }, .{ .regs = 181, .static = 16, .bound = 256 }, .{ .regs = 181, .static = 16, .bound = 256 }, .{ .regs = 226, .static = 16, .bound = 256 }, .{ .regs = 226, .static = 16, .bound = 256 } } }, + .{ .name = "exl3_linear tf_exl3_linear_13_2_8", .usage = .{ .{ .regs = 216, .static = 16, .bound = 256 }, .{ .regs = 216, .static = 16, .bound = 256 }, .{ .regs = 216, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 } } }, + .{ .name = "exl3_linear tf_exl3_linear_2_1_8", .usage = .{ .{ .regs = 231, .static = 16, .bound = 256 }, .{ .regs = 231, .static = 16, .bound = 256 }, .{ .regs = 231, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 } } }, + .{ .name = "exl3_linear tf_exl3_linear_4_1_8", .usage = .{ .{ .regs = 231, .static = 16, .bound = 256 }, .{ .regs = 231, .static = 16, .bound = 256 }, .{ .regs = 231, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 } } }, + .{ .name = "exl3_linear tf_exl3_linear_8_1_8", .usage = .{ .{ .regs = 233, .static = 16, .bound = 256 }, .{ .regs = 233, .static = 16, .bound = 256 }, .{ .regs = 233, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 } } }, + .{ .name = "exl3_linear tf_exl3_linear_10_1_8", .usage = .{ .{ .regs = 214, .static = 16, .bound = 256 }, .{ .regs = 214, .static = 16, .bound = 256 }, .{ .regs = 214, .static = 16, .bound = 256 }, .{ .regs = 241, .static = 16, .bound = 256 }, .{ .regs = 241, .static = 16, .bound = 256 } } }, + .{ .name = "exl3_linear tf_exl3_linear_12_1_8", .usage = .{ .{ .regs = 214, .static = 16, .bound = 256 }, .{ .regs = 214, .static = 16, .bound = 256 }, .{ .regs = 214, .static = 16, .bound = 256 }, .{ .regs = 240, .static = 16, .bound = 256 }, .{ .regs = 240, .static = 16, .bound = 256 } } }, + .{ .name = "exl3_linear tf_exl3_linear_16_1_8", .usage = .{ .{ .regs = 220, .static = 16, .bound = 256 }, .{ .regs = 220, .static = 16, .bound = 256 }, .{ .regs = 220, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 } } }, + .{ .name = "exl3_linear tf_exl3_linear_2_0_8", .usage = .{ .{ .regs = 254, .static = 16, .bound = 256 }, .{ .regs = 254, .static = 16, .bound = 256 }, .{ .regs = 254, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 } } }, + .{ .name = "exl3_linear tf_exl3_linear_4_0_8", .usage = .{ .{ .regs = 254, .static = 16, .bound = 256 }, .{ .regs = 254, .static = 16, .bound = 256 }, .{ .regs = 254, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 } } }, + .{ .name = "exl3_linear tf_exl3_linear_6_0_8", .usage = .{ .{ .regs = 174, .static = 16, .bound = 256 }, .{ .regs = 174, .static = 16, .bound = 256 }, .{ .regs = 174, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 } } }, + .{ .name = "exl3_linear tf_exl3_linear_8_0_8", .usage = .{ .{ .regs = 255, .static = 16, .bound = 256 }, .{ .regs = 255, .static = 16, .bound = 256 }, .{ .regs = 255, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 } } }, + .{ .name = "exl3_linear tf_exl3_linear_10_0_8", .usage = .{ .{ .regs = 254, .static = 16, .bound = 256 }, .{ .regs = 254, .static = 16, .bound = 256 }, .{ .regs = 254, .static = 16, .bound = 256 }, .{ .regs = 231, .static = 16, .bound = 256 }, .{ .regs = 231, .static = 16, .bound = 256 } } }, + .{ .name = "exl3_linear tf_exl3_linear_12_0_8", .usage = .{ .{ .regs = 254, .static = 16, .bound = 256 }, .{ .regs = 254, .static = 16, .bound = 256 }, .{ .regs = 254, .static = 16, .bound = 256 }, .{ .regs = 231, .static = 16, .bound = 256 }, .{ .regs = 231, .static = 16, .bound = 256 } } }, + .{ .name = "exl3_linear tf_exl3_linear_14_0_8", .usage = .{ .{ .regs = 231, .static = 16, .bound = 256 }, .{ .regs = 231, .static = 16, .bound = 256 }, .{ .regs = 231, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 } } }, + .{ .name = "exl3_linear tf_exl3_linear_16_0_8", .usage = .{ .{ .regs = 220, .static = 16, .bound = 256 }, .{ .regs = 222, .static = 16, .bound = 256 }, .{ .regs = 222, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 }, .{ .regs = 128, .static = 16, .bound = 256 } } }, + .{ .name = "experts3 decode down", .usage = .{ .{ .regs = 198, .static = 0, .bound = 128 }, .{ .regs = 199, .static = 0, .bound = 128 }, .{ .regs = 199, .static = 0, .bound = 128 }, .{ .regs = 194, .static = 0, .bound = 128 }, .{ .regs = 194, .static = 0, .bound = 128 } } }, + .{ .name = "experts3_prefill pair", .usage = .{ .{ .regs = 179, .static = 0, .bound = 256 }, .{ .regs = 179, .static = 0, .bound = 256 }, .{ .regs = 179, .static = 0, .bound = 256 }, .{ .regs = 150, .static = 0, .bound = 256 }, .{ .regs = 150, .static = 0, .bound = 256 } } }, + .{ .name = "experts3 tf_experts3_widen", .usage = .{ .{ .regs = 32, .static = 0, .bound = 0 }, .{ .regs = 34, .static = 0, .bound = 0 }, .{ .regs = 34, .static = 0, .bound = 0 }, .{ .regs = 36, .static = 0, .bound = 0 }, .{ .regs = 36, .static = 0, .bound = 0 } } }, + .{ .name = "exl3_experts tf_exl3_down_combine", .usage = .{ .{ .regs = 32, .static = 16384, .bound = 0 }, .{ .regs = 40, .static = 16384, .bound = 0 }, .{ .regs = 40, .static = 16384, .bound = 0 }, .{ .regs = 42, .static = 16384, .bound = 0 }, .{ .regs = 42, .static = 16384, .bound = 0 } } }, + .{ .name = "exl3_experts tf_exl3_plan_rotate", .usage = .{ .{ .regs = 32, .static = 0, .bound = 0 }, .{ .regs = 33, .static = 0, .bound = 0 }, .{ .regs = 33, .static = 0, .bound = 0 }, .{ .regs = 32, .static = 0, .bound = 0 }, .{ .regs = 32, .static = 0, .bound = 0 } } }, + .{ .name = "exl3_candidate tf_exl3_tc_1", .usage = .{ .{ .regs = 128, .static = 8196, .bound = 256 }, .{ .regs = 127, .static = 8196, .bound = 256 }, .{ .regs = 127, .static = 8196, .bound = 256 }, .{ .regs = 128, .static = 8196, .bound = 256 }, .{ .regs = 128, .static = 8196, .bound = 256 } } }, + .{ .name = "exl3_candidate tf_exl3_prompt_1", .usage = .{ .{ .regs = 80, .static = 32768, .bound = 256 }, .{ .regs = 80, .static = 32768, .bound = 256 }, .{ .regs = 80, .static = 32768, .bound = 256 }, .{ .regs = 77, .static = 32768, .bound = 256 }, .{ .regs = 77, .static = 32768, .bound = 256 } } }, + .{ .name = "exl3_candidate tf_exl3_rotate_f", .usage = .{ .{ .regs = 28, .static = 0, .bound = 32 }, .{ .regs = 28, .static = 0, .bound = 32 }, .{ .regs = 28, .static = 0, .bound = 32 }, .{ .regs = 20, .static = 0, .bound = 32 }, .{ .regs = 20, .static = 0, .bound = 32 } } }, + .{ .name = "h3 h3_attention", .usage = .{ .{ .regs = 168, .static = 0, .bound = 128 }, .{ .regs = 168, .static = 0, .bound = 128 }, .{ .regs = 168, .static = 0, .bound = 128 }, .{ .regs = 208, .static = 0, .bound = 128 }, .{ .regs = 208, .static = 0, .bound = 128 } } }, + .{ .name = "h3 h3_topk", .usage = .{ .{ .regs = 32, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 38, .static = 0, .bound = 0 }, .{ .regs = 38, .static = 0, .bound = 0 } } }, + .{ .name = "drama3 d3_gemv", .usage = .{ .{ .regs = 54, .static = 0, .bound = 256 }, .{ .regs = 54, .static = 0, .bound = 256 }, .{ .regs = 54, .static = 0, .bound = 256 }, .{ .regs = 64, .static = 0, .bound = 256 }, .{ .regs = 64, .static = 0, .bound = 256 } } }, + .{ .name = "drama3 d3_conv_silu", .usage = .{ .{ .regs = 35, .static = 0, .bound = 0 }, .{ .regs = 35, .static = 0, .bound = 0 }, .{ .regs = 35, .static = 0, .bound = 0 }, .{ .regs = 38, .static = 0, .bound = 0 }, .{ .regs = 38, .static = 0, .bound = 0 } } }, + .{ .name = "drama3 d3_qk_rope", .usage = .{ .{ .regs = 28, .static = 1168, .bound = 0 }, .{ .regs = 28, .static = 1168, .bound = 0 }, .{ .regs = 28, .static = 1168, .bound = 0 }, .{ .regs = 26, .static = 1168, .bound = 0 }, .{ .regs = 26, .static = 1168, .bound = 0 } } }, + .{ .name = "drama3 d3_sample_main", .usage = .{ .{ .regs = 31, .static = 400, .bound = 1024 }, .{ .regs = 37, .static = 400, .bound = 1024 }, .{ .regs = 37, .static = 400, .bound = 1024 }, .{ .regs = 47, .static = 400, .bound = 1024 }, .{ .regs = 47, .static = 400, .bound = 1024 } } }, + .{ .name = "drama3 d3_sample_code_fast", .usage = .{ .{ .regs = 25, .static = 3616, .bound = 1024 }, .{ .regs = 25, .static = 3616, .bound = 1024 }, .{ .regs = 25, .static = 3616, .bound = 1024 }, .{ .regs = 25, .static = 3616, .bound = 1024 }, .{ .regs = 25, .static = 3616, .bound = 1024 } } }, + .{ .name = "drama3_codec c_vq_encode", .usage = .{ .{ .regs = 31, .static = 424, .bound = 0 }, .{ .regs = 39, .static = 424, .bound = 0 }, .{ .regs = 39, .static = 424, .bound = 0 }, .{ .regs = 39, .static = 424, .bound = 0 }, .{ .regs = 39, .static = 424, .bound = 0 } } }, + .{ .name = "drama3_codec c_attn", .usage = .{ .{ .regs = 32, .static = 0, .bound = 0 }, .{ .regs = 30, .static = 0, .bound = 0 }, .{ .regs = 30, .static = 0, .bound = 0 }, .{ .regs = 38, .static = 0, .bound = 0 }, .{ .regs = 38, .static = 0, .bound = 0 } } }, + .{ .name = "drama3_codec c_snake", .usage = .{ .{ .regs = 21, .static = 0, .bound = 0 }, .{ .regs = 21, .static = 0, .bound = 0 }, .{ .regs = 21, .static = 0, .bound = 0 }, .{ .regs = 26, .static = 0, .bound = 0 }, .{ .regs = 26, .static = 0, .bound = 0 } } }, + .{ .name = "drama3_fp8 decode gate-up", .usage = .{ .{ .regs = 157, .static = 0, .bound = 128 }, .{ .regs = 157, .static = 0, .bound = 128 }, .{ .regs = 157, .static = 0, .bound = 128 }, .{ .regs = 163, .static = 0, .bound = 128 }, .{ .regs = 163, .static = 0, .bound = 128 } } }, + .{ .name = "drama3_fp8 prompt gate-up", .usage = .{ .{ .regs = 199, .static = 32768, .bound = 128 }, .{ .regs = 199, .static = 32768, .bound = 128 }, .{ .regs = 199, .static = 32768, .bound = 128 }, .{ .regs = 214, .static = 32768, .bound = 128 }, .{ .regs = 214, .static = 32768, .bound = 128 } } }, + .{ .name = "latent tf_super_topk_few", .usage = .{ .{ .regs = 32, .static = 4352, .bound = 1024 }, .{ .regs = 38, .static = 4352, .bound = 1024 }, .{ .regs = 38, .static = 4352, .bound = 1024 }, .{ .regs = 32, .static = 4352, .bound = 1024 }, .{ .regs = 32, .static = 4352, .bound = 1024 } } }, + .{ .name = "ck tf_ck4_up_relu2_few", .usage = .{ .{ .regs = 19, .static = 0, .bound = 128 }, .{ .regs = 19, .static = 0, .bound = 128 }, .{ .regs = 19, .static = 0, .bound = 128 }, .{ .regs = 124, .static = 0, .bound = 128 }, .{ .regs = 124, .static = 0, .bound = 128 } } }, + .{ .name = "mamba tf_nemo_scan", .usage = .{ .{ .regs = 138, .static = 41088, .bound = 128 }, .{ .regs = 144, .static = 41088, .bound = 128 }, .{ .regs = 144, .static = 41088, .bound = 128 }, .{ .regs = 118, .static = 41088, .bound = 128 }, .{ .regs = 118, .static = 41088, .bound = 128 } } }, + } ++ joins.nvcc_132_after) }, + .{ .release = .{ .major = 13, .minor = 3 }, .usage = &([_]Override{ + .{ .name = "flashnext_batch fn_qsa_select", .usage = .{ .{ .regs = 32, .static = 1168, .bound = 1024 }, .{ .regs = 52, .static = 1168, .bound = 1024 }, .{ .regs = 52, .static = 1168, .bound = 1024 }, .{ .regs = 63, .static = 1168, .bound = 1024 }, .{ .regs = 63, .static = 1168, .bound = 1024 } } }, + } ++ joins.nvcc_133_after) }, +}; diff --git a/zig/src/core/contract/registry_joins.zig b/zig/src/core/contract/registry_joins.zig index 89fc2034c7b..c2a88c88b53 100644 --- a/zig/src/core/contract/registry_joins.zig +++ b/zig/src/core/contract/registry_joins.zig @@ -57,6 +57,7 @@ pub const all_metal = @import("lane_q8_records.zig").records ++ @import("attention_pv_records.zig").records ++ registry.metal ++ @import("delta_slots_records.zig").records ++ + @import("delta_slots_records.zig").columns ++ @import("flashnext_pending.zig").records ++ @import("simd_pairs_records.zig").records ++ @import("simd_half_records.zig").records ++ @@ -68,6 +69,8 @@ pub const all_metal = @import("lane_q8_records.zig").records ++ @import("prompt_index_records.zig").metal ++ @import("hc_activation_records.zig").metal ++ @import("qwen4_records.zig").metal ++ + @import("tree_round_metal_records.zig").records ++ + @import("q27_stack_records.zig").records ++ @import("lfm2_records.zig").records ++ @import("nemotron_experts_records.zig").records ++ @import("nemotron_pages_records.zig").records ++ @@ -78,9 +81,11 @@ pub const all_metal = @import("lane_q8_records.zig").records ++ @import("spark25_records.zig").records ++ @import("gemma_attention_records.zig").records ++ @import("moss_image_records.zig").records ++ + @import("idol_records.zig").records ++ @import("dsv41_metal_records.zig").records ++ @import("minimax_records.zig").records ++ @import("ling_route_records.zig").records ++ + @import("ling_mla_records.zig").records ++ @import("qwen27_moe_records.zig").records ++ @import("affine_gather_records.zig").records ++ @import("flint_records.zig").records ++ diff --git a/zig/src/core/contract/tree_round_metal_records.zig b/zig/src/core/contract/tree_round_metal_records.zig new file mode 100644 index 00000000000..2f846a93907 --- /dev/null +++ b/zig/src/core/contract/tree_round_metal_records.zig @@ -0,0 +1,6 @@ +//! Shared tree picks: exactly the two 32-thread, zero-threadgroup-memory launches in argmaxChunks. +const M = @import("limits.zig").MetalLaunch; +pub const records = [_]M{ + .{ .name = "tree round picks tf_round_pick_chunks", .threads = 32, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "tree round picks tf_round_pick_rows", .threads = 32, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, +}; diff --git a/zig/src/core/contract/xpu_records.zig b/zig/src/core/contract/xpu_records.zig index 50e8107ee3e..086d6536222 100644 --- a/zig/src/core/contract/xpu_records.zig +++ b/zig/src/core/contract/xpu_records.zig @@ -36,6 +36,42 @@ pub const records = [_]Record{ .launch = .{ .name = "embed", .symbol = "embed", .image = "glue", .format = glue, .threads = .{ 256, 1, 1 }, .sub_group = 16, .grf = 256 }, .usage = .{.{ .threads = .{ 256, 1, 1 }, .sub_group = 16, .grf = 256 }}, }, + .{ + .launch = .{ .name = "tp2_allreduce_f16", .symbol = "tp2_allreduce_f16", .image = "tp", .format = glue, .threads = .{ 256, 1, 1 }, .sub_group = 16, .grf = 256 }, + .usage = .{.{ .threads = .{ 256, 1, 1 }, .sub_group = 16, .grf = 256 }}, + }, + .{ + .launch = .{ .name = "tp4_allreduce_f16", .symbol = "tp4_allreduce_f16", .image = "tp", .format = glue, .threads = .{ 256, 1, 1 }, .sub_group = 16, .grf = 256 }, + .usage = .{.{ .threads = .{ 256, 1, 1 }, .sub_group = 16, .grf = 256 }}, + }, + .{ + .launch = .{ .name = "tp2_rs_f16", .symbol = "tp2_rs_f16", .image = "tp", .format = glue, .threads = .{ 256, 1, 1 }, .sub_group = 16, .grf = 256 }, + .usage = .{.{ .threads = .{ 256, 1, 1 }, .sub_group = 16, .grf = 256 }}, + }, + .{ + .launch = .{ .name = "tp4_rs_f16", .symbol = "tp4_rs_f16", .image = "tp", .format = glue, .threads = .{ 256, 1, 1 }, .sub_group = 16, .grf = 256 }, + .usage = .{.{ .threads = .{ 256, 1, 1 }, .sub_group = 16, .grf = 256 }}, + }, + .{ + .launch = .{ .name = "tp2_allreduce_bf16", .symbol = "tp2_allreduce_bf16", .image = "tp", .format = glue, .threads = .{ 256, 1, 1 }, .sub_group = 16, .grf = 256 }, + .usage = .{.{ .threads = .{ 256, 1, 1 }, .sub_group = 16, .grf = 256 }}, + }, + .{ + .launch = .{ .name = "tp4_allreduce_bf16", .symbol = "tp4_allreduce_bf16", .image = "tp", .format = glue, .threads = .{ 256, 1, 1 }, .sub_group = 16, .grf = 256 }, + .usage = .{.{ .threads = .{ 256, 1, 1 }, .sub_group = 16, .grf = 256 }}, + }, + .{ + .launch = .{ .name = "tp2_allreduce_f32", .symbol = "tp2_allreduce_f32", .image = "tp", .format = glue, .threads = .{ 256, 1, 1 }, .sub_group = 16, .grf = 256 }, + .usage = .{.{ .threads = .{ 256, 1, 1 }, .sub_group = 16, .grf = 256 }}, + }, + .{ + .launch = .{ .name = "tp4_allreduce_f32", .symbol = "tp4_allreduce_f32", .image = "tp", .format = glue, .threads = .{ 256, 1, 1 }, .sub_group = 16, .grf = 256 }, + .usage = .{.{ .threads = .{ 256, 1, 1 }, .sub_group = 16, .grf = 256 }}, + }, + .{ + .launch = .{ .name = "tp4_rs_f32", .symbol = "tp4_rs_f32", .image = "tp", .format = glue, .threads = .{ 256, 1, 1 }, .sub_group = 16, .grf = 256 }, + .usage = .{.{ .threads = .{ 256, 1, 1 }, .sub_group = 16, .grf = 256 }}, + }, }; /// Gate 5's planted XPU controls: one for each fit rule the audit must fire. diff --git a/zig/src/core/deltanet_kernels.zig b/zig/src/core/deltanet_kernels.zig index 9ecd5890d2c..a4abc6e4cd6 100644 --- a/zig/src/core/deltanet_kernels.zig +++ b/zig/src/core/deltanet_kernels.zig @@ -16,7 +16,18 @@ pub fn markList(rows: u32, marks: []const u32) ![MARKS]u32 { return list; } -pub const Pipelines = struct { pre: metal.Pipeline, tree: metal.Pipeline, tree_slots: [slot_kernels.len]metal.Pipeline, replay: metal.Pipeline, post: metal.Pipeline, conv_commit: metal.Pipeline }; +pub const Pipelines = struct { pre: metal.Pipeline, tree: metal.Pipeline, tree_slots: [slot_kernels.len]metal.Pipeline, replay: metal.Pipeline, post: metal.Pipeline, conv_commit: metal.Pipeline, columns: ?[column_kernels.len]metal.Pipeline = null, pre_vectors: ?metal.Pipeline = null }; + +/// Fitting rounds take the column scan, vector conv and row-side activation; off, the general kernels (checks). +pub var flat_glue = true; + +/// Slots of each column scan; a tree past the last takes `tree_slots`. +pub const column_kernels = [_]usize{ 1, 2, 4 }; + +pub fn columnKernel(peak: usize) ?usize { + for (column_kernels, 0..) |slots, index| if (peak <= slots) return index; + return null; +} /// Register slots of each tree_slots kernel; a tree takes the first that holds its peak of live states. pub const slot_kernels = [_]usize{ 1, 2, 4, 8, 16 }; @@ -70,6 +81,17 @@ pub const Kernels = struct { done += 1; } if (pipelines[7].simdWidth() != 32 or pipelines[7].maxThreads() < 128) return error.UnsupportedGdnPipeline; + var columns: [column_kernels.len]metal.Pipeline = undefined; + var columns_done: usize = 0; + errdefer for (columns[0..columns_done]) |p| p.deinit(); + inline for ([_][]const u8{ "columns_1", "columns_2", "columns_4" }, 0..) |name, index| { + columns[index] = try metal.Pipeline.init(device, library, "tf_delta_gdn_" ++ name, false); + columns_done += 1; + } + const pre_vectors = try metal.Pipeline.init(device, library, "tf_delta_gdn_pre_vectors", false); + errdefer pre_vectors.deinit(); + for (columns) |p| if (p.simdWidth() != 32 or p.maxThreads() < 32) return error.UnsupportedGdnPipeline; + if (pre_vectors.simdWidth() != 32 or pre_vectors.maxThreads() < 32) return error.UnsupportedGdnPipeline; return .{ .library = library, .pipelines = .{ @@ -79,6 +101,8 @@ pub const Kernels = struct { .replay = pipelines[2], .post = pipelines[3], .conv_commit = pipelines[4], + .columns = columns, + .pre_vectors = pre_vectors, }, .publish = pipelines[5], .clear = pipelines[6], @@ -108,6 +132,8 @@ pub const Kernels = struct { k.pre_step, }) |p| p.deinit(); for (k.pipelines.tree_slots) |p| p.deinit(); + if (k.pipelines.columns) |columns| for (columns) |p| p.deinit(); + if (k.pipelines.pre_vectors) |p| p.deinit(); k.library.deinit(); } }; diff --git a/zig/src/core/engine_api.zig b/zig/src/core/engine_api.zig index 1b358d4e303..1d0bd4c8919 100644 --- a/zig/src/core/engine_api.zig +++ b/zig/src/core/engine_api.zig @@ -125,6 +125,7 @@ pub const SpeechRequest = @import("speech_api.zig").SpeechRequest; pub const SpeechResult = @import("speech_api.zig").SpeechResult; pub const SpeechInfo = @import("speech_api.zig").SpeechInfo; pub const SpeechSubmitError = error{ Closed, Busy, InvalidRequest, Unsupported }; +pub const EncodeVoiceError = error{ BadWav, Closed, Failed, OutOfMemory }; pub const ImageRequest = @import("image_api.zig").ImageRequest; pub const ImageResult = @import("image_api.zig").ImageResult; pub const ImageInfo = @import("image_api.zig").ImageInfo; @@ -444,6 +445,8 @@ pub const Engine = struct { load: ?*const fn (ctx: *anyopaque, producer: ?load_ledger.Producer) void = null, /// Asked once per whole request: the returned message is the refusal, up to `refusal_bytes`; null: accepted. refusal: ?*const fn (ctx: *anyopaque, request: *const Request, out: []u8) ?[]const u8 = null, + /// A reference WAV file's codec rows in `gpa`, on the speech engine's own thread; null: it encodes no voices. + encode_voice: ?*const fn (ctx: *anyopaque, gpa: Allocator, wav: []const u8) EncodeVoiceError![][10]i32 = null, }; pub fn info(e: Engine) Info { @@ -561,7 +564,6 @@ pub const LaneHost = @import("lane_host.zig").LaneHost; pub const prefill_env = @import("lane_host_env.zig"); /// An opt-in family round planner for the lane host, in place of its `prefill_step` chunks (lane_rounds.zig). pub const Rounds = @import("lane_host.zig").Rounds; - /// Exact prompt reuse between requests, for any family (prompt_cache.zig). pub const prompt_cache = @import("prompt_cache.zig"); /// The same for a paged cache over the backend's own KV pages (prompt_radix.zig). @@ -572,7 +574,6 @@ pub const cache_modes = @import("cache_modes.zig"); /// Learned prompt-cache states on disk (prompt_imprint.zig), and when a shared cut goes there (prompt_learn.zig). pub const prompt_imprint = @import("prompt_imprint.zig"); pub const prompt_learn = @import("prompt_learn.zig"); - /// A question about a conversation's kept states, in RAM and on disk (rows_ask.zig). pub const ImprintAsk = @import("rows_ask.zig").Ask; pub const ImprintOp = @import("rows_ask.zig").Op; @@ -580,7 +581,6 @@ pub const ImprintDisk = @import("rows_ask.zig").Disk; /// Recall's record of the ids earlier requests read and wrote, for drafts (not the prompt cache's learned states). pub const recall_store = lanes.recall_store; - /// The idle keepalive's ticker and target contract. pub const keepalive = @import("keepalive.zig"); diff --git a/zig/src/core/fence.zig b/zig/src/core/fence.zig index 4fe59d82680..da86e057c95 100644 --- a/zig/src/core/fence.zig +++ b/zig/src/core/fence.zig @@ -1,5 +1,7 @@ //! MTLFence: orders untracked work across encoders and command buffers of one queue (each waits on the last update). const mtl = @import("metal"); +/// The real runtime's encoders may be Metal 4's; recording fakes in tests have no such field. +const metal4 = @hasField(mtl.ComputeEncoder, "m4"); pub const Fence = struct { id: mtl.objc.Id, @@ -10,11 +12,13 @@ pub const Fence = struct { /// The encoder's dispatches start after the work that last updated the fence. pub fn wait(self: Fence, enc: mtl.ComputeEncoder) void { + if (comptime metal4) if (enc.m4 != null) return mtl.metal4.waitForFence(enc.id, self.id); mtl.objc.msg(void, enc.id, "waitForFence:", .{self.id}); } /// Later waits see this encoder's work complete. pub fn update(self: Fence, enc: mtl.ComputeEncoder) void { + if (comptime metal4) if (enc.m4 != null) return mtl.metal4.updateFence(enc.id, self.id); mtl.objc.msg(void, enc.id, "updateFence:", .{self.id}); } diff --git a/zig/src/core/fixtures/gptq_synth/config.json b/zig/src/core/fixtures/gptq_synth/config.json new file mode 100644 index 00000000000..d5d067ace73 --- /dev/null +++ b/zig/src/core/fixtures/gptq_synth/config.json @@ -0,0 +1,28 @@ +{ + "architectures": ["Qwen3_5ForConditionalGeneration"], + "model_type": "qwen3_5", + "num_experts": 512, + "num_experts_per_tok": 5, + "shared_expert_intermediate_size": 1280, + "quantization_config": { + "quant_method": "gptq", + "bits": 4, + "group_size": 128, + "sym": true, + "desc_act": false, + "lm_head": true, + "dynamic": { + "+:.*lm_head$": {"bits": 4}, + "-:.*linear_attn.*": {"bits": 4}, + "-:.*self_attn.*": {"bits": 4}, + "-:.*hyper_connection.*": {"bits": 4}, + "-:.*visual.*": {"bits": 4}, + "-:.*shared_expert.*": {"bits": 4}, + "-:.*\\.ple\\..*": {"bits": 4}, + "-:.*embed.*": {"bits": 4}, + "-:.*fc_hidden.*": {"bits": 4}, + "-:.*layers\\.48\\..*": {"bits": 4}, + "-:.*\\.gate$": {"bits": 4} + } + } +} diff --git a/zig/src/core/kv_pool.zig b/zig/src/core/kv_pool.zig index 0179b930ff2..22b6ca6fca3 100644 --- a/zig/src/core/kv_pool.zig +++ b/zig/src/core/kv_pool.zig @@ -216,6 +216,12 @@ pub const Notify = struct { /// A family's pool as the load ledger reads it: tokens a page, and the contiguous run it needs (0: none). pub const Source = struct { pool: *Pool, page_tokens: u32, run_pages: u32 = 0 }; +/// A tier's notice that a page has no holders or readers and its frame, if any, is free again. +pub const Freed = struct { + ctx: *anyopaque, + call: *const fn (ctx: *anyopaque, id: u32) void, +}; + /// What an idle pool must show: nothing promised, every page free or the store's alone, none waiting on readers. pub const Census = struct { total: usize, free: usize, promised: usize, kept: usize, leased: usize, pending: usize = 0 }; @@ -237,6 +243,7 @@ pub const Pool = struct { ledger: ?Gate = null, // the lane host's ledger, the only test a promise passes; null: the pool's own pages depth: u8 = 0, // public changes in progress: the outermost one notifies, after nested calls and rollbacks retired: retirement.Retired = .{}, // pages a lease gave back mid-stream, until their readers are done + freed: ?Freed = null, pub fn init(gpa: Allocator, count: usize, page_bytes: u64) !Pool { const refs = try gpa.alloc(u32, count); @@ -557,8 +564,14 @@ pub const Pool = struct { } }; +/// The host tier: logical pages in host RAM and device frames that cache them (kv_tier.zig). +pub const tier = @import("kv_tier.zig"); +pub const Tier = tier.Tier; + test { _ = @import("kv_pool_test.zig"); + _ = @import("kv_tier.zig"); + _ = @import("kv_pool_freed_test.zig"); _ = @import("kv_pool_counts_test.zig"); _ = @import("kv_pool_walk_test.zig"); _ = @import("kv_pool_notify_test.zig"); diff --git a/zig/src/core/kv_pool_freed_test.zig b/zig/src/core/kv_pool_freed_test.zig new file mode 100644 index 00000000000..80ba1438a2d --- /dev/null +++ b/zig/src/core/kv_pool_freed_test.zig @@ -0,0 +1,64 @@ +//! A tier frees frames only when the pool makes their pages reusable, including after delayed readers finish. +const std = @import("std"); +const kv = @import("kv_pool.zig"); +const t = std.testing; + +const Seen = struct { + calls: usize = 0, + fn call(ctx: *anyopaque, id: u32) void { + const s: *Seen = @ptrCast(@alignCast(ctx)); + std.debug.assert(id == 0); + s.calls += 1; + } +}; + +test "pool freed hook: lease, store and run release notify once after the last holder" { + for (0..3) |mode| { + var p = try kv.Pool.init(t.allocator, 1, 64); + defer p.deinit(); + var seen: Seen = .{}; + p.freed = .{ .ctx = &seen, .call = Seen.call }; + var l: kv.Lease = .{}; + try p.promise(&l, 1); + if (mode == 2) { + const id = p.claimRun(&l, 1).?; + p.releaseRun(id, 1); + p.finish(&l); + } else { + const id = try p.take(&l); + if (mode == 1) p.retain(id); + p.finish(&l); + if (mode == 1) { + try t.expectEqual(@as(usize, 0), seen.calls); + p.release(id); + } + } + try t.expectEqual(@as(usize, 1), seen.calls); + try t.expect(p.idle()); + } +} + +test "pool freed hook: a retired pinned frame survives until its reader settles" { + var host: [64]u8 = @splat(0); + var tier: kv.Tier = undefined; + try tier.init(t.allocator, &host, 1, 64); + defer tier.deinit(); + var l: kv.tier.Lease = .{}; + defer tier.finish(&l); + try tier.reserve(&l, 1, 1); + try tier.cover(&l, 1, null); + const id = l.pages.ids.items[0]; + const fill = try tier.pin(&l, id); + const ticket: kv.tier.Ticket = .{ .frame = fill.frame, .gen = fill.gen }; + try kv.retirement.retire(&tier.pool, &l.pages, 0, 7); + try t.expect(tier.valid(id, ticket)); + try t.expectEqual(@as(usize, 0), tier.nfree); + try kv.retirement.settle(&tier.pool, 6); + try t.expect(tier.valid(id, ticket)); + try tier.unpin(&l, id); + try kv.retirement.settle(&tier.pool, 7); + try t.expect(!tier.valid(id, ticket)); + try t.expectEqual(@as(usize, 1), tier.nfree); + try kv.retirement.settle(&tier.pool, 7); + try t.expectEqual(@as(usize, 1), tier.nfree); +} diff --git a/zig/src/core/kv_pool_retire.zig b/zig/src/core/kv_pool_retire.zig index d66b1c89c66..8d9a7664fcd 100644 --- a/zig/src/core/kv_pool_retire.zig +++ b/zig/src/core/kv_pool_retire.zig @@ -81,6 +81,7 @@ pub fn freeOrPend(p: *Pool, id: u32) void { const r = &p.retired; if (r.marked.items.len > 0 and r.tokens[id] > r.settled) return r.pending.appendAssumeCapacity(id); // room: one a page clear(p, id); + if (p.freed) |f| f.call(f.ctx, id); p.free[p.nfree] = id; p.nfree += 1; } @@ -98,6 +99,7 @@ pub fn settle(p: *Pool, token: u64) error{LaneMemory}!void { keep += 1; } else { clear(p, id); + if (p.freed) |f| f.call(f.ctx, id); p.free[p.nfree] = id; p.nfree += 1; } diff --git a/zig/src/core/kv_tier.zig b/zig/src/core/kv_tier.zig new file mode 100644 index 00000000000..fbd0ce23e33 --- /dev/null +++ b/zig/src/core/kv_tier.zig @@ -0,0 +1,434 @@ +//! A host tier for the page pool: logical pages whose canonical rows live in host RAM, cached by device frames. +const std = @import("std"); +const kv = @import("kv_pool.zig"); +const Allocator = std.mem.Allocator; + +/// No frame (for a page) or no page (for a frame). +pub const none: u32 = std.math.maxInt(u32); + +/// What the ranks of one model agree on before they open a tier: the smallest of each. +pub const Shape = struct { + host_pages: usize, + frames: usize, + + pub fn agree(a: Shape, b: Shape) Shape { + return .{ .host_pages = @min(a.host_pages, b.host_pages), .frames = @min(a.frames, b.frames) }; + } +}; + +/// A deliberate bug a test turns on to show that the check beside it fails without the rule: never set outside tests. +pub const Fault = enum { none, keep_generation, ignore_pins, ignore_dirty, unpinned_dirty, keep_failed_miss }; + +/// A page a call pinned: its frame, the frame's generation, and whether the family must copy the page in. +pub const Fill = struct { page: u32, frame: u32, gen: u32, miss: bool }; + +/// A page's frame as a device table saw it: current while the frame's generation is the same. +pub const Ticket = struct { frame: u32, gen: u32 }; + +/// A stream's reservation in both currencies: pages (the pool's lease) and the frames it may pin at once. +pub const Lease = struct { + pages: kv.Lease = .{}, + frames: usize = 0, + pins: std.ArrayList(u32) = .empty, // one entry per pin, a page id + lent: std.ArrayList(u32) = .empty, // frames lent to the stream: mapped to no page, the family's to manage +}; + +pub const Census = struct { frames: usize, free: usize, resident: usize, pinned: usize, dirty: usize, promised: usize, lent: usize }; + +pub const Tier = struct { + gpa: Allocator, + pool: kv.Pool, // logical pages; the host store holds `pool.total()` of them + host: []u8, // canonical rows, `pool.total() * page_bytes`, borrowed (pinned host memory in a server) + frame_of: []u32, // per page: its frame or `none` + dirty: []bool, // per page: the frame holds rows the host store lacks + page_of: []u32, // per frame: its page or `none` + gen: []u32, // per frame: changes whenever the frame stops holding the page it held + stamp: []u64, // per frame: the LRU clock at its last use + pinned: []u32, // per frame: calls reading it + free_frames: []u32, + lent_mark: []bool, // per frame: lent to a lease + nfree: usize, + promised: usize = 0, // frames promised, summed over leases + nlent: usize = 0, // frames lent, summed over leases + clock: u64 = 0, + fault: Fault = .none, + + /// In place (the pool's release hook points here): `host.len / page_bytes` logical pages, `frames` frames. + pub fn init(t: *Tier, gpa: Allocator, host: []u8, frames: usize, page_bytes: u64) !void { + if (page_bytes == 0 or host.len % page_bytes != 0 or frames == 0 or host.len == 0) + return error.BadTierGeometry; + const npages: usize = @intCast(host.len / page_bytes); + var pool = try kv.Pool.init(gpa, npages, page_bytes); + errdefer pool.deinit(); + const frame_of = try gpa.alloc(u32, npages); + errdefer gpa.free(frame_of); + const dirty = try gpa.alloc(bool, npages); + errdefer gpa.free(dirty); + const page_of = try gpa.alloc(u32, frames); + errdefer gpa.free(page_of); + const gen = try gpa.alloc(u32, frames); + errdefer gpa.free(gen); + const stamp = try gpa.alloc(u64, frames); + errdefer gpa.free(stamp); + const pinned = try gpa.alloc(u32, frames); + errdefer gpa.free(pinned); + const free_frames = try gpa.alloc(u32, frames); + errdefer gpa.free(free_frames); + const lent_mark = try gpa.alloc(bool, frames); + @memset(frame_of, none); + @memset(dirty, false); + @memset(page_of, none); + @memset(gen, 0); + @memset(stamp, 0); + @memset(pinned, 0); + @memset(lent_mark, false); + for (free_frames, 0..) |*f, i| f.* = @intCast(frames - 1 - i); // frame 0 first + t.* = .{ .gpa = gpa, .pool = pool, .host = host, .frame_of = frame_of, .dirty = dirty, .page_of = page_of, .gen = gen, .stamp = stamp, .pinned = pinned, .free_frames = free_frames, .lent_mark = lent_mark, .nfree = frames }; + t.pool.freed = .{ .ctx = t, .call = freed }; + } + + pub fn deinit(t: *Tier) void { + t.pool.deinit(); + t.gpa.free(t.frame_of); + t.gpa.free(t.dirty); + t.gpa.free(t.page_of); + t.gpa.free(t.gen); + t.gpa.free(t.stamp); + t.gpa.free(t.pinned); + t.gpa.free(t.free_frames); + t.gpa.free(t.lent_mark); + t.* = undefined; + } + + pub fn count(t: *const Tier) usize { + return t.page_of.len; + } + + pub fn shape(t: *const Tier) Shape { + return .{ .host_pages = t.pool.total(), .frames = t.count() }; + } + + /// Promise `pages` pages and `n` frames to `l`, or neither: LaneMemory or FrameMemory, whichever does not fit. + pub fn reserve(t: *Tier, l: *Lease, pages: usize, n: usize) error{ LaneMemory, FrameMemory }!void { + if (t.promised + n > t.count()) return error.FrameMemory; + try t.pool.promise(&l.pages, pages); + t.promised += n; + l.frames += n; + } + + /// Whether `pages` and `n` frames could be promised now (the store's idle pages counted). + pub fn fits(t: *const Tier, pages: usize, n: usize) bool { + return t.promised + n <= t.count() and t.pool.fits(pages); + } + + /// `l` covers `n` pages, as `Pool.cover`. + pub fn cover(t: *Tier, l: *Lease, n: usize, table: ?kv.Table) !void { + return t.pool.cover(&l.pages, n, table); + } + + /// The frame of `id`, if it has one. + pub fn resident(t: *const Tier, id: u32) ?Ticket { + const f = t.frame_of[id]; + return if (f == none) null else .{ .frame = f, .gen = t.gen[f] }; + } + + /// Whether a table entry written from `tk` still names `id`'s rows. + pub fn valid(t: *const Tier, id: u32, tk: Ticket) bool { + return t.page_of[tk.frame] == id and t.gen[tk.frame] == tk.gen; + } + + /// Pin `id` for a call: a frame if it has none (a miss: copy `host_page(id)` in); FrameMemory past the promise. + pub fn pin(t: *Tier, l: *Lease, id: u32) error{ FrameMemory, OutOfMemory }!Fill { + if (t.pool.refs[id] == 0) std.debug.panic("kv tier: page {d} pinned while free", .{id}); + if (l.pins.items.len + l.lent.items.len >= l.frames) return error.FrameMemory; + try l.pins.ensureUnusedCapacity(t.gpa, 1); + var miss = false; + if (t.frame_of[id] == none) { + const f = t.takeFrame() orelse return error.FrameMemory; + t.page_of[f] = id; + t.frame_of[id] = f; + miss = true; + } + const f = t.frame_of[id]; + t.pinned[f] += 1; + t.touch(id); + l.pins.appendAssumeCapacity(id); + return .{ .page = id, .frame = f, .gen = t.gen[f], .miss = miss }; + } + + /// Pin every page of `ids` into `out`, or none of them. + pub fn fill(t: *Tier, l: *Lease, ids: []const u32, out: []Fill) !void { + std.debug.assert(out.len >= ids.len); + var done: usize = 0; + errdefer { + for (ids[0..done]) |id| t.unpin(l, id) catch {}; + for (out[0..done]) |o| t.undo(o); // a miss was never copied in: its frame must not stay mapped + } + for (ids, 0..) |id, i| { + out[i] = try t.pin(l, id); + done += 1; + } + } + + /// The frame a failed batch took for a miss goes back unmapped (generation moved on), unless something pins it. + fn undo(t: *Tier, o: Fill) void { + if (t.fault == .keep_failed_miss or !o.miss or t.frame_of[o.page] != o.frame or t.pinned[o.frame] != 0) return; + t.unmap(o.frame); + t.free_frames[t.nfree] = o.frame; + t.nfree += 1; + } + + /// One pin of `id` fewer. Dirty: the last pin of a page whose rows the host store lacks cannot go (sync it first). + pub fn unpin(t: *Tier, l: *Lease, id: u32) error{ NotPinned, Dirty }!void { + var i = l.pins.items.len; + while (i > 0) : (i -= 1) if (l.pins.items[i - 1] == id) break; + if (i == 0) return error.NotPinned; + const f = t.frame_of[id]; + if (t.pinned[f] == 1 and t.dirty[id] and t.fault != .ignore_dirty) return error.Dirty; + _ = l.pins.orderedRemove(i - 1); + t.pinned[f] -= 1; + } + + /// Lend `n` frames to `l` for its life: mapped to no page, never a victim, counted in its promise like pins. + pub fn lend(t: *Tier, l: *Lease, n: usize) error{ FrameMemory, OutOfMemory }!void { + if (l.pins.items.len + l.lent.items.len + n > l.frames) return error.FrameMemory; + try l.lent.ensureUnusedCapacity(t.gpa, n); + var taken: usize = 0; + errdefer t.giveBackTo(l, l.lent.items.len - taken); + while (taken < n) : (taken += 1) { + const f = t.takeFrame() orelse return error.FrameMemory; + t.gen[f] +%= 1; + t.lent_mark[f] = true; + l.lent.appendAssumeCapacity(f); + t.nlent += 1; + } + } + + /// Lend `l` `n` consecutive free frames (a family's state run) for its life; the first frame, or FrameMemory. + pub fn lendRun(t: *Tier, l: *Lease, n: usize) error{ FrameMemory, OutOfMemory }!u32 { + if (n == 0 or l.pins.items.len + l.lent.items.len + n > l.frames) return error.FrameMemory; + var start: usize = 0; + var run: usize = 0; + for (t.page_of, t.lent_mark, 0..) |p, m, f| { + if (p == none and !m) run += 1 else run = 0; + if (run == n) { + start = f + 1 - n; + break; + } + } else return error.FrameMemory; + try l.lent.ensureUnusedCapacity(t.gpa, n); + var kept: usize = 0; + for (t.free_frames[0..t.nfree]) |f| if (f < start or f >= start + n) { + t.free_frames[kept] = f; + kept += 1; + }; + t.nfree = kept; + for (start..start + n) |f| { + t.gen[f] +%= 1; + t.lent_mark[f] = true; + l.lent.appendAssumeCapacity(@intCast(f)); + } + t.nlent += n; + return @intCast(start); + } + + /// The frames lent to `l` go back to the free frames, their generation moved on. + pub fn giveBack(t: *Tier, l: *Lease) void { + t.giveBackTo(l, 0); + } + + fn giveBackTo(t: *Tier, l: *Lease, keep: usize) void { + while (l.lent.items.len > keep) { + const f = l.lent.pop().?; + t.gen[f] +%= 1; + t.lent_mark[f] = false; + t.free_frames[t.nfree] = f; + t.nfree += 1; + t.nlent -= 1; + } + } + + /// The LRU clock moves on for `id` (a hit the device saw, or a call that read it). + pub fn touch(t: *Tier, id: u32) void { + const f = t.frame_of[id]; + if (f == none) return; + t.clock += 1; + t.stamp[f] = t.clock; + } + + /// Rows were written into `id`'s frame, which `l` pins: the host store lacks them until `sync`. + pub fn markDirty(t: *Tier, l: *const Lease, id: u32) error{NotPinned}!void { + if (t.fault != .unpinned_dirty and std.mem.indexOfScalar(u32, l.pins.items, id) == null) return error.NotPinned; + if (t.frame_of[id] == none) std.debug.panic("kv tier: page {d} written with no frame", .{id}); + t.dirty[id] = true; + } + + /// The family copied `id`'s frame to `host_page(id)`: the frame may be dropped. + pub fn sync(t: *Tier, id: u32) void { + t.dirty[id] = false; + } + + /// Where a page's canonical rows go (a flush writes here). + pub fn host_page(t: *Tier, id: u32) []u8 { + const b: usize = @intCast(t.pool.page_bytes); + return t.host[id * b ..][0..b]; + } + + /// The canonical rows of `id` for a snapshot or a fill; Unsynced while its frame holds rows not flushed yet. + pub fn canonical(t: *const Tier, id: u32) error{Unsynced}![]const u8 { + if (t.dirty[id]) return error.Unsynced; + const b: usize = @intCast(t.pool.page_bytes); + return t.host[id * b ..][0..b]; + } + + /// Drop up to `n` unpinned frames, least recently used first; the count dropped. + pub fn evict(t: *Tier, n: usize) usize { + var done: usize = 0; + while (done < n) : (done += 1) { + const f = t.victim() orelse break; + t.unmap(f); + t.free_frames[t.nfree] = f; + t.nfree += 1; + } + return done; + } + + /// Whether `l` can end: none of its pinned pages is left dirty and unpinned (a page only it holds goes with it). + pub fn canFinish(t: *const Tier, l: *const Lease) bool { + if (t.fault == .ignore_dirty) return true; + for (l.pins.items) |id| { + if (!t.dirty[id]) continue; + const f = t.frame_of[id]; + var mine: usize = 0; // this lease's own pins of the page + for (l.pins.items) |q| mine += @intFromBool(q == id); + if (f != none and t.pinned[f] > mine) continue; // another stream still pins it + const own = std.mem.indexOfScalar(u32, l.pages.ids.items, id) != null; + if (!own or t.pool.refs[id] > 1) return false; + } + for (l.pages.ids.items) |id| if (t.dirty[id] and t.pool.refs[id] > 1) return false; + return true; + } + + /// The stream ended: its pins, frames, promise and pages go back (a page nobody else holds loses its frame). + pub fn finish(t: *Tier, l: *Lease) void { + if (t.fault == .none and !t.canFinish(l)) std.debug.panic("kv tier: a stream ended with unflushed rows pinned or shared", .{}); + for (l.pins.items) |id| { + const f = t.frame_of[id]; + if (f != none) t.pinned[f] -= 1 else if (t.fault == .none) std.debug.panic("kv tier: pinned page {d} lost its frame", .{id}); + } + l.pins.deinit(t.gpa); + t.giveBack(l); + l.lent.deinit(t.gpa); + t.promised -= l.frames; + t.pool.finish(&l.pages); + l.* = .{}; + } + + pub fn census(t: *const Tier) Census { + var c: Census = .{ .frames = t.count(), .free = t.nfree, .resident = 0, .pinned = 0, .dirty = 0, .promised = t.promised, .lent = t.nlent }; + for (t.page_of, t.pinned) |p, n| { + c.resident += @intFromBool(p != none); + c.pinned += @intFromBool(n > 0); + } + for (t.dirty) |d| c.dirty += @intFromBool(d); + return c; + } + + /// Nothing promised, pinned or dirty, and every frame free or holding a page still held (the store's). + pub fn idle(t: *const Tier) bool { + const c = t.census(); + return t.pool.idle() and c.promised == 0 and c.pinned == 0 and c.dirty == 0 and c.lent == 0 and c.free + c.resident == c.frames; + } + + /// The mapping's own consistency; an error names the broken rule. Tests call it after every step. + pub fn audit(t: *const Tier) error{Broken}!void { + var mapped: usize = 0; + for (t.page_of, 0..) |p, f| { + if (p == none) { + if (t.pinned[f] != 0) return error.Broken; // a pin on an empty frame + continue; + } + mapped += 1; + if (t.frame_of[p] != f) return error.Broken; // page and frame disagree + if (t.pool.refs[p] == 0) return error.Broken; // a free page keeps a frame + } + if (mapped + t.nfree + t.nlent != t.count()) return error.Broken; // frames neither free, mapped nor lent, or two + for (t.free_frames[0..t.nfree]) |f| if (t.page_of[f] != none or t.lent_mark[f]) return error.Broken; + var marked: usize = 0; + for (t.lent_mark, t.page_of) |m, p| { + marked += @intFromBool(m); + if (m and p != none) return error.Broken; // a lent frame holds a page + } + if (marked != t.nlent) return error.Broken; + for (t.frame_of, 0..) |f, p| { + if (f != none and t.page_of[f] != p) return error.Broken; + if (t.dirty[p] and f == none) return error.Broken; // unflushed rows with no frame + } + if (t.promised > t.count()) return error.Broken; + } + + /// A hash of what two ranks must hold alike: mapping, generations, LRU order, pins, holders and promises. + pub fn digest(t: *const Tier) u64 { + var h = std.hash.Wyhash.init(0); + h.update(std.mem.sliceAsBytes(t.frame_of)); + h.update(std.mem.sliceAsBytes(t.page_of)); + h.update(std.mem.sliceAsBytes(t.gen)); + h.update(std.mem.sliceAsBytes(t.stamp)); + h.update(std.mem.sliceAsBytes(t.pinned)); + h.update(std.mem.sliceAsBytes(t.free_frames[0..t.nfree])); + h.update(std.mem.sliceAsBytes(t.pool.refs)); + h.update(std.mem.sliceAsBytes(t.pool.free[0..t.pool.nfree])); + const counts = [_]u64{ t.promised, t.pool.promised, t.clock, t.nlent }; + h.update(std.mem.sliceAsBytes(&counts)); + return h.final(); + } + + /// A free frame, or the least recently used unpinned one dropped. + fn takeFrame(t: *Tier) ?u32 { + if (t.nfree > 0) { + t.nfree -= 1; + return t.free_frames[t.nfree]; + } + const f = t.victim() orelse return null; + t.unmap(f); + return f; + } + + /// The mapped frame with the oldest stamp, not pinned and with no unflushed rows (the lowest index among equals). + fn victim(t: *const Tier) ?u32 { + var best: ?u32 = null; + for (t.page_of, 0..) |p, f| { + if (p == none) continue; + if (t.pinned[f] > 0 and t.fault != .ignore_pins) continue; + if (t.dirty[p] and t.fault != .ignore_dirty) continue; + if (best == null or t.stamp[f] < t.stamp[best.?]) best = @intCast(f); + } + return best; + } + + /// The frame stops holding its page: the generation moves on so a table naming it is stale. + fn unmap(t: *Tier, f: u32) void { + const p = t.page_of[f]; + if (t.dirty[p] and t.fault != .ignore_dirty) std.debug.panic("kv tier: frame {d} dropped with page {d} unflushed", .{ f, p }); + t.frame_of[p] = none; + t.dirty[p] = false; + t.page_of[f] = none; + if (t.fault != .keep_generation) t.gen[f] +%= 1; + } + + /// The pool freed `id` (its last holder let go): its frame is free again. + fn freed(ctx: *anyopaque, id: u32) void { + const t: *Tier = @ptrCast(@alignCast(ctx)); + const f = t.frame_of[id]; + if (f == none) return; + if (t.pinned[f] != 0 and t.fault == .none) std.debug.panic("kv tier: page {d} freed while pinned", .{id}); + t.dirty[id] = false; // the page is gone: rows nobody can read need no flush + t.unmap(f); + t.free_frames[t.nfree] = f; + t.nfree += 1; + } +}; + +test { + _ = @import("kv_tier_test.zig"); +} diff --git a/zig/src/core/kv_tier_test.zig b/zig/src/core/kv_tier_test.zig new file mode 100644 index 00000000000..760c7d3d189 --- /dev/null +++ b/zig/src/core/kv_tier_test.zig @@ -0,0 +1,591 @@ +//! The host tier: two currencies, eviction order, pins, generations, canonical rows, lockstep ranks, mutants. +const std = @import("std"); +const kv = @import("kv_pool.zig"); +const kt = @import("kv_tier.zig"); +const Tier = kt.Tier; +const Lease = kt.Lease; +const expect = std.testing.expect; +const expectEqual = std.testing.expectEqual; +const gpa = std.testing.allocator; + +const page_bytes = 8; + +test "tier geometry: zero page bytes, partial host pages, zero frames and zero pages refuse before allocation" { + var host: [9]u8 = undefined; + const Case = struct { bytes: usize, frames: usize = 1, page: u64 = page_bytes }; + for ([_]Case{ + .{ .bytes = 8, .page = 0 }, + .{ .bytes = 7 }, + .{ .bytes = 9 }, + .{ .bytes = 8, .frames = 0 }, + .{ .bytes = 0 }, + }) |c| { + var failing = std.testing.FailingAllocator.init(gpa, .{ .fail_index = 0 }); + var tier: Tier = undefined; + try std.testing.expectError(error.BadTierGeometry, tier.init(failing.allocator(), host[0..c.bytes], c.frames, c.page)); + try expect(!failing.has_induced_failure); + } +} + +test "tier geometry: one byte, one page and one frame is the smallest valid tier" { + var host = [_]u8{7}; + var tier: Tier = undefined; + try tier.init(gpa, &host, 1, 1); + defer tier.deinit(); + try expectEqual(@as(usize, 1), tier.pool.total()); + try expectEqual(@as(usize, 1), tier.count()); + try std.testing.expectEqualSlices(u8, &host, tier.host_page(0)); +} + +/// A tier of `pages` logical pages and `frames` frames over a host store and a fake device. +const Rig = struct { + host: []u8, + dev: []u8, + tier: Tier, + + fn open(r: *Rig, pages: usize, frames: usize) !void { + r.host = try gpa.alloc(u8, pages * page_bytes); + errdefer gpa.free(r.host); + @memset(r.host, 0); + r.dev = try gpa.alloc(u8, frames * page_bytes); + errdefer gpa.free(r.dev); + @memset(r.dev, 0); + try r.tier.init(gpa, r.host, frames, page_bytes); + } + + fn close(r: *Rig) void { + r.tier.deinit(); + gpa.free(r.host); + gpa.free(r.dev); + } + + fn frame(r: *Rig, f: u32) []u8 { + return r.dev[f * page_bytes ..][0..page_bytes]; + } + + /// A stream with `pages` pages covered and `frames` frames promised. + fn lease(r: *Rig, pages: usize, frames: usize) !Lease { + return r.leaseLent(pages, frames, 0); + } + + /// A stream that also has `lent` of its frames lent for its life. + fn leaseLent(r: *Rig, pages: usize, frames: usize, lent: usize) !Lease { + var l: Lease = .{}; + errdefer r.tier.finish(&l); + try r.tier.reserve(&l, pages, frames); + try r.tier.cover(&l, pages, null); + try r.tier.lend(&l, lent); + return l; + } + + /// Pin `id`, copying its canonical rows in on a miss. + fn pin(r: *Rig, l: *Lease, id: u32) !kt.Fill { + const f = try r.tier.pin(l, id); + if (f.miss) @memcpy(r.frame(f.frame), r.tier.host_page(id)); + return f; + } + + /// Write `b` into every row byte of the pinned page and flush it to the host store. + fn write(r: *Rig, l: *const Lease, id: u32, b: u8) void { + const tk = r.tier.resident(id).?; + @memset(r.frame(tk.frame), b); + r.tier.markDirty(l, id) catch unreachable; + } + + fn flush(r: *Rig, id: u32) void { + const tk = r.tier.resident(id).?; + @memcpy(r.tier.host_page(id), r.frame(tk.frame)); + r.tier.sync(id); + } +}; + +test "two currencies: a promise that fits one and not the other takes nothing, and finishing returns both" { + var r: Rig = undefined; + try r.open(8, 3); + defer r.close(); + const t = &r.tier; + var a = try r.lease(4, 2); + try std.testing.expectError(error.FrameMemory, t.reserve(&a, 1, 2)); // frames: 2 + 2 > 3 + try expectEqual(@as(usize, 0), a.pages.promised); + try expectEqual(@as(usize, 2), t.promised); + var b: Lease = .{}; + try std.testing.expectError(error.LaneMemory, t.reserve(&b, 5, 1)); // pages: 4 + 5 > 8 + try expectEqual(@as(usize, 2), t.promised); // the frame promise was not kept + try expectEqual(@as(usize, 0), t.pool.promised); + try expect(!t.fits(5, 1) and t.fits(4, 1) and !t.fits(4, 2)); + var c = try r.lease(4, 1); + try expect(!t.fits(1, 0)); // every page is promised or taken + t.finish(&a); + t.finish(&c); + t.finish(&b); + try expect(t.idle()); + try t.audit(); +} + +test "a lease cannot pin more frames than it promised, and a failed batch pins nothing" { + var r: Rig = undefined; + try r.open(8, 4); + defer r.close(); + const t = &r.tier; + var a = try r.lease(4, 2); + var out: [3]kt.Fill = undefined; + const ids = a.pages.ids.items; + try std.testing.expectError(error.FrameMemory, t.fill(&a, ids[0..3], &out)); + try expectEqual(@as(usize, 0), t.census().pinned); + try expectEqual(@as(usize, 0), a.pins.items.len); + try expect(t.resident(ids[0]) == null and t.resident(ids[1]) == null); // the misses of the failed batch were unmapped + try t.fill(&a, ids[0..2], out[0..2]); + try expect(out[0].miss and out[1].miss); + try expectEqual(@as(usize, 2), t.census().pinned); + try std.testing.expectError(error.FrameMemory, t.pin(&a, ids[2])); + t.finish(&a); + try expect(t.idle()); +} + +test "eviction takes the least recently used unpinned frame, and a touch moves a page to the back" { + var r: Rig = undefined; + try r.open(8, 3); + defer r.close(); + const t = &r.tier; + var a = try r.lease(6, 1); + const ids = a.pages.ids.items; + for (ids[0..3]) |id| { // one frame promised: pin, read, unpin, three times over + _ = try r.pin(&a, id); + try t.unpin(&a, id); + } + try expectEqual(@as(usize, 3), t.census().resident); + t.touch(ids[0]); // order now 1, 2, 0 + const f = try r.pin(&a, ids[3]); // evicts page 1 + try expect(f.miss); + try expect(t.resident(ids[1]) == null and t.resident(ids[0]) != null and t.resident(ids[2]) != null); + try t.unpin(&a, ids[3]); + try expectEqual(@as(usize, 1), t.evict(1)); // page 2 is next + try expect(t.resident(ids[2]) == null and t.resident(ids[0]) != null); + try expectEqual(@as(usize, 2), t.evict(5)); // 0 and 3: all that is left + try expectEqual(@as(usize, 3), t.census().free); + try t.audit(); + t.finish(&a); +} + +test "pinned frames are never evicted, and a dirty page stays until its rows reach the host store" { + var r: Rig = undefined; + try r.open(8, 2); + defer r.close(); + const t = &r.tier; + var a = try r.lease(2, 1); + var b = try r.lease(2, 1); + const pa = a.pages.ids.items[0]; + const pb = b.pages.ids.items; + _ = try r.pin(&a, pa); + r.write(&a, pa, 7); + _ = try r.pin(&b, pb[0]); + try t.unpin(&b, pb[0]); + _ = try r.pin(&b, pb[1]); // the one frame that can go is pb[0]'s + try expect(t.resident(pa) != null and t.resident(pb[0]) == null); + try std.testing.expectError(error.Dirty, t.unpin(&a, pa)); + try expectEqual(@as(usize, 0), t.evict(2)); // pa pinned and dirty, pb[1] pinned + try t.unpin(&b, pb[1]); + try expectEqual(@as(usize, 1), t.evict(2)); // only pb[1] + try expect(t.resident(pa) != null); + try std.testing.expectError(error.Unsynced, t.canonical(pa)); + r.flush(pa); + try t.unpin(&a, pa); + try expectEqual(@as(u8, 7), (try t.canonical(pa))[3]); + try expectEqual(@as(usize, 1), t.evict(2)); + t.finish(&a); + t.finish(&b); + try expect(t.idle()); +} + +/// Whether a table entry written before a frame was dropped and filled again with the same page is taken for current. +fn staleAccepted(fault: kt.Fault) !bool { + var r: Rig = undefined; + try r.open(4, 1); + defer r.close(); + r.tier.fault = fault; + var a = try r.lease(2, 1); + defer r.tier.finish(&a); + const p = a.pages.ids.items; + const f0 = try r.pin(&a, p[0]); + const old: kt.Ticket = .{ .frame = f0.frame, .gen = f0.gen }; + try r.tier.unpin(&a, p[0]); + _ = try r.pin(&a, p[1]); // the only frame is recycled + try r.tier.unpin(&a, p[1]); + _ = try r.pin(&a, p[0]); // and returns to the first page: same frame, new contents + try r.tier.unpin(&a, p[0]); + return r.tier.valid(p[0], old); +} + +test "generations: a recycled frame is not read through a table written before" { + try expect(!try staleAccepted(.none)); + try expect(try staleAccepted(.keep_generation)); // mutation: without the generation the stale table passes +} + +/// Whether a frame a call pins survives another stream's miss. +fn pinnedSurvives(fault: kt.Fault) !bool { + var r: Rig = undefined; + try r.open(4, 2); + defer r.close(); + r.tier.fault = fault; + var a = try r.lease(1, 1); + defer r.tier.finish(&a); + var b = try r.lease(2, 1); + defer r.tier.finish(&b); + const pa = a.pages.ids.items[0]; + _ = try r.pin(&a, pa); // the oldest stamp, and pinned + _ = try r.pin(&b, b.pages.ids.items[0]); + try r.tier.unpin(&b, b.pages.ids.items[0]); + _ = try r.pin(&b, b.pages.ids.items[1]); + return r.tier.resident(pa) != null; +} + +test "pin rule: the frame a call holds survives a miss; mutation: ignoring pins evicts it" { + try expect(try pinnedSurvives(.none)); + try expect(!try pinnedSurvives(.ignore_pins)); +} + +test "freeing a page (its last holder lets go) frees its frame; a page the store still holds keeps it" { + var r: Rig = undefined; + try r.open(4, 2); + defer r.close(); + const t = &r.tier; + var a = try r.lease(2, 2); + const p = try gpa.dupe(u32, a.pages.ids.items); // ids outlive the lease + defer gpa.free(p); + _ = try r.pin(&a, p[0]); + r.write(&a, p[0], 5); + r.flush(p[0]); + _ = try r.pin(&a, p[1]); + t.pool.retain(p[0]); // the prompt store keeps the first page + t.finish(&a); + try expect(t.resident(p[0]) != null and t.resident(p[1]) == null); + try expectEqual(@as(usize, 1), t.census().free); + try expectEqual(@as(u8, 5), (try t.canonical(p[0]))[0]); + try t.pool.drop(p[0]); + try expect(t.resident(p[0]) == null and t.idle()); + try t.audit(); +} + +/// A fake serving loop: streams open, pin, write, flush, unpin, finish; every row read equals the page's last write. +const Sim = struct { + r: Rig, + rng: std.Random.DefaultPrng, + slots: [3]?Lease = .{ null, null, null }, + model: [16]u8 = @splat(0), // the byte last written to a page (0: none) + next: u8 = 1, + misses: usize = 0, + reads: usize = 0, + + fn open(s: *Sim, seed: u64, frames: usize) !void { + s.* = .{ .r = undefined, .rng = .init(seed) }; + try s.r.open(16, frames); + } + + fn close(s: *Sim) void { + for (&s.slots) |*l| if (l.*) |*x| s.r.tier.finish(x); + s.r.close(); + } + + fn check(s: *Sim, id: u32, tk: kt.Ticket) !void { + if (s.model[id] == 0) return; + for (s.r.frame(tk.frame)) |x| try expectEqual(s.model[id], x); + s.reads += 1; + } + + fn step(s: *Sim) !void { + const t = &s.r.tier; + const rnd = s.rng.random(); + const op = rnd.uintLessThan(u32, 100); + const k = rnd.uintLessThan(usize, s.slots.len); + const l: *Lease = if (s.slots[k]) |*x| x else { + if (op < 60) s.slots[k] = s.r.leaseLent(4, 3, 1) catch null; + return; + }; + const ids = l.pages.ids.items; + const id = ids[rnd.uintLessThan(usize, ids.len)]; + switch (op) { + 0...34 => { + const f = s.r.pin(l, id) catch |e| { + if (e == error.FrameMemory and l.pins.items.len + l.lent.items.len >= l.frames) return; + return e; + }; + s.misses += @intFromBool(f.miss); + try s.check(id, .{ .frame = f.frame, .gen = f.gen }); + }, + 35...59 => if (l.pins.items.len > 0) { + const p = l.pins.items[rnd.uintLessThan(usize, l.pins.items.len)]; + s.model[p] = s.next; + s.next = if (s.next == 255) 1 else s.next + 1; + s.r.write(l, p, s.model[p]); + }, + 60...79 => if (l.pins.items.len > 0) { + const p = l.pins.items[rnd.uintLessThan(usize, l.pins.items.len)]; + if (t.dirty[p]) s.r.flush(p); + try t.unpin(l, p); + }, + 80...89 => _ = t.evict(1), + else => { + for (l.pins.items) |p| if (t.dirty[p]) s.r.flush(p); + for (ids) |p| s.model[p] = 0; + t.finish(l); + s.slots[k] = null; + }, + } + try t.audit(); + for (t.page_of, 0..) |p, f| if (p != kt.none and !t.dirty[p]) try s.check(p, .{ .frame = @intCast(f), .gen = t.gen[f] }); + } +}; + +test "a random serving loop with fewer frames than pages: the audit holds, every read equals the last write, and it ends idle" { + inline for (.{ 1, 2, 3 }) |seed| { + var s: Sim = undefined; + try s.open(seed, 6); + defer s.close(); + for (0..4000) |_| try s.step(); + try expect(s.misses > 100 and s.reads > 500); + for (&s.slots) |*l| if (l.*) |*x| { + for (x.pins.items) |p| if (s.r.tier.dirty[p]) s.r.flush(p); + s.r.tier.finish(x); + l.* = null; + }; + _ = s.r.tier.evict(100); + try expect(s.r.tier.idle()); + } +} + +test "two ranks in lockstep: the same openings and pins give the same frames, generations and order, step after step" { + var a: Sim = undefined; + var b: Sim = undefined; + try a.open(9, 6); + defer a.close(); + try b.open(9, 6); + defer b.close(); + for (0..3000) |_| { + try a.step(); + try b.step(); + try expectEqual(a.r.tier.digest(), b.r.tier.digest()); + } +} + +test "two ranks: a step only one rank takes is caught by the digest at once" { + var a: Sim = undefined; + var b: Sim = undefined; + try a.open(9, 6); + defer a.close(); + try b.open(9, 6); + defer b.close(); + var caught: ?usize = null; + for (0..3000) |i| { + try a.step(); + if (i == 1500) _ = b.r.tier.evict(1) else try b.step(); // rank 1 evicts instead of the step rank 0 took + if (a.r.tier.digest() != b.r.tier.digest()) { + caught = i; + break; + } + } + try expect(caught != null); +} + +test "ranks agree on the smaller shape before they open" { + const a: kt.Shape = .{ .host_pages = 100, .frames = 40 }; + const b: kt.Shape = .{ .host_pages = 90, .frames = 48 }; + try expectEqual(kt.Shape{ .host_pages = 90, .frames = 40 }, a.agree(b)); + try expectEqual(a.agree(b), b.agree(a)); +} + +test "lent frames: counted in the frame promise, never victims or mapped, back at finish with a new generation" { + var r: Rig = undefined; + try r.open(8, 4); + defer r.close(); + const t = &r.tier; + var a = try r.leaseLent(4, 3, 2); // two lent, one left to pin + try expectEqual(@as(usize, 2), t.census().lent); + try expectEqual(@as(usize, 2), a.lent.items.len); + try std.testing.expectError(error.FrameMemory, t.lend(&a, 2)); + const gen0 = t.gen[a.lent.items[0]]; + var b = try r.lease(4, 1); + const ids = a.pages.ids.items; + _ = try r.pin(&a, ids[0]); + try std.testing.expectError(error.FrameMemory, t.pin(&a, ids[1])); // the lent frames used the promise + try t.unpin(&a, ids[0]); + for (b.pages.ids.items) |id| { // misses cycle through the two frames left; the lent ones are never taken + _ = try r.pin(&b, id); + try t.unpin(&b, id); + _ = try r.pin(&a, ids[1]); + try t.unpin(&a, ids[1]); + for (a.lent.items) |f| try expect(t.page_of[f] == kt.none); + } + try expect(t.evict(10) <= 2); // only the mapped frames can go, the lent ones are not among them + try t.audit(); + const lent0 = a.lent.items[0]; + t.finish(&a); + try expect(t.gen[lent0] != gen0); + try expectEqual(@as(usize, 0), t.census().lent); + t.finish(&b); + try expect(t.idle()); + try t.audit(); +} + +test "ranks lending a different count are told apart by the digest" { + var a: Rig = undefined; + var b: Rig = undefined; + try a.open(8, 4); + defer a.close(); + try b.open(8, 4); + defer b.close(); + var la = try a.leaseLent(4, 3, 2); + defer a.tier.finish(&la); + var lb = try b.leaseLent(4, 3, 2); + defer b.tier.finish(&lb); + try expectEqual(a.tier.digest(), b.tier.digest()); + try b.tier.lend(&lb, 0); + var lc = try b.leaseLent(0, 1, 1); + defer b.tier.finish(&lc); + try expect(a.tier.digest() != b.tier.digest()); +} + +test "a lent run is consecutive frames, leaves the free frames, and comes back at finish" { + var r: Rig = undefined; + try r.open(8, 6); + defer r.close(); + const t = &r.tier; + var a = try r.lease(2, 4); + _ = try r.pin(&a, a.pages.ids.items[0]); // a mapped frame in the way + const first = try t.lendRun(&a, 3); + try expectEqual(@as(usize, 3), t.census().lent); + for (a.lent.items, 0..) |f, i| try expectEqual(first + i, f); + try t.audit(); + var b = try r.lease(2, 2); + try std.testing.expectError(error.FrameMemory, t.lendRun(&b, 3)); // past b's promise + _ = try r.pin(&b, b.pages.ids.items[0]); + _ = try r.pin(&b, b.pages.ids.items[1]); + try std.testing.expectEqual(@as(usize, 0), t.nfree); // 1 mapped (a) + 3 lent + 2 mapped (b) + t.finish(&a); + t.finish(&b); + try expect(t.idle()); + try t.audit(); + var c = try r.lease(1, 6); + defer t.finish(&c); + try expectEqual(@as(u32, 0), try t.lendRun(&c, 6)); +} + +/// A failed batch, then the same pages pinned again through the rig: the frames must equal the host pages. +fn failedFillReads(fault: kt.Fault) !bool { + var r: Rig = undefined; + try r.open(8, 4); + defer r.close(); + r.tier.fault = fault; + for (r.host, 0..) |*b, i| b.* = @intCast(1 + i / page_bytes); // page k holds k + 1 + @memset(r.dev, 0xee); // the frames hold something else + var a = try r.lease(4, 2); + defer r.tier.finish(&a); + const ids = a.pages.ids.items; + var out: [3]kt.Fill = undefined; + try std.testing.expectError(error.FrameMemory, r.tier.fill(&a, ids[0..3], &out)); + try r.tier.audit(); + for (ids[0..2]) |id| { + const f = try r.pin(&a, id); + if (!std.mem.eql(u8, r.frame(f.frame), r.tier.host_page(id))) return false; + } + return true; +} + +test "a failed batch leaves no miss mapped: the pages pinned again read the host rows; mutation: keeping the mapping reads stale frames" { + try expect(try failedFillReads(.none)); + try expect(!try failedFillReads(.keep_failed_miss)); +} + +test "a failed batch moves the generation of the frames it unmapped" { + var r: Rig = undefined; + try r.open(4, 2); + defer r.close(); + var a = try r.lease(3, 2); + defer r.tier.finish(&a); + const ids = a.pages.ids.items; + var out: [3]kt.Fill = undefined; + const before = [2]u32{ r.tier.gen[0], r.tier.gen[1] }; + try std.testing.expectError(error.FrameMemory, r.tier.fill(&a, ids[0..3], &out)); + try expect(r.tier.gen[0] != before[0] and r.tier.gen[1] != before[1]); + try expectEqual(@as(usize, 2), r.tier.census().free); +} + +test "dirty needs a pin by the lease: an unpinned frame cannot be marked; mutation: a dirty frame nobody pins starves a lease inside its promise" { + var r: Rig = undefined; + try r.open(4, 2); + defer r.close(); + var a = try r.lease(1, 1); + defer r.tier.finish(&a); + var b = try r.lease(1, 1); + defer r.tier.finish(&b); + const pa = a.pages.ids.items[0]; + _ = try r.pin(&a, pa); + try r.tier.unpin(&a, pa); + try std.testing.expectError(error.NotPinned, r.tier.markDirty(&a, pa)); + try std.testing.expectError(error.NotPinned, r.tier.markDirty(&b, pa)); // pinned by nobody of b + try r.tier.audit(); + // the mutant lets the mark through on a frame no lease pins, and the only frame is then stuck + var m: Rig = undefined; + try m.open(4, 2); + defer m.close(); + m.tier.fault = .unpinned_dirty; + var c = try m.lease(2, 1); + defer m.tier.finish(&c); + var d = try m.lease(1, 1); + defer m.tier.finish(&d); + for (c.pages.ids.items) |pc| { // both frames hold c's pages, unpinned + _ = try m.pin(&c, pc); + try m.tier.unpin(&c, pc); + } + for (c.pages.ids.items) |pc| try m.tier.markDirty(&c, pc); + try std.testing.expectError(error.FrameMemory, m.pin(&d, d.pages.ids.items[0])); +} + +/// A lease that pins a dirty page it does not own, after the owner let go of its pin: whether it may end. +fn endsWithForeignDirty(fault: kt.Fault) !bool { + var r: Rig = undefined; + try r.open(4, 2); + defer r.close(); + r.tier.fault = fault; + var a = try r.lease(1, 1); + var b = try r.lease(1, 1); + const pa = a.pages.ids.items[0]; + _ = try r.pin(&a, pa); + _ = try r.pin(&b, pa); + r.write(&a, pa, 9); + try r.tier.unpin(&a, pa); // b still pins it + const ok = r.tier.canFinish(&b); + if (ok) { + r.tier.finish(&b); + r.flush(pa); // too late for a real stream; the test only wants the tier consistent to close + } else { + r.flush(pa); + r.tier.finish(&b); + } + r.tier.finish(&a); + return ok; +} + +test "a stream cannot end while it holds the last pin of a dirty page, its own table or not; mutation: ignoring dirty lets it" { + try expect(!try endsWithForeignDirty(.none)); + try expect(try endsWithForeignDirty(.ignore_dirty)); +} + +test "a stream ends cleanly once the dirty pages it pins are flushed, and one that shares a dirty page of its own cannot" { + var r: Rig = undefined; + try r.open(4, 2); + defer r.close(); + const t = &r.tier; + var a = try r.lease(2, 2); + const p = a.pages.ids.items; + _ = try r.pin(&a, p[0]); + r.write(&a, p[0], 3); + try expect(t.canFinish(&a)); // its own page and its only holder: the page goes with it + t.pool.retain(p[0]); + try expect(!t.canFinish(&a)); // now another holder would read rows the host lacks + r.flush(p[0]); + try expect(t.canFinish(&a)); + const keep = p[0]; + t.finish(&a); + try t.pool.drop(keep); + try expect(t.idle()); +} diff --git a/zig/src/core/lane_projection.zig b/zig/src/core/lane_projection.zig index 14e6029d370..52bcea48307 100644 --- a/zig/src/core/lane_projection.zig +++ b/zig/src/core/lane_projection.zig @@ -5,6 +5,8 @@ const ks = @import("kernel_sources"); const frags = @import("frags.zig"); /// The tensor units' affine products by expert, beside the lane layouts (one module for their shared fragments). pub const affine_mm = @import("affine_mm.zig"); +/// qk: 4-bit g64 products on weight_layout as load leaves it, in tf_lane_reg's words. +pub const qk = @import("qk_projection.zig"); pub const weight_layout = "u32[ceil(N/32)][K/group][32][group*bits/32], low-bit-first codes, columns past N zero"; pub const reg_layout = "u32[N/32][K/64][2][32 lanes][4] 4-bit codes, regBlock order"; @@ -292,6 +294,22 @@ pub const Projection = struct { return p.encodeImpl(e, x, w, sb, sums, y, rows); } + /// tf_lane_sums of `rows` rows of x into this projection's scratch, and a barrier; callers order its reuse. + pub fn encodeOwnSums(p: Projection, e: mtl.ComputeEncoder, x: Ref, rows: u32) !Sums { + const pipe = p.sums_pipe orelse return error.SumsNeedReg; + if (rows == 0 or rows > p.max_rows) return error.InvalidRows; + try checkRef(x, rows * p.k * 2, 2); + const stride: u32 = 16 * ((rows + 15) / 16); + e.setPipeline(pipe); + e.setBuffer(x.buf, x.off, 0); + e.setValue(@as(i32, @intCast(rows)), 1); + e.setBuffer(p.sums_buffer.?, 0, 2); + e.setValue(@as(i32, @intCast(stride)), 3); + e.dispatchThreads(.{ .width = stride * p.group_count }, .{ .width = 256 }); + e.barrier(); + return .{ .ref = .{ .buf = p.sums_buffer.? }, .stride = stride }; + } + fn encodeImpl(p: Projection, e: mtl.ComputeEncoder, x: Ref, w: Ref, sb: Ref, given: ?Sums, y: Ref, rows: u32) !void { if (rows == 0 or rows > p.max_rows) return error.InvalidRows; const blocks = (rows + 15) / 16; @@ -300,15 +318,7 @@ pub const Projection = struct { try checkRef(w, p.weight_bytes, if (p.reg) 16 else 8); try checkRef(sb, p.metadata_bytes, 16); try checkRef(y, ((rows - 1) * p.y_stride + p.n) * p.output_bytes, p.output_bytes); - if (given == null) if (p.sums_pipe) |pipe| { - e.setPipeline(pipe); - e.setBuffer(x.buf, x.off, 0); - e.setValue(@as(i32, @intCast(rows)), 1); - e.setBuffer(p.sums_buffer.?, 0, 2); - e.setValue(@as(i32, @intCast(stride)), 3); - e.dispatchThreads(.{ .width = stride * p.group_count }, .{ .width = 256 }); - e.barrier(); - }; + if (given == null and p.sums_pipe != null) _ = try p.encodeOwnSums(e, x, rows); e.setPipeline(p.pipe); e.setBuffer(x.buf, x.off, 0); e.setBuffer(w.buf, w.off, 1); @@ -335,6 +345,10 @@ fn checkRef(r: Ref, need: usize, alignment: usize) !void { if (r.off > len or need > len - r.off) return error.BufferTooSmall; } +test { + _ = qk; // qk_projection.zig's tests run with this module's +} + test "a reg layout's rows size its sums scratch, never its kernel source" { const base = Layout{ .n = 34816, .k = 5120, .format = .{ .bits = 4, .group = 64 }, .precompute_sums = true, .reg = true }; var long = base; diff --git a/zig/src/core/modelopt.zig b/zig/src/core/modelopt.zig index a0269f164d0..8a3951df906 100644 --- a/zig/src/core/modelopt.zig +++ b/zig/src/core/modelopt.zig @@ -198,17 +198,17 @@ fn block(root: std.json.Value) ?std.json.ObjectMap { return null; } -fn object(v: ?std.json.Value) ?std.json.ObjectMap { +pub fn object(v: ?std.json.Value) ?std.json.ObjectMap { const x = v orelse return null; return if (x == .object) x.object else null; } -fn text(v: ?std.json.Value) ?[]const u8 { +pub fn text(v: ?std.json.Value) ?[]const u8 { const x = v orelse return null; return if (x == .string) x.string else null; } -fn int(v: ?std.json.Value) ?i64 { +pub fn int(v: ?std.json.Value) ?i64 { const x = v orelse return null; return if (x == .integer) x.integer else null; } diff --git a/zig/src/core/picture/jpeg.zig b/zig/src/core/picture/jpeg.zig index d4771030605..f277f37c153 100644 --- a/zig/src/core/picture/jpeg.zig +++ b/zig/src/core/picture/jpeg.zig @@ -61,7 +61,7 @@ fn load(io: std.Io, a: Allocator) error{ NoJpegLibrary, JpegLibraryVersion }!Fns } fn find(io: std.Io, a: Allocator) Loaded { - if (platform.c.getenv(env)) |named| return open(io, a, std.mem.span(named)) orelse .missing; + if ((platform.environment.Process{}).get(env)) |named| return open(io, a, named) orelse .missing; var seen_wrong = false; if (std.process.executableDirPathAlloc(io, a)) |exe| { defer a.free(exe); diff --git a/zig/src/core/picture/webp.zig b/zig/src/core/picture/webp.zig index 5073e5ed667..059f87c8325 100644 --- a/zig/src/core/picture/webp.zig +++ b/zig/src/core/picture/webp.zig @@ -42,7 +42,7 @@ fn load(io: std.Io, a: Allocator) error{ NoWebpLibrary, WebpLibraryVersion }!Fns } fn find(io: std.Io, a: Allocator) Loaded { - if (std.c.getenv(env)) |named| return open(std.mem.span(named)) orelse .missing; + if ((@import("sys").environment.Process{}).get(env)) |named| return open(named) orelse .missing; var seen_wrong = false; if (std.process.executableDirPathAlloc(io, a)) |exe| { defer a.free(exe); diff --git a/zig/src/core/qk_projection.zig b/zig/src/core/qk_projection.zig new file mode 100644 index 00000000000..d254c61b089 --- /dev/null +++ b/zig/src/core/qk_projection.zig @@ -0,0 +1,104 @@ +//! qk (core/qk.metal): 4-bit g64 products on weight_layout as load leaves it, tf_lane_reg's words on the same K split. +const std = @import("std"); +const mtl = @import("metal"); +const ks = @import("kernel_sources"); +const lane = @import("lane_projection.zig"); + +/// tf_qk_args. +pub const Args = extern struct { rows: i32, k: i32, n: i32, groups: i32, stride: i32 }; + +/// The largest K split a tile takes: its slices add up through threadgroup memory. +pub const max_split = 8; + +/// Rows a threadgroup takes: all of `rows`, rounded to 8, up to 48 while slices fit threadgroup memory, else 32. +pub fn blockRows(rows: u32, sk: u32) u32 { + const whole = (rows + 7) / 8 * 8; + if (whole <= 48 and threadgroupBytes(whole, sk) <= 32768) return whole; + return 32; +} + +/// Threadgroup memory a tile's slices add up through: each slice past the first keeps a lane's values for 32 lanes. +pub fn threadgroupBytes(block: u32, sk: u32) usize { + return @as(usize, sk -| 1) * block * 32 * @sizeOf(f32); +} + +pub const Pipelines = struct { + allocator: std.mem.Allocator, + device: mtl.Device, + cache: std.AutoHashMapUnmanaged([2]u32, mtl.Pipeline) = .empty, + + pub fn init(allocator: std.mem.Allocator, device: mtl.Device) Pipelines { + return .{ .allocator = allocator, .device = device }; + } + + pub fn deinit(q: *Pipelines) void { + var it = q.cache.valueIterator(); + while (it.next()) |p| p.deinit(); + q.cache.deinit(q.allocator); + } + + /// The pipeline of a K split and a block of rows, compiled the first time it is asked for. + pub fn get(q: *Pipelines, sk: u32, block: u32) !mtl.Pipeline { + if (sk == 0 or sk > max_split or block == 0 or block % 8 != 0 or block > 48 or threadgroupBytes(block, sk) > 32768) return error.InvalidSchedule; + const key = [2]u32{ sk, block }; + if (q.cache.get(key)) |p| return p; + if (!q.device.tensorUnits()) return error.TensorUnitsRequired; + const text = try std.fmt.allocPrint(q.allocator, "#define TF_SK {d}\n#define TF_ROWS {d}\n{s}", .{ sk, block, ks.core_qk }); + defer q.allocator.free(text); + const lib = try mtl.Library.fromSource(q.device, text, mtl.CompileOptions.mlx()); + defer lib.deinit(); + const p = try mtl.Pipeline.init(q.device, lib, "tf_qk", false); + errdefer p.deinit(); + if (p.simdWidth() != 32 or p.maxThreads() < 32 * sk) return error.UnsupportedPipelineShape; + try q.cache.put(q.allocator, key, p); + return p; + } + + /// y = x W^T for `rows` rows: w in weight_layout, sb in metadata_layout, x's group sums; one dispatch, no barrier. + pub fn encode(q: *Pipelines, e: mtl.ComputeEncoder, n: usize, k: usize, sk: u32, x: lane.Ref, w: lane.Ref, sb: lane.Ref, sums: lane.Sums, y: lane.Ref, rows: u32) !void { + if (n == 0 or n % 32 != 0 or k == 0 or k % 64 != 0 or n > std.math.maxInt(i32) / 16 or k > std.math.maxInt(i32) / 16) return error.InvalidShape; + if (rows == 0 or sums.stride < rows) return error.InvalidRows; + const groups = k / 64; + try checkRef(x, @as(usize, rows) * k * 2, 2); + try checkRef(w, n * k / 2, 16); + try checkRef(sb, n * groups * 4, 16); + try checkRef(sums.ref, ((groups - 1) * @as(usize, sums.stride) + rows) * 4, 4); + try checkRef(y, @as(usize, rows) * n * 2, 8); + const block = blockRows(rows, sk); + e.setPipeline(try q.get(sk, block)); + e.setBuffer(x.buf, x.off, 0); + e.setBuffer(w.buf, w.off, 1); + e.setBuffer(sb.buf, sb.off, 2); + e.setBuffer(sums.ref.buf, sums.ref.off, 3); + e.setBuffer(y.buf, y.off, 4); + e.setValue(Args{ .rows = @intCast(rows), .k = @intCast(k), .n = @intCast(n), .groups = @intCast(groups), .stride = @intCast(sums.stride) }, 5); + e.dispatchGroups(mtl.Size.of(n / 32, (rows + block - 1) / block, 1), mtl.Size.of(32 * sk, 1, 1)); + } +}; + +/// Whether this GPU compiles qk: tensor units, and a runtime compiler that takes uint4b_format. +pub fn available(allocator: std.mem.Allocator, device: mtl.Device) bool { + if (!device.tensorUnits()) return false; + var q = Pipelines.init(allocator, device); + defer q.deinit(); + _ = q.get(1, 16) catch return false; + return true; +} + +fn checkRef(r: lane.Ref, need: usize, alignment: usize) !void { + if (r.off % alignment != 0) return error.MisalignedBuffer; + const len = r.buf.length(); + if (r.off > len or need > len - r.off) return error.BufferTooSmall; +} + +test "a block takes every row up to 48 while its slices fit threadgroup memory, else 32" { + try std.testing.expectEqual(@as(u32, 8), blockRows(1, 2)); + try std.testing.expectEqual(@as(u32, 16), blockRows(13, 4)); + try std.testing.expectEqual(@as(u32, 48), blockRows(48, 4)); + try std.testing.expectEqual(@as(u32, 32), blockRows(48, 8)); // 7 slices of 48 rows: 43,008 bytes + try std.testing.expectEqual(@as(u32, 32), blockRows(64, 1)); + try std.testing.expectEqual(@as(u32, 32), blockRows(2048, 2)); + for ([_]u32{ 1, 2, 4, 8 }) |sk| for (1..129) |rows| { + try std.testing.expect(threadgroupBytes(blockRows(@intCast(rows), sk), sk) <= 32768); + }; +} diff --git a/zig/src/core/quant/gptq.zig b/zig/src/core/quant/gptq.zig new file mode 100644 index 00000000000..6529b6f0cbd --- /dev/null +++ b/zig/src/core/quant/gptq.zig @@ -0,0 +1,349 @@ +//! AutoGPTQ v1 weights (4-bit symmetric groups of 128, no act order): the rules, the stored tensors, an fp64 reference. +const std = @import("std"); +const ckpt = @import("../checkpoint.zig"); +const modelopt = @import("../modelopt.zig"); +const Why = modelopt.Why; +const object = modelopt.object; +const text = modelopt.text; +const int = modelopt.int; + +const Allocator = std.mem.Allocator; +const Checkpoint = ckpt.Checkpoint; +const Tensor = ckpt.Tensor; + +/// The width and the group a config declares: anything else is refused by its field. +pub const bits = 4; +pub const group = 128; +/// The zero point of symmetric weights as qzeros stores it: 8 - 1, so a code reads as (nibble - 8). +pub const zero_nibble = 7; + +/// What a `dynamic` rule does to the module its pattern matches. +pub const Kind = enum { quantize, skip }; + +/// One `dynamic` rule: the pattern after its `+:` or `-:`, which Python's re.match anchors at the start. +pub const Rule = struct { pattern: []const u8, kind: Kind }; + +/// A GPTQ quantization_config after admission, prepared to say which modules it stores quantized. +pub const Config = struct { + arena: std.heap.ArenaAllocator, + rules: []const Rule = &.{}, + + /// The modules it quantizes: the last rule matching `module` decides, `default` where no rule does. + pub fn quantizedDefault(self: *const Config, module: []const u8, default: bool) bool { + var q = default; + for (self.rules) |r| { + if (regexMatch(r.pattern, module)) q = r.kind == .quantize; + } + return q; + } + + /// The modules it quantizes, a module no rule names included. + pub fn quantized(self: *const Config, module: []const u8) bool { + return self.quantizedDefault(module, true); + } + + pub fn deinit(self: *Config) void { + self.arena.deinit(); + } +}; + +/// The GPTQ block of `config_json` admitted, else null when no `quantization_config` declares `quant_method` gptq. +pub fn admit(gpa: Allocator, config_json: []const u8, why: *Why) !?Config { + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const parsed = try std.json.parseFromSliceLeaky(std.json.Value, arena.allocator(), config_json, .{}); + if (parsed != .object) return null; + return config(gpa, parsed.object, why); +} + +/// `admit` over an already parsed config.json: the file's top-level object, whose text tower is read too. +pub fn config(gpa: Allocator, root: std.json.ObjectMap, why: *Why) !?Config { + for ([_]?std.json.ObjectMap{ root, object(root.get("text_config")) }) |source| { + const q = object((source orelse continue).get("quantization_config")) orelse continue; + const method = text(q.get("quant_method")) orelse continue; + if (!std.ascii.eqlIgnoreCase(method, "gptq")) continue; + return try dialect(gpa, q, why); + } + return null; +} + +/// The fields and the rules this reader reads; a value outside them is refused by its field or rule name. +fn dialect(gpa: Allocator, q: std.json.ObjectMap, why: *Why) !Config { + const width = int(q.get("bits")); + if (width != bits) { + why.set("quantization_config.bits: {?d}, expected 4", .{width}); + return error.UnsupportedQuantization; + } + const size = int(q.get("group_size")); + if (size != group) { + why.set("quantization_config.group_size: {?d}, expected 128", .{size}); + return error.UnsupportedQuantization; + } + if (!holds(q.get("sym"), true)) { + why.set("quantization_config.sym: {?}, expected true", .{flag(q.get("sym"))}); + return error.UnsupportedQuantization; + } + if (q.get("desc_act")) |v| switch (v) { + .bool => |act| if (act) { + why.set("quantization_config.desc_act: true, this reader reads no act order", .{}); + return error.UnsupportedQuantization; + }, + else => { + why.set("quantization_config.desc_act: {s}, expected a bool", .{kindOf(v)}); + return error.UnsupportedQuantization; + }, + }; + if (q.get("checkpoint_format")) |v| { + const format = text(v) orelse { + why.set("quantization_config.checkpoint_format: {s}, expected gptq", .{kindOf(v)}); + return error.UnsupportedQuantization; + }; + if (!std.mem.eql(u8, format, "gptq")) { + why.set("quantization_config.checkpoint_format: {s}, expected gptq", .{format}); + return error.UnsupportedQuantization; + } + } + const dyn = object(q.get("dynamic")) orelse { + const found = if (q.get("dynamic") == null) "absent" else "not an object"; + why.set("quantization_config.dynamic: {s}, this reader reads its rules", .{found}); + return error.UnsupportedQuantization; + }; + var c: Config = .{ .arena = .init(gpa) }; + errdefer c.deinit(); + const a = c.arena.allocator(); + const rules = try a.alloc(Rule, dyn.count()); + var it = dyn.iterator(); + var i: usize = 0; + while (it.next()) |kv| : (i += 1) { + const key = kv.key_ptr.*; + const kind: Kind = if (std.mem.startsWith(u8, key, "+:")) .quantize else if (std.mem.startsWith(u8, key, "-:")) .skip else { + why.set("quantization_config.dynamic {s}: no +: or -: prefix", .{key}); + return error.UnsupportedQuantization; + }; + if (!supported(key[2..])) { + why.set("quantization_config.dynamic {s}: outside this reader's matcher", .{key}); + return error.UnsupportedQuantization; + } + try ruleMath(kv.value_ptr.*, key, why); + rules[i] = .{ .pattern = try a.dupe(u8, key[2..]), .kind = kind }; + } + c.rules = rules; + if (!c.quantizedDefault("lm_head", holds(q.get("lm_head"), true))) { + why.set("quantization_config.lm_head: {?}, the rules do not store the head int4", .{flag(q.get("lm_head"))}); + return error.UnsupportedQuantization; + } + return c; +} + +/// A rule's own value: a width or a group other than the admitted one is mixed precision this reader does not read. +fn ruleMath(v: std.json.Value, key: []const u8, why: *Why) !void { + if (v == .null) return; + const o = object(v) orelse { + why.set("quantization_config.dynamic {s}: not an object of bits", .{key}); + return error.UnsupportedQuantization; + }; + if (int(o.get("bits"))) |b| if (b != bits) { + why.set("quantization_config.dynamic {s}: bits {d}, expected 4", .{ key, b }); + return error.UnsupportedQuantization; + }; + if (int(o.get("group_size"))) |g| if (g != group) { + why.set("quantization_config.dynamic {s}: group_size {d}, expected 128", .{ key, g }); + return error.UnsupportedQuantization; + }; +} + +/// Whether a pattern uses only what `regexMatch` reads, so a rule outside the subset is refused rather than misread. +fn supported(pattern: []const u8) bool { + if (pattern.len == 0) return false; + var i: usize = 0; + var atom = false; + while (i < pattern.len) : (i += 1) { + switch (pattern[i]) { + '\\' => { + // an escaped alphanumeric is a class or an anchor in Python's re, never that character + if (i + 1 >= pattern.len or std.ascii.isAlphanumeric(pattern[i + 1])) return false; + i += 1; + atom = true; + }, + '.' => atom = true, + '*', '+' => { + if (!atom) return false; + atom = false; + }, + '$' => return i + 1 == pattern.len, + '?', '[', ']', '(', ')', '{', '}', '|', '^' => return false, + else => atom = true, + } + } + return true; +} + +/// Python's re.match for the subset the rules use: literals, '.', '\x' escapes, '*' and '+' after an atom, a final '$'. +pub fn regexMatch(pattern: []const u8, module: []const u8) bool { + return reAt(pattern, 0, module, 0); +} + +const Atom = struct { len: usize, lit: ?u8 }; + +fn reAtom(pattern: []const u8, p: usize) Atom { + if (pattern[p] == '\\' and p + 1 < pattern.len) return .{ .len = 2, .lit = pattern[p + 1] }; + if (pattern[p] == '.') return .{ .len = 1, .lit = null }; + return .{ .len = 1, .lit = pattern[p] }; +} + +fn reOne(lit: ?u8, c: u8) bool { + return if (lit) |l| l == c else true; +} + +fn reAt(pattern: []const u8, p: usize, module: []const u8, t: usize) bool { + if (p == pattern.len) return true; + if (pattern[p] == '$' and p + 1 == pattern.len) return t == module.len; + const atom = reAtom(pattern, p); + const next = p + atom.len; + if (next < pattern.len and (pattern[next] == '*' or pattern[next] == '+')) { + const least: usize = if (pattern[next] == '+') 1 else 0; + var n: usize = 0; + while (t + n < module.len and reOne(atom.lit, module[t + n])) n += 1; + var k: usize = n + 1; + while (k > least) { + k -= 1; + if (reAt(pattern, next + 1, module, t + k)) return true; + } + return false; + } + if (t < module.len and reOne(atom.lit, module[t])) return reAt(pattern, next, module, t + 1); + return false; +} + +/// One module as stored: qweight int32 [k / 8, n], scales f16 [k / 128, n], qzeros int32 [k / 128, n / 8]. +pub const Host = struct { qweight: Tensor, scales: Tensor, qzeros: Tensor, n: usize, k: usize }; + +/// `module`'s tensors from `ck`, each refusal logged; the byte views live as long as the checkpoint's map. +pub fn read(ck: *Checkpoint, module: []const u8, n: usize, k: usize) !Host { + var why: Why = .{}; + return readWhy(ck, module, n, k, &why) catch |e| { + if (why.len > 0) std.log.err("{s}", .{why.text()}); + return e; + }; +} + +/// `read`, the refusal kept in `why` instead of the log (tests read it). +pub fn readWhy(ck: *Checkpoint, module: []const u8, n: usize, k: usize, why: *Why) !Host { + if (n == 0 or k == 0 or n % 8 != 0 or k % group != 0) { + why.set("{s}: [n, k] of [{d}, {d}] is not 4-bit groups of 128 in words of 8 codes", .{ module, n, k }); + return error.UnexpectedTensor; + } + const qweight = try fetch(ck, module, "qweight", .i32, &.{ k / 8, n }, why); + const scales = try fetch(ck, module, "scales", .f16, &.{ k / group, n }, why); + const qzeros = try fetch(ck, module, "qzeros", .i32, &.{ k / group, n / 8 }, why); + if (zerosOff(qzeros.bytes)) |at| { + why.set("{s}.qzeros: byte {d} is 0x{x:0>2}, a symmetric weight's every nibble is 7", .{ module, at, qzeros.bytes[at] }); + return error.UnsupportedQuantization; + } + var buf: [320]u8 = undefined; + const gidx = try std.fmt.bufPrint(&buf, "{s}.g_idx", .{module}); + if (ck.has(gidx)) { + const g = try ck.get(gidx); + if (g.numel() != 0) { + why.set("{s}.g_idx: {t} {any}, act order is not read", .{ module, g.dtype, g.shape[0..g.rank] }); + return error.UnexpectedTensor; + } + } + return .{ .qweight = qweight, .scales = scales, .qzeros = qzeros, .n = n, .k = k }; +} + +/// `{module}.{tail}` of `dtype` and `shape`, its bytes whole; a missing tensor refused by name. +fn fetch(ck: *Checkpoint, module: []const u8, tail: []const u8, dtype: ckpt.DType, shape: []const usize, why: *Why) !Tensor { + var buf: [320]u8 = undefined; + const name = try std.fmt.bufPrint(&buf, "{s}.{s}", .{ module, tail }); + if (!ck.has(name)) { + why.set("{s}: no {s}, a GPTQ weight stores it", .{ module, tail }); + return error.MissingTensor; + } + const t = try ck.get(name); + var need: usize = 1; + for (shape) |d| need = std.math.mul(usize, need, d) catch return error.UnexpectedTensor; + if (t.is(dtype, shape)) { + if (need * dtype.size() == t.bytes.len) return t; + why.set("{s}: {d} bytes, {t} {any} needs {d}", .{ name, t.bytes.len, dtype, shape, need * dtype.size() }); + return error.UnexpectedTensor; + } + why.set("{s}: {t} {any}, expected {t} {any}", .{ name, t.dtype, t.shape[0..t.rank], dtype, shape }); + return error.UnexpectedTensor; +} + +/// Weights of a module: its columns by its inputs. +pub fn elements(h: Host) usize { + return h.n * h.k; +} + +/// The dequantized weight of input `k` in column `n`: (code - 8) * scale, exact in binary64. +pub fn weight(h: Host, n: usize, k: usize) f64 { + return @as(f64, @floatFromInt(@as(i32, code(h, n, k)) - 8)) * scale(h, n, k); +} + +/// The code of input `k` in column `n`: nibble `k % 8` of the word at [k / 8, n] (0..15). +pub fn code(h: Host, n: usize, k: usize) u8 { + std.debug.assert(n < h.n and k < h.k); + const at = ((k / 8) * h.n + n) * 4; + const w = std.mem.readInt(u32, h.qweight.bytes[at..][0..4], .little); + return @intCast((w >> @intCast(4 * (k % 8))) & 0xF); +} + +/// The fp16 scale of the group holding input `k` in column `n`, widened exactly. +pub fn scale(h: Host, n: usize, k: usize) f64 { + std.debug.assert(n < h.n and k < h.k); + const at = ((k / group) * h.n + n) * 2; + const half: f16 = @bitCast(std.mem.readInt(u16, h.scales.bytes[at..][0..2], .little)); + return @floatCast(half); +} + +/// Every weight, row-major [n, k], into `out`. +pub fn reference(h: Host, out: []f64) error{UnexpectedTensor}!void { + if (!sized(h) or out.len != elements(h)) return error.UnexpectedTensor; + for (0..h.n) |n| for (0..h.k) |k| { + out[n * h.k + k] = weight(h, n, k); + }; +} + +/// The stored tensors hold exactly what `Host`'s [n, k] says they do. +fn sized(h: Host) bool { + if (h.n == 0 or h.k == 0 or h.n % 8 != 0 or h.k % group != 0) return false; + const words = h.k / 8 * h.n; + if (!h.qweight.is(.i32, &.{ h.k / 8, h.n }) or h.qweight.bytes.len != words * 4) return false; + const scales = h.k / group * h.n; + if (!h.scales.is(.f16, &.{ h.k / group, h.n }) or h.scales.bytes.len != scales * 2) return false; + return h.qzeros.is(.i32, &.{ h.k / group, h.n / 8 }) and h.qzeros.bytes.len == scales / 8 * 4; +} + +/// The first qzeros byte whose two nibbles are not both `zero_nibble`, else null. +pub fn zerosOff(qzeros: []const u8) ?usize { + const all: u8 = zero_nibble << 4 | zero_nibble; + for (qzeros, 0..) |b, i| if (b != all) return i; + return null; +} + +fn flag(v: ?std.json.Value) ?bool { + const x = v orelse return null; + return if (x == .bool) x.bool else null; +} + +/// The JSON kind of `v`, so a refusal of a field that is not the type it must be says what it found. +fn kindOf(v: std.json.Value) []const u8 { + return switch (v) { + .null => "null", + .bool => "a bool", + .integer, .float, .number_string => "a number", + .string => "a string", + .array => "an array", + .object => "an object", + }; +} + +fn holds(v: ?std.json.Value, want: bool) bool { + return (flag(v) orelse false) == want; +} + +test { + _ = @import("gptq_test.zig"); +} diff --git a/zig/src/core/quant/gptq_test.zig b/zig/src/core/quant/gptq_test.zig new file mode 100644 index 00000000000..c2ed4d97afa --- /dev/null +++ b/zig/src/core/quant/gptq_test.zig @@ -0,0 +1,570 @@ +//! gptq: the shared AutoGPTQ v1 reader (core/quant/gptq.zig) on a synthetic checkpoint, against binary64. +const std = @import("std"); +const gptq = @import("gptq.zig"); +const ckpt = @import("../checkpoint.zig"); +const fixture = @import("../checkpoint_fixture.zig"); +const Why = @import("../modelopt.zig").Why; + +const testing = std.testing; +const a = testing.allocator; +const io = testing.io; + +const config_json = @embedFile("../fixtures/gptq_synth/config.json"); + +/// The two modules the synthetic checkpoint holds, and the [n, k] each one stores. +const expert = "model.language_model.layers.0.mlp.experts.0.gate_proj"; +const head = "language_model.lm_head"; + +/// The fp16 bit patterns the fixture stores: awkward mantissas, a subnormal, a negative and a negative zero. +const scale_bits = [2][8]u16{ + .{ 0x3C00, 0x3555, 0xB800, 0x0011, 0x4900, 0x7BFF, 0x8000, 0x3E00 }, + .{ 0x4200, 0xBC00, 0x5000, 0x3400, 0x0001, 0x3800, 0xC000, 0x3900 }, +}; + +/// The code of input `k` in column `c` the fixture writes: a full 0..15 cycle per column, a third of a turn apart. +fn codeOf(c: usize, k: usize) u8 { + return @intCast((k + 3 * c) % 16); +} + +/// What those codes and scale bits mean by the format's definition, in binary64. +fn want(c: usize, k: usize) f64 { + const half: f16 = @bitCast(scale_bits[k / gptq.group][c]); + return @as(f64, @floatFromInt(@as(i32, codeOf(c, k)) - 8)) * @as(f64, @floatCast(half)); +} + +/// AutoGPTQ v1's qweight packing, written from the format: word [k / 8][n], nibble j is input 8w + j, low first. +fn pack(k: usize, n: usize) ![]u8 { + const out = try a.alloc(u8, (k / 8) * n * 4); + @memset(out, 0); + for (0..k / 8) |w| for (0..n) |c| for (0..8) |j| { + const q = codeOf(c, w * 8 + j); + out[(w * n + c) * 4 + j / 2] |= if (j % 2 == 0) q else q << 4; + }; + return out; +} + +/// The scales [k / 128][n] as fp16 bit patterns, little-endian. +fn scales(k: usize, n: usize) ![]u8 { + const out = try a.alloc(u8, (k / gptq.group) * n * 2); + for (0..k / gptq.group) |g| for (0..n) |c| { + std.mem.writeInt(u16, out[(g * n + c) * 2 ..][0..2], scale_bits[g][c], .little); + }; + return out; +} + +/// qzeros [k / 128][n / 8] int32 whose every nibble is 7, so every zero point the format reads is 8. +fn zeros(k: usize, n: usize) ![]u8 { + const out = try a.alloc(u8, (k / gptq.group) * (n / 8) * 4); + @memset(out, 0x77); + return out; +} + +/// The synthetic checkpoint's six tensors, packed to the format; `entries` is what the safetensors image holds. +const Synth = struct { + const modules = [2][]const u8{ expert, head }; + const ns = [2]usize{ 8, 8 }; + const ks = [2]usize{ 256, 128 }; + const tails = [3][]const u8{ "qweight", "scales", "qzeros" }; + const dtypes = [3][]const u8{ "I32", "F16", "I32" }; + + bytes: [6][]u8 = undefined, + shapes: [6][2]usize = undefined, + names: [6][160]u8 = undefined, + entries: [6]fixture.Entry = undefined, + + fn init(s: *Synth) !void { + for (0..2) |m| for (0..3) |t| { + const i = m * 3 + t; + const n = ns[m]; + const k = ks[m]; + s.bytes[i] = switch (t) { + 0 => try pack(k, n), + 1 => try scales(k, n), + else => try zeros(k, n), + }; + s.shapes[i] = switch (t) { + 0 => .{ k / 8, n }, + 1 => .{ k / gptq.group, n }, + else => .{ k / gptq.group, n / 8 }, + }; + const name = try std.fmt.bufPrint(&s.names[i], "{s}.{s}", .{ modules[m], tails[t] }); + s.entries[i] = .{ .name = name, .dtype = dtypes[t], .shape = &s.shapes[i], .bytes = s.bytes[i] }; + }; + } + + fn deinit(s: *Synth) void { + for (s.bytes) |b| a.free(b); + } +}; + +/// A checkpoint folder: `config.json` and one `model.safetensors`. +const Folder = struct { + tmp: testing.TmpDir, + path: [160]u8 = undefined, + len: usize = 0, + ck: ckpt.Checkpoint = undefined, + + fn open(f: *Folder, entries: []const fixture.Entry) !void { + f.tmp = testing.tmpDir(.{}); + errdefer f.tmp.cleanup(); + try f.tmp.dir.writeFile(io, .{ .sub_path = "config.json", .data = config_json }); + try fixture.write(a, io, f.tmp.dir, "model.safetensors", entries); + const sub = try std.fmt.bufPrint(&f.path, ".zig-cache/tmp/{s}", .{f.tmp.sub_path}); + f.len = sub.len; + f.ck = try ckpt.Checkpoint.openModel(a, io, sub); + } + + /// The folder as the checkpoint opened it. + fn dir(f: *const Folder) []const u8 { + return f.path[0..f.len]; + } + + fn close(f: *Folder) void { + f.ck.close(); + f.tmp.cleanup(); + } + + /// The folder's own config.json, as the checkpoint's file. + fn configText(f: *Folder) ![]u8 { + var buf: [192]u8 = undefined; + const path = try std.fmt.bufPrint(&buf, "{s}/config.json", .{f.dir()}); + return std.Io.Dir.cwd().readFileAlloc(io, path, a, .limited(1 << 16)); + } +}; + +test "gptq: the synthetic checkpoint's config is admitted and names the modules it stores quantized" { + var s: Synth = .{}; + try s.init(); + defer s.deinit(); + var f: Folder = .{ .tmp = undefined }; + try f.open(&s.entries); + defer f.close(); + const json = try f.configText(); + defer a.free(json); + var why: Why = .{}; + var cfg = (try gptq.admit(a, json, &why)).?; + defer cfg.deinit(); + try testing.expectEqual(@as(usize, 11), cfg.rules.len); + try testing.expectEqual(@as(usize, 0), why.len); + for ([_][]const u8{ + expert, + "model.language_model.layers.47.mlp.experts.511.down_proj", + "model.language_model.layers.3.mlp.experts.0.up_proj", + "language_model.lm_head", + }) |m| try testing.expect(cfg.quantized(m)); + for ([_][]const u8{ + "model.language_model.layers.0.linear_attn.in_proj_qkv", + "model.language_model.layers.3.self_attn.q_proj", + "model.language_model.layers.0.attn_hyper_connection.input_mix_weight_up", + "model.visual.blocks.0.attn.qkv", + "model.language_model.layers.0.mlp.shared_expert.gate_proj", + "model.language_model.layers.0.ple.embedding", + "model.language_model.embed_tokens", + "model.language_model.layers.0.mlp.fc_hidden", + "model.language_model.layers.48.mlp.down_proj", + "model.language_model.layers.0.mlp.gate", + }) |m| try testing.expect(!cfg.quantized(m)); +} + +test "gptq: the stored tensors dequantize to the binary64 fixture" { + var s: Synth = .{}; + try s.init(); + defer s.deinit(); + var f: Folder = .{ .tmp = undefined }; + try f.open(&s.entries); + defer f.close(); + const h = try gptq.read(&f.ck, expert, 8, 256); + try testing.expectEqual(@as(usize, 8 * 256), gptq.elements(h)); + var got: [8 * 256]f64 = undefined; + try gptq.reference(h, &got); + for (0..8) |c| for (0..256) |k| { + const bits: u64 = @bitCast(got[c * 256 + k]); + if (bits != @as(u64, @bitCast(want(c, k)))) { + std.debug.print("column {d} input {d}: 0x{x:0>16}, expected 0x{x:0>16}\n", .{ c, k, bits, @as(u64, @bitCast(want(c, k))) }); + return error.TestUnexpectedResult; + } + }; + // the binary64 fixture: every code, both groups, a negative, a subnormal and a negative zero + const spot = [_]struct { c: usize, k: usize, want: f64 }{ + .{ .c = 0, .k = 0, .want = -8.0 }, // q -8 x 1 + .{ .c = 0, .k = 1, .want = -7.0 }, // q -7 x 1 + .{ .c = 0, .k = 2, .want = -6.0 }, + .{ .c = 0, .k = 3, .want = -5.0 }, + .{ .c = 0, .k = 4, .want = -4.0 }, + .{ .c = 0, .k = 5, .want = -3.0 }, + .{ .c = 0, .k = 6, .want = -2.0 }, + .{ .c = 0, .k = 7, .want = -1.0 }, + .{ .c = 0, .k = 8, .want = 0.0 }, // q 0, the zero point itself + .{ .c = 0, .k = 9, .want = 1.0 }, + .{ .c = 0, .k = 10, .want = 2.0 }, + .{ .c = 0, .k = 11, .want = 3.0 }, + .{ .c = 0, .k = 12, .want = 4.0 }, + .{ .c = 0, .k = 13, .want = 5.0 }, + .{ .c = 0, .k = 14, .want = 6.0 }, + .{ .c = 0, .k = 15, .want = 7.0 }, + .{ .c = 1, .k = 0, .want = -1.666259765625 }, // q -5 x 0.333251953125 + .{ .c = 1, .k = 1, .want = -1.3330078125 }, + .{ .c = 1, .k = 2, .want = -0.999755859375 }, + .{ .c = 1, .k = 3, .want = -0.66650390625 }, + .{ .c = 1, .k = 4, .want = -0.333251953125 }, + .{ .c = 1, .k = 5, .want = 0.0 }, + .{ .c = 1, .k = 6, .want = 0.333251953125 }, + .{ .c = 1, .k = 7, .want = 0.66650390625 }, + .{ .c = 2, .k = 0, .want = 1.0 }, // q -2 x -0.5 + .{ .c = 2, .k = 1, .want = 0.5 }, + .{ .c = 2, .k = 2, .want = -0.0 }, // a zero code under a negative scale keeps the product's sign + .{ .c = 2, .k = 3, .want = -0.5 }, + .{ .c = 3, .k = 0, .want = 1.0132789611816406e-06 }, // a subnormal scale, q 1 + .{ .c = 3, .k = 1, .want = 2.0265579223632812e-06 }, + .{ .c = 0, .k = 128, .want = -24.0 }, // the second group's own scale, q -8 x 3 + .{ .c = 0, .k = 129, .want = -21.0 }, + .{ .c = 0, .k = 130, .want = -18.0 }, + .{ .c = 0, .k = 131, .want = -15.0 }, + .{ .c = 0, .k = 132, .want = -12.0 }, + .{ .c = 0, .k = 133, .want = -9.0 }, + .{ .c = 0, .k = 134, .want = -6.0 }, + .{ .c = 0, .k = 135, .want = -3.0 }, + .{ .c = 7, .k = 128, .want = -1.875 }, // q -3 x 0.625 + .{ .c = 7, .k = 129, .want = -1.25 }, + .{ .c = 7, .k = 130, .want = -0.625 }, + .{ .c = 7, .k = 131, .want = 0.0 }, + .{ .c = 4, .k = 128, .want = 2.384185791015625e-07 }, // the smallest subnormal, q 4 + .{ .c = 4, .k = 129, .want = 2.980232238769531e-07 }, + .{ .c = 6, .k = 0, .want = 0.0 }, // a negative-zero scale turns a negative code positive + .{ .c = 6, .k = 1, .want = 0.0 }, + }; + for (spot) |p| try testing.expectEqual(@as(u64, @bitCast(p.want)), @as(u64, @bitCast(got[p.c * 256 + p.k]))); + try testing.expectEqual(@as(u8, 15), gptq.code(h, 0, 15)); + try testing.expectEqual(@as(u8, 8), gptq.code(h, 2, 2)); // the zero point itself + try testing.expectEqual(@as(f64, 0.333251953125), gptq.scale(h, 1, 100)); + try testing.expectEqual(@as(f64, 3), gptq.scale(h, 0, 128)); + try testing.expectEqual(@as(u64, @bitCast(@as(f64, 2.0))), @as(u64, @bitCast(gptq.weight(h, 0, 10)))); + const hd = try gptq.read(&f.ck, head, 8, 128); + var one: [8 * 128]f64 = undefined; + try gptq.reference(hd, &one); + try testing.expectEqual(@as(u64, @bitCast(@as(f64, -8.0))), @as(u64, @bitCast(one[0]))); + try testing.expectEqual(@as(u64, @bitCast(@as(f64, -24.0))), @as(u64, @bitCast(got[128]))); +} + +test "gptq: the matcher reads the rule subset and anchors as Python's re.match does" { + const cases = [_]struct { pattern: []const u8, hit: []const u8, miss: []const u8 }{ + .{ .pattern = ".*lm_head$", .hit = "language_model.lm_head", .miss = "language_model.lm_head.weight" }, + .{ .pattern = ".*\\.gate$", .hit = "model.language_model.layers.0.mlp.gate", .miss = "model.language_model.layers.0.mlp.gate_proj" }, + .{ .pattern = ".*linear_attn.*", .hit = "model.language_model.layers.0.linear_attn.in_proj_qkv", .miss = "model.language_model.layers.0.self_attn.q_proj" }, + .{ .pattern = ".*self_attn.*", .hit = "model.language_model.layers.3.self_attn.q_proj", .miss = "model.language_model.layers.3.mlp.experts.0.gate_proj" }, + .{ .pattern = ".*hyper_connection.*", .hit = "model.language_model.layers.0.attn_hyper_connection.input_mix_weight_up", .miss = "model.language_model.layers.0.mlp.experts.0.gate_proj" }, + .{ .pattern = ".*visual.*", .hit = "model.visual.blocks.0.attn.qkv", .miss = "model.language_model.embed_tokens" }, + .{ .pattern = ".*shared_expert.*", .hit = "model.language_model.layers.0.mlp.shared_expert.gate_proj", .miss = "model.language_model.layers.0.mlp.experts.0.gate_proj" }, + .{ .pattern = ".*\\.ple\\..*", .hit = "model.language_model.layers.0.ple.embedding", .miss = "model.language_model.layers.0.pleb" }, + .{ .pattern = ".*embed.*", .hit = "model.language_model.embed_tokens", .miss = "model.language_model.layers.0.mlp.down_proj" }, + .{ .pattern = ".*fc_hidden.*", .hit = "model.language_model.layers.0.mlp.fc_hidden.weight", .miss = "model.language_model.layers.0.mlp.experts.0.gate_proj" }, + .{ .pattern = ".*layers\\.48\\..*", .hit = "model.language_model.layers.48.mlp.down_proj", .miss = "model.language_model.layers.4.mlp.down_proj" }, + }; + for (cases) |c| { + try testing.expect(gptq.regexMatch(c.pattern, c.hit)); + try testing.expect(!gptq.regexMatch(c.pattern, c.miss)); + } + try testing.expect(gptq.regexMatch("abc", "abcdef")); // re.match anchors at the start, not the end + try testing.expect(!gptq.regexMatch("abc", "xabc")); + try testing.expect(gptq.regexMatch("a.c", "abc")); + try testing.expect(!gptq.regexMatch("a.c", "ac")); + try testing.expect(gptq.regexMatch("a\\.c", "a.c")); + try testing.expect(!gptq.regexMatch("a\\.c", "abc")); + try testing.expect(gptq.regexMatch("a*b", "aaab")); // '*' and '+' backtrack + try testing.expect(gptq.regexMatch("a*b", "b")); + try testing.expect(!gptq.regexMatch("a*b", "aaac")); + try testing.expect(gptq.regexMatch("a+b", "aaab")); + try testing.expect(!gptq.regexMatch("a+b", "b")); + try testing.expect(gptq.regexMatch("$", "")); + try testing.expect(!gptq.regexMatch("$", "x")); + try testing.expect(gptq.regexMatch(".*\\.48\\..*", "layers.48.x")); + try testing.expect(!gptq.regexMatch(".*\\.48\\..*", "layers.480.x")); +} + +test "gptq: an escape of an alphanumeric character is refused, as Python's re reads it as a class or an anchor" { + // Python's re matches model.layers.12.mlp.x here; read as a literal d it matches layers.d.mlp instead + try refuses( + \\"quant_method": "gptq", "bits": 4, "group_size": 128, "sym": true, "desc_act": false, "lm_head": true, "dynamic": {"+:.*lm_head$": {"bits": 4}, "-:.*layers\\.\\d+\\.mlp.*": {"bits": 4}} + , "quantization_config.dynamic -:.*layers\\.\\d+\\.mlp.*: outside this reader's matcher"); + try refuses( + \\"quant_method": "gptq", "bits": 4, "group_size": 128, "sym": true, "desc_act": false, "lm_head": true, "dynamic": {"+:.*lm_head$": {"bits": 4}, "-:.*\\w+.*": {"bits": 4}} + , "quantization_config.dynamic -:.*\\w+.*: outside this reader's matcher"); + try refuses( + \\"quant_method": "gptq", "bits": 4, "group_size": 128, "sym": true, "desc_act": false, "lm_head": true, "dynamic": {"+:.*lm_head$": {"bits": 4}, "-:.*\\s+\\b.*": {"bits": 4}} + , "quantization_config.dynamic -:.*\\s+\\b.*: outside this reader's matcher"); + // an escape of a non-alphanumeric character is the character itself, in Python's re and in this matcher + try testing.expect(gptq.regexMatch("a\\+b", "a+b")); + try testing.expect(!gptq.regexMatch("a\\+b", "aab")); + try testing.expect(gptq.regexMatch("a\\$", "a$")); + try testing.expect(gptq.regexMatch("a\\\\b", "a\\b")); + var why: Why = .{}; + var plus = (try gptq.admit(a, jsonOf( + \\"quant_method": "gptq", "bits": 4, "group_size": 128, "sym": true, "desc_act": false, "lm_head": true, "dynamic": {"+:.*lm_head$": {"bits": 4}, "-:a\\+b.*": {"bits": 4}} + ), &why)).?; + defer plus.deinit(); + try testing.expect(!plus.quantized("a+bzzz")); + try testing.expect(plus.quantized("aab")); +} + +/// `fields` as a config.json's quantization_config, so one field can be changed per case. +fn jsonOf(comptime fields: []const u8) []const u8 { + return "{\"quantization_config\": {" ++ fields ++ "}}"; +} + +/// `jsonOf(fields)` is refused as unsupported, its reason exactly `text`. +fn refuses(comptime fields: []const u8, text: []const u8) !void { + var why: Why = .{}; + try testing.expectError(error.UnsupportedQuantization, gptq.admit(a, jsonOf(fields), &why)); + try testing.expectEqualStrings(text, why.text()); +} + +/// The admitted fields: the fixture's shape, with the head rule alone in `dynamic`. +const ok = + \\"quant_method": "gptq", "bits": 4, "group_size": 128, "sym": true, "desc_act": false, "checkpoint_format": "gptq", + \\"lm_head": true, "dynamic": {"+:.*lm_head$": {"bits": 4}} +; + +test "gptq: a config outside the dialect is refused by its field or rule name" { + var why: Why = .{}; + var cfg = (try gptq.admit(a, jsonOf(ok), &why)).?; + cfg.deinit(); + try refuses( + \\"quant_method": "gptq", "bits": 8, "group_size": 128, "sym": true, "lm_head": true, "dynamic": {"+:.*lm_head$": {"bits": 4}} + , "quantization_config.bits: 8, expected 4"); + try refuses( + \\"quant_method": "gptq", "group_size": 128, "sym": true, "lm_head": true, "dynamic": {"+:.*lm_head$": {"bits": 4}} + , "quantization_config.bits: null, expected 4"); + try refuses( + \\"quant_method": "gptq", "bits": 4, "group_size": 64, "sym": true, "lm_head": true, "dynamic": {"+:.*lm_head$": {"bits": 4}} + , "quantization_config.group_size: 64, expected 128"); + try refuses( + \\"quant_method": "gptq", "bits": 4, "sym": true, "lm_head": true, "dynamic": {"+:.*lm_head$": {"bits": 4}} + , "quantization_config.group_size: null, expected 128"); + try refuses( + \\"quant_method": "gptq", "bits": 4, "group_size": 128, "sym": false, "lm_head": true, "dynamic": {"+:.*lm_head$": {"bits": 4}} + , "quantization_config.sym: false, expected true"); + try refuses( + \\"quant_method": "gptq", "bits": 4, "group_size": 128, "lm_head": true, "dynamic": {"+:.*lm_head$": {"bits": 4}} + , "quantization_config.sym: null, expected true"); + try refuses( + \\"quant_method": "gptq", "bits": 4, "group_size": 128, "sym": true, "desc_act": true, "lm_head": true, "dynamic": {"+:.*lm_head$": {"bits": 4}} + , "quantization_config.desc_act: true, this reader reads no act order"); + try refuses( + \\"quant_method": "gptq", "bits": 4, "group_size": 128, "sym": true, "desc_act": "false", "lm_head": true, "dynamic": {"+:.*lm_head$": {"bits": 4}} + , "quantization_config.desc_act: a string, expected a bool"); + try refuses( + \\"quant_method": "gptq", "bits": 4, "group_size": 128, "sym": true, "desc_act": null, "lm_head": true, "dynamic": {"+:.*lm_head$": {"bits": 4}} + , "quantization_config.desc_act: null, expected a bool"); + try refuses( + \\"quant_method": "gptq", "bits": 4, "group_size": 128, "sym": true, "checkpoint_format": "marlin", "lm_head": true, "dynamic": {"+:.*lm_head$": {"bits": 4}} + , "quantization_config.checkpoint_format: marlin, expected gptq"); + try refuses( + \\"quant_method": "gptq", "bits": 4, "group_size": 128, "sym": true, "checkpoint_format": "GPTQ", "lm_head": true, "dynamic": {"+:.*lm_head$": {"bits": 4}} + , "quantization_config.checkpoint_format: GPTQ, expected gptq"); + try refuses( + \\"quant_method": "gptq", "bits": 4, "group_size": 128, "sym": true, "checkpoint_format": 1, "lm_head": true, "dynamic": {"+:.*lm_head$": {"bits": 4}} + , "quantization_config.checkpoint_format: a number, expected gptq"); + try refuses( + \\"quant_method": "gptq", "bits": 4, "group_size": 128, "sym": true, "desc_act": false, "lm_head": false, "dynamic": {"-:.*linear_attn.*": {"bits": 4}} + , "quantization_config.lm_head: false, the rules do not store the head int4"); + try refuses( + \\"quant_method": "gptq", "bits": 4, "group_size": 128, "sym": true, "lm_head": true, "dynamic": {"-:.*lm_head$": {"bits": 4}} + , "quantization_config.lm_head: true, the rules do not store the head int4"); + try refuses( + \\"quant_method": "gptq", "bits": 4, "group_size": 128, "sym": true, "dynamic": {"-:.*linear_attn.*": {"bits": 4}} + , "quantization_config.lm_head: null, the rules do not store the head int4"); + try refuses( + \\"quant_method": "gptq", "bits": 4, "group_size": 128, "sym": true, "lm_head": true + , "quantization_config.dynamic: absent, this reader reads its rules"); + try refuses( + \\"quant_method": "gptq", "bits": 4, "group_size": 128, "sym": true, "lm_head": true, "dynamic": ["+:.*lm_head$"] + , "quantization_config.dynamic: not an object, this reader reads its rules"); + try refuses( + \\"quant_method": "gptq", "bits": 4, "group_size": 128, "sym": true, "lm_head": true, "dynamic": {"lm_head": {"bits": 4}} + , "quantization_config.dynamic lm_head: no +: or -: prefix"); + try refuses( + \\"quant_method": "gptq", "bits": 4, "group_size": 128, "sym": true, "lm_head": true, "dynamic": {"+:.*lm_head$": {"bits": 4}, "-:.*linear_attn(.*": {"bits": 4}} + , "quantization_config.dynamic -:.*linear_attn(.*: outside this reader's matcher"); + try refuses( + \\"quant_method": "gptq", "bits": 4, "group_size": 128, "sym": true, "lm_head": true, "dynamic": {"+:.*lm_head$": {"bits": 4}, "-:^model.*": {"bits": 4}} + , "quantization_config.dynamic -:^model.*: outside this reader's matcher"); + try refuses( + \\"quant_method": "gptq", "bits": 4, "group_size": 128, "sym": true, "lm_head": true, "dynamic": {"+:.*lm_head$": {"bits": 4}, "-:a**": {"bits": 4}} + , "quantization_config.dynamic -:a**: outside this reader's matcher"); + try refuses( + \\"quant_method": "gptq", "bits": 4, "group_size": 128, "sym": true, "lm_head": true, "dynamic": {"+:.*lm_head$": {"bits": 4}, "-:a$b": {"bits": 4}} + , "quantization_config.dynamic -:a$b: outside this reader's matcher"); + try refuses( + \\"quant_method": "gptq", "bits": 4, "group_size": 128, "sym": true, "lm_head": true, "dynamic": {"+:.*lm_head$": {"bits": 4}, "-:": {"bits": 4}} + , "quantization_config.dynamic -:: outside this reader's matcher"); + try refuses( + \\"quant_method": "gptq", "bits": 4, "group_size": 128, "sym": true, "lm_head": true, "dynamic": {"+:.*lm_head$": {"bits": 8}} + , "quantization_config.dynamic +:.*lm_head$: bits 8, expected 4"); + try refuses( + \\"quant_method": "gptq", "bits": 4, "group_size": 128, "sym": true, "lm_head": true, "dynamic": {"+:.*lm_head$": {"bits": 4, "group_size": 64}} + , "quantization_config.dynamic +:.*lm_head$: group_size 64, expected 128"); + try refuses( + \\"quant_method": "gptq", "bits": 4, "group_size": 128, "sym": true, "lm_head": true, "dynamic": {"+:.*lm_head$": 4} + , "quantization_config.dynamic +:.*lm_head$: not an object of bits"); +} + +test "gptq: a config that declares no gptq block is not this reader's, and the head rule may stand alone" { + var why: Why = .{}; + for ([_][]const u8{ + \\{} + , + \\{"quantization": {"group_size": 32, "bits": 4}} + , + \\{"quantization_config": {"quant_method": "modelopt", "quant_algo": "NVFP4"}} + , + \\{"quantization_config": {"quant_method": "exl3"}} + , + \\[1] + }) |json| { + const declared = try gptq.admit(a, json, &why); + try testing.expect(declared == null); + } + // the head is quantized by its rule alone, as the export may leave lm_head out of the config + var forced = (try gptq.admit(a, + \\{"quantization_config": {"quant_method": "gptq", "bits": 4, "group_size": 128, "sym": true, "lm_head": false, + \\ "dynamic": {"+:.*lm_head$": null}}} + , &why)).?; + defer forced.deinit(); + try testing.expect(forced.quantized("language_model.lm_head")); + // a rule set with no exclusions quantizes whatever it is asked about + var all = (try gptq.admit(a, + \\{"text_config": {"quantization_config": {"quant_method": "gptq", "bits": 4, "group_size": 128, "sym": true, + \\ "lm_head": true, "dynamic": {}}}} + , &why)).?; + defer all.deinit(); + try testing.expectEqual(@as(usize, 0), all.rules.len); + try testing.expect(all.quantized("model.language_model.layers.0.linear_attn.in_proj_qkv")); + // GPTQ spelled in another case is the same method + var upper = (try gptq.admit(a, jsonOf( + \\"quant_method": "GPTQ", "bits": 4, "group_size": 128, "sym": true, "lm_head": true, "dynamic": {"+:.*lm_head$": {"bits": 4}} + ), &why)).?; + upper.deinit(); +} + +test "gptq: the last rule matching a module decides, and no rule leaves it quantized" { + var why: Why = .{}; + var cfg = (try gptq.admit(a, + \\{"quantization_config": {"quant_method": "gptq", "bits": 4, "group_size": 128, "sym": true, "lm_head": true, + \\ "dynamic": {"-:.*experts.*": {"bits": 4}, "+:.*gate_proj$": {"bits": 4}}}} + , &why)).?; + defer cfg.deinit(); + try testing.expect(!cfg.quantized("m.experts.0.down_proj")); + try testing.expect(cfg.quantized("m.experts.0.gate_proj")); + var other = (try gptq.admit(a, + \\{"quantization_config": {"quant_method": "gptq", "bits": 4, "group_size": 128, "sym": true, "lm_head": true, + \\ "dynamic": {"+:.*gate_proj$": {"bits": 4}, "-:.*experts.*": {"bits": 4}}}} + , &why)).?; + defer other.deinit(); + try testing.expect(!other.quantized("m.experts.0.gate_proj")); + try testing.expect(!other.quantized("m.experts.0.up_proj")); + try testing.expect(other.quantized("m.layers.0.mlp.gate_proj")); +} + +/// `entries` read as `module` [n, k] fail with `err`, the refusal saying exactly `text`. +fn refusedTensor(entries: []const fixture.Entry, module: []const u8, n: usize, k: usize, err: anyerror, text: []const u8) !void { + var f: Folder = .{ .tmp = undefined }; + try f.open(entries); + defer f.close(); + var why: Why = .{}; + try testing.expectError(err, gptq.readWhy(&f.ck, module, n, k, &why)); + try testing.expectEqualStrings(text, why.text()); +} + +const one_shape = [_]usize{1}; +const one_byte = [_]u8{0}; + +/// `entries` in `buf` with tensor `i` replaced by `e`, or by an unrelated tensor when `e` is null. +fn edited(buf: *[7]fixture.Entry, entries: [6]fixture.Entry, i: usize, e: ?fixture.Entry) []const fixture.Entry { + @memcpy(buf[0..6], &entries); + buf[6] = .{ .name = "x.unrelated", .dtype = "U8", .shape = &one_shape, .bytes = &one_byte }; + buf[i] = e orelse buf[6]; + return buf[0..6]; +} + +test "gptq: every tensor it refuses is named, the zero point and act order included" { + var s: Synth = .{}; + try s.init(); + defer s.deinit(); + var f: Folder = .{ .tmp = undefined }; + try f.open(&s.entries); + defer f.close(); + _ = try gptq.read(&f.ck, expert, 8, 256); + _ = try gptq.read(&f.ck, head, 8, 128); + var buf: [7]fixture.Entry = undefined; + const E = error.UnexpectedTensor; + const Q = error.UnsupportedQuantization; + try refusedTensor(&s.entries, expert, 5, 256, E, expert ++ ": [n, k] of [5, 256] is not 4-bit groups of 128 in words of 8 codes"); + try refusedTensor(&s.entries, expert, 8, 192, E, expert ++ ": [n, k] of [8, 192] is not 4-bit groups of 128 in words of 8 codes"); + try refusedTensor(&s.entries, expert, 8, 128, E, expert ++ ".qweight: i32 { 32, 8 }, expected i32 { 16, 8 }"); + var wide = [_]usize{ 16, 16 }; + const qw_wide: fixture.Entry = .{ .name = s.entries[0].name, .dtype = "I32", .shape = &wide, .bytes = s.bytes[0] }; + try refusedTensor(edited(&buf, s.entries, 0, qw_wide), expert, 8, 256, E, expert ++ ".qweight: i32 { 16, 16 }, expected i32 { 32, 8 }"); + const qw_u8: fixture.Entry = .{ .name = s.entries[0].name, .dtype = "U8", .shape = &s.shapes[0], .bytes = s.bytes[0][0..256] }; + try refusedTensor(edited(&buf, s.entries, 0, qw_u8), expert, 8, 256, E, expert ++ ".qweight: u8 { 32, 8 }, expected i32 { 32, 8 }"); + var f32_scales: [64]u8 = @splat(0); + const sc_f32: fixture.Entry = .{ .name = s.entries[1].name, .dtype = "F32", .shape = &s.shapes[1], .bytes = &f32_scales }; + try refusedTensor(edited(&buf, s.entries, 1, sc_f32), expert, 8, 256, E, expert ++ ".scales: f32 { 2, 8 }, expected f16 { 2, 8 }"); + const sc_bf16: fixture.Entry = .{ .name = s.entries[1].name, .dtype = "BF16", .shape = &s.shapes[1], .bytes = s.bytes[1] }; + try refusedTensor(edited(&buf, s.entries, 1, sc_bf16), expert, 8, 256, E, expert ++ ".scales: bf16 { 2, 8 }, expected f16 { 2, 8 }"); + var flipped = [_]usize{ 8, 2 }; + const sc_flipped: fixture.Entry = .{ .name = s.entries[1].name, .dtype = "F16", .shape = &flipped, .bytes = s.bytes[1] }; + try refusedTensor(edited(&buf, s.entries, 1, sc_flipped), expert, 8, 256, E, expert ++ ".scales: f16 { 8, 2 }, expected f16 { 2, 8 }"); + var half = [_]usize{ 2, 2 }; + var wide_zeroes: [16]u8 = @splat(0); + const qz_wide: fixture.Entry = .{ .name = s.entries[2].name, .dtype = "I32", .shape = &half, .bytes = &wide_zeroes }; + try refusedTensor(edited(&buf, s.entries, 2, qz_wide), expert, 8, 256, E, expert ++ ".qzeros: i32 { 2, 2 }, expected i32 { 2, 1 }"); + const bad = try a.dupe(u8, s.bytes[5]); + defer a.free(bad); + bad[3] = 0x87; + const qz_bad: fixture.Entry = .{ .name = s.entries[5].name, .dtype = "I32", .shape = &s.shapes[5], .bytes = bad }; + try refusedTensor(edited(&buf, s.entries, 5, qz_bad), head, 8, 128, Q, head ++ ".qzeros: byte 3 is 0x87, a symmetric weight's every nibble is 7"); + bad[3] = 0x78; + try refusedTensor(edited(&buf, s.entries, 5, qz_bad), head, 8, 128, Q, head ++ ".qzeros: byte 3 is 0x78, a symmetric weight's every nibble is 7"); + bad[3] = 0x77; + bad[0] = 0x00; + try refusedTensor(edited(&buf, s.entries, 5, qz_bad), head, 8, 128, Q, head ++ ".qzeros: byte 0 is 0x00, a symmetric weight's every nibble is 7"); + // a store that hands back fewer bytes than its header declares (checkpoint_direct's copies) is refused by name + var copies: std.StringHashMapUnmanaged([]const u8) = .empty; + defer copies.deinit(a); + try copies.put(a, s.entries[0].name, s.bytes[0][0..1020]); + var short: Folder = .{ .tmp = undefined }; + try short.open(&s.entries); + defer short.close(); + short.ck.copies = &copies; + var why: Why = .{}; + try testing.expectError(E, gptq.readWhy(&short.ck, expert, 8, 256, &why)); + try testing.expectEqualStrings(expert ++ ".qweight: 1020 bytes, i32 { 32, 8 } needs 1024", why.text()); + try refusedTensor(edited(&buf, s.entries, 2, null), expert, 8, 256, error.MissingTensor, expert ++ ": no qzeros, a GPTQ weight stores it"); + try refusedTensor(edited(&buf, s.entries, 3, null), head, 8, 128, error.MissingTensor, head ++ ": no qweight, a GPTQ weight stores it"); + var order = [_]usize{128}; + var gbytes: [128 * 4]u8 = @splat(0); + var with_g: [7]fixture.Entry = undefined; + @memcpy(with_g[0..6], &s.entries); + with_g[6] = .{ .name = head ++ ".g_idx", .dtype = "I32", .shape = &order, .bytes = &gbytes }; + try refusedTensor(&with_g, head, 8, 128, E, head ++ ".g_idx: i32 { 128 }, act order is not read"); + // an empty g_idx is what a desc_act false export leaves behind: it is read and kept out of the way + var none = [_]usize{0}; + with_g[6] = .{ .name = head ++ ".g_idx", .dtype = "I32", .shape = &none, .bytes = &.{} }; + var g: Folder = .{ .tmp = undefined }; + try g.open(&with_g); + defer g.close(); + const hd = try gptq.read(&g.ck, head, 8, 128); + _ = try gptq.read(&g.ck, expert, 8, 256); + try testing.expectEqual(@as(u64, @bitCast(@as(f64, -8.0))), @as(u64, @bitCast(gptq.weight(hd, 0, 0)))); + try testing.expectEqual(@as(usize, 0), g.ck.unused()); +} + +test "gptq: the zero point check reads both nibbles of every word" { + try testing.expectEqual(@as(?usize, null), gptq.zerosOff(&.{ 0x77, 0x77, 0x77, 0x77 })); + try testing.expectEqual(@as(?usize, null), gptq.zerosOff(&.{})); + try testing.expectEqual(@as(?usize, null), gptq.zerosOff(&.{ 0x77, 0x77 })); + try testing.expectEqual(@as(?usize, 0), gptq.zerosOff(&.{ 0x78, 0x77 })); + try testing.expectEqual(@as(?usize, 1), gptq.zerosOff(&.{ 0x77, 0x87 })); + try testing.expectEqual(@as(?usize, 2), gptq.zerosOff(&.{ 0x77, 0x77, 0x00 })); + try testing.expectEqual(@as(?usize, 1), gptq.zerosOff(&.{ 0x77, 0x7F })); +} diff --git a/zig/src/core/quant/quant.zig b/zig/src/core/quant/quant.zig index 3c03930cf01..1a6b47234b3 100644 --- a/zig/src/core/quant/quant.zig +++ b/zig/src/core/quant/quant.zig @@ -15,6 +15,8 @@ pub const experts = @import("experts.zig"); /// FP8 and NVFP4 values and fp64 references; host only (no Format: their kernels' layouts are each backend's). pub const fp8 = @import("fp8.zig"); pub const nvfp4 = @import("nvfp4.zig"); +/// AutoGPTQ v1 weights (4-bit symmetric groups of 128) and their fp64 reference; host only, as `fp8`. +pub const gptq = @import("gptq.zig"); pub const widen = @import("widen.zig"); const Allocator = std.mem.Allocator; diff --git a/zig/src/core/root.zig b/zig/src/core/root.zig index a34a9aa8437..caac0deebd9 100644 --- a/zig/src/core/root.zig +++ b/zig/src/core/root.zig @@ -87,6 +87,7 @@ test { _ = shard_edit; _ = lora_merge; _ = quant; + _ = quant.gptq; _ = nvfp4_rows; _ = route_ref; _ = nvfp4_csf; diff --git a/zig/src/core/rows_all_test.zig b/zig/src/core/rows_all_test.zig index a8912ea3714..916b32fa871 100644 --- a/zig/src/core/rows_all_test.zig +++ b/zig/src/core/rows_all_test.zig @@ -7,6 +7,7 @@ test { _ = @import("rows_write.zig").io; _ = @import("rows_test.zig"); _ = @import("rows_spill_test.zig"); + _ = @import("rows_isolation_test.zig"); _ = @import("rows_async_test.zig"); _ = @import("rows_close_test.zig"); _ = @import("rows_stage_test.zig"); diff --git a/zig/src/core/rows_isolation_test.zig b/zig/src/core/rows_isolation_test.zig new file mode 100644 index 00000000000..4bcea0e2e91 --- /dev/null +++ b/zig/src/core/rows_isolation_test.zig @@ -0,0 +1,151 @@ +//! KV isolation across sessions: a spilled and dropped state, a retired page, and a disjoint session admitted between. +const std = @import("std"); +const platform = @import("sys"); +const pc = @import("prompt_cache.zig"); +const rows = @import("rows_store.zig"); +const Fake = @import("rows_fake.zig").Fake; +const fresh = @import("rows_fake.zig").fresh; +const Pooled = @import("prompt_cache_fake.zig").Fake; +const pooledFresh = @import("prompt_cache_test.zig").fresh; +const rmTree = @import("prompt_imprint_test.zig").rmTree; +const Allocator = std.mem.Allocator; + +const rules: pc.Rules = .{ .lookahead = 1, .min_prompt = 0, .min_gap = 1 }; + +fn root(buf: []u8, tag: []const u8) []const u8 { + return std.fmt.bufPrint(buf, "/tmp/tf-isolation-{s}-{d}", .{ tag, platform.c.getpid() }) catch unreachable; +} + +/// Session `c`'s prompt of `n` tokens: no token is shared with another session's, and every length is the same. +fn session(a: Allocator, c: u32, n: u32) ![]u32 { + const out = try a.alloc(u32, n); + for (out, 0..) |*t, i| t.* = @intCast(50_000 + c * 10_000 + i); + return out; +} + +/// The session's next turn: its first 601 tokens, then two new ones. +fn next(a: Allocator, p: []const u32) ![]u32 { + return std.mem.concat(a, u32, &.{ p[0..601], &[_]u32{ 1, 2 } }); +} + +/// One request: its plan, then a pass from it (`f.restored_ok` holds whether every restore equalled a fresh pass). +fn request(a: Allocator, s: *pc.Store, f: *Fake, p: []const u32, history: u32) !struct { from: u32, sum: u64 } { + f.prompt = p; + const plan = try s.begin(a, p, history, &.{}, f.starts, null, f.spans); + return .{ .from = plan.from, .sum = f.pass(s, plan) }; +} + +/// A RAM budget that holds one state of `at` tokens, not two. +fn one(f: *Fake, at: u32) u64 { + return Fake.snapshots(f).vtable.bytes(f, at) + 1000; +} + +fn blockFiles(dir: [:0]const u8) usize { + const d = platform.c.opendir(dir) orelse return 0; + defer _ = platform.c.closedir(d); + var n: usize = 0; + while (platform.c.readdir(d)) |ent| n += @intFromBool(std.mem.endsWith(u8, std.mem.sliceTo(&ent.name, 0), ".blk")); + return n; +} + +test "rows isolation: B admitted after A is spilled and dropped never resumes A's rows; A resumes exactly its own" { + const gpa = std.testing.allocator; + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const a = arena.allocator(); + var buf: [128]u8 = undefined; + const dir = root(&buf, "spill"); + defer rmTree(dir); + var f: Fake = .{ .gpa = gpa }; + var s = pc.Store.init(gpa, f.snapshots(), rules, one(&f, 600)); + const r = try rows.attach(gpa, &s, .{ .sync_writes = true, .root = dir, .identity = 7, .cap = 1 << 34, .floor = 0, .daily = 1 << 40, .lookahead = 1, .spill = .evicted }); + defer r.deinit(); + defer s.deinit(); + // A and B share no token, and keep states at the same positions + const sa = try session(a, 1, 700); + const sb = try session(a, 2, 700); + _ = try request(a, &s, &f, sa, 600); + const b1 = try request(a, &s, &f, sb, 600); // A leaves RAM for disk + try std.testing.expectEqual(@as(usize, 1), r.states.items.len); + try std.testing.expectEqual(@as(usize, 1), s.entries.items.len); + try std.testing.expectEqualSlices(u32, sb[0..600], s.entries.items[0].tokens[0..600]); + // (1) B's first turn and its next resume nothing of A's: B prefills, then resumes its own RAM state + try std.testing.expectEqual(@as(u32, 0), b1.from); + try std.testing.expectEqual(fresh(sb), b1.sum); + const b_next = try next(a, sb); + const b2 = try request(a, &s, &f, b_next, 602); + try std.testing.expectEqual(@as(u32, 600), b2.from); + try std.testing.expect(f.restored_ok); + try std.testing.expectEqual(fresh(b_next), b2.sum); + try std.testing.expectEqual(@as(u64, 0), r.counts.reads); // A's spilled file was not read for B + // (2) A's next turn resumes A's spilled state, equal to a fresh pass of A's own tokens + const a_next = try next(a, sa); + const a2 = try request(a, &s, &f, a_next, 602); + try std.testing.expectEqual(@as(u32, 600), a2.from); + try std.testing.expect(f.restored_ok); + try std.testing.expectEqual(fresh(a_next), a2.sum); + try std.testing.expectEqual(@as(u64, 1), r.counts.reads); +} + +test "rows isolation: after A's spilled state and blocks are retired and B's are written, A's lookup takes nothing" { + const gpa = std.testing.allocator; + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const a = arena.allocator(); + var buf: [128]u8 = undefined; + const dir = root(&buf, "retire"); + defer rmTree(dir); + var f: Fake = .{ .gpa = gpa }; + var s = pc.Store.init(gpa, f.snapshots(), rules, one(&f, 600)); + const r = try rows.attach(gpa, &s, .{ .sync_writes = true, .root = dir, .identity = 7, .cap = 1 << 34, .floor = 0, .daily = 1 << 40, .lookahead = 1, .spill = .evicted }); + defer r.deinit(); + defer s.deinit(); + const sa = try session(a, 1, 700); + const sb = try session(a, 2, 700); + _ = try request(a, &s, &f, sa, 600); + _ = try request(a, &s, &f, sb, 600); // A on disk + try std.testing.expectEqual(@as(usize, 1), r.states.items.len); + try std.testing.expect(blockFiles(r.dir) > 0); + r.remove(0); // A's state retired: its file and blocks go + try std.testing.expectEqual(@as(usize, 0), r.states.items.len); + try std.testing.expectEqual(@as(usize, 0), blockFiles(r.dir)); + _ = try request(a, &s, &f, try session(a, 3, 700), 600); // B's state takes the disk A's left + try std.testing.expectEqual(@as(usize, 1), r.states.items.len); + try std.testing.expect(blockFiles(r.dir) > 0); + // (3) A's prefix matches no state's tokens: nothing is read or restored, and A prefills its own tokens + const a_next = try next(a, sa); + try std.testing.expectEqual(@as(?usize, null), r.best(a_next, &.{}, &.{}, 0)); + const reads = r.counts.reads; + const got = try request(a, &s, &f, a_next, 602); + try std.testing.expectEqual(@as(u32, 0), got.from); + try std.testing.expectEqual(reads, r.counts.reads); + try std.testing.expect(f.restored_ok); + try std.testing.expectEqual(fresh(a_next), got.sum); +} + +test "rows isolation: storage A's dropped state left spare and B's save reused is never resumed for A's prefix" { + const gpa = std.testing.allocator; + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const a = arena.allocator(); + var f: Pooled = .{ .gpa = gpa }; + var s = pc.Store.init(gpa, f.pooled(), .{ .min_prompt = 0 }, 1 << 20); + defer s.deinit(); + const sa = [_]u32{ 11, 12, 13, 14, 15, 16, 17, 18 }; + const sb = [_]u32{ 21, 22, 23, 24, 25, 26, 27, 28 }; + f.at, f.sum = .{ 4, pooledFresh(sa[0..4]) }; + try std.testing.expect(s.keep(&sa, 4, null, &.{}, &.{})); + s.remove(0); // A's page retired: its storage stays spare + try std.testing.expectEqual(@as(u64, 94), s.spare()); + f.at, f.sum = .{ 4, pooledFresh(sb[0..4]) }; + try std.testing.expect(s.keep(&sb, 4, null, &.{}, &.{})); // B's state reuses that page + try std.testing.expectEqual(@as(u64, 0), s.spare()); + // (3) the lookup for A's prefix compares tokens first: B's entry at the same position is not restored + const l = try s.lookup(a, &sa, 4, &.{}, &.{}, &.{}); + try std.testing.expect(l.entry == null); + f.at, f.sum = .{ 999, 0 }; // a restore would overwrite these + const plan = try s.begin(a, &sa, 4, &.{}, &.{}, null, &.{}); + try std.testing.expectEqual(@as(u32, 0), plan.from); + try std.testing.expectEqual(@as(u32, 999), f.at); + try std.testing.expectEqual(pooledFresh(&sa), f.pass(&s, &sa, plan)); +} diff --git a/zig/src/core/tree_round_gpu.zig b/zig/src/core/tree_round_gpu.zig index 17fa6eede22..74bd5f5037c 100644 --- a/zig/src/core/tree_round_gpu.zig +++ b/zig/src/core/tree_round_gpu.zig @@ -4,19 +4,60 @@ const mtl = @import("metal"); pub const contract = @import("tree_round"); const source = @import("tree_round_sources").text; pub const Ref = struct { buf: mtl.Buffer, off: usize = 0 }; +/// `Ops.argmaxChunks` takes a row's argmax over chunks of its vocabulary, on every core; off, it is `argmax` (checks). +pub var chunked_picks = true; +const chunk_tokens = 1024; +const max_chunks = 512; +const chunk_best_bytes = 12; pub const Ops = struct { argmax_pipe: mtl.Pipeline, match_pipe: mtl.Pipeline, + chunks_pipe: mtl.Pipeline, + rows_pipe: mtl.Pipeline, + chunk_best: mtl.Buffer, pub fn init(device: mtl.Device) !Ops { const lib = try mtl.Library.fromSource(device, source, mtl.CompileOptions.mlx()); defer lib.deinit(); const argmax_pipe = try mtl.Pipeline.init(device, lib, "tf_round_bf16_argmax", false); errdefer argmax_pipe.deinit(); - return .{ .argmax_pipe = argmax_pipe, .match_pipe = try mtl.Pipeline.init(device, lib, "tf_tree_round_match", false) }; + const match_pipe = try mtl.Pipeline.init(device, lib, "tf_tree_round_match", false); + errdefer match_pipe.deinit(); + const chunks_pipe = try mtl.Pipeline.init(device, lib, "tf_round_pick_chunks", false); + errdefer chunks_pipe.deinit(); + const rows_pipe = try mtl.Pipeline.init(device, lib, "tf_round_pick_rows", false); + errdefer rows_pipe.deinit(); + const bytes = contract.max_rows * max_chunks * chunk_best_bytes; + const chunk_best = try device.buffer(bytes, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); + return .{ .argmax_pipe = argmax_pipe, .match_pipe = match_pipe, .chunks_pipe = chunks_pipe, .rows_pipe = rows_pipe, .chunk_best = chunk_best }; } pub fn deinit(ops: Ops) void { ops.argmax_pipe.deinit(); ops.match_pipe.deinit(); + ops.chunks_pipe.deinit(); + ops.rows_pipe.deinit(); + ops.chunk_best.deinit(); + } + /// The same picks as `argmax`, through a scratch buffer: the caller keeps one call at a time on an encoder. + pub fn argmaxChunks(ops: Ops, e: mtl.ComputeEncoder, logits: Ref, out: Ref, p: contract.Argmax) !void { + const chunks = (p.vocab + chunk_tokens - 1) / chunk_tokens; + if (!chunked_picks or chunks > max_chunks or chunks < 8) return ops.argmax(e, logits, out, p); + try contract.checkArgmax(p); + const cells = try std.math.add(usize, try std.math.mul(usize, p.rows - 1, p.stride), p.vocab); + const bytes = try std.math.mul(usize, cells, 2); + try check(logits, bytes, 2); + try check(out, @as(usize, p.rows) * @sizeOf(contract.Pick), 4); + try distinct(out, @as(usize, p.rows) * @sizeOf(contract.Pick), logits, bytes); + e.setPipeline(ops.chunks_pipe); + e.setBuffer(logits.buf, logits.off, 0); + e.setBuffer(ops.chunk_best, 0, 1); + e.setValue(p, 2); + e.dispatchGroups(mtl.Size.of(chunks, p.rows, 1), mtl.Size.of(32, 1, 1)); + e.barrier(); + e.setPipeline(ops.rows_pipe); + e.setBuffer(ops.chunk_best, 0, 0); + e.setBuffer(out.buf, out.off, 1); + e.setValue(p, 2); + e.dispatchGroups(mtl.Size.of(p.rows, 1, 1), mtl.Size.of(32, 1, 1)); } pub fn argmax(ops: Ops, e: mtl.ComputeEncoder, logits: Ref, picks: Ref, p: contract.Argmax) !void { try contract.checkArgmax(p); diff --git a/zig/src/core/tree_slots.zig b/zig/src/core/tree_slots.zig index 260fb2a61b4..34fd2fbc9cb 100644 --- a/zig/src/core/tree_slots.zig +++ b/zig/src/core/tree_slots.zig @@ -21,6 +21,25 @@ pub fn build(gpa: std.mem.Allocator, parents: []const i32, steps: []Step, first: return planner.peak; } +/// A schedule as flow words: row, then slots to restore and save into plus one, 0 for none; false for a forest. +pub fn flows(steps: []const Step, words: []u32) bool { + for (steps, words, 0..) |step, *word, at| { + if ((at > 0 and step.read_slot < 0) or step.row > 0xffff) return false; + const continues = at == 0 or step.read_slot == steps[at - 1].write_slot; + const restore: u32 = if (continues) 0 else @intCast(step.read_slot + 1); + var save: u32 = 0; + for (steps[at + 1 ..], at + 1..) |later, j| { + if (j > at + 1 and later.read_slot == step.write_slot) { + save = @intCast(step.write_slot + 1); + break; + } + if (later.write_slot == step.write_slot) break; + } + word.* = step.row | (restore << 16) | (save << 24); + } + return true; +} + const Builder = struct { parents: []const i32, sizes: []const usize, @@ -92,6 +111,41 @@ fn rowsOf(steps: anytype) [steps.len]u32 { return rows; } +test "flow words compute every row from the same parent as the slot schedule" { + var random: u64 = 4099; + for ([_]usize{ 2, 5, 16, 33, 64 }) |width| { + var parents: [64]i32 = undefined; + var steps: [64]Step = undefined; + var words: [64]u32 = undefined; + var expected: [64]u64 = undefined; + for (0..32) |_| { + for (parents[0..width], 0..) |*parent, row| { + random = random *% 6364136223846793005 +% 1442695040888963407; + parent.* = if (row == 0) -1 else @intCast(random % row); + const value = if (parent.* < 0) @as(u64, 23) else expected[@intCast(parent.*)]; + expected[row] = value *% 65537 +% row +% 1; + } + _ = try build(std.testing.allocator, parents[0..width], steps[0..width], 7, 16); + try std.testing.expect(flows(steps[0..width], words[0..width])); + var kept: [max_slots]u64 = @splat(0); + var state: u64 = 23; + for (words[0..width]) |word| { + const restore = (word >> 16) & 0xff; + if (restore != 0) state = kept[restore - 1]; + const row = (word & 0xffff) - 7; + state = state *% 65537 +% row +% 1; + try std.testing.expectEqual(expected[row], state); + if (word >> 24 != 0) kept[(word >> 24) - 1] = state; + } + } + } + const forest = [_]i32{ -1, 0, -1 }; + var steps: [3]Step = undefined; + var words: [3]u32 = undefined; + _ = try build(std.testing.allocator, &forest, &steps, 0, 16); + try std.testing.expect(!flows(&steps, &words)); +} + test "long chains need one slot and stars need two independent of depth or width" { var parents: [512]i32 = undefined; var steps: [parents.len]Step = undefined; diff --git a/zig/src/cuda/exl3_experts.zig b/zig/src/cuda/exl3_experts.zig index 005e007fd2d..b907b3a3044 100644 --- a/zig/src/cuda/exl3_experts.zig +++ b/zig/src/cuda/exl3_experts.zig @@ -5,6 +5,7 @@ const module = @import("module.zig"); const launch_ = @import("launch.zig"); const stream_ = @import("stream.zig"); const kernels = @import("kernels.zig"); +const grouped = @import("grouped.zig"); const exl3 = @import("exl3.zig"); const Driver = driver.Driver; const Module = module.Module; @@ -41,6 +42,12 @@ pub const Layer = struct { alpha: f32 = 0, // SwiGLU-OAI's sigmoid scale (act_mode 2) }; +/// The item plan a decode window takes: the family's Router and the plan buffer the caller holds. +pub const Items = struct { + router: *const grouped.Router, + plan: grouped.Plan, +}; + /// What one projection launches (experts.py default_config): the 8-tile 4-warp K splits, shape-fixed; n % 128 required. pub fn plan(k: usize, n: usize, gateup: bool) !u32 { const cands = [_]usize{ if (gateup) 4 else 1, 2, 1 }; @@ -66,12 +73,21 @@ pub const Scratch = struct { /// The byte size of the scratch buffers for a layer and row capacity, or error.TileNotBuilt when plan() fails. pub fn scratchBytes(l: Layer, rows: usize, slots: usize) !usize { + return layoutBytes(l, rows, slots, l.dims * 4); +} + +/// The decode item plan's scratch: scratchBytes() without y, which the down epilogue writes into `ey` instead. +pub fn fusedBytes(l: Layer, rows: usize, slots: usize) !usize { + return layoutBytes(l, rows, slots, 0); +} + +fn layoutBytes(l: Layer, rows: usize, slots: usize, y_pair: usize) !usize { const g_sk = try plan(l.dims, l.width, true); const d_sk = try plan(l.width, l.dims, false); const p = rows * slots; const maxu = @min(p, l.experts); return align256(p * l.dims * 2) + align256(p * l.dims * 2) + align256(p * l.width * 2) + - align256(@max(2 * g_sk * l.width, d_sk * l.dims) * p * 4) + align256(p * l.dims * 4) + + align256(@max(2 * g_sk * l.width, d_sk * l.dims) * p * 4) + align256(p * y_pair) + align256(maxu * 4) + 256 + align256(maxu * rows * 4); } @@ -81,6 +97,17 @@ fn align256(n: usize) usize { /// The pointers into one allocation of scratchBytes(), or error.TileNotBuilt when plan() fails. pub fn scratch(base: u64, l: Layer, rows: usize, slots: usize) !Scratch { + return carve(base, l, rows, slots, l.dims * 4); +} + +/// The pointers into one allocation of fusedBytes(); y is 0 (the down epilogue writes the caller's `ey` rows). +pub fn fusedScratch(base: u64, l: Layer, rows: usize, slots: usize) !Scratch { + var sc = try carve(base, l, rows, slots, 0); + sc.y = 0; + return sc; +} + +fn carve(base: u64, l: Layer, rows: usize, slots: usize, y_pair: usize) !Scratch { const p = rows * slots; const g_sk = try plan(l.dims, l.width, true); const d_sk = try plan(l.width, l.dims, false); @@ -97,7 +124,7 @@ pub fn scratch(base: u64, l: Layer, rows: usize, slots: usize) !Scratch { const xu = take(&at, p * l.dims * 2); const xd = take(&at, p * l.width * 2); const z = take(&at, @max(2 * g_sk * l.width, d_sk * l.dims) * p * 4); - const y = take(&at, p * l.dims * 4); + const y = take(&at, p * y_pair); const ids = take(&at, maxu * 4); const count = take(&at, 4); const members = take(&at, maxu * rows * 4); @@ -156,6 +183,11 @@ pub const Experts = struct { /// The routed experts of `rows` rows: group, rotate in, grouped gate/up, SwiGLU, grouped down, wts-weighted sum. pub fn run(e: *const Experts, s: Stream, l: Layer, x: u64, x_stride: usize, x_dtype: DType, pick: u64, wts: u64, rows: usize, out: u64, sc: Scratch) !void { + try e.runWith(s, l, x, x_stride, x_dtype, pick, wts, rows, out, sc, 0, null); + } + + /// run() on a decode window's item plan (`it`): the grouped kernels in standard mode, the slot rows in `ey`. + pub fn runWith(e: *const Experts, s: Stream, l: Layer, x: u64, x_stride: usize, x_dtype: DType, pick: u64, wts: u64, rows: usize, out: u64, sc: Scratch, ey: u64, it: ?Items) !void { const d = l.dims; const w = l.width; const slots = sc.slots; @@ -173,17 +205,32 @@ pub const Experts = struct { return @intCast(v); } }.f; + // A decode window's item plan: the picks grouped into 16-pair items, the grouped kernels in standard mode. + const items = it != null; // one codebook a launch, a plan, and ey to write the slot rows into: nothing else + if (items and (l.codebook != .mcg or wts != 0 or out != 0 or ey == 0 or it.?.plan.members == 0 or it.?.plan.items == 0 or it.?.plan.counts == 0)) return error.TileNotBuilt; + const nx: usize = if (items) grouped.maxItems(p, l.experts + 1, 16) else maxu; // grid x and nexp_max + const mtu: usize = if (items) 1 else mt; // member tiles a program (a 16-pair item, or ceil(rows/16)) + const uids = if (items) it.?.plan.items else sc.ids; + const ucount = if (items) it.?.plan.counts else sc.count; + const members = if (items) it.?.plan.members else sc.members; + const maxm_a: i32 = if (items) 16 else i32d(rows); + const std_a: i32 = if (items) 1 else 0; + const skip_a: i32 = if (items) i32d(l.experts) else -1; - var a: launch_.Args = .{}; - a.add(pick); - a.add(sc.ids); - a.add(sc.count); - a.add(sc.members); - a.add(i32d(rows)); - a.add(i32d(slots)); - a.add(i32d(l.experts)); - a.add(i32d(rows)); - try launch_.launch(e.group, .{ .grid = .{ .x = 1, .y = 1, .z = 1 }, .block = .{ .x = 1024, .y = 1, .z = 1 }, .shared = @intCast(rows * slots * 4) }, s, &a); + if (items) { + try it.?.router.route(s, pick, p, l.experts + 1, 16, it.?.plan); + } else { + var a: launch_.Args = .{}; + a.add(pick); + a.add(sc.ids); + a.add(sc.count); + a.add(sc.members); + a.add(i32d(rows)); + a.add(i32d(slots)); + a.add(i32d(l.experts)); + a.add(i32d(rows)); + try launch_.launch(e.group, .{ .grid = .{ .x = 1, .y = 1, .z = 1 }, .block = .{ .x = 1024, .y = 1, .z = 1 }, .shared = @intCast(rows * slots * 4) }, s, &a); + } var r: launch_.Args = .{}; r.add(x); @@ -206,22 +253,22 @@ pub const Experts = struct { g.add(l.up); g.add(l.gate_k2); g.add(l.up_k2); - g.add(sc.ids); - g.add(sc.count); - g.add(sc.members); + g.add(uids); + g.add(ucount); + g.add(members); g.add(sc.z); g.add(i32d(d)); g.add(i32d(w)); g.add(i32d(p)); g.add(i32d(g_sk)); - g.add(i32d(rows)); + g.add(maxm_a); g.add(i32d(slots)); - g.add(i32d(maxu)); + g.add(i32d(nx)); g.add(@as(i32, 2)); g.add(i32d(l.gu_stride)); - g.add(@as(i32, 0)); - g.add(@as(i32, -1)); - try launch_.launch(e.grouped[@backingInt(l.codebook)], .{ .grid = .{ .x = @intCast(maxu), .y = @intCast(w / 128), .z = @intCast(2 * g_sk * mt) }, .block = .{ .x = 128, .y = 1, .z = 1 } }, s, &g); + g.add(std_a); + g.add(skip_a); + try launch_.launch(e.grouped[@backingInt(l.codebook)], .{ .grid = .{ .x = @intCast(nx), .y = @intCast(w / 128), .z = @intCast(2 * g_sk * mtu) }, .block = .{ .x = 128, .y = 1, .z = 1 } }, s, &g); var ep: launch_.Args = .{}; ep.add(sc.z); @@ -245,28 +292,28 @@ pub const Experts = struct { dn.add(l.down); dn.add(l.down_k2); dn.add(l.down_k2); - dn.add(sc.ids); - dn.add(sc.count); - dn.add(sc.members); + dn.add(uids); + dn.add(ucount); + dn.add(members); dn.add(sc.z); dn.add(i32d(w)); dn.add(i32d(d)); dn.add(i32d(p)); dn.add(i32d(d_sk)); - dn.add(i32d(rows)); + dn.add(maxm_a); dn.add(i32d(slots)); - dn.add(i32d(maxu)); + dn.add(i32d(nx)); dn.add(@as(i32, 1)); dn.add(@as(i32, 0)); - dn.add(@as(i32, 0)); - dn.add(@as(i32, -1)); - try launch_.launch(e.grouped[@backingInt(l.codebook)], .{ .grid = .{ .x = @intCast(maxu), .y = @intCast(d / 128), .z = @intCast(d_sk * mt) }, .block = .{ .x = 128, .y = 1, .z = 1 } }, s, &dn); + dn.add(std_a); + dn.add(skip_a); + try launch_.launch(e.grouped[@backingInt(l.codebook)], .{ .grid = .{ .x = @intCast(nx), .y = @intCast(d / 128), .z = @intCast(d_sk * mtu) }, .block = .{ .x = 128, .y = 1, .z = 1 } }, s, &dn); var cb: launch_.Args = .{}; cb.add(sc.z); cb.add(pick); cb.add(l.svh_d); - cb.add(sc.y); + cb.add(if (items) ey else sc.y); // items: write ey's routed slot rows in place (no copy back) cb.add(wts); cb.add(out); cb.add(i32d(p)); diff --git a/zig/src/cuda/nccl.zig b/zig/src/cuda/nccl.zig index c1248b72d71..f362f24d692 100644 --- a/zig/src/cuda/nccl.zig +++ b/zig/src/cuda/nccl.zig @@ -44,7 +44,7 @@ pub const Config = extern struct { graph_stream_ordering: c_int = std.math.minInt(c_int), }; -pub const Error = platform.optional_libraries.Failure || error{ LibraryUnavailable, MissingSymbol, NcclFailed, NcclVersion }; +pub const Error = platform.optional_libraries.Failure || platform.environment.Error || error{ LibraryUnavailable, MissingSymbol, NcclFailed, NcclVersion }; pub const in_progress: Result = 7; // ncclInProgress: a non-blocking communicator's call is still running @@ -76,8 +76,17 @@ pub const Library = struct { lib: platform.DynLib, api: Api, + /// TF_NCCL_LIB's value as the library to open: a path is kept as written; unset, empty and blank keep libnccl.so.2. + pub fn pathFrom(raw: ?[]const u8) platform.environment.Error![]const u8 { + return try platform.environment.path("TF_NCCL_LIB", raw) orelse "libnccl.so.2"; + } + + fn configuredPath() platform.environment.Error![]const u8 { + return pathFrom(platform.environment.Process.get(.{}, "TF_NCCL_LIB")); + } + pub fn open() Error!Library { - return openPath("libnccl.so.2"); + return openPath(try configuredPath()); } pub fn openPath(path: []const u8) Error!Library { @@ -145,6 +154,29 @@ pub const Library = struct { } }; +test "NCCL library: TF_NCCL_LIB overrides the default; unset and empty keep it" { + const name = "TF_NCCL_LIB"; + const saved = if (platform.getenv(name)) |v| try std.testing.allocator.dupeSentinel(u8, v, 0) else null; + defer if (saved) |v| { + _ = platform.env.setenv(name, v, 1); + std.testing.allocator.free(v); + } else { + _ = platform.env.unsetenv(name); + }; + try std.testing.expectEqual(@as(c_int, 0), platform.env.unsetenv(name)); + try std.testing.expectEqualStrings("libnccl.so.2", try Library.configuredPath()); + try std.testing.expectEqual(@as(c_int, 0), platform.env.setenv(name, "/fixture/nccl/libnccl.so.2", 1)); + try std.testing.expectEqualStrings("/fixture/nccl/libnccl.so.2", try Library.configuredPath()); + try std.testing.expectEqual(@as(c_int, 0), platform.env.setenv(name, " ./nccl/libnccl.so.2 ", 1)); + try std.testing.expectEqualStrings(" ./nccl/libnccl.so.2 ", try Library.configuredPath()); + try std.testing.expectEqual(@as(c_int, 0), platform.env.setenv(name, "", 1)); + try std.testing.expectEqualStrings("libnccl.so.2", try Library.configuredPath()); + try std.testing.expectEqual(@as(c_int, 0), platform.env.setenv(name, "libnccl.so.2\n", 1)); + try std.testing.expectError(error.InvalidEnvironment, Library.open()); + try std.testing.expectEqual(@as(c_int, 0), platform.env.setenv(name, " \t", 1)); + try std.testing.expectEqualStrings("libnccl.so.2", try Library.configuredPath()); +} + test "nonblocking communicator config preserves the public ABI defaults" { const c: Config = .{}; try std.testing.expectEqual(@as(usize, 96), @sizeOf(Config)); diff --git a/zig/src/fabric/tp/config.zig b/zig/src/fabric/tp/config.zig index 0771cef1c6a..b34309164c5 100644 --- a/zig/src/fabric/tp/config.zig +++ b/zig/src/fabric/tp/config.zig @@ -2,6 +2,7 @@ const std = @import("std"); const log = @import("log.zig"); const graph_cache = @import("cuda").graph_cache; +const nccl = @import("cuda").nccl; pub const Backend = enum { /// NCCL for everything (the default). @@ -116,7 +117,7 @@ pub const Config = struct { if (get("TF_TP_FAILFAST")) |v| c.failfast = !(std.mem.eql(u8, v, "0") or std.mem.eql(u8, v, "off")); c.grace_ns = try seconds(get, "TF_TP_FAILFAST_GRACE_S", 1.0, 0, 60); c.report_ns = try seconds(get, "TF_TP_PEER_MEM_S", 0.5, 0.01, 60); - if (get("TF_NCCL_LIB")) |p| c.nccl_lib = p; + c.nccl_lib = nccl.Library.pathFrom(get("TF_NCCL_LIB")) catch return error.BadSetting; c.roce_hca = get("TF_TP_ROCE_HCA"); c.link = get("TF_TP_LINK"); c.roce_hcas = try int(u8, get, "TF_TP_ROCE_HCAS", 2, 1, 2); @@ -265,6 +266,15 @@ test "defaults: the plan link 7 ports past the rendezvous, NCCL, fail-fast on" { try std.testing.expectEqual(std.time.ns_per_s / 2, c.report_ns); } +test "TF_NCCL_LIB follows the loader's rule: a path is kept, blank keeps libnccl.so.2, a control byte is refused" { + Fake.pairs = &.{.{ "TF_NCCL_LIB", "/fixture/nccl/libnccl.so.2" }}; + try std.testing.expectEqualStrings("/fixture/nccl/libnccl.so.2", (try Config.parse(&Fake.get)).nccl_lib); + Fake.pairs = &.{.{ "TF_NCCL_LIB", " \t" }}; + try std.testing.expectEqualStrings("libnccl.so.2", (try Config.parse(&Fake.get)).nccl_lib); + Fake.pairs = &.{.{ "TF_NCCL_LIB", "libnccl.so.2\n" }}; + try std.testing.expectError(error.BadSetting, Config.parse(&Fake.get)); +} + test "bad settings are refused and the digest ignores the rank" { Fake.pairs = &.{.{ "TF_TP_RANK", "2" }}; try std.testing.expectError(error.BadSetting, Config.parse(&Fake.get)); diff --git a/zig/src/fabric/tp/gpu_main.zig b/zig/src/fabric/tp/gpu_main.zig index 56a6ccaed45..76934d10313 100644 --- a/zig/src/fabric/tp/gpu_main.zig +++ b/zig/src/fabric/tp/gpu_main.zig @@ -166,7 +166,7 @@ const DeviceRun = struct { /// The failed-transport check's host-only forms (fail-fast off, a hold): TF_TP_ALLOW_HOST_ONLY=1 and no RDMA wire. fn hostOnlyAllowed(cfg: tp.Config) bool { - const flag = std.mem.eql(u8, std.mem.span(std.c.getenv("TF_TP_ALLOW_HOST_ONLY") orelse ""), "1"); + const flag = std.mem.eql(u8, (@import("sys").environment.Process{}).get("TF_TP_ALLOW_HOST_ONLY") orelse "", "1"); return flag and (cfg.backend != .roce or cfg.roce_wire == .shm); } diff --git a/zig/src/families/dory/cuda_native.zig b/zig/src/families/dory/cuda_native.zig index 28dcdd00ab4..032c30d5b2e 100644 --- a/zig/src/families/dory/cuda_native.zig +++ b/zig/src/families/dory/cuda_native.zig @@ -155,9 +155,9 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: [ }; } -fn envOff(name: [*:0]const u8) bool { - const v = std.c.getenv(name) orelse return false; - return std.mem.eql(u8, std.mem.span(v), "0"); +fn envOff(name: [:0]const u8) bool { + const v = (@import("sys").environment.Process{}).get(name) orelse return false; + return std.mem.eql(u8, v, "0"); } fn gib(b: u64) f64 { diff --git a/zig/src/families/dory/names.zig b/zig/src/families/dory/names.zig index 17364e7cd0e..4aa7046b071 100644 --- a/zig/src/families/dory/names.zig +++ b/zig/src/families/dory/names.zig @@ -223,8 +223,8 @@ test "every tensor of a tiny NVFP4, MXFP8 and bf16 checkpoint maps" { } /// The checkpoint at the `env` directory: 72 sublayers, an mlp last, its end tokens. -fn pinnedMaps(env: [*:0]const u8) !void { - const dir = @import("sys").getenv(env) orelse return error.SkipZigTest; +fn pinnedMaps(env: [:0]const u8) !void { + const dir = (@import("sys").environment.Process{}).get(env) orelse return error.SkipZigTest; const c = try Config.read(testing.allocator, io, dir); var ck = try Checkpoint.openModel(testing.allocator, io, dir); defer ck.close(); diff --git a/zig/src/families/drama3/model.zig b/zig/src/families/drama3/model.zig index 7543a6a3571..5ee5ba123f4 100644 --- a/zig/src/families/drama3/model.zig +++ b/zig/src/families/drama3/model.zig @@ -7,6 +7,7 @@ pub const max_reference_samples = 30 * 44100; pub fn reference(samples: []const f32, rate: u32) !void { if (rate == 0 or rate > 192000 or samples.len == 0 or samples.len > @as(usize, rate) * 30) return error.BadReference; + if (rate / std.math.gcd(rate, @as(u32, 44100)) > 640) return error.BadReference; for (samples) |s| if (!std.math.isFinite(s)) return error.BadReference; } @@ -53,3 +54,10 @@ test "typed reference rows are bounded and agree with their semantic code" { try std.testing.expectError(error.BadCode, validate(&rows, ids, 16, 8)); try std.testing.expectError(error.BadPromptSize, validate(&rows, ids, 2, 1)); } + +test "voice reference: reduced resample width accepts standard rates and refuses pathological rates" { + for ([_]u32{ 8000, 11025, 16000, 22050, 24000, 32000, 44100, 48000, 64000, 88200, 96000, 176400, 192000 }) |rate| + try reference(&.{0}, rate); + for ([_]u32{ 44101, 44113, 191999 }) |rate| + try std.testing.expectError(error.BadReference, reference(&.{0}, rate)); +} diff --git a/zig/src/families/drama3/wav.zig b/zig/src/families/drama3/wav.zig index 494e5faea41..21c75ee2818 100644 --- a/zig/src/families/drama3/wav.zig +++ b/zig/src/families/drama3/wav.zig @@ -34,7 +34,7 @@ pub fn parse(gpa: std.mem.Allocator, bytes: []const u8) !Audio { } else if (std.mem.eql(u8, id, "data")) { data = body; } - at += 8 + len + (len & 1); + at += 8 + @as(usize, len) + (len & 1); } const d = data orelse return error.BadWav; if (channels == 0 or rate == 0) return error.BadWav; @@ -163,3 +163,21 @@ test "resampling keeps torchaudio's output length and a constant signal's level" try std.testing.expectEqual(@as(usize, 4410), y.len); for (y[200 .. y.len - 200]) |v| try std.testing.expectApproxEqAbs(@as(f32, 0.25), v, 2e-3); } + +test "voice WAV: a huge trailing chunk cannot overflow the RIFF advance" { + var bytes: [44]u8 = undefined; + header(&bytes, 44100, 0); + @memcpy(bytes[36..40], "JUNK"); + std.mem.writeInt(u32, bytes[40..44], 0xFFFFFFF8, .little); + try std.testing.expectError(error.BadWav, parse(std.testing.allocator, &bytes)); +} + +test "voice WAV: a truncated maximal data chunk is bounded by the available bytes" { + var bytes: [46]u8 = @splat(0); + header(bytes[0..44], 44100, 1); + std.mem.writeInt(u32, bytes[40..44], 0xFFFFFFFF, .little); + const audio = try parse(std.testing.allocator, &bytes); + defer audio.deinit(std.testing.allocator); + try std.testing.expectEqual(@as(usize, 1), audio.samples.len); + try std.testing.expectEqual(@as(f32, 0), audio.samples[0]); +} diff --git a/zig/src/families/flashnext/cuda_lanes_load.zig b/zig/src/families/flashnext/cuda_lanes_load.zig index 1e53ebfafb3..3ebc849aeb8 100644 --- a/zig/src/families/flashnext/cuda_lanes_load.zig +++ b/zig/src/families/flashnext/cuda_lanes_load.zig @@ -91,7 +91,7 @@ pub fn open(comptime F: type, gpa: std.mem.Allocator, io: std.Io, ctx: *const cu own.confidence = try @import("sys").environment.read(f64, "TF_FLASHNEXT_CONFIDENCE", mtp.default_confidence); } errdefer if (own.head) |h| h.deinit(); - @import("cuda_prompt_wt.zig").dropPageCache(io, dir, e.ngram.files.items); + @import("cuda_prompt_wt.zig").dropPageCache(gpa, io, dir, e.ngram.files.items); const window = @min(o.context + mtp.max_rows, prompt.max_tokens); // and an attention block's block scores at the window (64 MiB at 262,144 tokens) _ = try own.engine.reserveScores(window, @min(o.context, own.engine.chunk)); diff --git a/zig/src/families/flashnext/cuda_prompt_wt.zig b/zig/src/families/flashnext/cuda_prompt_wt.zig index 423194ba607..1c7ed4b5124 100644 --- a/zig/src/families/flashnext/cuda_prompt_wt.zig +++ b/zig/src/families/flashnext/cuda_prompt_wt.zig @@ -79,24 +79,32 @@ const Shard = struct { } fn close(self: *Shard) void { - // A shard may mix loaded tensors with the n-gram table still read at runtime. - if (!runtimePages(self.f.names.keys())) self.f.release(std.heap.page_allocator); // no keep list: scratch unused + self.drop(std.heap.page_allocator); self.f.close(self.io); } + /// The shard's pages out of the page cache, except the n-gram table's: a shard may mix both (embed, HC, MTP). + fn drop(self: *const Shard, scratch: std.mem.Allocator) void { + var keep: std.ArrayList([]const u8) = .empty; + defer keep.deinit(scratch); + for (self.f.names.keys()) |name| if (runtimePage(name)) keep.append(scratch, self.f.get(name).?.bytes) catch return; + self.f.releaseExcept(keep.items, scratch); + } + fn get(self: *const Shard, name: []const u8) ?Tensor { return self.f.get(name); } }; -fn runtimePages(names: []const []const u8) bool { - for (names) |name| if (std.mem.indexOf(u8, name, ".ple_embedding.ngram_embedding.") != null) return true; - return false; +fn runtimePage(name: []const u8) bool { + return std.mem.indexOf(u8, name, ".ple_embedding.ngram_embedding.") != null; } -/// The final load-only sweep excludes the n-gram table's live mappings. -pub fn dropPageCache(io: std.Io, dir: []const u8, keep: anytype) void { - core.checkpoint.cache.directory(io, dir, keep); +/// The final load-only sweep over the index's shards excludes the n-gram table's live mappings. +pub fn dropPageCache(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, keep: anytype) void { + const paths = core.checkpoint.shardFiles(gpa, io, dir) catch return; + defer core.checkpoint.freeShardFiles(gpa, paths); + core.checkpoint.cache.shards(io, paths, keep); } pub const Store = struct { @@ -188,8 +196,8 @@ pub const Store = struct { /// Borrowers expire here; their shards stay open, pages dropped, until the load ends (or close if not kept). pub fn release(self: *Store) void { for (self.held.items) |h| { - // the borrowers' pages leave this process (their bytes are copied), except the n-gram table's (Shard.close) - if (!runtimePages(h.file.f.names.keys())) h.file.f.release(self.gpa); + // the borrowers' pages leave this process (their bytes are copied), except the n-gram table's + h.file.drop(self.gpa); self.released.append(self.gpa, h) catch { var kept = h.file; kept.close(); @@ -295,7 +303,7 @@ pub const Store = struct { } else try self.openShard(file); if (self.file) |*f| { // its pages dropped as close drops them: the n-gram table's stay - if (!runtimePages(f.f.names.keys())) f.f.release(self.gpa); + f.drop(self.gpa); self.released.appendAssumeCapacity(.{ .rel = self.rel, .file = f.* }); } self.rel = next.rel; @@ -579,6 +587,7 @@ test { } test "Flash Next load cache: a mixed PLE shard keeps its runtime pages" { - try std.testing.expect(runtimePages(&.{ "language_model.model.norm.weight", "language_model.model.layers.1.ple.ple_embedding.ngram_embedding.shards.0.weight" })); - try std.testing.expect(!runtimePages(&.{ "language_model.model.norm.weight", "language_model.mtp.norm.weight" })); + try std.testing.expect(runtimePage("language_model.model.layers.1.ple.ple_embedding.ngram_embedding.shards.0.weight")); + try std.testing.expect(!runtimePage("language_model.model.norm.weight")); + try std.testing.expect(!runtimePage("language_model.mtp.norm.weight")); } diff --git a/zig/src/families/gemma4/gemma4.zig b/zig/src/families/gemma4/gemma4.zig index 6ad0e3911ec..75b13955841 100644 --- a/zig/src/families/gemma4/gemma4.zig +++ b/zig/src/families/gemma4/gemma4.zig @@ -20,6 +20,7 @@ pub const snapshot = @import("snapshot.zig"); test { _ = backend; + _ = @import("model.zig"); _ = assistant; _ = assistant_weights; _ = config; diff --git a/zig/src/families/gemma4/model.zig b/zig/src/families/gemma4/model.zig index 7246940f2de..d9eeef3b66a 100644 --- a/zig/src/families/gemma4/model.zig +++ b/zig/src/families/gemma4/model.zig @@ -161,12 +161,15 @@ pub const Model = struct { if (m.config.geo.unified()) { try vision_unified.addTensors(&m.checkpoint, m.device, files); if (!vision_unified.present(&m.checkpoint)) return error.NoGemmaVision; - m.vision = .{ .embedder = try vision_unified.Embedder.load(m.gpa, m.device, &m.checkpoint, m.config.geo.hidden, m.pipes(m.config.widths.vision.bits), m.config.widths.vision) }; + // bound first: a failed load must leave m.vision null, not a tag with no embedder behind it + const e = try vision_unified.Embedder.load(m.gpa, m.device, &m.checkpoint, m.config.geo.hidden, m.pipes(m.config.widths.vision.bits), m.config.widths.vision); + m.vision = .{ .embedder = e }; return; } try vision.addTensors(&m.checkpoint, m.device, files); if (!vision.present(&m.checkpoint)) return error.NoGemmaVision; - m.vision = .{ .encoder = try vision.Vision.load(m.gpa, m.device, &m.checkpoint, m.pipes(m.config.widths.vision.bits), m.config.widths.vision, m.config.geo.hidden) }; + const v = try vision.Vision.load(m.gpa, m.device, &m.checkpoint, m.pipes(m.config.widths.vision.bits), m.config.widths.vision, m.config.geo.hidden); + m.vision = .{ .encoder = v }; } /// The drafter's taps, in its feature order: each a layer whose output (layer scalar applied) it reads. @@ -195,3 +198,33 @@ pub const Model = struct { m.gpa.destroy(m); } }; + +test "a tower that fails to load leaves the model without one, so deinit frees nothing that was never made" { + if (comptime !@hasDecl(mtl.Device, "init")) return error.SkipZigTest; + const device = mtl.Device.init() catch return error.SkipZigTest; + defer device.deinit(); + const gpa = std.testing.allocator; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + // the name vision_unified.present() looks for, so loadVision reaches Embedder.load + const header = + \\{"vision_embedder.patch_dense.weight":{"dtype":"BF16","shape":[2],"data_offsets":[0,4]}} + ; + var data: [8 + header.len + 4]u8 = @splat(0); + std.mem.writeInt(u64, data[0..8], header.len, .little); + @memcpy(data[8..][0..header.len], header); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "model.safetensors", .data = &data }); + const dir = try std.fmt.allocPrint(gpa, ".zig-cache/tmp/{s}", .{tmp.sub_path}); + defer gpa.free(dir); + var m: Model = undefined; + m.gpa = gpa; + m.device = device; + m.checkpoint = ckpt.Checkpoint.init(gpa); + defer m.checkpoint.deinit(); + m.vision = null; + m.config = .{ .geo = cfg.unified12b, .context = 1 }; + m.config.geo.hidden = vision_unified.width + 1; // a width the embedder cannot project to: Embedder.load refuses it + for (&m.mm) |*p| p.* = @as(affine_mm.Pipes, undefined); // never read: the refusal comes first + try std.testing.expectError(error.UnexpectedGemmaVisionTensor, m.loadVision(std.testing.io, dir)); + try std.testing.expect(m.vision == null); +} diff --git a/zig/src/families/glm/checks.zig b/zig/src/families/glm/checks.zig index 98fa944e277..7bdc4778cc6 100644 --- a/zig/src/families/glm/checks.zig +++ b/zig/src/families/glm/checks.zig @@ -173,7 +173,7 @@ pub fn checkMatmul(e: *Engine, prompt: []const u32) !void { fwd.boundary(&x, b.enc, rows, false, L.hc.?[0], L.in_norm); fwd.qmv(&x, b.enc, e.k.qmv_kda_in, e.sc.normed, a.in_proj, out, rows); affine_mm.rowSums(b.enc, e.k.mm_bf16, 64, e.sc.normed, pr.sums, rows, a.in_proj.k); - affine_mm.dense(b.enc, e.k.mm_bf16, e.sc.normed, pr.sums, a.in_proj, pr.proj, rows); + affine_mm.denseBm(b.enc, e.k.mm_bf16, e.sc.normed, pr.sums, a.in_proj, pr.proj, rows, if (e.k.m3_fast) 32 else 64); try e.finish(b.cb, b.enc); const want: [*]const u16 = @ptrCast(@alignCast(out.addr())); const got: [*]const u16 = @ptrCast(@alignCast(pr.proj.addr())); diff --git a/zig/src/families/glm/cuda_engine_prof.zig b/zig/src/families/glm/cuda_engine_prof.zig index 925aade490c..8b3bbe479fd 100644 --- a/zig/src/families/glm/cuda_engine_prof.zig +++ b/zig/src/families/glm/cuda_engine_prof.zig @@ -13,8 +13,7 @@ pub fn freeProfs(e: *Engine) void { } pub fn heatRoot() []const u8 { - const p = std.c.getenv("TF_HEAT_ROOT") orelse return @import("heat").default_root; - const s = std.mem.span(p); + const s = (@import("sys").environment.Process{}).get("TF_HEAT_ROOT") orelse return @import("heat").default_root; return if (s.len == 0) @import("heat").default_root else s; } diff --git a/zig/src/families/glm/cuda_env_test.zig b/zig/src/families/glm/cuda_env_test.zig index a74685852f0..4d601ab113e 100644 --- a/zig/src/families/glm/cuda_env_test.zig +++ b/zig/src/families/glm/cuda_env_test.zig @@ -22,6 +22,7 @@ const reals = [_][:0]const u8{"TF_GLM_DRAFT_CONFIDENCE"}; /// The window GLM may serve past config.json's: GLM's raisedCeiling reads it at the open, after these rows' check. const windows = [_][:0]const u8{"TF_GLM_CONTEXT_CEILING"}; const words = [_][:0]const u8{"TF_GLM_EXPERT_FORM"}; +const added = [_][:0]const u8{ "TF_GLM_INDEX_CUDA", "TF_GLM_KV_HOST_GIB", "TF_GLM_RANK", "TF_GLM_WORLD" }; /// The row by name without `rule`, so a missing row fails an assertion instead of panicking. fn row(name: []const u8) !e.Rule { @@ -60,12 +61,13 @@ test "GLM strict env: every GLM reader's name is a glm row, and the glm scope ho for (reals) |name| try t.expectEqual(e.Kind.real, (try row(name)).kind); for (windows) |name| try t.expectEqual(e.Kind.u64, (try row(name)).kind); for (words) |name| try t.expectEqual(e.Kind.word, (try row(name)).kind); + for (added) |name| try t.expect((try row(name)).kind != .flag); var n: usize = 0; for (e.rules) |r| if (r.scope == .glm) { try t.expect(std.mem.startsWith(u8, r.name, "TF_GLM_")); n += 1; }; - try t.expectEqual(switches.len + counts.len + reals.len + windows.len + words.len, n); + try t.expectEqual(switches.len + counts.len + reals.len + windows.len + words.len + added.len, n); } test "GLM strict env: the expert form takes classic or factored, leaves blank to the race, and refuses the rest by name" { diff --git a/zig/src/families/glm/cuda_exl3.zig b/zig/src/families/glm/cuda_exl3.zig index 682db10e3f9..9c30d912979 100644 --- a/zig/src/families/glm/cuda_exl3.zig +++ b/zig/src/families/glm/cuda_exl3.zig @@ -142,12 +142,16 @@ fn picksBytes(rows: usize) usize { const cap: usize = @min(rows, chunk_rows); return std.mem.alignForward(usize, cap * top_k * 4, 256); } +/// A decode chunk must fit both the compact fallback and the nine-slot item layout. +fn decodeBytes(l: common.Layer, n: usize) !usize { + return @max(try common.scratchBytes(l, n, top_k), try common.fusedBytes(l, n, top_k + 1)); +} pub fn scratchBytes(rows: usize, dims: usize, width: usize, prefill: bool, shx: bool) [4]usize { var l = shape(dims, width); l.shared_input = shx; if (prefill and common.prompt.eligible(l)) return .{ common.prompt.bytes(l, @min(rows, prompt_rows), top_k + 1) catch unreachable, 4, 4, 4 }; const n: usize = @min(rows, chunk_rows); - return .{ picksBytes(rows) + (common.scratchBytes(shape(dims, width), n, top_k) catch unreachable), 4, 4, 4 }; + return .{ picksBytes(rows) + (decodeBytes(shape(dims, width), n) catch unreachable), 4, 4, 4 }; } /// `height` rows of `width` bytes, `spitch` apart at `src`, to `dpitch` apart at `dst`, in one call. fn copyRows(stream: cuda.Stream, dst: u64, dpitch: usize, src: u64, spitch: usize, width: usize, height: usize, what: []const u8) !void { @@ -168,10 +172,20 @@ pub fn run(k: *const Kernels, ek: *const experts.Kernels, stream: cuda.Stream, w } return; } + if (!prompt) { + const cap: usize = @min(rows, chunk_rows); + const scratch = try common.fusedScratch(sc.picks + picksBytes(rows), l, cap, slots); + var at: usize = 0; + while (at < rows) : (at += chunk_rows) { + const n: usize = @min(chunk_rows, rows - at); + try k.runWith(stream, l, x + at * x_stride * 2, x_stride, .bf16, picks + at * slots * 4, 0, n, 0, scratch, ey + at * slots * dims * 4, .{ .router = &ek.router, .plan = plan_buf }); + } + return; + } return compact(k, stream, w, sc, x, x_stride, picks, slots, rows, count, dims, width, limit, ey); } -/// Compact routed picks and output for decode or prompt layers without the whole-pass kernel. +/// Compact routed picks and output for prompt layers without the whole-pass kernel. fn compact(k: *const Kernels, stream: cuda.Stream, w: Experts, sc: Scratch, x: u64, x_stride: usize, picks: u64, slots: usize, rows: usize, count: usize, dims: usize, width: usize, limit: f32, ey: u64) !void { const l = layer(w, count, dims, width, limit); const cap: usize = @min(rows, chunk_rows); diff --git a/zig/src/families/glm/cuda_follow.zig b/zig/src/families/glm/cuda_follow.zig index 25ef795ed98..11ac9a4053a 100644 --- a/zig/src/families/glm/cuda_follow.zig +++ b/zig/src/families/glm/cuda_follow.zig @@ -154,7 +154,7 @@ pub const Leader = struct { return @intFromBool(x.e.prompt_logprobs != null); } - /// No stream is left: the other ranks sleep on their lines until the next step instead of spinning in NCCL. + /// No stream is left, or rank 0's tower is about to run: the other ranks sleep on their lines until the next step. pub fn idle(x: Leader) !void { if (x.link.asleep or !cuda.tp_watch.open()) return; try x.send(.{ .kind = @backingInt(Kind.idle) }, &.{}); @@ -216,6 +216,13 @@ pub const Leader = struct { try x.send(.{ .kind = @backingInt(Kind.pool), .depth = streams, .a = pages, .seed = page_bytes }, &.{}); } + /// Rank 0's tower encodes the bound slot's images past `from` with the other ranks asleep (#3614), then their rows. + pub fn encode(x: Leader, v: *images_mod.Images, list: []const @import("lanes").stream.Image, from: usize) !void { + try x.idle(); // a net plugin may time out an NCCL wait as long as the pass: they wait on their lines instead + try v.begin(x.e.slot, list, from); // a refusal leaves every rank as it was, asleep until rank 0's next step + try x.images(v); + } + /// The prompt pass's image rows (rank 0 encoded them for the bound slot) to every rank: spans, then the rows. pub fn images(x: Leader, v: *const images_mod.Images) !void { try x.flush(); diff --git a/zig/src/families/glm/cuda_index.zig b/zig/src/families/glm/cuda_index.zig index 4dd75d770f3..542822b9f67 100644 --- a/zig/src/families/glm/cuda_index.zig +++ b/zig/src/families/glm/cuda_index.zig @@ -23,16 +23,17 @@ pub const Mode = enum { scores, pub fn parse(text: ?[]const u8) !Mode { - 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; + const n = try @import("sys").environment.value(u32, "TF_GLM_INDEX_CUDA", text, 0); + return switch (n) { + 0 => .both, + 1 => .off, + 2 => .scores, + else => unreachable, + }; } pub fn read() !Mode { - const v = std.c.getenv("TF_GLM_INDEX_CUDA") orelse return .both; - return parse(std.mem.span(v)); + return parse((@import("sys").environment.Process{}).get("TF_GLM_INDEX_CUDA")); } }; @@ -103,8 +104,8 @@ test "GLM index: TF_GLM_INDEX_CUDA is on unless 0, scores bisects, and a typo is 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")); + try std.testing.expectError(error.InvalidEnvironment, Mode.parse("on")); + try std.testing.expectError(error.InvalidEnvironment, Mode.parse("off")); } test "GLM index: the scores grid covers 8 rows a CTA and 16 pool blocks a CTA" { diff --git a/zig/src/families/glm/cuda_kv_host.zig b/zig/src/families/glm/cuda_kv_host.zig index 852db4dab75..6866d0d78cb 100644 --- a/zig/src/families/glm/cuda_kv_host.zig +++ b/zig/src/families/glm/cuda_kv_host.zig @@ -26,8 +26,8 @@ fn pagesOf(gib: ?f64, page: u64, capacity: usize) usize { /// TF_GLM_KV_HOST_GIB's host pages, else one full window's. pub fn hostPages(page: u64, capacity: usize) usize { - const v = std.c.getenv("TF_GLM_KV_HOST_GIB") orelse return pagesOf(null, page, capacity); - return pagesOf(std.fmt.parseFloat(f64, std.mem.span(v)) catch null, page, capacity); + const gib = @import("sys").environment.read(?f64, "TF_GLM_KV_HOST_GIB", null) catch null; + return pagesOf(gib, page, capacity); } /// The plan's `pages` (counted by their device keys alone), held to the host pages when the pages are in host memory. diff --git a/zig/src/families/glm/cuda_l2pf.zig b/zig/src/families/glm/cuda_l2pf.zig index c5fefb0216b..9cdfda0e0f3 100644 --- a/zig/src/families/glm/cuda_l2pf.zig +++ b/zig/src/families/glm/cuda_l2pf.zig @@ -100,7 +100,10 @@ fn sources(l: weights.Layer, site: Site) Sources { }, }, .f => switch (l.ffn) { - .moe => |m| s.add(m.router), + .moe => |m| { + s.add(m.router); + s.proj(m.shared_gu); // read after the routed experts, which no table holds (the router picks them) + }, .dense => |m| switch (m.w) { .nvfp4 => |x| { s.lane(x.gate); @@ -310,10 +313,11 @@ test "the table: each site's sources in its matmuls' order, site n from the next d.mixer.mla.q_b = .{ .bf16 = 0x7000_0000 }; d.ffn = .{ .dense = undefined }; d.ffn.dense.w = .{ .bf16 = .{ .gu = 0x9000_0000, .down = 0xa000_0000 } }; - var e: weights.Layer = undefined; // layer 1: KDA on the lane and MoE + var e: weights.Layer = undefined; // layer 1: KDA on the lane and MoE, its shared expert block FP8 on the lane e.mixer = .{ .kda = k }; e.ffn = .{ .moe = undefined }; e.ffn.moe.router = 0x5000_0000; + e.ffn.moe.shared_gu = .{ .fp8g = .{ .mode = .fp8g, .codes = 0xb000_0000, .scales = 0x8000_0000, .n = 64, .k = 64, .npad = 64 } }; const MiB = 1 << 20; var bufs = [_]cuda.DeviceBuffer{ .{ .d = undefined, .ptr = 0x1000_0000, .len = 1 * MiB }, @@ -324,6 +328,8 @@ test "the table: each site's sources in its matmuls' order, site n from the next .{ .d = undefined, .ptr = 0x6000_0000, .len = 16 * MiB }, .{ .d = undefined, .ptr = 0x7000_0000, .len = 17 * MiB }, .{ .d = undefined, .ptr = 0x9000_0000, .len = 34 * MiB }, + .{ .d = undefined, .ptr = 0x8000_0000, .len = 1 * MiB }, + .{ .d = undefined, .ptr = 0xb000_0000, .len = 16 * MiB }, }; var rows: std.ArrayList([2]i64) = .empty; defer rows.deinit(t.allocator); @@ -333,8 +339,10 @@ test "the table: each site's sources in its matmuls' order, site n from the next .{ 0x1000_0000, 1 * MiB }, // layer 0's n: layer 1's qkv scales whole, then its codes' head .{ 0x2000_0000, 11 * MiB }, .{ 0x9000_0000, 12 * MiB }, // layer 0's f: its gate and up's head - .{ 0x5000_0000, 2 * MiB }, // layer 1's f: its router; its n would be the head's, its o is KDA's o - .{ 0x4000_0000, 12 * MiB }, + .{ 0x5000_0000, 2 * MiB }, // layer 1's f: its router, then its shared gate-up's scales and its codes' head + .{ 0x8000_0000, 1 * MiB }, + .{ 0xb000_0000, 9 * MiB }, + .{ 0x4000_0000, 12 * MiB }, // layer 1's o, KDA's o; its n would be the head's }; try t.expectEqualSlices([2]i64, &want, rows.items); try t.expectEqualSlices(Span, &.{ @@ -342,8 +350,8 @@ test "the table: each site's sources in its matmuls' order, site n from the next .{ .at = 2, .rows = 1, .bytes = 12 * MiB }, .{ .at = 3 }, // DSA: no site o .{ .at = 3 }, - .{ .at = 3, .rows = 1, .bytes = 2 * MiB }, - .{ .at = 4, .rows = 1, .bytes = 12 * MiB }, + .{ .at = 3, .rows = 3, .bytes = 12 * MiB }, + .{ .at = 6, .rows = 1, .bytes = 12 * MiB }, }, &spans); rows.clearRetainingCapacity(); try t.expect(!try table(t.allocator, bufs[1..], &.{ d, e }, 12 * MiB, &rows, &spans)); diff --git a/zig/src/families/glm/cuda_lanes.zig b/zig/src/families/glm/cuda_lanes.zig index 08436c4d045..37eedcc152a 100644 --- a/zig/src/families/glm/cuda_lanes.zig +++ b/zig/src/families/glm/cuda_lanes.zig @@ -360,8 +360,7 @@ pub const Lanes = struct { fn images(self: *Lanes, s: *lanes.Stream, from: ?engine.Resume) !void { if (s.images.len == 0) return; const v = self.x.e.images orelse return error.NoVision; - try v.begin(self.x.e.slot, s.images, if (from) |r| r.at else 0); // a refusal here leaves every rank as it was - try self.x.images(v); + try self.x.encode(v, s.images, if (from) |r| r.at else 0); } const Sink = @import("cuda_prompt_sink.zig").Sink; diff --git a/zig/src/families/glm/cuda_native.zig b/zig/src/families/glm/cuda_native.zig index 0aef928c1d5..e933c6b4c81 100644 --- a/zig/src/families/glm/cuda_native.zig +++ b/zig/src/families/glm/cuda_native.zig @@ -134,10 +134,10 @@ pub fn kvPool(p: *anyopaque) ?kv.Source { pub const Place = struct { rank: usize, world: usize }; pub fn place() !Place { - const r = std.c.getenv("TF_GLM_RANK") orelse return error.NoRank; - const w = std.c.getenv("TF_GLM_WORLD") orelse return error.NoRank; - const p: Place = .{ .rank = std.fmt.parseInt(usize, std.mem.span(r), 10) catch return error.NoRank, .world = std.fmt.parseInt(usize, std.mem.span(w), 10) catch return error.NoRank }; - return checked(p); + const settings = @import("sys").environment; + const r = (try settings.read(?u64, "TF_GLM_RANK", null)) orelse return error.NoRank; + const w = (try settings.read(?u64, "TF_GLM_WORLD", null)) orelse return error.NoRank; + return checked(.{ .rank = @intCast(r), .world = @intCast(w) }); } /// A place the family serves: a rank inside its world, and at most `ranks.max_world` ranks. @@ -199,7 +199,7 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: [ try @import("cuda_env.zig").startup(); try @import("cuda_env.zig").requestStartsAlone(o.learn_conversations); // before any rank opens const p = try place(); - const roce_bytes = try roceBytes(if (std.c.getenv("TF_ROCE_MAX_KB")) |v| std.mem.span(v) else null); + const roce_bytes = try roceBytes((@import("sys").environment.Process{}).get("TF_ROCE_MAX_KB")); if (p.world > 1 and std.c.getenv("NCCL_COMM_ID") == null) return error.NoCommId; var problem: []const u8 = ""; var set = ranks.Settings.read(&ranks.environment, &problem) catch |err| { @@ -208,7 +208,7 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: [ }; try @import("cuda_roce_multi.zig").validate(p.world, p.rank, set.roce_multi); set.kv8 = o.kv8; - if (share_mod.moved(if (std.c.getenv("TF_GLM_KV_SHARE")) |v| std.mem.span(v) else "")) return error.GlmKvShareMoved; // before any rank opens + if (share_mod.moved((@import("sys").environment.Process{}).get("TF_GLM_KV_SHARE") orelse "")) return error.GlmKvShareMoved; // before any rank opens const share_snaps = try kp.sharing(); if (share_mod.tooMany(share_snaps)) { std.log.err("TF_KV_SHARE={d} asks more kept states than the {d} it keeps: set {d} or fewer", .{ share_snaps, kv.most_snaps, kv.most_snaps }); diff --git a/zig/src/families/glm/cuda_roce_multi.zig b/zig/src/families/glm/cuda_roce_multi.zig index eb116a5c2db..d5d6a7122d9 100644 --- a/zig/src/families/glm/cuda_roce_multi.zig +++ b/zig/src/families/glm/cuda_roce_multi.zig @@ -32,7 +32,7 @@ fn fallsBack(err: anyerror, entered: bool) bool { /// fabric/tp's bootstrap, ports, wire and kernel, and a probe against the group's NCCL: each step every rank's or none. fn borrow(gpa: std.mem.Allocator, io: std.Io, d: *const cuda.Driver, g: *const Group, cfg: tp.Config, entered: *bool) !*Wire { - const path = std.mem.span(std.c.getenv("TF_TP_KERNEL_IMAGE") orelse return error.NoKernelImage); + const path = (@import("sys").environment.Process{}).get("TF_TP_KERNEL_IMAGE") orelse return error.NoKernelImage; const image = try std.Io.Dir.cwd().readFileAllocOptions(io, path, gpa, .limited(1 << 26), .@"16", null); defer gpa.free(image); // the module copies it at load var b = try tp.Bootstrap.open(cfg); diff --git a/zig/src/families/glm/forward.zig b/zig/src/families/glm/forward.zig index 82c5db3158b..3b02434e676 100644 --- a/zig/src/families/glm/forward.zig +++ b/zig/src/families/glm/forward.zig @@ -433,7 +433,8 @@ pub fn selectKeys(x: *const Ctx, e: mtl.ComputeEncoder, mi: usize, iq: Ref, q_st e.setPipeline(k.index_decode); // a row's heads as the tensor op's rows (glm_index_nax.metal) bind(e, 0, .{ iq, iw, x.s.mla[mi].pool, scores }); e.setValue(ScoreArgs{ .p0 = p0, .q_stride = q_stride, .w_stride = c.i_heads, .s_stride = s_stride, .rows = n }, 4); - e.dispatchGroups(size((most + 127) / 128, n, 1), size(128, 1, 1)); + const blk_step: u32 = if (k.m3_fast) 64 else 128; + e.dispatchGroups(size((most + blk_step - 1) / blk_step, n, 1), size(128, 1, 1)); e.setPipeline(k.index_select); bind(e, 0, .{ scores, indices }); e.setValue(SelectArgs{ .p0 = p0, .top = c.i_topk / c.kpool, .width = c.keyWidth(), .s_stride = s_stride, .i_stride = c.keyWidth() }, 2); diff --git a/zig/src/families/glm/kernels.zig b/zig/src/families/glm/kernels.zig index 5adf7c38643..e930d4b034f 100644 --- a/zig/src/families/glm/kernels.zig +++ b/zig/src/families/glm/kernels.zig @@ -103,13 +103,14 @@ pub const Kernels = struct { mm_bf16: affine_mm.Pipes, // prompt chunks' 4-bit g64 matmuls on the tensor units (core/affine_mm.zig): dense, gathers mm_f32: affine_mm.Pipes, // and with fp32 out: expert parallel by rows' down partials wide: ?wide.Pipes = null, // the products at other widths (wide.zig), for a checkpoint that has one + m3_fast: bool, // pre-M5 Metal dispatch geometry (32x64 affine_mm, 4-sg KDA scan, 32x64/64 index NAX) pub fn deinit(k: *Kernels) void { const info = @typeInfo(Kernels).@"struct"; inline for (info.field_names, info.field_types) |name, T| { if (T == mtl.Pipeline) @field(k, name).deinit() else if (T == ?wide.Pipes) { if (k.wide) |*w| w.deinit(); - } else if (T != u64) for (&@field(k, name)) |*p| p.deinit(); + } else if (T != u64 and T != bool) for (&@field(k, name)) |*p| p.deinit(); } } @@ -231,6 +232,8 @@ pub fn visitSources(gpa: std.mem.Allocator, device: mtl.Device, visitor: anytype fn assemble(gpa: std.mem.Allocator, device: mtl.Device, k: *Kernels, visitor: anytype) !void { k.wide = null; + const m3_fast = !device.tensorUnits(); + k.m3_fast = m3_fast; var jobs: [generated.len + 23]Job = undefined; inline for (generated, 0..) |g, i| { const src = comptime kernelOf(g.key); @@ -263,13 +266,14 @@ fn assemble(gpa: std.mem.Allocator, device: mtl.Device, k: *Kernels, visitor: an defer gpa.free(igate_src); var igate_out: [1]mtl.Pipeline = undefined; jobs[generated.len + 6] = .{ .device = device, .source = igate_src, .names = &.{moe_route.names[0]}, .out = &igate_out }; - const m16_src = try affine_mm.source(device, gpa, .{}); + const m16_src = try affine_mm.source(device, gpa, .{ .glm_m3_fast = m3_fast }); defer gpa.free(m16_src); - const m32_src = try affine_mm.source(device, gpa, .{ .out_f32 = true }); + const m32_src = try affine_mm.source(device, gpa, .{ .out_f32 = true, .glm_m3_fast = m3_fast }); defer gpa.free(m32_src); jobs[generated.len + 7] = .{ .device = device, .source = m16_src, .names = &affine_mm.names, .out = &k.mm_bf16 }; jobs[generated.len + 8] = .{ .device = device, .source = m32_src, .names = &affine_mm.names, .out = &k.mm_f32 }; - const kda_src = try std.mem.concat(gpa, u8, &.{ comptime kernelOf("kda_rows").source, sources.glm_kda_prompt }); + const m3_def = if (m3_fast) "#define TF_GLM_M3_FAST 1\n" else ""; + const kda_src = try std.mem.concat(gpa, u8, &.{ comptime kernelOf("kda_rows").source, m3_def, sources.glm_kda_prompt }); defer gpa.free(kda_src); var kda_out: [6]mtl.Pipeline = undefined; jobs[generated.len + 9] = .{ .device = device, .source = kda_src, .names = &.{ "glm_kda_prep", "glm_kda_scan", "glm_kda_post", "glm_kda_prep_tp", "glm_kda_scan_tp", "glm_kda_post_tp" }, .out = &kda_out }; @@ -294,7 +298,9 @@ fn assemble(gpa: std.mem.Allocator, device: mtl.Device, k: *Kernels, visitor: an const absorb_tp_src = try frags.source(device, gpa, absorb_tp_raw); defer gpa.free(absorb_tp_src); jobs[generated.len + 14] = .{ .device = device, .source = absorb_tp_src, .names = &.{"glm_absorb_nax"}, .out = @as(*[1]mtl.Pipeline, &k.absorb_nax_tp) }; - const index_src = try frags.source(device, gpa, sources.glm_index_nax); + const index_raw = try std.mem.concat(gpa, u8, &.{ m3_def, sources.glm_index_nax }); + defer gpa.free(index_raw); + const index_src = try frags.source(device, gpa, index_raw); defer gpa.free(index_src); var index_out: [2]mtl.Pipeline = undefined; jobs[generated.len + 15] = .{ .device = device, .source = index_src, .names = &.{ "glm_index_scores_nax", "glm_index_decode" }, .out = &index_out }; diff --git a/zig/src/families/glm/prompt.zig b/zig/src/families/glm/prompt.zig index d2f8e748395..3477002b19b 100644 --- a/zig/src/families/glm/prompt.zig +++ b/zig/src/families/glm/prompt.zig @@ -191,7 +191,7 @@ fn run(e: mtl.ComputeEncoder, grid: [3]usize, group: [3]usize) void { fn qmm(p: *const Prompt, e: mtl.ComputeEncoder, x: Ref, q: wts.Affine, y: Ref, M: u32) void { if (!wide.native(q)) return qmmAt(p, e, x, q.k, q, y, M); affine_mm.rowSums(e, p.mm.mm_bf16, 64, x, p.sums, M, q.k); - affine_mm.dense(e, p.mm.mm_bf16, x, p.sums, q, y, M); + affine_mm.denseBm(e, p.mm.mm_bf16, x, p.sums, q, y, M, if (p.mm.m3_fast) 32 else 64); } /// `qmm` over x's rows `ld` elements apart (a slice of a wider row). @@ -206,13 +206,13 @@ fn qmmAt(p: *const Prompt, e: mtl.ComputeEncoder, x: Ref, ld: u32, q: wts.Affine ); const mm = p.mm.mm_bf16; affine_mm.rowSumsAt(e, mm, 64, x, p.sums, M, q.k, ld); - affine_mm.denseBatch(e, mm, x, p.sums, q, y, M, 1, .{ .x_row = @intCast(ld), .y_row = @intCast(pitch) }); + affine_mm.denseBatchBm(e, mm, x, p.sums, q, y, M, 1, .{ .x_row = @intCast(ld), .y_row = @intCast(pitch) }, if (p.mm.m3_fast) 32 else 64); } /// `qmm` with fp32 out (TP2: one Mac's partial of a row-split projection). fn qmmF32(p: *const Prompt, e: mtl.ComputeEncoder, x: Ref, q: wts.Affine, y: Ref, M: u32) void { affine_mm.rowSums(e, p.mm.mm_bf16, 64, x, p.sums, M, q.k); - affine_mm.dense(e, p.mm.mm_f32, x, p.sums, q, y, M); + affine_mm.denseBm(e, p.mm.mm_f32, x, p.sums, q, y, M, if (p.mm.m3_fast) 32 else 64); } /// Routed experts' gate, up and SwiGLU on the M rows of `x_in` its pairs read (expert order) into `act` ([n, gate.n]). @@ -377,7 +377,7 @@ fn kdaChunk(p: *const Prompt, x: *const fwd.Ctx, e: mtl.ComputeEncoder, ki: usiz e.setPipeline(if (tp) k.kda_scan_tp else k.kda_scan); bind(e, 0, .{ q, kk, v, g, beta, L.st[if (r0 == 0) cur else 1 - cur], L.st[1 - cur], sy }); e.setValue(@as(i32, @intCast(m)), 8); - e.dispatchGroups(size(c.kda_dim / 64, H, 1), size(512, 1, 1)); + if (x.k.m3_fast) e.dispatchGroups(size(c.kda_dim / 16, H, 1), size(128, 1, 1)) else e.dispatchGroups(size(c.kda_dim / 64, H, 1), size(512, 1, 1)); } if (!fwd.on(x, "kda_post")) continue; e.setPipeline(if (tp) k.kda_post_tp else k.kda_post); @@ -386,7 +386,7 @@ fn kdaChunk(p: *const Prompt, x: *const fwd.Ctx, e: mtl.ComputeEncoder, ki: usiz bind(e, 4, .{ p.y.at(@as(usize, r0) * W * 2), p.proj }); fwd.shape(e, 6, .{ M, pitch }); // every block writes the next chunk's conv window, the same rows bind(e, 7, .{ L.cs[cur], L.cs[1 - cur] }); - e.dispatchGroups(size(m, H, 1), size(32, 1, 1)); + if (x.k.m3_fast) e.dispatchGroups(size(m, H / 4, 1), size(128, 1, 1)) else e.dispatchGroups(size(m, H, 1), size(32, 1, 1)); } } @@ -411,7 +411,8 @@ fn unabsorb(p: *const Prompt, x: *const fwd.Ctx, e: mtl.ComputeEncoder, w: *cons q.b = q.b.at(@as(usize, c.nope) * (K / 64) * 2); q.n = c.v_dim; affine_mm.rowSums(e, p.mm.mm_bf16, 64, p.att, p.sums, M * H, K); - affine_mm.denseBatch(e, p.mm.mm_bf16, p.att, p.sums, q, p.vals, M, H, .{ .x_row = @intCast(H * K), .y_row = @intCast(H * c.v_dim), .sums_row = @intCast(H), .x_batch = @intCast(K), .y_batch = @intCast(c.v_dim), .sums_batch = 1, .w_batch = @intCast(per) }); + const bs: affine_mm.Strides = .{ .x_row = @intCast(H * K), .y_row = @intCast(H * c.v_dim), .sums_row = @intCast(H), .x_batch = @intCast(K), .y_batch = @intCast(c.v_dim), .sums_batch = 1, .w_batch = @intCast(per) }; + affine_mm.denseBatchBm(e, p.mm.mm_bf16, p.att, p.sums, q, p.vals, M, H, bs, if (p.mm.m3_fast) 32 else 64); } /// `n` rows' key lists from index scores over every pooled block they read (positions p0..), scores on tensor units. @@ -419,10 +420,11 @@ fn selectKeys(p: *const Prompt, x: *const fwd.Ctx, e: mtl.ComputeEncoder, mi: us const c = x.c; const s_stride = x.s.cap / c.kpool + 1; const most = (p0 + n) / c.kpool; // the last row's blocks + const rm: u32 = if (x.k.m3_fast) 32 else 64; e.setPipeline(x.k.index_scores_nax); bind(e, 0, .{ iq, iw, x.s.mla[mi].pool, p.sscore }); e.setValue([5]u32{ p0, c.qrProj(), c.i_heads, s_stride, n }, 4); - e.dispatchGroups(size((most + 63) / 64, (n + 63) / 64, 1), size(128, 1, 1)); + e.dispatchGroups(size((most + 63) / 64, (n + rm - 1) / rm, 1), size(128, 1, 1)); e.setPipeline(x.k.index_select); bind(e, 0, .{ p.sscore, indices }); e.setValue([5]u32{ p0, c.i_topk / c.kpool, c.keyWidth(), s_stride, c.keyWidth() }, 2); diff --git a/zig/src/families/glm/wide.zig b/zig/src/families/glm/wide.zig index 52cc962efd4..b7cd74dbeb4 100644 --- a/zig/src/families/glm/wide.zig +++ b/zig/src/families/glm/wide.zig @@ -45,6 +45,7 @@ pub const Pipes = struct { mm6: affine_mm.Pipes, zeros: mtl.Buffer, // expert ids all 0: a dense GLU through the by-ids kernel (the shared expert) hash: u64, // every source compiled here + mm_bm: u32, // affine_mm dense row-tile height: 32 pre-M5 (TF_GLM_M3_FAST), 64 on M5 pub fn deinit(p: *Pipes) void { inline for (.{ @@ -188,11 +189,12 @@ fn build(gpa: std.mem.Allocator, device: mtl.Device, kda: []const u8, made: *Mad h.update(sources.ops_embed_norm); try lib(made, device, sources.ops_embed_norm, &.{ "tf_embed_b6_g64", "tf_embed_b8_g64" }, &p.embed); for ([_]u8{ 8, 2, 5, 6 }, [_]*affine_mm.Pipes{ &p.mm8, &p.mm2, &p.mm5, &p.mm6 }) |bits, out| { - const src = try affine_mm.source(device, gpa, .{ .bits = bits, .group = 64 }); + const src = try affine_mm.source(device, gpa, .{ .bits = bits, .group = 64, .glm_m3_fast = !device.tensorUnits() }); defer gpa.free(src); h.update(src); try lib(made, device, src, &affine_mm.names, out); } + p.mm_bm = if (device.tensorUnits()) 64 else 32; p.zeros = try device.buffer(64 * 4, mtl.ResourceOptions.shared); @memset(p.zeros.slice(i32, 64), 0); p.hash = h.final(); @@ -263,7 +265,7 @@ pub fn headsBatch(p: *const Pipes, e: mtl.ComputeEncoder, q: Affine, h: u32, io: var head = q; head.n = ny; affine_mm.rowSumsAt(e, pipes, 64, io.in, sums, io.rows, h * kx, io.ldx); // a head's sums one row apart - affine_mm.denseBatch(e, pipes, io.in, sums, head, io.out, io.rows, h, .{ + affine_mm.denseBatchBm(e, pipes, io.in, sums, head, io.out, io.rows, h, .{ .x_row = @intCast(io.ldx), .y_row = @intCast(io.ldo), .sums_row = @intCast(h), @@ -271,7 +273,7 @@ pub fn headsBatch(p: *const Pipes, e: mtl.ComputeEncoder, q: Affine, h: u32, io: .y_batch = @intCast(ny), .sums_batch = 1, .w_batch = @intCast(ny), - }); + }, p.mm_bm); } /// x [rows, k] through bf16 W [n, k]: scalar path, kept for tests / non-prefill callers (decode-side eh uses mtp.zig). @@ -470,17 +472,8 @@ pub fn denseMm(p: *const Pipes, e: mtl.ComputeEncoder, q: Affine, io: Io, sums: }; if (!summed) affine_mm.rowSumsAt(e, pipes, 64, io.in, sums, io.rows, q.k, io.ldx); // every member's: one k, g64 summed = true; - affine_mm.denseBatch( - e, - pipes, - io.in, - sums, - one, - part.out, - io.rows, - 1, - .{ .x_row = @intCast(io.ldx), .y_row = @intCast(io.ldo) }, - ); + const strides: affine_mm.Strides = .{ .x_row = @intCast(io.ldx), .y_row = @intCast(io.ldo) }; + affine_mm.denseBatchBm(e, pipes, io.in, sums, one, part.out, io.rows, 1, strides, p.mm_bm); } } diff --git a/zig/src/families/idol/config.zig b/zig/src/families/idol/config.zig new file mode 100644 index 00000000000..d399755886a --- /dev/null +++ b/zig/src/families/idol/config.zig @@ -0,0 +1,71 @@ +//! Idol's denoiser geometry, and the check that a snapshot's config.json names that denoiser. +const std = @import("std"); + +pub const hidden = 1024; +pub const heads = 16; +pub const head_dim = hidden / heads; +pub const ffn = 4 * hidden; +pub const layers = 24; +/// The noise and condition refiners' blocks, each. +pub const refiners = 2; +pub const latent_rows = 8192; +pub const latent_channels = 16; +pub const camera_channels = 5; +/// DINOv3 ViT-H+/16 rows at 1024 x 1024: 64 x 64 patches, the class token and four registers. +pub const cond_rows = 4101; +pub const cond_channels = 1280; +pub const cond2_channels = 128; +/// Latent, condition and camera rows through the joint blocks. +pub const joint_rows = latent_rows + cond_rows + 1; +/// RePo's hidden width (model_channels / 8) and its frequencies per head: 10, 10 and 12 for x, y and z. +pub const repo_hidden = hidden / 8; +pub const repo_pairs = head_dim / 2; +pub const time_dim = 256; +/// Every transformer block's LayerNorm32, fixed in idol-sdk's layers.py, not a config setting. +pub const block_eps: f32 = 1e-6; +/// RePo's LayerNorm32 and the output's F.layer_norm take torch's default. +pub const default_eps: f32 = 1e-5; +/// Modulated blocks: the noise refiner's, then the joint blocks. +pub const modulated = refiners + layers; + +/// Accepts the snapshot config whose denoiser this family runs (LatentSeqMMFlowModel at its released size). +pub fn check(gpa: std.mem.Allocator, text: []const u8) !void { + const doc = try std.json.parseFromSlice(std.json.Value, gpa, text, .{}); + defer doc.deinit(); + if (doc.value != .object) return error.BadConfig; + const den = doc.value.object.get("denoiser") orelse return error.BadConfig; + if (den != .object) return error.BadConfig; + const name = den.object.get("name") orelse return error.BadConfig; + if (name != .string or !std.mem.eql(u8, name.string, "LatentSeqMMFlowModel")) return error.NotIdol; + const args = den.object.get("args") orelse return error.BadConfig; + if (args != .object) return error.BadConfig; + const want = .{ .{ "q_token_length", latent_rows }, .{ "in_channels", latent_channels }, .{ "cam_channels", camera_channels }, .{ "model_channels", hidden }, .{ "cond_channels", cond_channels }, .{ "cond2_channels", cond2_channels }, .{ "num_blocks", layers }, .{ "num_refiner_blocks", refiners }, .{ "num_heads", heads }, .{ "mlp_ratio", 4 } }; + inline for (want) |kv| { + const v = args.object.get(kv[0]) orelse return error.BadConfig; + if (v != .integer or v.integer != kv[1]) { + std.log.warn("idol: denoiser {s} is not {d}; this family runs the released geometry only", .{ kv[0], kv[1] }); + return error.UnsupportedGeometry; + } + } +} + +const sample = + \\{"denoiser": {"name": "LatentSeqMMFlowModel", "args": {"q_token_length": 8192, "in_channels": 16, + \\ "cam_channels": 5, "model_channels": 1024, "cond_channels": 1280, "cond2_channels": 128, "num_blocks": 24, + \\ "num_refiner_blocks": 2, "num_heads": 16, "mlp_ratio": 4}}, "image_size": 1024, "max_voxel_level": 8} +; + +test "the released denoiser config passes; another depth, width or class does not" { + const a = std.testing.allocator; + try check(a, sample); + const deeper = try std.mem.replaceOwned(u8, a, sample, "\"num_blocks\": 24", "\"num_blocks\": 12"); + defer a.free(deeper); + try std.testing.expectError(error.UnsupportedGeometry, check(a, deeper)); + const missing = try std.mem.replaceOwned(u8, a, sample, "\"mlp_ratio\": 4", "\"mlp\": 4"); + defer a.free(missing); + try std.testing.expectError(error.BadConfig, check(a, missing)); + const other = try std.mem.replaceOwned(u8, a, sample, "LatentSeqMMFlowModel", "LatentFlowModel"); + defer a.free(other); + try std.testing.expectError(error.NotIdol, check(a, other)); + try std.testing.expectError(error.BadConfig, check(a, "{\"decoder\": {}}")); +} diff --git a/zig/src/families/idol/host.zig b/zig/src/families/idol/host.zig new file mode 100644 index 00000000000..33dd0086492 --- /dev/null +++ b/zig/src/families/idol/host.zig @@ -0,0 +1,147 @@ +//! The host's part of an Idol denoiser pass: the schedule, the time modulation, the camera token and its velocity. +const std = @import("std"); +const cfg = @import("config.zig"); +const Host = @import("weights.zig").Host; + +const H = cfg.hidden; + +pub fn half(x: f32) f32 { + return @as(f16, @floatCast(x)); +} + +/// y[o] = sum over k of x[k] w[o, k] + b[o] in fp32, w stored (outputs, inputs). +pub fn project(w: []const f32, b: []const f32, x: []const f32, y: []f32) void { + std.debug.assert(w.len == x.len * y.len and b.len == y.len); + const V = @Vector(8, f32); + for (y, 0..) |*o, row| { + const ws = w[row * x.len ..][0..x.len]; + var acc: V = @splat(0); + var k: usize = 0; + while (k + 8 <= x.len) : (k += 8) acc += @as(V, ws[k..][0..8].*) * @as(V, x[k..][0..8].*); + var sum = @reduce(.Add, acc); + while (k < x.len) : (k += 1) sum += ws[k] * x[k]; + o.* = sum + b[row]; + } +} + +fn silu(x: f32) f32 { + return x / (1.0 + @exp(-x)); +} + +fn gelu(x: f32) f32 { + return 0.5 * x * (1.0 + std.math.tanh(0.7978845608028654 * (x + 0.044715 * x * x * x))); +} + +/// The sampler's times: t = s u / (1 + (s - 1) u) for u from 1 to 0 in `steps` (steps + 1 values), in float64. +pub fn schedule(out: []f64, rescale: f64) void { + const steps = out.len - 1; + for (out, 0..) |*t, i| { + const u = 1.0 - @as(f64, @floatFromInt(i)) / @as(f64, @floatFromInt(steps)); + t.* = rescale * u / (1.0 + (rescale - 1.0) * u); + } +} + +/// The modulated blocks' six fp16 vectors each (shift, 1 + scale, gate for attention, then for the MLP). +pub const vectors = 6; +pub const Mods = [cfg.modulated][vectors][H]f16; + +/// t_embedder's output [1024] at model time `t` (1000 times the flow time), in fp32. +pub fn timeEmbedding(w: Host, t: f32, out: *[H]f32) void { + const halfdim = cfg.time_dim / 2; + var freq: [cfg.time_dim]f32 = undefined; + const lg: f32 = @floatCast(-@log(@as(f64, 10000))); + for (0..halfdim) |i| { + const a = t * @exp(lg * @as(f32, @floatFromInt(i)) / @as(f32, halfdim)); + freq[i] = @cos(a); + freq[halfdim + i] = @sin(a); + } + var mid: [H]f32 = undefined; + project(w.t1, w.t1_b, &freq, &mid); + for (&mid) |*v| v.* = silu(v.*); + project(w.t2, w.t2_b, &mid, out); +} + +/// Every modulated block's vectors and the output's fp32 shift and scale at model time `t`. +pub fn modulation(w: Host, t: f32, mods: *Mods, head: *[2][H]f32) void { + var emb: [H]f32 = undefined; + timeEmbedding(w, t, &emb); + var act: [H]f32 = undefined; + for (&act, emb) |*o, v| o.* = silu(v); + var tmod: [6 * H]f32 = undefined; + project(w.ada, w.ada_b, &act, &tmod); + for (&tmod) |*v| v.* = half(v.*); + for (mods, w.shifts) |*m, shift| { + for (0..6 * H) |i| { + const v = half(tmod[i] + half(shift[i])); + const part = i / H; + // the scales (parts 1 and 4) enter as fp16(1 + scale) + m[part][i % H] = @floatCast(if (part == 1 or part == 4) half(1.0 + v) else v); + } + } + for (0..2) |p| for (0..H) |i| { + head[p][i] = w.head[p * H + i] + emb[i]; + }; +} + +/// The camera token: cam_refiner's MLP of the five camera values, in fp32, then fp16. +pub fn cameraToken(w: Host, camera: *const [cfg.camera_channels]f32, out: []f16) void { + var mid: [H]f32 = undefined; + project(w.cam1, w.cam1_b, camera, &mid); + for (&mid) |*v| v.* = gelu(v.*); + var tok: [H]f32 = undefined; + project(w.cam2, w.cam2_b, &mid, &tok); + for (out, tok) |*o, v| o.* = @floatCast(v); +} + +/// The camera velocity from the last joint row: F.layer_norm (eps 1e-5), modulated by `head`, then cam_out_layer. +pub fn cameraVelocity(w: Host, row: []const f16, head: *const [2][H]f32, out: *[cfg.camera_channels]f32) void { + var x: [H]f32 = undefined; + var mean: f32 = 0; + for (&x, row) |*o, v| { + o.* = v; + mean += o.*; + } + mean /= H; + var q: f32 = 0; + for (x) |v| q += (v - mean) * (v - mean); + const inv = 1.0 / @sqrt(q / H + cfg.default_eps); + // shift is the table's first half, scale its second + for (&x, 0..) |*v, i| v.* = ((v.* - mean) * inv) * (1.0 + head[1][i]) + head[0][i]; + project(w.cam_out, w.cam_out_b, &x, out); +} + +/// The latents' fixed position embedding [8192, 1024] in fp16: sin then cos of each axis at 2^k frequencies. +pub fn positions(pos: []const f32, out: []f16) void { + std.debug.assert(pos.len == cfg.latent_rows * 3 and out.len == cfg.latent_rows * H); + const fd = H / 3 / 2; + const max_res = 16; + var freqs: [fd]f32 = undefined; + const rest = fd - max_res; + for (&freqs, 0..) |*f, i| { + const e: f32 = if (i < max_res) @floatFromInt(i) else @as(f32, @floatFromInt(i - max_res)) / @as(f32, rest) * max_res; + f.* = std.math.pow(f32, 2, e); + } + for (0..cfg.latent_rows) |r| { + const o = out[r * H ..][0..H]; + // outer(x.reshape(-1), freqs) then cat(sin, cos) per value: each axis's fd sines, then its fd cosines + for (0..3) |a| for (0..fd) |j| { + const ang = pos[r * 3 + a] * freqs[j] * 2 * std.math.pi; + o[a * 2 * fd + j] = @floatCast(@sin(ang)); + o[a * 2 * fd + fd + j] = @floatCast(@cos(ang)); + }; + for (o[6 * fd ..]) |*v| v.* = 0; + } +} + +test "the schedule runs from 1 to 0, denser at high noise for rescale 3" { + var t: [51]f64 = undefined; + schedule(&t, 3.0); + try std.testing.expectEqual(@as(f64, 1), t[0]); + try std.testing.expectEqual(@as(f64, 0), t[50]); + try std.testing.expectApproxEqAbs(@as(f64, 0.75), t[25], 1e-12); +} + +test "fp16 rounding is to nearest, ties to even" { + try std.testing.expectEqual(@as(f32, 1.0), half(1.0 + 1.0 / 4096.0)); + try std.testing.expectEqual(@as(f32, 1.0 + 1.0 / 512.0), half(1.0 + 3.0 / 2048.0)); +} diff --git a/zig/src/families/idol/idol.zig b/zig/src/families/idol/idol.zig new file mode 100644 index 00000000000..a2aff609445 --- /dev/null +++ b/zig/src/families/idol/idol.zig @@ -0,0 +1,19 @@ +//! Idol image to 3D: its denoiser on Metal (a denoiser beside the lane engine, not a token family). +pub const config = @import("config.zig"); +pub const host = @import("host.zig"); +pub const weights = @import("weights.zig"); +pub const kernels = @import("kernels.zig"); +pub const model = @import("model.zig"); +pub const reference = @import("reference.zig"); +pub const Model = model.Model; +pub const Condition = model.Condition; +pub const Timing = model.Timing; + +test { + _ = config; + _ = host; + _ = weights; + _ = kernels; + _ = model; + _ = reference; +} diff --git a/zig/src/families/idol/kernels.zig b/zig/src/families/idol/kernels.zig new file mode 100644 index 00000000000..2efe840cdc2 --- /dev/null +++ b/zig/src/families/idol/kernels.zig @@ -0,0 +1,209 @@ +//! Idol's Metal pipelines: its fp16 projections and steps, fp32 projections and head-64 attention. +const std = @import("std"); +const mtl = @import("metal"); +const sources = @import("kernel_sources"); +const frags = @import("../../core/frags.zig"); +const cfg = @import("config.zig"); +pub const Ref = @import("../../core/qwen_vl/weights.zig").Ref; + +/// Each pipeline by its function. +pub const names = [_][]const u8{ + "id_linear_00", + "id_linear_01", + "id_linear_10", + "id_linear_11", + "id_linear_gelu_00", + "id_linear_gelu_01", + "id_linear_gelu_10", + "id_linear_gelu_11", + "id_norm", + "id_norm32", + "id_repo", + "id_qk", + "id_gate_add", + "id_embed", + "id_cond", + "id_bias32", + "id_gemm32", + "id_split_0", + "id_split_1", + "id_norm_split", + "id_attention_00", + "id_attention_01", + "id_attention_10", + "id_attention_11", +}; +const linear_first = 0; +const attention_first = blk: { + for (names, 0..) |n, i| if (std.mem.eql(u8, n, "id_attention_00")) break :blk i; + unreachable; +}; + +pub const Norm = enum(u32) { plain = 0, affine = 1, modulated = 2 }; + +pub const Kernels = struct { + own: mtl.Library, + p: [names.len]mtl.Pipeline, + + pub fn load(gpa: std.mem.Allocator, device: mtl.Device) !Kernels { + var k: Kernels = undefined; + const own = try frags.source(device, gpa, sources.idol); + defer gpa.free(own); + k.own = try mtl.Library.fromSource(device, own, mtl.CompileOptions.mlx()); + errdefer k.own.deinit(); + var made: usize = 0; + errdefer for (k.p[0..made]) |p| p.deinit(); + for (names, 0..) |name, i| { + k.p[i] = try mtl.Pipeline.init(device, k.own, name, false); + made += 1; + } + return k; + } + + pub fn deinit(k: *Kernels) void { + for (k.p) |p| p.deinit(); + k.own.deinit(); + } + + pub fn get(k: *const Kernels, comptime name: []const u8) mtl.Pipeline { + inline for (names, 0..) |n, i| if (comptime std.mem.eql(u8, n, name)) return k.p[i]; + @compileError("no pipeline " ++ name); + } + + /// y [M, N] (rows `ldd` apart) = x [M, K] w^T in fp32 FMA, w as stored [N, K]; K % 32, N % 64 (or N < 64, % 8) = 0. + pub fn linear32(k: *const Kernels, e: mtl.ComputeEncoder, x: Ref, w: Ref, y: Ref, M: usize, N: usize, K: usize, ldd: usize) void { + std.debug.assert(K % 32 == 0 and (N % 64 == 0 or (N < 64 and N % 8 == 0))); + const params = [4]u32{ @intCast(M), @intCast(N), @intCast(K), @intCast(ldd) }; + bind(e, k.get("id_gemm32"), &.{ x, w, y }, params); + e.dispatchGroups(mtl.Size.of((N + 63) / 64, (M + 63) / 64, 1), mtl.Size.of(128, 1, 1)); + } + + /// c [M, 256] fp32 = x3 [M, 3072] w3^T over fp16: a split LayerNorm's rows and a RePo layer's split maps. + pub fn split(k: *const Kernels, e: mtl.ComputeEncoder, x3: Ref, w3: Ref, c: Ref, M: usize) void { + const N = 2 * cfg.repo_hidden; + const K = 3 * cfg.hidden; + const tn: usize = N / 64; + const tm = (M + 63) / 64; + const swz: u6 = if (tm <= 3) 0 else 1; + e.setPipeline(if (M % 64 == 0) k.get("id_split_1") else k.get("id_split_0")); + e.setBuffer(x3.buf, x3.off, 0); + e.setBuffer(w3.buf, w3.off, 1); + var p: [16]i32 = @splat(0); + const vals = [_]usize{ M, N, K, K, K, N, tn, tm, 1, M * N, K, swz, 0, 0 }; + for (vals, 0..) |v, i| p[i] = @intCast(v); + e.setBytes(std.mem.asBytes(&p), 2); + e.setBuffer(c.buf, c.off, 3); + const tiles = (tn << swz) * ((tm + (@as(usize, 1) << swz) - 1) >> swz); + e.dispatchThreads(mtl.Size.of(tiles * 32, 2, 2), mtl.Size.of(32, 2, 2)); + } + + /// x3 rows [hi | hi | lo] of the affine LayerNorm32 of x's rows, for `split`. + pub fn normSplit(k: *const Kernels, e: mtl.ComputeEncoder, x: Ref, w: Ref, b: Ref, x3: Ref, rows: usize, eps: f32) void { + const params = extern struct { width: u32, eps: f32, mode: u32 }{ .width = cfg.hidden, .eps = eps, .mode = 1 }; + bind(e, k.get("id_norm_split"), &.{ x, w, b, x3 }, params); + e.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(256, 1, 1)); + } + + /// y [M, N] = fp16(x w^T + b) in fp16 with fp32 sums, then GELU (rounded again) when `gelu`. + pub fn linear(k: *const Kernels, e: mtl.ComputeEncoder, x: Ref, w: Ref, b: Ref, y: Ref, M: usize, N: usize, K: usize, gelu: bool) void { + const tn = (N + 127) / 128; + const tm = (M + 63) / 64; + const form = @as(usize, @intFromBool(M % 64 == 0)) * 2 + @intFromBool(N % 128 == 0); + e.setPipeline(k.p[linear_first + @as(usize, @intFromBool(gelu)) * 4 + form]); + e.setBuffer(x.buf, x.off, 0); + e.setBuffer(w.buf, w.off, 1); + var p: [16]i32 = @splat(0); + const vals = [_]usize{ M, N, K, K, K, N, tn, tm, 0, K / 256 }; + for (vals, 0..) |v, i| p[i] = @intCast(v); + e.setBytes(std.mem.asBytes(&p), 2); + e.setBuffer(y.buf, y.off, 3); + e.setBuffer(b.buf, b.off, 4); + e.dispatchGroups(mtl.Size.of(tn, tm, 1), mtl.Size.of(256, 1, 1)); + } + + /// o rows [Lq, heads * 64] = softmax(q k^T / 8) v for q [heads, Lq, 64] and k, v [heads, Lk, 64]. + pub fn attention(k: *const Kernels, e: mtl.ComputeEncoder, q: Ref, kb: Ref, vb: Ref, o: Ref, lq: usize, lk: usize) void { + const form = @as(usize, @intFromBool(lq % 64 == 0)) * 2 + @intFromBool(lk % 32 == 0); + const nq = (lq + 63) / 64; + const nk = (lk + 31) / 32; + e.setPipeline(k.p[attention_first + form]); + for ([_]Ref{ q, kb, vb }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); + // heads, q rows, k rows, k blocks, last q block, last k block, rows in the last q block and in the last k block + var params: [8]i32 = .{ cfg.heads, @intCast(lq), @intCast(lk), @intCast(nk), @intCast(nq - 1), @intCast(nk - 1), @intCast(lq - (nq - 1) * 64), @intCast(lk - (nk - 1) * 32) }; + e.setBytes(std.mem.asBytes(¶ms), 3); + var f: [4]f32 = .{ 1.0 / @sqrt(@as(f32, cfg.head_dim)), 0, 0, 0 }; + e.setBytes(std.mem.asBytes(&f), 4); + e.setBuffer(o.buf, o.off, 5); + e.dispatchGroups(mtl.Size.of(nq, cfg.heads, 1), mtl.Size.of(32, 4, 1)); + } + + /// y = LayerNorm32 of x's rows in fp32 rounded to fp16, then affine (w, b fp32) or modulated (s1, sh fp16). + pub fn norm(k: *const Kernels, e: mtl.ComputeEncoder, x: Ref, w: Ref, b: Ref, s1: Ref, sh: Ref, y: Ref, rows: usize, eps: f32, mode: Norm) void { + const params = extern struct { width: u32, eps: f32, mode: u32 }{ .width = cfg.hidden, .eps = eps, .mode = @backingInt(mode) }; + bind(e, k.get("id_norm"), &.{ x, w, b, s1, sh, y }, params); + e.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(256, 1, 1)); + } + + /// y fp32 = LayerNorm of x's rows times w plus b (affine), or times (1 + w) plus b (modulated). + pub fn norm32(k: *const Kernels, e: mtl.ComputeEncoder, x: Ref, w: Ref, b: Ref, y: Ref, rows: usize, eps: f32, mode: Norm) void { + const params = extern struct { width: u32, eps: f32, mode: u32 }{ .width = cfg.hidden, .eps = eps, .mode = @backingInt(mode) }; + bind(e, k.get("id_norm32"), &.{ x, w, b, y }, params); + e.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(256, 1, 1)); + } + + /// cos, sin [rows, 16, 32] of RePo from its gate and content sums (fp32 rows of 256) and final map. + pub fn repo(k: *const Kernels, e: mtl.ComputeEncoder, gc: Ref, inv: f32, final: Ref, freqs: Ref, cos: Ref, sin: Ref, rows: usize) void { + const params = extern struct { rows: u32, stride: u32, inv: f32 }{ .rows = @intCast(rows), .stride = 2 * cfg.repo_hidden, .inv = inv }; + bind(e, k.get("id_repo"), &.{ gc, final, freqs, cos, sin }, params); + e.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(64, 1, 1)); + } + + /// q, k, v heads [16, rows, 64] from packed qkv rows: rotated by cos, sin, then normed by gq, gk. + pub fn heads(k: *const Kernels, e: mtl.ComputeEncoder, qkv: Ref, gq: Ref, gk: Ref, cos: Ref, sin: Ref, q: Ref, kk: Ref, v: Ref, rows: usize) void { + const params = extern struct { rows: u32, scale: f32 }{ .rows = @intCast(rows), .scale = @sqrt(@as(f32, cfg.head_dim)) }; + bind(e, k.get("id_qk"), &.{ qkv, gq, gk, cos, sin, q, kk, v }, params); + e.dispatchGroups(mtl.Size.of(rows, 2, 1), mtl.Size.of(256, 1, 1)); + } + + /// x [rows, 1024] += y gated by the fp16 vector g, in place. + pub fn gateAdd(k: *const Kernels, e: mtl.ComputeEncoder, x: Ref, y: Ref, g: Ref, rows: usize) void { + bind(e, k.get("id_gate_add"), &.{ x, y, g }, @as(u32, cfg.hidden)); + e.dispatchThreads(mtl.Size.of(cfg.hidden, rows, 1), mtl.Size.of(256, 1, 1)); + } + + /// x [8192, 1024] = fp16(fp16(z w^T + b) + pe). + pub fn embed(k: *const Kernels, e: mtl.ComputeEncoder, z: Ref, w: Ref, b: Ref, pe: Ref, x: Ref) void { + e.setPipeline(k.get("id_embed")); + for ([_]Ref{ z, w, b, pe, x }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.dispatchThreads(mtl.Size.of(cfg.hidden, cfg.latent_rows, 1), mtl.Size.of(256, 1, 1)); + } + + /// y [rows, 1024] = fp16((a + ba) + (c + bc)). + pub fn cond(k: *const Kernels, e: mtl.ComputeEncoder, a: Ref, ba: Ref, c: Ref, bc: Ref, y: Ref, rows: usize) void { + bind(e, k.get("id_cond"), &.{ a, ba, c, bc, y }, @as(u32, cfg.hidden)); + e.dispatchThreads(mtl.Size.of(cfg.hidden, rows, 1), mtl.Size.of(256, 1, 1)); + } + + /// y [rows, width] += b by column, fp32. + pub fn bias32(k: *const Kernels, e: mtl.ComputeEncoder, y: Ref, b: Ref, rows: usize, width: usize) void { + bind(e, k.get("id_bias32"), &.{ y, b }, @as(u32, @intCast(width))); + e.dispatchThreads(mtl.Size.of(width, rows, 1), mtl.Size.of(@min(width, 256), 1, 1)); + } +}; + +/// One kernel's buffers in order, then its parameters at the next index. +pub fn bind(e: mtl.ComputeEncoder, p: mtl.Pipeline, refs: []const Ref, params: anytype) void { + e.setPipeline(p); + for (refs, 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setValue(params, refs.len); +} + +test "every Idol pipeline compiles and loads on this GPU" { + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const device = mtl.Device.init() catch return error.SkipZigTest; + defer device.deinit(); + if (!device.tensorUnits()) return error.SkipZigTest; + var k = try Kernels.load(std.testing.allocator, device); + k.deinit(); +} diff --git a/zig/src/families/idol/model.zig b/zig/src/families/idol/model.zig new file mode 100644 index 00000000000..27c6e12a134 --- /dev/null +++ b/zig/src/families/idol/model.zig @@ -0,0 +1,244 @@ +//! Idol's denoiser on Metal: the image condition refined once, then latent, condition and camera rows each step. +const std = @import("std"); +const mtl = @import("metal"); +const cfg = @import("config.zig"); +const host = @import("host.zig"); +const wts = @import("weights.zig"); +const ks = @import("kernels.zig"); +const Ref = ks.Ref; + +const H = cfg.hidden; +const F = cfg.ffn; +const L = cfg.joint_rows; +const R = cfg.latent_rows; +const C = cfg.cond_rows; + +pub const Timing = struct { wall: f64, gpu: f64, host: f64 }; + +/// A refined image condition: the condition refiner's rows [4101, 1024] fp16. +pub const Condition = struct { + rows: mtl.Buffer, + + pub fn deinit(c: *Condition) void { + c.rows.deinit(); + } +}; + +/// The scratch buffer's parts in bytes, in the order of Model's views. +const parts = [_]usize{ + L * H * 2, L * H * 2, L * 3 * H * 2, L * H * 2, L * H * 2, L * H * 2, L * H * 2, L * H * 2, + L * F * 2, L * H * 4, L * 2 * cfg.repo_hidden * 4, L * cfg.heads * cfg.repo_pairs * 4, L * cfg.heads * cfg.repo_pairs * 4, R * cfg.latent_channels * 4, R * cfg.latent_channels * 4, cfg.modulated * host.vectors * H * 2, + 2 * H * 4, C * cfg.cond_channels * 4, C * cfg.cond2_channels * 4, H * 2, R * H * 2, +}; + +pub fn scratchBytes() usize { + var total: usize = 0; + for (parts) |n| total += std.mem.alignForward(usize, n, 256); + return total; +} + +pub const Model = struct { + gpa: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + k: ks.Kernels, + w: wts.Weights, + scratch: mtl.Buffer, + // fp16 rows: the stream, a norm's output, packed qkv, heads [16, rows, 64], attention rows, a projection's output + x: Ref, + xn: Ref, + qkv: Ref, + q: Ref, + k_: Ref, + v: Ref, + att: Ref, + y: Ref, + /// the MLP's GELU rows + u: Ref, + /// fp32 rows: RePo's norm (and the condition's two projections), its gate | content sums, cos and sin + ln: Ref, + gc: Ref, + cos: Ref, + sin: Ref, + lat: Ref, + vel: Ref, + mods: Ref, + head: Ref, + f1: Ref, + f2: Ref, + ones: Ref, + pe: Ref, + /// The model time `mods` and `head` hold, if any. + time: ?f32 = null, + + /// The denoiser of snapshot folder `dir`. + pub fn load(gpa: std.mem.Allocator, io: std.Io, device: mtl.Device, dir: []const u8) !*Model { + // qualified on the M5's tensor units alone: the projections and attention take another path before them + if (!device.tensorUnits()) { + std.log.err("idol: {s} has no tensor units; this family runs on the M5's alone, the only chip it was checked on", .{device.name()}); + return error.TensorUnitsRequired; + } + const t = try gpa.create(Model); + errdefer gpa.destroy(t); + t.* = undefined; + t.gpa = gpa; + t.device = device; + t.time = null; + t.queue = try device.queue(); + errdefer t.queue.deinit(); + t.k = try ks.Kernels.load(gpa, device); + errdefer t.k.deinit(); + t.w = try wts.load(gpa, io, device, dir); + errdefer t.w.deinit(); + t.scratch = try device.buffer(scratchBytes(), mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); + var at: usize = 0; + const views = [_]*Ref{ &t.x, &t.xn, &t.qkv, &t.q, &t.k_, &t.v, &t.att, &t.y, &t.u, &t.ln, &t.gc, &t.cos, &t.sin, &t.lat, &t.vel, &t.mods, &t.head, &t.f1, &t.f2, &t.ones, &t.pe }; + for (views, parts) |view, n| { + view.* = .{ .buf = t.scratch, .off = at }; + at += std.mem.alignForward(usize, n, 256); + } + @memset(halves(t.ones, H), 1.0); + host.positions(t.w.host.pos, halves(t.pe, R * H)); + return t; + } + + pub fn deinit(t: *Model) void { + t.scratch.deinit(); + t.w.deinit(); + t.k.deinit(); + t.queue.deinit(); + t.gpa.destroy(t); + } + + fn floats(r: Ref, n: usize) []f32 { + return @as([*]f32, @ptrCast(@alignCast(r.addr())))[0..n]; + } + + fn halves(r: Ref, n: usize) []f16 { + return @as([*]f16, @ptrCast(@alignCast(r.addr())))[0..n]; + } + + /// The modulated block `i`'s vector `part` (0 shift, 1 one plus scale, 2 gate; 3 to 5 the MLP's). + fn vec(t: *const Model, i: usize, part: usize) Ref { + return t.mods.at(((i * host.vectors) + part) * H * 2); + } + + /// The image condition: DINOv3 rows [4101, 1280] and FLUX.2 VAE rows [4101, 128] (zeros: the negative branch). + pub fn condition(t: *Model, feature1: []const f32, feature2: []const f32) !Condition { + if (feature1.len != C * cfg.cond_channels or feature2.len != C * cfg.cond2_channels) return error.ConditionRows; + var c: Condition = .{ .rows = try t.device.buffer(C * H * 2, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked) }; + errdefer c.rows.deinit(); + @memcpy(floats(t.f1, feature1.len), feature1); + @memcpy(floats(t.f2, feature2.len), feature2); + const started = mtl.clock.seconds(); + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = t.queue.commandBuffer(); + const e = cb.compute(.serial); + const a = t.ln; + const b = t.ln.at(C * H * 4); + t.k.linear32(e, t.f1, t.w.cond, a, C, H, cfg.cond_channels, H); + t.k.linear32(e, t.f2, t.w.cond2, b, C, H, cfg.cond2_channels, H); + t.k.cond(e, a, t.w.cond_b, b, t.w.cond2_b, t.x, C); + for (t.w.context, t.w.context_repo) |blk, r| t.block(e, blk, r, C, null); + _ = try finish(cb, e, started, 0); + @memcpy(halves(.{ .buf = c.rows }, C * H), halves(t.x, C * H)); + return c; + } + + /// The velocity of latent [8192, 16] and camera [5] at model time `time` (1000 times t) under condition `c`. + pub fn forward(t: *Model, c: *const Condition, latent: []const f32, camera: *const [cfg.camera_channels]f32, time: f32, velocity: []f32, camera_velocity: *[cfg.camera_channels]f32) !Timing { + if (latent.len != R * cfg.latent_channels or velocity.len != latent.len) return error.LatentRows; + const started = mtl.clock.seconds(); + if (t.time != time) { + t.time = null; + host.modulation(t.w.host, time, @ptrCast(@alignCast(t.mods.addr())), @ptrCast(@alignCast(t.head.addr()))); + t.time = time; + } + @memcpy(floats(t.lat, latent.len), latent); + @memcpy(halves(t.x.at(R * H * 2), C * H), halves(.{ .buf = c.rows }, C * H)); + host.cameraToken(t.w.host, camera, halves(t.x.at((L - 1) * H * 2), H)); + const spent = mtl.clock.seconds() - started; + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = t.queue.commandBuffer(); + const e = cb.compute(.serial); + t.k.embed(e, t.lat, t.w.input, t.w.input_b, t.pe, t.x); + for (t.w.noise, t.w.noise_repo, 0..) |blk, r, i| t.block(e, blk, r, R, i); + for (t.w.blocks, t.w.repo, 0..) |blk, r, i| t.block(e, blk, r, L, cfg.refiners + i); + const head: Ref = t.head; + t.k.norm32(e, t.x, head.at(H * 4), head, t.ln, R, cfg.default_eps, .modulated); + t.k.linear32(e, t.ln, t.w.out, t.vel, R, cfg.latent_channels, H, cfg.latent_channels); + t.k.bias32(e, t.vel, t.w.out_b, R, cfg.latent_channels); + const timing = try finish(cb, e, started, spent); + @memcpy(velocity, floats(t.vel, velocity.len)); + host.cameraVelocity(t.w.host, halves(t.x.at((L - 1) * H * 2), H), @ptrCast(@alignCast(t.head.addr())), camera_velocity); + return timing; + } + + /// Modulated block `index` alone at model time `time` on `rows` (the noise refiner's 8192, else 12294) given rows. + pub fn blockAt(t: *Model, index: usize, rows: []const f16, time: f32) !void { + const n: usize = if (index < cfg.refiners) R else L; + if (index >= cfg.modulated or rows.len != n * H) return error.BlockRows; + if (t.time != time) { + t.time = null; + host.modulation(t.w.host, time, @ptrCast(@alignCast(t.mods.addr())), @ptrCast(@alignCast(t.head.addr()))); + t.time = time; + } + @memcpy(halves(t.x, rows.len), rows); + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = t.queue.commandBuffer(); + const e = cb.compute(.serial); + if (index < cfg.refiners) t.block(e, t.w.noise[index], t.w.noise_repo[index], n, index) else t.block(e, t.w.blocks[index - cfg.refiners], t.w.repo[index - cfg.refiners], n, index); + _ = try finish(cb, e, mtl.clock.seconds(), 0); + } + + /// The stream's first `rows` rows as the last pass left them, fp16. + pub fn stream(t: *const Model, rows: usize) []const f16 { + return halves(t.x, rows * H); + } + + fn finish(cb: mtl.CommandBuffer, e: mtl.ComputeEncoder, started: f64, spent: f64) !Timing { + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |msg| { + std.log.err("idol: a pass failed on the GPU: {s}", .{msg}); + return error.GpuFailure; + } + return .{ .wall = mtl.clock.seconds() - started, .gpu = cb.gpuSeconds(), .host = spent }; + } + + /// One block over the stream's first `rows` rows: modulated block `mod`, or the condition refiner's (null). + fn block(t: *const Model, e: mtl.ComputeEncoder, b: wts.Block, r: wts.Repo, rows: usize, mod: ?usize) void { + const k = &t.k; + // RePo: angles from the block's input rows + k.normSplit(e, t.x, r.norm, r.norm_b, t.qkv, rows, cfg.default_eps); + k.split(e, t.qkv, r.maps, t.gc, rows); + k.repo(e, t.gc, r.inv, r.final, r.freqs, t.cos, t.sin, rows); + if (mod) |m| { + k.norm(e, t.x, t.ln, t.ln, t.vec(m, 1), t.vec(m, 0), t.xn, rows, cfg.block_eps, .modulated); + } else { + k.norm(e, t.x, b.norm1, b.norm1_b, t.ones, t.ones, t.xn, rows, cfg.block_eps, .affine); + } + k.linear(e, t.xn, b.qkv, b.qkv_b, t.qkv, rows, 3 * H, H, false); + k.heads(e, t.qkv, b.q_norm, b.k_norm, t.cos, t.sin, t.q, t.k_, t.v, rows); + k.attention(e, t.q, t.k_, t.v, t.att, rows, rows); + k.linear(e, t.att, b.out, b.out_b, t.y, rows, H, H, false); + k.gateAdd(e, t.x, t.y, if (mod) |m| t.vec(m, 2) else t.ones, rows); + if (mod) |m| { + k.norm(e, t.x, t.ln, t.ln, t.vec(m, 4), t.vec(m, 3), t.xn, rows, cfg.block_eps, .modulated); + } else { + k.norm(e, t.x, b.norm2, b.norm2_b, t.ones, t.ones, t.xn, rows, cfg.block_eps, .affine); + } + k.linear(e, t.xn, b.up, b.up_b, t.u, rows, F, H, true); + k.linear(e, t.u, b.down, b.down_b, t.y, rows, H, F, false); + k.gateAdd(e, t.x, t.y, if (mod) |m| t.vec(m, 5) else t.ones, rows); + } +}; + +test "scratch for the joint rows fits a GPU buffer, each part 256-aligned" { + try std.testing.expect(scratchBytes() < 1 << 31); + try std.testing.expectEqual(@as(usize, 12294), L); +} diff --git a/zig/src/families/idol/reference.zig b/zig/src/families/idol/reference.zig new file mode 100644 index 00000000000..549b92fa99c --- /dev/null +++ b/zig/src/families/idol/reference.zig @@ -0,0 +1,79 @@ +//! Comparing a velocity with idol-sdk's: cosine, largest difference and worst row, and the gate against fp32. +const std = @import("std"); + +pub const Match = struct { max_abs: f64, cosine: f64, worst_row: f64 }; + +/// Largest absolute difference, cosine, and the largest relative L2 error of one row of `width`. +pub fn match(ours: []const f32, theirs: []const f32, width: usize) Match { + std.debug.assert(ours.len == theirs.len and ours.len % width == 0); + var dot: f64 = 0; + var aa: f64 = 0; + var bb: f64 = 0; + var most: f64 = 0; + var worst: f64 = 0; + var row: usize = 0; + while (row < ours.len) : (row += width) { + var rd: f64 = 0; + var rb: f64 = 0; + for (ours[row..][0..width], theirs[row..][0..width]) |a, b| { + const d = @as(f64, a) - b; + dot += @as(f64, a) * b; + aa += @as(f64, a) * a; + bb += @as(f64, b) * b; + rd += d * d; + rb += @as(f64, b) * b; + most = @max(most, @abs(d)); + } + worst = @max(worst, @sqrt(rd / @max(rb, 1e-30))); + } + return .{ .max_abs = most, .cosine = dot / @sqrt(@max(aa * bb, 1e-300)), .worst_row = worst }; +} + +/// How far ours may sit from the fp32 ruler: this many times the torch fp16 reference's own distance. +pub const factor = 2.0; + +/// Against the fp32 ruler: worst row and 1 - cosine within `factor` times the fp16 reference's own; non-finite fails. +pub fn within(ours: Match, reference: Match) bool { + if (!std.math.isFinite(ours.cosine) or !std.math.isFinite(ours.worst_row)) return false; + return ours.worst_row <= factor * reference.worst_row and (1 - ours.cosine) <= factor * (1 - reference.cosine); +} + +/// The cosine half of `within`: for a velocity, whose worst row the gate takes over the whole run instead. +pub fn withinCosine(ours: Match, reference: Match) bool { + return std.math.isFinite(ours.cosine) and (1 - ours.cosine) <= factor * (1 - reference.cosine); +} + +test "a velocity matches itself exactly" { + const v = [_]f32{ 1, -2, 3, 0.5, 0.25, -1 }; + const m = match(&v, &v, 3); + try std.testing.expectEqual(@as(f64, 0), m.max_abs); + try std.testing.expectEqual(@as(f64, 0), m.worst_row); + try std.testing.expectApproxEqAbs(@as(f64, 1), m.cosine, 1e-15); +} + +test "a planted 5% error in one row fails the gate though everything else repeats exactly" { + const a = std.testing.allocator; + const n = 64 * 16; + const ruler = try a.alloc(f32, n); + defer a.free(ruler); + const fp16 = try a.alloc(f32, n); + defer a.free(fp16); + const ours = try a.alloc(f32, n); + defer a.free(ours); + var rng = std.Random.DefaultPrng.init(7); + for (ruler, fp16, ours) |*r, *f, *o| { + r.* = rng.random().floatNorm(f32); + f.* = r.* * (1 + 1e-3 * rng.random().floatNorm(f32)); + o.* = r.* * (1 + 1e-3 * rng.random().floatNorm(f32)); + } + const reference = match(fp16, ruler, 16); + try std.testing.expect(within(match(ours, ruler, 16), reference)); + for (ours[5 * 16 ..][0..16]) |*o| o.* *= 1.05; + try std.testing.expect(!within(match(ours, ruler, 16), reference)); +} + +test "non-finite values fail the gate" { + const ruler = [_]f32{ 1, 2, 3, 4 }; + const bad = [_]f32{ 1, std.math.nan(f32), 3, 4 }; + try std.testing.expect(!within(match(&bad, &ruler, 2), match(&ruler, &ruler, 2))); +} diff --git a/zig/src/families/idol/weights.zig b/zig/src/families/idol/weights.zig new file mode 100644 index 00000000000..27d872168c1 --- /dev/null +++ b/zig/src/families/idol/weights.zig @@ -0,0 +1,310 @@ +//! Idol's denoiser tensors (fp32 as stored): the blocks' linears to fp16 at load as idol-sdk does, the rest fp32. +const std = @import("std"); +const mtl = @import("metal"); +const ck = @import("../../core/checkpoint_metal.zig"); +const cfg = @import("config.zig"); +const Ref = @import("../../core/qwen_vl/weights.zig").Ref; + +const H = cfg.hidden; + +/// A transformer block: fp16 linears and biases, fp32 head RMSNorm gammas [16, 64]; norms only in the refiner. +pub const Block = struct { qkv: Ref, qkv_b: Ref, out: Ref, out_b: Ref, up: Ref, up_b: Ref, down: Ref, down_b: Ref, q_norm: Ref, k_norm: Ref, norm1: Ref = undefined, norm1_b: Ref = undefined, norm2: Ref = undefined, norm2_b: Ref = undefined }; + +/// A RePo layer: fp32 norm; gate | content maps over `inv` (a power of two) as fp16 [hi | lo | hi]; final map, freqs. +pub const Repo = struct { norm: Ref, norm_b: Ref, maps: Ref, inv: f32, final: Ref, freqs: Ref }; + +const repos = 2 * cfg.refiners + cfg.layers; +const map_bytes = 2 * cfg.repo_hidden * 3 * H * 2; + +/// The power of two that puts a map's largest magnitude in [2^13, 2^14), so its fp16 halves keep their bits. +fn mapScale(gate: []const f32, content: []const f32) f32 { + var most: f32 = 0; + for (gate) |v| most = @max(most, @abs(v)); + for (content) |v| most = @max(most, @abs(v)); + if (most == 0 or !std.math.isFinite(most)) return 1; + return std.math.ldexp(@as(f32, 1), 13 - std.math.ilogb(most)); +} + +/// Row `n` of a map as [hi | lo | hi] fp16 of `scale` times its values. +fn split(src: []const f32, scale: f32, dst: []f16) void { + for (src, 0..) |v, i| { + const x = v * scale; + const hi: f16 = @floatCast(x); + dst[i] = hi; + dst[H + i] = @floatCast(x - @as(f32, hi)); + dst[2 * H + i] = hi; + } +} + +/// The fp32 vectors and small matrices the host reads each timestep. +pub const Host = struct { + t1: []const f32, + t1_b: []const f32, + t2: []const f32, + t2_b: []const f32, + ada: []const f32, + ada_b: []const f32, + cam1: []const f32, + cam1_b: []const f32, + cam2: []const f32, + cam2_b: []const f32, + cam_out: []const f32, + cam_out_b: []const f32, + /// Each modulated block's own shift table [6144]: the noise refiner's, then the joint blocks'. + shifts: [cfg.modulated][]const f32, + /// The output's shift table [2, 1024]. + head: []const f32, + pos: []const f32, +}; + +pub const Weights = struct { + ck: ck.Checkpoint, + noise: [cfg.refiners]Block, + context: [cfg.refiners]Block, + blocks: [cfg.layers]Block, + noise_repo: [cfg.refiners]Repo, + context_repo: [cfg.refiners]Repo, + repo: [cfg.layers]Repo, + input: Ref, + input_b: Ref, + cond: Ref, + cond_b: Ref, + cond2: Ref, + cond2_b: Ref, + out: Ref, + out_b: Ref, + host: Host, + + pub fn deinit(w: *Weights) void { + w.ck.deinit(); + } +}; + +const linears = [_][]const u8{ "attn.qkv", "attn.out", "mlp.mlp.0", "mlp.mlp.2" }; + +/// The blocks' linear weights stay in the file: load reads each once into its fp16 copy. +fn later(name: []const u8, rank: usize) bool { + if (rank != 2) return false; + const owned = std.mem.startsWith(u8, name, "blocks.") or std.mem.startsWith(u8, name, "noise_refiner.") or std.mem.startsWith(u8, name, "context_refiner."); + return owned and std.mem.endsWith(u8, name, ".weight"); +} + +fn check(t: ck.Tensor, name: []const u8, shape: []const usize) !void { + if (t.dtype != .f32 or t.rank != shape.len or !std.mem.eql(usize, t.shape[0..t.rank], shape)) { + std.log.err("idol: {s} is {t} {any}; the denoiser reads f32 {any}", .{ name, t.dtype, t.shape[0..t.rank], shape }); + return error.UnexpectedTensor; + } +} + +fn take(c: *const ck.Checkpoint, name: []const u8, shape: []const usize) !Ref { + const t = try c.get(name); + try check(t, name, shape); + if (t.offset % 16 != 0) return error.UnalignedTensor; + return .{ .buf = t.buffer, .off = t.offset }; +} + +fn floats(c: *const ck.Checkpoint, name: []const u8, shape: []const usize) ![]const f32 { + const t = try c.get(name); + try check(t, name, shape); + return t.host(f32); +} + +/// fp16 values written into an owned buffer, bump-allocated 256-aligned. +const Halves = struct { + buf: mtl.Buffer, + at: usize = 0, + stage: []f32, + + fn put(h: *Halves, src: []const f32) Ref { + const dst = @as([*]f16, @ptrCast(@alignCast(h.buf.contents() + h.at)))[0..src.len]; + for (dst, src) |*o, v| o.* = @floatCast(v); + const r: Ref = .{ .buf = h.buf, .off = h.at }; + h.at += std.mem.alignForward(usize, src.len * 2, ck.alignment); + return r; + } + + /// A deferred fp32 weight read in staged pieces, rounded to fp16. + fn read(h: *Halves, c: *const ck.Checkpoint, name: []const u8, shape: [2]usize) !Ref { + const d = c.deferred.get(name) orelse return error.MissingTensor; + if (d.dtype != .f32 or d.rank != 2 or d.shape[0] != shape[0] or d.shape[1] != shape[1]) { + std.log.err("idol: {s} is {t} {any}; the denoiser reads f32 {any}", .{ name, d.dtype, d.shape[0..d.rank], shape }); + return error.UnexpectedTensor; + } + const n = shape[0] * shape[1]; + const r: Ref = .{ .buf = h.buf, .off = h.at }; + const dst = @as([*]f16, @ptrCast(@alignCast(h.buf.contents() + h.at)))[0..n]; + var done: usize = 0; + while (done < n) { + const part = @min(h.stage.len, n - done); + try c.read(name, done * 4, std.mem.sliceAsBytes(h.stage[0..part])); + for (dst[done..][0..part], h.stage[0..part]) |*o, v| o.* = @floatCast(v); + done += part; + } + h.at += std.mem.alignForward(usize, n * 2, ck.alignment); + return r; + } +}; + +const per_block = blk: { + var n: usize = 0; + for ([_]usize{ 3 * H * H, 3 * H, H * H, H, cfg.ffn * H, cfg.ffn, H * cfg.ffn, H }) |v| n += std.mem.alignForward(usize, v * 2, ck.alignment); + break :blk n; +}; + +fn block(c: *const ck.Checkpoint, h: *Halves, prefix: []const u8, i: usize, affine: bool) !Block { + var name: [96]u8 = undefined; + const P = struct { + fn n(buf: []u8, p: []const u8, j: usize, s: []const u8) ![]const u8 { + return std.fmt.bufPrint(buf, "{s}.{d}.{s}", .{ p, j, s }); + } + }; + var b: Block = undefined; + b.qkv = try h.read(c, try P.n(&name, prefix, i, "attn.qkv.weight"), .{ 3 * H, H }); + b.qkv_b = h.put(try floats(c, try P.n(&name, prefix, i, "attn.qkv.bias"), &.{3 * H})); + b.out = try h.read(c, try P.n(&name, prefix, i, "attn.out.weight"), .{ H, H }); + b.out_b = h.put(try floats(c, try P.n(&name, prefix, i, "attn.out.bias"), &.{H})); + b.up = try h.read(c, try P.n(&name, prefix, i, "mlp.mlp.0.weight"), .{ cfg.ffn, H }); + b.up_b = h.put(try floats(c, try P.n(&name, prefix, i, "mlp.mlp.0.bias"), &.{cfg.ffn})); + b.down = try h.read(c, try P.n(&name, prefix, i, "mlp.mlp.2.weight"), .{ H, cfg.ffn }); + b.down_b = h.put(try floats(c, try P.n(&name, prefix, i, "mlp.mlp.2.bias"), &.{H})); + b.q_norm = try take(c, try P.n(&name, prefix, i, "attn.q_norm.gamma"), &.{ cfg.heads, cfg.head_dim }); + b.k_norm = try take(c, try P.n(&name, prefix, i, "attn.k_norm.gamma"), &.{ cfg.heads, cfg.head_dim }); + if (affine) { + b.norm1 = try take(c, try P.n(&name, prefix, i, "norm1.weight"), &.{H}); + b.norm1_b = try take(c, try P.n(&name, prefix, i, "norm1.bias"), &.{H}); + b.norm2 = try take(c, try P.n(&name, prefix, i, "norm2.weight"), &.{H}); + b.norm2_b = try take(c, try P.n(&name, prefix, i, "norm2.bias"), &.{H}); + } + return b; +} + +/// A RePo layer; its two maps into `pack` at `slot`, and its three frequency vectors as 32 values after every map. +fn repo(c: *const ck.Checkpoint, pack: mtl.Buffer, slot: usize, prefix: []const u8, i: usize) !Repo { + var name: [96]u8 = undefined; + var r: Repo = undefined; + r.norm = try take(c, try std.fmt.bufPrint(&name, "{s}.{d}.norm.weight", .{ prefix, i }), &.{H}); + r.norm_b = try take(c, try std.fmt.bufPrint(&name, "{s}.{d}.norm.bias", .{ prefix, i }), &.{H}); + const gate = try floats(c, try std.fmt.bufPrint(&name, "{s}.{d}.gate_map.weight", .{ prefix, i }), &.{ cfg.repo_hidden, H }); + const content = try floats(c, try std.fmt.bufPrint(&name, "{s}.{d}.content_map.weight", .{ prefix, i }), &.{ cfg.repo_hidden, H }); + const scale = mapScale(gate, content); + const maps = @as([*]f16, @ptrCast(@alignCast(pack.contents() + slot * map_bytes)))[0 .. 2 * cfg.repo_hidden * 3 * H]; + for (0..2 * cfg.repo_hidden) |n| { + const src = if (n < cfg.repo_hidden) gate[n * H ..][0..H] else content[(n - cfg.repo_hidden) * H ..][0..H]; + split(src, scale, maps[n * 3 * H ..][0 .. 3 * H]); + } + r.maps = .{ .buf = pack, .off = slot * map_bytes }; + r.inv = 1 / scale; + r.final = try take(c, try std.fmt.bufPrint(&name, "{s}.{d}.final_map.weight", .{ prefix, i }), &.{ 3 * cfg.heads, cfg.repo_hidden }); + const freqs = repos * map_bytes; + const dst = @as([*]f32, @ptrCast(@alignCast(pack.contents() + freqs)))[slot * cfg.repo_pairs ..][0..cfg.repo_pairs]; + var at: usize = 0; + inline for (.{ .{ "freqs_0", 10 }, .{ "freqs_1", 10 }, .{ "freqs_2", 12 } }) |f| { + const src = try floats(c, try std.fmt.bufPrint(&name, "{s}.{d}.{s}", .{ prefix, i, f[0] }), &.{f[1]}); + @memcpy(dst[at..][0..f[1]], src); + at += f[1]; + } + r.freqs = .{ .buf = pack, .off = freqs + slot * cfg.repo_pairs * 4 }; + return r; +} + +/// The snapshot folder `dir`: config.json checked, then denoiser.safetensors's every tensor, each read once. +pub fn load(gpa: std.mem.Allocator, io: std.Io, device: mtl.Device, dir: []const u8) !Weights { + var arena_state = std.heap.ArenaAllocator.init(gpa); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + const config = try std.Io.Dir.cwd().readFileAlloc(io, try std.fs.path.join(arena, &.{ dir, "config.json" }), arena, .limited(1 << 20)); + try cfg.check(gpa, config); + var w: Weights = undefined; + w.ck = ck.Checkpoint.init(gpa); + errdefer w.ck.deinit(); + const path = try std.fmt.allocPrintSentinel(arena, "{s}/denoiser.safetensors", .{dir}, 0); + try w.ck.addFileSplit(device, path, "", null, later); + const opts = mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked; + const blocks = 2 * cfg.refiners + cfg.layers; + const fp16 = try device.buffer(blocks * per_block, opts); + w.ck.own(fp16, blocks * per_block) catch |err| { + fp16.deinit(); + return err; + }; + const pack_bytes = repos * (map_bytes + cfg.repo_pairs * 4); + const pack = try device.buffer(pack_bytes, opts); + w.ck.own(pack, pack_bytes) catch |err| { + pack.deinit(); + return err; + }; + var h: Halves = .{ .buf = fp16, .stage = try arena.alloc(f32, 4 << 20) }; + for (&w.noise, &w.context, &w.noise_repo, &w.context_repo, 0..) |*n, *x, *nr, *xr, i| { + n.* = try block(&w.ck, &h, "noise_refiner", i, false); + x.* = try block(&w.ck, &h, "context_refiner", i, true); + nr.* = try repo(&w.ck, pack, i, "noise_repo_layers", i); + xr.* = try repo(&w.ck, pack, cfg.refiners + i, "context_repo_layers", i); + } + for (&w.blocks, &w.repo, 0..) |*b, *r, i| { + b.* = try block(&w.ck, &h, "blocks", i, false); + r.* = try repo(&w.ck, pack, 2 * cfg.refiners + i, "repo_layers", i); + } + w.ck.closeFiles(); + w.input = try take(&w.ck, "input_layer.weight", &.{ H, cfg.latent_channels }); + w.input_b = try take(&w.ck, "input_layer.bias", &.{H}); + w.cond = try take(&w.ck, "cond_embedder.weight", &.{ H, cfg.cond_channels }); + w.cond_b = try take(&w.ck, "cond_embedder.bias", &.{H}); + w.cond2 = try take(&w.ck, "cond_embedder2.weight", &.{ H, cfg.cond2_channels }); + w.cond2_b = try take(&w.ck, "cond_embedder2.bias", &.{H}); + w.out = try take(&w.ck, "out_layer.weight", &.{ cfg.latent_channels, H }); + w.out_b = try take(&w.ck, "out_layer.bias", &.{cfg.latent_channels}); + var hw: Host = undefined; + hw.t1 = try floats(&w.ck, "t_embedder.mlp.0.weight", &.{ H, cfg.time_dim }); + hw.t1_b = try floats(&w.ck, "t_embedder.mlp.0.bias", &.{H}); + hw.t2 = try floats(&w.ck, "t_embedder.mlp.2.weight", &.{ H, H }); + hw.t2_b = try floats(&w.ck, "t_embedder.mlp.2.bias", &.{H}); + hw.ada = try floats(&w.ck, "adaLN_modulation.1.weight", &.{ 6 * H, H }); + hw.ada_b = try floats(&w.ck, "adaLN_modulation.1.bias", &.{6 * H}); + hw.cam1 = try floats(&w.ck, "cam_refiner.mlp.0.weight", &.{ H, cfg.camera_channels }); + hw.cam1_b = try floats(&w.ck, "cam_refiner.mlp.0.bias", &.{H}); + hw.cam2 = try floats(&w.ck, "cam_refiner.mlp.2.weight", &.{ H, H }); + hw.cam2_b = try floats(&w.ck, "cam_refiner.mlp.2.bias", &.{H}); + hw.cam_out = try floats(&w.ck, "cam_out_layer.weight", &.{ cfg.camera_channels, H }); + hw.cam_out_b = try floats(&w.ck, "cam_out_layer.bias", &.{cfg.camera_channels}); + var name: [64]u8 = undefined; + for (&hw.shifts, 0..) |*s, i| { + const n = if (i < cfg.refiners) try std.fmt.bufPrint(&name, "noise_refiner.{d}.shift_table", .{i}) else try std.fmt.bufPrint(&name, "blocks.{d}.shift_table", .{i - cfg.refiners}); + s.* = try floats(&w.ck, n, &.{ 1, 6 * H }); + } + hw.head = try floats(&w.ck, "shift_table", &.{ 1, 2, H }); + hw.pos = try floats(&w.ck, "pos_pe", &.{ 1, cfg.latent_rows, 3 }); + w.host = hw; + // a block's 4 linears, 4 biases and 2 gammas, the context refiner's 4 norms, the shift tables; 8 a RePo layer + const all = 2 * cfg.refiners + cfg.layers; + const read = 10 * all + 4 * cfg.refiners + cfg.modulated + 8 * all + 8 + 12 + 2; + const total = w.ck.tensors.count() + w.ck.deferred.count(); + if (total != read) { + std.log.err("idol: denoiser.safetensors has {d} tensors; this family reads {d}", .{ total, read }); + return error.UnexpectedTensors; + } + return w; +} + +test "a map's split halves sum back to its scaled values within fp32's rounding" { + var src: [H]f32 = undefined; + var rng = std.Random.DefaultPrng.init(3); + for (&src) |*v| v.* = 0.05 * rng.random().floatNorm(f32); + const scale = mapScale(&src, &src); + try std.testing.expect(scale >= 1); + var dst: [3 * H]f16 = undefined; + split(&src, scale, &dst); + for (src, 0..) |v, i| { + const back = (@as(f32, dst[i]) + @as(f32, dst[H + i])) / scale; + try std.testing.expect(@abs(back - v) <= @abs(v) * 1e-6 + 1e-12); + try std.testing.expectEqual(dst[i], dst[2 * H + i]); + } +} + +test "the blocks' linear weights, and only they, stay in the file for their fp16 copies" { + try std.testing.expect(later("blocks.3.attn.qkv.weight", 2)); + try std.testing.expect(later("context_refiner.1.mlp.mlp.2.weight", 2)); + try std.testing.expect(!later("blocks.3.attn.qkv.bias", 1)); + try std.testing.expect(!later("blocks.3.attn.q_norm.gamma", 2)); + try std.testing.expect(!later("context_refiner.0.norm1.weight", 1)); + try std.testing.expect(!later("repo_layers.0.gate_map.weight", 2)); + try std.testing.expect(!later("cond_embedder.weight", 2)); +} diff --git a/zig/src/families/ling/host_test.zig b/zig/src/families/ling/host_test.zig index e339b37f0c2..516726dd005 100644 --- a/zig/src/families/ling/host_test.zig +++ b/zig/src/families/ling/host_test.zig @@ -10,9 +10,29 @@ test { _ = @import("synth.zig"); _ = @import("route.zig"); _ = @import("kda.zig"); + _ = @import("mla.zig"); + _ = @import("mla_rope_test.zig"); } test "the float64 oracle handles tiny's null SwiGLU lists" { const src = @embedFile("oracle/ling_forward.py"); try std.testing.expect(std.mem.indexOf(u8, src, "null (Ling-3.0-tiny)") != null); } + +test "the float64 oracle's mla takes a pos0 so a chunk is not always arange(T) from 0" { + const src = @embedFile("oracle/ling_forward.py"); + try std.testing.expect(std.mem.indexOf(u8, src, "def mla(self, x, p, pos0=0)") != null); + try std.testing.expect(std.mem.indexOf(u8, src, "def one_mla(") != null); + try std.testing.expect(std.mem.indexOf(u8, src, "pos0 + torch.arange(T, dtype=torch.float64)") != null); + try std.testing.expect(std.mem.indexOf(u8, src, "attends only over the rows it is given") != null); + try std.testing.expect(std.mem.indexOf(u8, src, "kv_a_proj_with_mqa") != null); +} + +test "mla dump runs ling_forward.py --mla-layer for TFLINGA1" { + const src = @embedFile("oracle/mla_dump.py"); + try std.testing.expect(std.mem.indexOf(u8, src, "ling_forward.py") != null); + try std.testing.expect(std.mem.indexOf(u8, src, "--mla-layer") != null); + try std.testing.expect(std.mem.indexOf(u8, src, "TFLINGA1") != null); + try std.testing.expect(std.mem.indexOf(u8, src, "Random values in Ling-3.0-tiny tensor shapes") != null); + try std.testing.expect(std.mem.indexOf(u8, src, "sys.argv") != null); +} diff --git a/zig/src/families/ling/mla.zig b/zig/src/families/ling/mla.zig new file mode 100644 index 00000000000..75b7ea3388a --- /dev/null +++ b/zig/src/families/ling/mla.zig @@ -0,0 +1,276 @@ +//! Ling MLA mixer after the linears: unabsorbed python-style (ling_forward.py mla), plus RoPE helpers. +const std = @import("std"); +const config = @import("config.zig"); +const bf16_round = @import("bf16_round"); + +pub const lat: u32 = 512; +pub const rope_dim: u32 = 64; +pub const nope: u32 = 128; +pub const vd: u32 = 128; +pub const key: u32 = lat + rope_dim; +pub const qd: u32 = nope + rope_dim; +pub const nfreq: u32 = rope_dim / 2; +pub const theta_tiny: f64 = 6_000_000; +pub const eps_tiny: f32 = 1e-6; + +pub const Shape = struct { + heads: u32, + eps: f32, + theta: f64, + + pub fn of(c: *const config.Config) Shape { + return .{ .heads = c.mla_heads, .eps = c.eps, .theta = c.rope_theta }; + } + + pub fn scale(s: Shape) f64 { + _ = s; + return 1.0 / @sqrt(@as(f64, @floatFromInt(qd))); + } + + pub fn outWidth(s: Shape) u32 { + return s.heads * vd; + } +}; + +/// 1 / theta ** (arange(0, rope, 2) / rope): frequency i is 2i / 64. +pub fn invFreq(theta: f64, i: usize) f64 { + return 1.0 / std.math.pow(f64, theta, @as(f64, @floatFromInt(2 * i)) / @as(f64, @floatFromInt(rope_dim))); +} + +/// One 64-vector at absolute pos: even/odd pairs, then cat(a*c-b*s, b*c+a*s). out and z are rope_dim long. +pub fn rotate(out: []f64, z: []const f64, pos: u32, theta: f64) void { + std.debug.assert(out.len == rope_dim and z.len == rope_dim); + for (0..nfreq) |i| { + const ang = @as(f64, @floatFromInt(pos)) * invFreq(theta, i); + const c = @cos(ang); + const s = @sin(ang); + const a = z[2 * i]; + const b = z[2 * i + 1]; + out[i] = a * c - b * s; + out[nfreq + i] = b * c + a * s; + } +} + +/// T rows of 64 at pos0 + t, the chunk/resume case. out and z are T * rope_dim. +pub fn rotateRows(out: []f64, z: []const f64, rows: u32, pos0: u32, theta: f64) void { + std.debug.assert(out.len == rows * rope_dim and z.len == rows * rope_dim); + for (0..rows) |t| { + rotate(out[t * rope_dim ..][0..rope_dim], z[t * rope_dim ..][0..rope_dim], pos0 + @as(u32, @intCast(t)), theta); + } +} + +/// (T, H) to (T, H*128): each head gate repeated across the value columns. +pub fn expandGate(out: []u16, g: []const u16, rows: u32, heads: u32) void { + std.debug.assert(g.len == rows * heads and out.len == rows * heads * vd); + for (0..rows) |t| { + for (0..heads) |h| { + const v = g[t * heads + h]; + const lo = (t * heads + h) * vd; + for (0..vd) |d| out[lo + d] = v; + } + } +} + +fn r64(comptime round: bool, v: f64) f64 { + if (!round) return v; + return bf16_round.bf16(v); +} + +fn sig(x: f64) f64 { + if (x >= 0) { + const e = @exp(-x); + return 1.0 / (1.0 + e); + } + const e = @exp(x); + return e / (1.0 + e); +} + +fn mixAs( + comptime round: bool, + alloc: std.mem.Allocator, + y: []f64, + q: []const f32, + kv: []const f32, + w_rms: []const f32, + kvb: []const f32, + g: []const f32, + s: Shape, + rows: u32, + pos0: u32, +) !void { + const H = s.heads; + const T = rows; + std.debug.assert(y.len == T * H * vd); + std.debug.assert(q.len == T * H * qd); + std.debug.assert(kv.len == T * key); + std.debug.assert(w_rms.len == lat); + std.debug.assert(kvb.len == H * (nope + vd) * lat); + std.debug.assert(g.len == T * H); + + const lat_t = try alloc.alloc(f64, T * lat); + defer alloc.free(lat_t); + const krope = try alloc.alloc(f64, T * rope_dim); + defer alloc.free(krope); + const qrope = try alloc.alloc(f64, T * H * rope_dim); + defer alloc.free(qrope); + const k_nope = try alloc.alloc(f64, T * H * nope); + defer alloc.free(k_nope); + const v = try alloc.alloc(f64, T * H * vd); + defer alloc.free(v); + + const eps: f64 = s.eps; + for (0..T) |t| { + var ss: f64 = 0; + for (0..lat) |i| { + const x: f64 = kv[t * key + i]; + ss += x * x; + } + const rstd = 1.0 / @sqrt(ss / @as(f64, lat) + eps); + for (0..lat) |i| { + const yn = @as(f64, kv[t * key + i]) * rstd; + lat_t[t * lat + i] = r64(round, r64(round, yn) * w_rms[i]); + } + var z: [rope_dim]f64 = undefined; + var out: [rope_dim]f64 = undefined; + for (0..rope_dim) |i| z[i] = kv[t * key + lat + i]; + rotate(&out, &z, pos0 + @as(u32, @intCast(t)), s.theta); + for (0..rope_dim) |i| krope[t * rope_dim + i] = r64(round, out[i]); + for (0..H) |h| { + for (0..rope_dim) |i| z[i] = q[(t * H + h) * qd + nope + i]; + rotate(&out, &z, pos0 + @as(u32, @intCast(t)), s.theta); + for (0..rope_dim) |i| qrope[(t * H + h) * rope_dim + i] = r64(round, out[i]); + } + } + + for (0..H) |h| { + for (0..T) |t| { + for (0..nope) |d| { + var acc: f64 = 0; + const w0 = ((h * (nope + vd) + d) * lat); + for (0..lat) |c| acc += lat_t[t * lat + c] * kvb[w0 + c]; + k_nope[(t * H + h) * nope + d] = r64(round, acc); + } + for (0..vd) |d| { + var acc: f64 = 0; + const w0 = ((h * (nope + vd) + nope + d) * lat); + for (0..lat) |c| acc += lat_t[t * lat + c] * kvb[w0 + c]; + v[(t * H + h) * vd + d] = r64(round, acc); + } + } + } + + const sc = s.scale(); + const scores = try alloc.alloc(f64, H * T * T); + defer alloc.free(scores); + for (0..H) |h| { + for (0..T) |t| { + for (0..T) |k| { + if (k > t) { + scores[(h * T + t) * T + k] = -std.math.inf(f64); + continue; + } + var p: f64 = 0; + const qb = (t * H + h) * qd; + const kb = (k * H + h) * nope; + for (0..nope) |d| p += @as(f64, q[qb + d]) * k_nope[kb + d]; + const qr = (t * H + h) * rope_dim; + for (0..rope_dim) |d| p += qrope[qr + d] * krope[k * rope_dim + d]; + scores[(h * T + t) * T + k] = p * sc; + } + } + } + + for (0..H) |h| { + for (0..T) |t| { + var m: f64 = -std.math.inf(f64); + const row = scores[(h * T + t) * T ..][0..T]; + for (0..t + 1) |k| m = @max(m, row[k]); + var den: f64 = 0; + for (0..t + 1) |k| { + row[k] = @exp(row[k] - m); + den += row[k]; + } + for (0..t + 1) |k| row[k] /= den; + var o: [vd]f64 = @splat(0); + for (0..t + 1) |k| { + const a = row[k]; + const vb = (k * H + h) * vd; + for (0..vd) |d| o[d] += a * v[vb + d]; + } + const gate = r64(round, sig(g[t * H + h])); + for (0..vd) |d| y[(t * H + h) * vd + d] = r64(round, r64(round, o[d]) * gate); + } + } +} + +/// Unabsorbed MLA in float64, r = identity. Causal over the given rows; pos0 is RoPE only. +pub fn mixF64( + alloc: std.mem.Allocator, + y: []f64, + q: []const f32, + kv: []const f32, + w_rms: []const f32, + kvb: []const f32, + g: []const f32, + s: Shape, + rows: u32, + pos0: u32, +) !void { + try mixAs(false, alloc, y, q, kv, w_rms, kvb, g, s, rows, pos0); +} + +/// Same mixer with r = bf16 at ling_forward.py's points (RMS, kv_b, rot, attn@v, gate). +pub fn mixBf16( + alloc: std.mem.Allocator, + y: []f64, + q: []const f32, + kv: []const f32, + w_rms: []const f32, + kvb: []const f32, + g: []const f32, + s: Shape, + rows: u32, + pos0: u32, +) !void { + try mixAs(true, alloc, y, q, kv, w_rms, kvb, g, s, rows, pos0); +} + +test "tiny MLA geometry is 16 heads, 512 latent, 64 rope, 128 nope/v, softmax 1/sqrt(192)" { + const tiny = @embedFile("fixtures/tiny_config.json"); + var why: config.Why = .{}; + const c = try config.parse(std.testing.allocator, tiny, &why); + const s = Shape.of(&c); + try std.testing.expectEqual(@as(u32, 16), s.heads); + try std.testing.expectEqual(@as(u32, 512), lat); + try std.testing.expectEqual(@as(u32, 64), c.rope_dim); + try std.testing.expectEqual(@as(u32, 128), c.nope); + try std.testing.expectEqual(@as(u32, 128), c.v_dim); + try std.testing.expectEqual(config.RopeStyle.gptj, c.rope_style); + try std.testing.expectEqual(@as(f64, 6000000), s.theta); + try std.testing.expectEqual(@as(f32, @floatCast(s.scale())), c.smScale()); +} + +test "expandGate repeats each head value across 128 columns" { + const g = [_]u16{ 0x3f80, 0x4000, 0x4040, 0xc000 }; + var out: [2 * 2 * vd]u16 = undefined; + expandGate(&out, &g, 2, 2); + for (0..vd) |d| { + try std.testing.expectEqual(@as(u16, 0x3f80), out[d]); + try std.testing.expectEqual(@as(u16, 0x4000), out[vd + d]); + try std.testing.expectEqual(@as(u16, 0x4040), out[2 * vd + d]); + try std.testing.expectEqual(@as(u16, 0xc000), out[3 * vd + d]); + } +} + +test "mixF64 of zeros is zeros" { + const a = std.testing.allocator; + const s = Shape{ .heads = 1, .eps = eps_tiny, .theta = theta_tiny }; + var y: [vd]f64 = undefined; + const q: [qd]f32 = @splat(0); + const kv: [key]f32 = @splat(0); + const w: [lat]f32 = @splat(1); + const kvb: [1 * (nope + vd) * lat]f32 = @splat(0); + const g = [_]f32{0}; + try mixF64(a, &y, &q, &kv, &w, &kvb, &g, s, 1, 0); + for (y) |v| try std.testing.expectEqual(@as(f64, 0), v); +} diff --git a/zig/src/families/ling/mla_rope_test.zig b/zig/src/families/ling/mla_rope_test.zig new file mode 100644 index 00000000000..fd808e28aa2 --- /dev/null +++ b/zig/src/families/ling/mla_rope_test.zig @@ -0,0 +1,84 @@ +//! Ling MLA RoPE: GPT-J pairs then halves, matching ling_forward.py rot() and HF apply_rotary_pos_emb_interleave. +const std = @import("std"); +const config = @import("config.zig"); +const bf16_round = @import("bf16_round"); +const mla = @import("mla.zig"); + +pub const rope_dim: u32 = mla.rope_dim; +pub const nfreq: u32 = mla.nfreq; +pub const invFreq = mla.invFreq; +pub const rotate = mla.rotate; +pub const rotateRows = mla.rotateRows; + +fn tinyTheta() !f64 { + var why: config.Why = .{}; + const c = try config.parse(std.testing.allocator, @embedFile("fixtures/tiny_config.json"), &why); + try std.testing.expectEqual(@as(u32, 64), c.rope_dim); + try std.testing.expectEqual(config.RopeStyle.gptj, c.rope_style); + try std.testing.expectEqual(@as(f64, 6000000), c.rope_theta); + try std.testing.expectEqual(@as(u32, 192), c.qkDim()); + try std.testing.expectEqual(@as(f32, @floatCast(1.0 / @sqrt(@as(f64, 192.0)))), c.smScale()); + return c.rope_theta; +} + +test "tiny MLA rope is 64 GPT-J columns, theta 6e6, softmax 1/sqrt(192)" { + _ = try tinyTheta(); +} + +test "pos 0 writes GPT-J pairs as halves: the identity rotation" { + const theta = try tinyTheta(); + var z: [rope_dim]f64 = undefined; + for (&z, 0..) |*v, i| v.* = @as(f64, @floatFromInt(i)) + 0.25; + var out: [rope_dim]f64 = undefined; + rotate(&out, &z, 0, theta); + for (0..nfreq) |i| { + try std.testing.expectEqual(z[2 * i], out[i]); + try std.testing.expectEqual(z[2 * i + 1], out[nfreq + i]); + } +} + +test "pos 1, 8 and 1024 rotate the first pair by pos radians (frequency 0 is theta^0 = 1)" { + const theta = try tinyTheta(); + try std.testing.expectEqual(@as(f64, 1), invFreq(theta, 0)); + var z: [rope_dim]f64 = @splat(0); + z[0] = 1; + z[1] = 0; + for ([_]u32{ 1, 8, 1024 }) |pos| { + var out: [rope_dim]f64 = undefined; + rotate(&out, &z, pos, theta); + const p: f64 = @floatFromInt(pos); + try std.testing.expectApproxEqAbs(@cos(p), out[0], 1e-12); + try std.testing.expectApproxEqAbs(@sin(p), out[nfreq], 1e-12); + for (1..nfreq) |i| { + try std.testing.expectEqual(@as(f64, 0), out[i]); + try std.testing.expectEqual(@as(f64, 0), out[nfreq + i]); + } + } +} + +test "a pos0 offset of 8 on four rows equals rotating each row at its absolute index" { + const theta = try tinyTheta(); + const rows: u32 = 4; + const pos0: u32 = 8; + var z: [rows * rope_dim]f64 = undefined; + for (&z, 0..) |*v, i| v.* = @as(f64, @floatFromInt(i % 17)) * 0.125 - 1.0; + var chunk: [rows * rope_dim]f64 = undefined; + rotateRows(&chunk, &z, rows, pos0, theta); + var fresh: [rows * rope_dim]f64 = undefined; + for (0..rows) |t| { + rotate(fresh[t * rope_dim ..][0..rope_dim], z[t * rope_dim ..][0..rope_dim], pos0 + @as(u32, @intCast(t)), theta); + } + for (&chunk, fresh) |a, b| try std.testing.expectEqual(a, b); +} + +test "round32 keeps signalling NaN 0x7f800001 and all-ones 0x7fffffff as NaN" { + const cases = [_]u32{ 0x7f800001, 0x7fffffff }; + for (cases) |u| { + const v: f32 = @bitCast(u); + try std.testing.expect(std.math.isNan(v)); + const h = bf16_round.bits(v); + try std.testing.expectEqual(@as(u16, @truncate((u >> 16) | 0x40)), h); + try std.testing.expect(std.math.isNan(bf16_round.value(h))); + try std.testing.expect(std.math.isNan(bf16_round.round32(v))); + } +} diff --git a/zig/src/families/ling/oracle/ling_forward.py b/zig/src/families/ling/oracle/ling_forward.py index 5f51f6b576e..aab4c520286 100644 --- a/zig/src/families/ling/oracle/ling_forward.py +++ b/zig/src/families/ling/oracle/ling_forward.py @@ -99,7 +99,8 @@ def kda(self, x, p): y = out / torch.sqrt((out * out).mean(-1, keepdim=True) + self.eps) * w * torch.sigmoid(gate) return self.lin(r(y).reshape(T, H * dk), p + "o_proj") - def mla(self, x, p): + def mla(self, x, p, pos0=0): + """One MLA layer. x is the pre-normed residual [T, hidden]; attends only over the rows it is given.""" c, r, ck = self.c, self.r, self.ck T, H = x.shape[0], c["num_attention_heads"] nope, rope, dv, lw = c["qk_nope_head_dim"], c["qk_rope_head_dim"], c["v_head_dim"], c["kv_lora_rank"] @@ -108,7 +109,7 @@ def mla(self, x, p): lat = self.norm(kv[:, :lw], ck.t(p + "kv_a_layernorm.weight")) kvb = self.lin(lat, p + "kv_b_proj").view(T, H, nope + dv) inv = 1.0 / c["rope_theta"] ** (torch.arange(0, rope, 2, dtype=torch.float64) / rope) - ang = torch.arange(T, dtype=torch.float64)[:, None] * inv + ang = (pos0 + torch.arange(T, dtype=torch.float64))[:, None] * inv cos, sin = torch.cos(ang), torch.sin(ang) def rot(z): # GPT-J pairs (rope_interleave), out in halves as HF's interleave helper writes them @@ -181,6 +182,11 @@ def mtp_logits(self, ids): return self.norm(x, ck.t(p + "final_layernorm.weight")) @ ck.lin("lm_head").T +def one_mla(ck, c, x, layer, r, pos0=0): + """One MLA layer's output [T, hidden] from its pre-normed input x. Same Model.mla, not a second copy.""" + return Model(ck, c, r).mla(x, f"model.layers.{layer}.attention.", pos0) + + def main(): a = argparse.ArgumentParser(description=__doc__) a.add_argument("ckpt", help="a ling-synth directory (config.json, model.safetensors) or a sharded checkpoint's") @@ -189,11 +195,35 @@ def main(): a.add_argument("--picks", help="route on these picks (i32 [MoE layers][tokens][top_k], the graph's) instead") a.add_argument("--mtp", help="also the MTP layer's logits (float64, bf16 points) and its own picks, to this file") a.add_argument("--ids", help="these tokens (i32, ling-lanes' OUT.ids) instead of the fixed walk; --tokens follows") + a.add_argument("--mla-layer", type=int, metavar="I", help="write one MLA layer's output from --acts instead of full-decoder logits") + a.add_argument("--pos0", type=int, default=0, help="RoPE origin of row 0 of --acts; attention is still only over these rows") + a.add_argument("--acts", help="float64 [T, hidden] pre-normed input for --mla-layer") o = a.parse_args() c = json.load(open(os.path.join(o.ckpt, "config.json"))) one = os.path.join(o.ckpt, "model.safetensors") ck = Ckpt(one if os.path.exists(one) else o.ckpt) V = c["vocab_size"] + if o.mla_layer is not None: + if not o.acts: + a.error("--mla-layer needs --acts") + i = o.mla_layer + stem = f"model.layers.{i}.attention.kv_a_proj_with_mqa" + if not any(k == stem or k.startswith(stem + ".") for k in ck.keys): + a.error(f"layer {i} has no {stem} in the checkpoint: not an MLA layer, or the index is not in this file") + hidden = c["hidden_size"] + raw = torch.frombuffer(bytearray(open(o.acts, "rb").read()), dtype=torch.float64) + if raw.numel() % hidden != 0: + a.error(f"--acts length {raw.numel()} is not a multiple of hidden {hidden}") + x = raw.view(-1, hidden) + T = x.shape[0] + with torch.no_grad(): + y64 = one_mla(ck, c, x, i, lambda z: z, o.pos0) + ybf = one_mla(ck, c, x, i, bf16, o.pos0) + with open(o.out, "wb") as f: + f.write(b"TFLINGA1" + struct.pack("<4I", T, hidden, i, o.pos0)) + f.write(y64.contiguous().numpy().tobytes() + ybf.contiguous().numpy().tobytes()) + print("mla layer", i, "tokens", T, "pos0", o.pos0, "rms", y64.pow(2).mean().sqrt().item()) + return if o.ids: ids = torch.frombuffer(bytearray(open(o.ids, "rb").read()), dtype=torch.int32).long() else: diff --git a/zig/src/families/ling/oracle/mla_dump.py b/zig/src/families/ling/oracle/mla_dump.py new file mode 100644 index 00000000000..80f05157b2b --- /dev/null +++ b/zig/src/families/ling/oracle/mla_dump.py @@ -0,0 +1,216 @@ +"""Tiny-shape MLA dump (TFLINGA1). Random values in Ling-3.0-tiny tensor shapes, not checkpoint weights.""" +from __future__ import annotations + +import importlib.util +import json +import os +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +import torch +from safetensors.torch import save_file + +HERE = Path(__file__).resolve().parent +FIXTURES = HERE.parent / "fixtures" +TINY_CONFIG = FIXTURES / "tiny_config.json" +LAYER = 3 +MAGIC_M1 = b"TFLINGM1" + + +def load(name, path): + spec = importlib.util.spec_from_file_location(name, path) + mod = importlib.util.module_from_spec(spec) + sys.modules[name] = mod + spec.loader.exec_module(mod) + return mod + + +lf = load("ling_forward", HERE / "ling_forward.py") + + +class FakeCkpt: + def __init__(self, tensors): + self.tensors = tensors + self.keys = set(tensors) + + def t(self, name): + return self.tensors[name] + + def lin(self, module): + return self.t(module + ".weight").double() + + +class CaptureModel(lf.Model): + def lin(self, x, module): + y = super().lin(x, module) + self.captured[module] = y.detach().clone() + if module.endswith("dense"): + self.y_pre_dense = x.detach().clone() + return y + + +def f32_bytes(t): + return t.detach().cpu().contiguous().to(torch.float32).numpy().tobytes() + + +def f64_bytes(t): + return t.detach().cpu().contiguous().to(torch.float64).numpy().tobytes() + + +def make_weights(cfg, g): + H = cfg["num_attention_heads"] + hidden = cfg["hidden_size"] + qa = cfg["q_lora_rank"] + lw = cfg["kv_lora_rank"] + nope, rope, dv = cfg["qk_nope_head_dim"], cfg["qk_rope_head_dim"], cfg["v_head_dim"] + p = f"model.layers.{LAYER}.attention." + scale = cfg.get("initializer_range", 0.02) + + def rand(*shape): + return torch.randn(*shape, generator=g, dtype=torch.float64) * scale + + def rand1(*shape): + return 0.5 + 0.5 * torch.randn(*shape, generator=g, dtype=torch.float64) + + return { + p + "q_a_proj.weight": rand(qa, hidden), + p + "q_a_layernorm.weight": rand1(qa), + p + "q_b_proj.weight": rand(H * (nope + rope), qa), + p + "kv_a_proj_with_mqa.weight": rand(lw + rope, hidden), + p + "kv_a_layernorm.weight": rand1(lw), + p + "kv_b_proj.weight": rand(H * (nope + dv), lw), + p + "g_proj.weight": rand(H, hidden), + p + "dense.weight": rand(hidden, H * dv), + } + + +def capture(cfg, tensors_f64, x, pos0): + p = f"model.layers.{LAYER}.attention." + model = CaptureModel(FakeCkpt(tensors_f64), cfg, lambda z: z) + model.captured = {} + model.y_pre_dense = None + with torch.no_grad(): + out = model.mla(x, p, pos0) + H = cfg["num_attention_heads"] + q = model.captured[p + "q_b_proj"].view(x.shape[0], H, -1) + kv = model.captured[p + "kv_a_proj_with_mqa"] + g = model.captured[p + "g_proj"] + return { + "q": q, + "kv": kv, + "g": g, + "y_pre": model.y_pre_dense, + "y": out, + "w_rms": tensors_f64[p + "kv_a_layernorm.weight"], + "kvb": tensors_f64[p + "kv_b_proj.weight"], + "Wo": tensors_f64[p + "dense.weight"], + } + + +def run_cli(ckpt_dir, acts_path, out_path, pos0): + subprocess.check_call( + [ + sys.executable, + str(HERE / "ling_forward.py"), + str(ckpt_dir), + str(out_path), + "--mla-layer", + str(LAYER), + "--acts", + str(acts_path), + "--pos0", + str(pos0), + ] + ) + + +def write_case_files(tmp, cfg, tensors_f32, x, pos0, a1_path): + ckpt_dir = Path(tmp) / "ckpt" + ckpt_dir.mkdir(exist_ok=True) + with open(ckpt_dir / "config.json", "w") as f: + json.dump(cfg, f, indent=2) + save_file(tensors_f32, ckpt_dir / "model.safetensors") + acts_path = Path(tmp) / f"acts_p{pos0}.bin" + acts_path.write_bytes(f64_bytes(x)) + run_cli(ckpt_dir, acts_path, a1_path, pos0) + raw = a1_path.read_bytes() + assert raw[:8] == b"TFLINGA1", raw[:8] + T, hidden, layer, p0 = struct.unpack_from("<4I", raw, 8) + assert T == x.shape[0] and hidden == cfg["hidden_size"] and layer == LAYER and p0 == pos0 + n = T * hidden + y64 = torch.frombuffer(bytearray(raw[24 : 24 + n * 8]), dtype=torch.float64).clone().view(T, hidden) + ybf = torch.frombuffer(bytearray(raw[24 + n * 8 : 24 + 2 * n * 8]), dtype=torch.float64).clone().view(T, hidden) + return y64, ybf + + +def pack_mixer(cfg, tensors_f64, cases, path): + H = cfg["num_attention_heads"] + hidden = cfg["hidden_size"] + w_rms = tensors_f64[f"model.layers.{LAYER}.attention.kv_a_layernorm.weight"] + kvb = tensors_f64[f"model.layers.{LAYER}.attention.kv_b_proj.weight"] + Wo = tensors_f64[f"model.layers.{LAYER}.attention.dense.weight"] + with open(path, "wb") as f: + f.write(MAGIC_M1) + f.write(struct.pack("<4I", hidden, LAYER, H, len(cases))) + f.write(f32_bytes(w_rms)) + f.write(f32_bytes(kvb)) + f.write(f32_bytes(Wo)) + for case in cases: + T = case["q"].shape[0] + f.write(struct.pack("<2I", T, case["pos0"])) + f.write(f32_bytes(case["q"].reshape(T, -1))) + f.write(f32_bytes(case["kv"])) + f.write(f32_bytes(case["g"])) + f.write(f64_bytes(case["y_pre"])) + f.write(f64_bytes(case["y64"])) + f.write(f64_bytes(case["ybf"])) + + +def main(): + out = Path(sys.argv[1] if len(sys.argv) > 1 else "/tmp/ling-mla-dumps") + out.mkdir(parents=True, exist_ok=True) + cfg = json.loads(TINY_CONFIG.read_text()) + g = torch.Generator().manual_seed(0x74696E79) + tensors_f64 = make_weights(cfg, g) + tensors_f32 = {k: v.float().contiguous() for k, v in tensors_f64.items()} + tensors_cli = {k: v.double() for k, v in tensors_f32.items()} + specs = ( + (4, 0, 0x6D6C61, "mla_tiny_t4_pos0.bin"), + (2, 30000, 0x6D6C62, "mla_tiny_t2_pos30000.bin"), + ) + packed = [] + with tempfile.TemporaryDirectory() as tmp: + for T, pos0, seed, a1_name in specs: + gx = torch.Generator().manual_seed(seed) + x = torch.randn(T, cfg["hidden_size"], generator=gx, dtype=torch.float64) + a1_path = out / a1_name + y64, ybf = write_case_files(tmp, cfg, tensors_f32, x, pos0, a1_path) + cap = capture(cfg, tensors_cli, x, pos0) + worst = (cap["y"] - y64).abs().max().item() + print(f"CaptureModel vs TFLINGA1 T={T} pos0={pos0} worst abs {worst:.6e}") + if worst > 1e-12: + raise SystemExit(f"CLI y64 does not match CaptureModel: {worst}") + packed.append( + { + "pos0": pos0, + "q": cap["q"], + "kv": cap["kv"], + "g": cap["g"], + "y_pre": cap["y_pre"], + "y64": y64, + "ybf": ybf, + } + ) + mixer_path = out / "mla_tiny_mixer.bin" + pack_mixer(cfg, tensors_cli, packed, mixer_path) + print("wrote", mixer_path, "bytes", mixer_path.stat().st_size) + for _, _, _, name in specs: + p = out / name + print("wrote", p, "bytes", p.stat().st_size) + + +if __name__ == "__main__": + main() diff --git a/zig/src/families/minimax_m3/cuda_native.zig b/zig/src/families/minimax_m3/cuda_native.zig index e8ae18b47c9..cc2fd4acc23 100644 --- a/zig/src/families/minimax_m3/cuda_native.zig +++ b/zig/src/families/minimax_m3/cuda_native.zig @@ -61,11 +61,12 @@ pub fn visionBytes(a: std.mem.Allocator, io: std.Io, dir: []const u8) !u64 { pub const Place = struct { rank: usize, world: usize }; pub fn place() !Place { - const r = std.c.getenv("TF_MINIMAX_RANK"); - const w = std.c.getenv("TF_MINIMAX_WORLD"); + const env = @import("sys").environment; + const r = try env.read(?u64, "TF_MINIMAX_RANK", null); + const w = try env.read(?u64, "TF_MINIMAX_WORLD", null); if (r == null and w == null) return .{ .rank = 0, .world = 1 }; if (r == null or w == null) return error.NoRank; - const p: Place = .{ .rank = std.fmt.parseInt(usize, std.mem.span(r.?), 10) catch return error.NoRank, .world = std.fmt.parseInt(usize, std.mem.span(w.?), 10) catch return error.NoRank }; + const p: Place = .{ .rank = @intCast(r.?), .world = @intCast(w.?) }; if (p.world < 1 or p.rank >= p.world) return error.NoRank; return p; } @@ -138,6 +139,7 @@ const Owned = struct { pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: []const u8, kernels: ?[]const u8, o: Options) !Loaded { _ = kernels; + try @import("sys").environment.checkScope(.minimax_m3, @import("sys").environment.Process{}); const p = try place(); try admit(@intCast(try ctx.attribute(.compute_capability_major) * 10 + try ctx.attribute(.compute_capability_minor)), p.world); if (p.world > 1 and std.c.getenv("NCCL_COMM_ID") == null) return error.NoCommId; @@ -192,7 +194,7 @@ fn openRank(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: [ if (p.world > 1) { // small gathers by RoCE writes on two ranks, both or neither (TF_ROCE=0: NCCL; TF_ROCE_MAX_KB: the cap) own.group = .{ .lib = own.lib.?, .comm = own.comm, .rank = p.rank, .world = p.world }; - if (p.world == 2) try own.group.?.openRoce(gpa, io, ctx.d, own.e.stream, try roceBytes(if (std.c.getenv("TF_ROCE_MAX_KB")) |v| std.mem.span(v) else null)); + if (p.world == 2) try own.group.?.openRoce(gpa, io, ctx.d, own.e.stream, try roceBytes((@import("sys").environment.Process{}).get("TF_ROCE_MAX_KB"))); own.e.exchange = .{ .nccl = .{ .lib = &own.lib.?, .comm = own.comm, .group = &own.group.? } }; } errdefer if (own.group) |*g| if (g.fast) |f| f.deinit(); diff --git a/zig/src/families/nemotron/backend.zig b/zig/src/families/nemotron/backend.zig index 208b412032b..969216e648f 100644 --- a/zig/src/families/nemotron/backend.zig +++ b/zig/src/families/nemotron/backend.zig @@ -100,7 +100,7 @@ pub const Metal = struct { .tokens = try m.device.buffer(ring * 4, opts), .prompt = try m.device.buffer(@max(o.capacity, 16) * 4, opts), .fence = try Fence.init(m.device), - .trace = platform.c.getenv("TF_SLIDE_TRACE") != null, + .trace = (@import("sys").environment.Process{}).get("TF_SLIDE_TRACE") != null, .coop_split = fwd.splitOn(), }; if (o.chunk > fused_rows) b.wide = try prefill.Prefill.init(m, @min(o.chunk, o.capacity)); diff --git a/zig/src/families/nemotron/choice.zig b/zig/src/families/nemotron/choice.zig deleted file mode 100644 index 5f0bea0e6d2..00000000000 --- a/zig/src/families/nemotron/choice.zig +++ /dev/null @@ -1,67 +0,0 @@ -//! A lesson's block per layer: directions its fact's rows outweigh the steady rows along, the first rank its router's. -const std = @import("std"); -const subspace = @import("subspace.zig"); -const adapters = @import("learn_shape.zig"); - -const n = adapters.candidates; -const block = adapters.block; - -/// What each layer has seen of the steady rows and the fact's answer rows, along its candidate directions. -pub const Choice = struct { - gpa: std.mem.Allocator, - steady: []f64, // [layers, n, n]: the steady rows' second moment - facts: []f64, // [layers, n, n]: the fact's answer rows' second moment - coef: []f32, // [layers, block, n]: each layer's new directions in the candidates' terms - - pub fn init(gpa: std.mem.Allocator, layers: usize) !Choice { - return .{ - .gpa = gpa, - .steady = try gpa.alloc(f64, layers * n * n), - .facts = try gpa.alloc(f64, layers * n * n), - .coef = try gpa.alloc(f32, layers * block * n), - }; - } - - pub fn deinit(c: *Choice) void { - inline for (.{ "steady", "facts", "coef" }) |f| c.gpa.free(@field(c, f)); - } - - pub fn reset(c: *Choice) void { - @memset(c.steady, 0); - @memset(c.facts, 0); - } - - /// Layer l's unit rows [rows, n], steady or the fact's; row `first` (how an answer opens) weighs as all after it. - pub fn add(c: *Choice, l: usize, rows: []const f32, fact: bool, first: usize) void { - const m = (if (fact) c.facts else c.steady)[l * n * n ..][0 .. n * n]; - const count = rows.len / n; - for (0..count) |r| { - const p = rows[r * n ..][0..n]; - const w: f64 = if (r == first) @floatFromInt(@max(count - first - 1, 1)) else 1; - for (0..n) |i| for (0..n) |j| { - m[i * n + j] += w * p[i] * p[j]; - }; - } - } - - /// Every layer's directions. - pub fn choose(c: *Choice) !void { - var threads: [16]?std.Thread = @splat(null); - var failed: [16]?anyerror = @splat(null); - const layers = c.coef.len / (block * n); - const k = @min(threads.len, layers); - for (threads[0..k], 0..) |*t, i| t.* = std.Thread.spawn(.{}, share, .{ c, i, k, &failed[i] }) catch null; - for (threads[0..k], 0..) |t, i| if (t) |th| th.join() else share(c, i, k, &failed[i]); - for (failed[0..k]) |f| if (f) |e| return e; - } - - fn share(c: *Choice, from: usize, step: usize, failed: *?anyerror) void { - var l = from; - while (l < c.coef.len / (block * n)) : (l += step) { - const coef = c.coef[l * block * n ..][0 .. block * n]; - subspace.outweigh(c.gpa, c.facts[l * n * n ..][0 .. n * n], c.steady[l * n * n ..][0 .. n * n], n, block, coef) catch |e| { - failed.* = e; - }; - } - } -}; diff --git a/zig/src/families/nemotron/cuda_engine.zig b/zig/src/families/nemotron/cuda_engine.zig index 3aa6c32a334..32f21bf2706 100644 --- a/zig/src/families/nemotron/cuda_engine.zig +++ b/zig/src/families/nemotron/cuda_engine.zig @@ -136,7 +136,7 @@ pub const Engine = struct { const e = try gpa.create(Engine); errdefer if (!keep_owner) gpa.destroy(e); e.* = .{ .gpa = gpa, .io = io, .ctx = ctx, .stream = undefined, .k = undefined, .w = undefined, .b = undefined, .c = undefined, .max_len = 0, .pinned = undefined, .history = undefined }; - e.trace = platform.c.getenv("TF_SLIDE_TRACE") != null; + e.trace = (@import("sys").environment.Process{}).get("TF_SLIDE_TRACE") != null; e.c = try Config.read(gpa, io, model_dir); try latent.place(&e.c); var load_cache = @import("core").checkpoint.cache.Load.begin(io, e.c.world > 1); diff --git a/zig/src/families/nemotron/cuda_latent.zig b/zig/src/families/nemotron/cuda_latent.zig index a119d6cbf5b..5bfeef06e43 100644 --- a/zig/src/families/nemotron/cuda_latent.zig +++ b/zig/src/families/nemotron/cuda_latent.zig @@ -87,12 +87,13 @@ pub fn partFloats(c: Config, rows: usize) usize { /// TF_NEMOTRON_RANK of TF_NEMOTRON_WORLD into `c`: both or neither; a world must hold whole shares. pub fn place(c: *Config) !void { - const r = std.c.getenv("TF_NEMOTRON_RANK"); - const w = std.c.getenv("TF_NEMOTRON_WORLD"); + const env = @import("sys").environment; + const r = try env.read(?u64, "TF_NEMOTRON_RANK", null); + const w = try env.read(?u64, "TF_NEMOTRON_WORLD", null); if (r == null and w == null) return; if (r == null or w == null) return error.NoRank; - c.rank = std.fmt.parseInt(usize, std.mem.span(r.?), 10) catch return error.NoRank; - c.world = std.fmt.parseInt(usize, std.mem.span(w.?), 10) catch return error.NoRank; + c.rank = @intCast(r.?); + c.world = @intCast(w.?); if (c.world < 1 or c.rank >= c.world) return error.NoRank; if (c.world == 1) return; if (c.latent == 0) { diff --git a/zig/src/families/nemotron/cuda_native.zig b/zig/src/families/nemotron/cuda_native.zig index 2b885e87403..78fbcefbe8a 100644 --- a/zig/src/families/nemotron/cuda_native.zig +++ b/zig/src/families/nemotron/cuda_native.zig @@ -110,14 +110,16 @@ const Owned = struct { gpa: std.mem.Allocator, e: *engine.Engine, head: ?*Head, /// Own-sequence graphs support both draw modes; drafting also captures the head. pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: []const u8, kernels: ?[]const u8, o: Options) !Loaded { - if (std.c.getenv("TF_NEMOTRON_RANK")) |r| if (!std.mem.eql(u8, std.mem.span(r), "0")) { // expert ranks never serve + try @import("sys").environment.checkScope(.nemotron, @import("sys").environment.Process{}); + const rank = try @import("sys").environment.read(?u64, "TF_NEMOTRON_RANK", null); + if (rank != null and rank.? != 0) { @import("cuda_worker.zig").serve(gpa, io, ctx, dir, o.precision) catch |err| { cuda.tp_watch.fail(@errorName(err)); // rank 0 stops with this rank's error std.log.err("expert rank stopped: {s}", .{@errorName(err)}); std.c._exit(1); // a stream may still wait on rank 0: a normal exit would join it }; std.process.exit(0); - }; + } const carve = try openCarveout(gpa, ctx); errdefer if (carve) |c| closeCarveout(gpa, c); const e = try engine.Engine.init(gpa, io, ctx, dir, kernels, .{ .context = o.context, .mtp = o.drafts, .graphs = true, .sampling = null, .segments = o.segments, .carveout = carve, .slide = o.slide, .vision = o.vision, .precision = o.precision }); @@ -206,7 +208,9 @@ fn release(p: *anyopaque) void { /// TF_CUDA_CARVEOUT=1: the display carveout KV planes go to first (cuda/carveout.zig); null when it is off. fn openCarveout(gpa: std.mem.Allocator, ctx: *const cuda.Context) !?*cuda.Carveout { const bytes = (try cuda.carveout.requested(false, env("TF_CUDA_CARVEOUT"), env("TF_CUDA_CARVEOUT_MIB"))) orelse return null; - const card: [*:0]const u8 = platform.c.getenv("TF_DRM_CARD") orelse cuda.carveout.default_card; + const raw_card = (@import("sys").environment.Process{}).get("TF_DRM_CARD") orelse cuda.carveout.default_card; + const card = try gpa.dupeSentinel(u8, raw_card, 0); + defer gpa.free(card); const c = try gpa.create(cuda.Carveout); errdefer gpa.destroy(c); c.* = cuda.Carveout.open(ctx.d, card, bytes) catch |err| { @@ -255,7 +259,7 @@ test "Nemotron paging: registered lookup preserves the native reader's live envi } fn env(name: [:0]const u8) ?[]const u8 { - return std.mem.span(platform.c.getenv(name) orelse return null); + return (@import("sys").environment.Process{}).get(name); } /// The tensors this family loads; the early check uses the same vision switch as open(). diff --git a/zig/src/families/nemotron/cuda_pages.zig b/zig/src/families/nemotron/cuda_pages.zig index 0950e8720df..0931d54b6fc 100644 --- a/zig/src/families/nemotron/cuda_pages.zig +++ b/zig/src/families/nemotron/cuda_pages.zig @@ -6,7 +6,7 @@ const Engine = @import("cuda_engine.zig").Engine; const state = @import("cuda_state.zig"); const reuse = @import("cuda_reuse.zig"); const mtp = @import("cuda_mtp.zig"); -const lesson_route = @import("lesson_route.zig"); +const lesson_route = @import("living").lesson_route; /// One paged sequence, made at load, and the lease of the stream that holds it. const Lane = struct { seq: *state.Seq, lease: kv.Lease = .{}, used: bool = false }; diff --git a/zig/src/families/nemotron/cuda_seq_graphs.zig b/zig/src/families/nemotron/cuda_seq_graphs.zig index 6486a6fc1b4..275bbfc400a 100644 --- a/zig/src/families/nemotron/cuda_seq_graphs.zig +++ b/zig/src/families/nemotron/cuda_seq_graphs.zig @@ -30,8 +30,8 @@ pub const Stats = struct { /// Whether TF_GRAPH_LOG=1 asks for a line a request: its captures, their time, its replays and eager windows. pub fn logFromEnv() bool { - const v = platform.c.getenv("TF_GRAPH_LOG") orelse return false; - return std.mem.eql(u8, std.mem.span(v), "1"); + const v = (@import("sys").environment.Process{}).get("TF_GRAPH_LOG") orelse return false; + return std.mem.eql(u8, v, "1"); } /// One graph of `body` on the bound sequence's buffers, instantiated and uploaded. diff --git a/zig/src/families/nemotron/editor.zig b/zig/src/families/nemotron/editor.zig deleted file mode 100644 index 7723596fc68..00000000000 --- a/zig/src/families/nemotron/editor.zig +++ /dev/null @@ -1,433 +0,0 @@ -//! A fact written at its subject: rank-one changes to a few shared-expert down projections, other keys' outputs kept. -const std = @import("std"); -const adapters = @import("learn_shape.zig"); -const lesson_route = @import("lesson_route.zig"); -const subspace = @import("subspace.zig"); - -const examples = @import("lesson_examples.zig"); -const Example = examples.Example; -const pick = examples.pick; - -/// The MoE layers a fact's change is spread over, first to last; its target is the residual after the last. -pub const layers = [_]usize{ 13, 15, 17 }; -const target_layer = layers[layers.len - 1]; - -const hold: f32 = 1e2; // the kept keys' mean second moment against a fact's own key, when a change is solved -const history_weight: f32 = 1e3; // an earlier fact's key against one kept row: it must keep its output exactly -const target_steps = 30; // Adam steps on the nudge that makes the fact's answers come out -const reach: f32 = 0.1; // each nudge step's size against the residual's -const decay: f32 = 0.5; // the nudge's squared size against the residual's, added to its loss -const furthest: f32 = 4; // the nudge's size at most, against the residual's -const enough: f32 = 0.05; // a mean answer loss low enough that the nudge stops early - -const Phase = enum { kept, facts, target, edits, done }; - -/// The lesson's acting lessons and flags for a step: every lesson kept so far and, once written, this one. -pub const Acting = lesson_route.Acting; - -/// An editor over trainer T (Metal's: its key, residual and nudge). -pub fn Editor(comptime T: type) type { - return struct { - const Self = @This(); - gpa: std.mem.Allocator, - kept: [layers.len]std.ArrayList(f32) = @splat(.empty), // each layer's kept keys [rows, W], this lesson's - history: [layers.len]std.ArrayList(f32) = @splat(.empty), // each layer's keys of every fact written so far - facts: std.ArrayList(Example) = .empty, // the fact's examples that have a subject row, those with answers first - answered: usize = 0, // facts[0..answered] have answers: the nudge is found on those, the key read on all - stay: []const []const Example = &.{}, // the examples whose outputs the change must keep - keys: std.ArrayList(f32) = .empty, // [facts, layers, W]: each example's key at each layer, as last read - base: std.ArrayList(f32) = .empty, // [facts, D]: the residual after the target layer at the subject row, unchanged - now: std.ArrayList(f32) = .empty, // [facts, D]: the same as last read - delta: std.ArrayList(f32) = .empty, // [4, D]: the nudge, its Adam moments, and a round's gradient - phase: Phase = .done, - at: usize = 0, - round: usize = 0, - loss: f32 = 0, - first_loss: f32 = 0, - last_loss: f32 = 0, - size: f32 = 0, // the subject rows' mean residual length after the target layer - - pub fn init(gpa: std.mem.Allocator) Self { - return .{ .gpa = gpa }; - } - - pub fn deinit(e: *Self) void { - for (&e.kept) |*s| s.deinit(e.gpa); - for (&e.history) |*s| s.deinit(e.gpa); - inline for (.{ "facts", "keys", "base", "now", "delta" }) |f| @field(e, f).deinit(e.gpa); - } - - /// Examples naming a subject (`answered` set the nudge, `asked` add keys) and ones to keep; false if too few. - pub fn begin(e: *Self, answered: []const []const Example, asked: []const []const Example, stay: []const []const Example) !bool { - e.facts.clearRetainingCapacity(); - for (answered) |xs| for (xs) |ex| if (ex.subject > 0 and ex.subject < ex.start) try e.facts.append(e.gpa, ex); - e.answered = e.facts.items.len; - if (e.answered < 2) return false; - for (asked) |xs| for (xs) |ex| if (ex.subject > 0 and ex.subject < ex.start) try e.facts.append(e.gpa, ex); - for (&e.kept) |*s| s.clearRetainingCapacity(); - e.stay = stay; - e.next(.kept); - return true; - } - - /// One unit (keys, a nudge step or a layer's change) run with `acting`; true once every layer has its change. - pub fn step(e: *Self, t: *T, acting: Acting) !bool { - return switch (e.phase) { - .kept => e.keptOnce(t, acting), - .facts => e.factsOnce(t, acting), - .target => e.targetOnce(t, acting), - .edits => e.editsOnce(t, acting), - .done => true, - }; - } - - /// The fact's keys joined to every layer's history, once its lesson stays: later facts keep its outputs. - pub fn settle(e: *Self) !void { - const w = keyWidth(e); - if (w == 0) return; - for (0..e.facts.items.len) |i| for (0..layers.len) |j| { - try e.history[j].appendSlice(e.gpa, e.keys.items[(i * layers.len + j) * w ..][0..w]); - }; - } - - /// The kept edit rounded into each layer's codes, all before any write (`host`: codes, addRounded, commit). - pub fn fold(e: *Self, t: *T, host: anytype) !void { - const c = t.b.m.config; - const w = c.shared_width; - const d = c.hidden; - const h = try e.gpa.alloc(f32, w * w); - defer e.gpa.free(h); - const delta = try e.gpa.alloc(f32, d * w); - defer e.gpa.free(delta); - var fresh: [layers.len][]u32 = @splat(&.{}); - defer for (fresh) |f| e.gpa.free(f); - const first = t.sites.first(); - const ranks = t.sites.cap * adapters.block; - for (layers, 0..) |l, j| { - const site = &t.sites.list[l]; - const a = site.a.slice(f32, ranks * site.in)[first * site.in ..][0..site.in]; - const b = site.b.slice(f32, ranks * site.out)[first * site.out ..][0..site.out]; - for (0..d) |o| for (delta[o * w ..][0..w], a) |*x, ai| { - x.* = adapters.scale * b[o] * ai; - }; - const add = secondMoment(e.kept[j].items, e.history[j].items, w, h); - const codes = try host.codes(l); - fresh[j] = try e.gpa.dupe(u32, codes.words); - const changed = try host.addRounded(fresh[j], codes.scales, codes.biases, d, w, delta, h, add); - std.log.info("slide: layer {d}'s down projection takes the change in {d} of its {d} codes", .{ l, changed, d * w }); - } - for (layers, fresh) |l, f| { - @memcpy((try host.codes(l)).words, f); - try host.commit(l); - } - } - - fn keyWidth(e: *const Self) usize { - return if (e.facts.items.len == 0) 0 else e.keys.items.len / (e.facts.items.len * layers.len); - } - - fn turn(ex: Example, acting: Acting) lesson_route.Turn { - return .{ .decide = ex.decide, .bits = acting, .whole = true }; - } - - fn keptOnce(e: *Self, t: *T, acting: Acting) !bool { - var n: usize = 0; - for (e.stay) |xs| n += xs.len; - if (e.at == n) { - e.next(.facts); - return false; - } - const ex = pick(e.stay, e.at); - e.at += 1; - _ = try t.step(ex.ids, ex.start, .keys, turn(ex, acting)); - for (layers, &e.kept) |l, *rows| for (0..ex.ids.len - 1) |r| try widen(e.gpa, rows, t.key(l, r)); - return false; - } - - fn factsOnce(e: *Self, t: *T, acting: Acting) !bool { - const c = t.b.m.config; - if (e.at == 0) { - e.keys.clearRetainingCapacity(); - e.base.clearRetainingCapacity(); - try e.keys.appendNTimes(e.gpa, 0, e.facts.items.len * layers.len * c.shared_width); - try e.base.appendNTimes(e.gpa, 0, e.facts.items.len * c.hidden); - } - if (e.at == e.facts.items.len) { - e.now.clearRetainingCapacity(); - try e.now.appendSlice(e.gpa, e.base.items); - e.size = 0; - for (0..e.answered) |i| e.size += @sqrt(subspace.dot(row(e.base.items, i, c.hidden), row(e.base.items, i, c.hidden))); - e.size /= @floatFromInt(e.answered); - e.delta.clearRetainingCapacity(); - try e.delta.appendNTimes(e.gpa, 0, 4 * c.hidden); - e.next(.target); - return false; - } - const i = e.at; - e.at += 1; - try e.read(t, i, null, acting, true); - return false; - } - - /// Example i's key at every layer (or only layer `only`) and its residual after the target layer, as now. - fn read(e: *Self, t: *T, i: usize, only: ?usize, acting: Acting, unchanged: bool) !void { - const c = t.b.m.config; - const ex = e.facts.items[i]; - _ = try t.step(ex.ids, ex.start, .keys, turn(ex, acting)); - for (layers, 0..) |l, j| { - if (only) |o| if (o != j) continue; - for (e.keys.items[(i * layers.len + j) * c.shared_width ..][0..c.shared_width], t.key(l, ex.subject)) |*o, b| o.* = f32of(b); - } - const into = if (unchanged) e.base.items else e.now.items; - for (row(into, i, c.hidden), t.residual(target_layer + 1, ex.subject)) |*o, b| o.* = f32of(b); - } - - fn targetOnce(e: *Self, t: *T, acting: Acting) !bool { - const d = t.b.m.config.hidden; - const delta = e.delta.items[0..d]; - const grad = e.delta.items[3 * d ..][0..d]; - if (e.at == 0) @memset(grad, 0); - if (e.at < e.answered) { - const ex = e.facts.items[e.at]; - e.at += 1; - t.nudge = .{ .layers = .{ @as(u64, 1) << target_layer, 0, 0 }, .rows = .{ ex.subject, 0, 0 } }; - @memcpy(t.delta.slice(f32, t.b.m.config.layers * d)[target_layer * d ..][0..d], delta); - const got = try t.step(ex.ids, ex.start, .target, turn(ex, acting)); - e.loss += got.loss; - for (grad, t.push.slice(f32, t.b.m.config.layers * d)[target_layer * d ..][0..d]) |*g, p| g.* += p; - return false; - } - const n: f32 = @floatFromInt(e.answered); - const mean = e.loss / n; - if (e.round == 0) e.first_loss = mean; - e.loss = 0; - e.at = 0; - e.round += 1; - if (mean < enough or e.round > target_steps) { - e.last_loss = mean; - std.log.info("slide: the subject's target found in {d} steps, the answers' loss {d:.3} to {d:.3}, its nudge {d:.2} of the residual", .{ e.round - 1, e.first_loss, mean, @sqrt(subspace.dot(delta, delta)) / e.size }); - e.next(.edits); - return false; - } - const m = e.delta.items[d..][0..d]; - const v = e.delta.items[2 * d ..][0..d]; - const lr = reach * e.size / @sqrt(@as(f32, @floatFromInt(d))); - const t1: f32 = @floatFromInt(e.round); - for (delta, m, v, grad) |*x, *mm, *vv, g0| { - const g = g0 / n + 2 * decay * x.* / (e.size * e.size); - mm.* = 0.9 * mm.* + 0.1 * g; - vv.* = 0.999 * vv.* + 0.001 * g * g; - const mh = mm.* / (1 - std.math.pow(f32, 0.9, t1)); - const vh = vv.* / (1 - std.math.pow(f32, 0.999, t1)); - x.* -= lr * mh / (@sqrt(vh) + 1e-8); - } - const len = @sqrt(subspace.dot(delta, delta)); - if (len > furthest * e.size) for (delta) |*x| { - x.* *= furthest * e.size / len; - }; - return false; - } - - fn editsOnce(e: *Self, t: *T, acting: Acting) !bool { - if (e.round == layers.len) { - e.next(.done); - return true; - } - if (e.at < e.facts.items.len) { - const i = e.at; - e.at += 1; - try e.read(t, i, e.round, acting, false); - return false; - } - try e.edit(t, e.round, acting); - e.at = 0; - e.round += 1; - return false; - } - - /// Layer j's rank-one change: the mean key sent to its share of the nudge left, kept and earlier keys held. - fn edit(e: *Self, t: *T, j: usize, acting: Acting) !void { - const c = t.b.m.config; - const w = c.shared_width; - const d = c.hidden; - const n: f32 = @floatFromInt(e.facts.items.len); - const na: f32 = @floatFromInt(e.answered); - const work = try e.gpa.alloc(f32, w + w + d); - defer e.gpa.free(work); - const key = work[0..w]; - const u = work[w..][0..w]; - const left = work[2 * w ..][0..d]; - @memset(work, 0); - for (0..e.facts.items.len) |i| subspace.axpy(key, 1 / n, e.keys.items[(i * layers.len + j) * w ..][0..w]); - for (0..e.answered) |i| for (left, row(e.base.items, i, d), row(e.now.items, i, d), e.delta.items[0..d]) |*o, b, now, dl| { - o.* += (b + dl - now) / na; - }; - for (left) |*o| o.* /= @floatFromInt(layers.len - j); - try solve(e.gpa, e.kept[j].items, e.history[j].items, w, key, u); - const s = subspace.dot(key, u); - const site = &t.sites.list[layers[j]]; - const first = t.sites.first(); - const ranks = t.sites.cap * adapters.block; - const a = site.a.slice(f32, ranks * site.in)[first * site.in ..][0..site.in]; - const b = site.b.slice(f32, ranks * site.out)[first * site.out ..][0..site.out]; - for (a, u) |*o, x| o.* = x / (1 + s); - for (b, left) |*o, x| o.* = x / adapters.scale; - t.sites.attach(&t.b.m.weights, true); - var loss: f32 = 0; - for (e.facts.items[0..e.answered]) |ex| loss += (try t.step(ex.ids, ex.start, .loss, turn(ex, acting))).loss; - std.log.info("slide: change at layer {d}: the key's reach over the kept rows {d:.1}, its change {d:.2} of the residual; the answers' loss with it {d:.3} (the nudge's {d:.3})", .{ layers[j], s, @sqrt(subspace.dot(left, left)) / e.size, loss / na, e.last_loss }); - } - - fn next(e: *Self, phase: Phase) void { - e.phase = phase; - e.at = 0; - e.round = 0; - e.loss = 0; - } - }; -} - -/// A bf16's value. -fn f32of(b: u16) f32 { - return @bitCast(@as(u32, b) << 16); -} - -fn row(xs: []f32, i: usize, n: usize) []f32 { - return xs[i * n ..][0..n]; -} - -/// A bf16 row appended as f32. -fn widen(gpa: std.mem.Allocator, rows: *std.ArrayList(f32), from: []const u16) !void { - try rows.ensureUnusedCapacity(gpa, from.len); - for (from) |b| rows.appendAssumeCapacity(f32of(b)); -} - -/// h = hold X^T X / rows + history_weight H^T H; returns the fold's diagonal add: a hundredth of the kept part's mean. -fn secondMoment(x: []const f32, hist: []const f32, w: usize, h: []f32) f32 { - const rows = x.len / w; - const scale = hold / @as(f32, @floatFromInt(@max(rows, 1))); - @memset(h[0 .. w * w], 0); - const Share = struct { - fn run(xs: []const f32, width: usize, coef: f32, out: []f32, from: usize, to: usize) void { - const n = xs.len / width; - for (0..n) |r| { - const v = xs[r * width ..][0..width]; - for (from..to) |i| { - const f = coef * v[i]; - if (f != 0) subspace.axpy(out[i * width ..][0..width], f, v); - } - } - } - }; - const threads = @min(std.Thread.getCpuCount() catch 1, 32); - var spawned: [32]?std.Thread = @splat(null); - for (0..threads) |k| spawned[k] = std.Thread.spawn(.{}, Share.run, .{ x, w, scale, h, w * k / threads, w * (k + 1) / threads }) catch null; - for (0..threads) |k| if (spawned[k]) |th| th.join() else Share.run(x, w, scale, h, w * k / threads, w * (k + 1) / threads); - var mean: f32 = 0; - for (0..w) |i| mean += h[i * w + i]; - Share.run(hist, w, history_weight, h, 0, w); - if (mean == 0) for (0..w) |i| { // nothing kept: the facts' keys set it after all - mean += h[i * w + i]; - }; - return 1e-2 * mean / @as(f32, @floatFromInt(w)) + 1e-12; -} - -/// u = C^-1 k, C = hold X^T X / rows + history_weight H^T H + mu I (X kept keys, H facts'), by preconditioned CG. -fn solve(gpa: std.mem.Allocator, x: []const f32, h: []const f32, w: usize, k: []const f32, u: []f32) !void { - const rows = x.len / w; - const hist = h.len / w; - const work = try gpa.alloc(f32, 5 * w); - defer gpa.free(work); - const diag = work[0..w]; - const r = work[w..][0..w]; - const z = work[2 * w ..][0..w]; - const p = work[3 * w ..][0..w]; - const ap = work[4 * w ..][0..w]; - const scale = hold / @as(f32, @floatFromInt(@max(rows, 1))); - @memset(diag, 0); - for (0..rows) |i| for (diag, x[i * w ..][0..w]) |*dg, v| { - dg.* += scale * v * v; - }; - for (0..hist) |i| for (diag, h[i * w ..][0..w]) |*dg, v| { - dg.* += history_weight * v * v; - }; - var mean: f32 = 0; - for (diag) |dg| mean += dg; - const mu = 1e-2 * mean / @as(f32, @floatFromInt(w)) + 1e-12; - for (diag) |*dg| dg.* += mu; - @memset(u, 0); - @memcpy(r, k); - for (z, r, diag) |*zi, ri, dg| zi.* = ri / dg; - @memcpy(p, z); - var rz = subspace.dot(r, z); - const stop = 1e-4 * @sqrt(subspace.dot(k, k)); - for (0..400) |_| { - try apply(gpa, x, scale, h, w, mu, p, ap); - const pap = subspace.dot(p, ap); - if (!(pap > 0)) break; - const alpha = rz / pap; - if (!std.math.isFinite(alpha)) break; - subspace.axpy(u, alpha, p); - subspace.axpy(r, -alpha, ap); - if (@sqrt(subspace.dot(r, r)) < stop) break; - for (z, r, diag) |*zi, ri, dg| zi.* = ri / dg; - const rz2 = subspace.dot(r, z); - for (p, z) |*pi, zi| pi.* = zi + rz2 / rz * pi.*; - rz = rz2; - } - for (u) |*v| if (!std.math.isFinite(v.*)) { - v.* = 0; - }; -} - -/// ap = C p, with C as `solve` holds it, the rows' products spread over threads. -fn apply(gpa: std.mem.Allocator, x: []const f32, scale: f32, h: []const f32, w: usize, mu: f32, p: []const f32, ap: []f32) !void { - const threads = @min(std.Thread.getCpuCount() catch 1, 16); - const parts = try gpa.alloc(f32, threads * w); - defer gpa.free(parts); - @memset(parts, 0); - const Share = struct { - fn run(xs: []const f32, hs: []const f32, width: usize, sc: f32, pp: []const f32, out: []f32, from: usize, step: usize) void { - const n = xs.len / width; - var i = from; - while (i < n + hs.len / width) : (i += step) { - const v = if (i < n) xs[i * width ..][0..width] else hs[(i - n) * width ..][0..width]; - const cf = (if (i < n) sc else history_weight) * subspace.dot(v, pp); - subspace.axpy(out, cf, v); - } - } - }; - var spawned: [16]?std.Thread = @splat(null); - for (0..threads) |i| spawned[i] = std.Thread.spawn(.{}, Share.run, .{ x, h, w, scale, p, parts[i * w ..][0..w], i, threads }) catch null; - for (0..threads) |i| if (spawned[i]) |th| th.join() else Share.run(x, h, w, scale, p, parts[i * w ..][0..w], i, threads); - for (ap, p) |*o, v| o.* = mu * v; - for (0..threads) |i| for (ap, parts[i * w ..][0..w]) |*o, v| { - o.* += v; - }; -} - -test "the solve inverts the kept rows' held second moment, earlier facts' keys among them" { - const gpa = std.testing.allocator; - const w = 16; - var x: [40 * w]f32 = undefined; - var h: [3 * w]f32 = undefined; - var prng = std.Random.DefaultPrng.init(3); - for (&x) |*v| v.* = prng.random().float(f32) - 0.5; - for (&h) |*v| v.* = prng.random().float(f32) - 0.5; - var k: [w]f32 = undefined; - for (&k, 0..) |*v, i| v.* = @floatFromInt(i % 3); - var u: [w]f32 = undefined; - try solve(gpa, &x, &h, w, &k, &u); - var diag_mean: f32 = 0; - for (0..w) |i| { - for (0..40) |r| diag_mean += hold / 40 * x[r * w + i] * x[r * w + i]; - for (0..3) |r| diag_mean += history_weight * h[r * w + i] * h[r * w + i]; - } - const mu = 1e-2 * diag_mean / w + 1e-12; - for (0..w) |i| { - var s: f32 = mu * u[i]; - for (0..40) |r| s += hold / 40 * x[r * w + i] * subspace.dot(x[r * w ..][0..w], &u); - for (0..3) |r| s += history_weight * h[r * w + i] * subspace.dot(h[r * w ..][0..w], &u); - try std.testing.expectApproxEqAbs(k[i], s, 2e-2 * (1 + @abs(k[i]))); - } -} diff --git a/zig/src/families/nemotron/gpu_round.zig b/zig/src/families/nemotron/gpu_round.zig index 33dfd4d7991..ab21d8c6304 100644 --- a/zig/src/families/nemotron/gpu_round.zig +++ b/zig/src/families/nemotron/gpu_round.zig @@ -352,7 +352,7 @@ pub fn run(gpa: std.mem.Allocator, b: *Metal, s: *lanes.Stream, o: Options, hook var mtp_known: usize = mtp0 + 1; var queued: u64 = 0; // rounds submitted var read: u64 = 0; // rounds whose records the host took - const log = platform.c.getenv("TF_ROUND_LOG") != null; + const log = (@import("sys").environment.Process{}).get("TF_ROUND_LOG") != null; var widths: [32]usize = undefined; var window_ms: [32]f64 = undefined; for (b.costs.window[0..b.costs.windows], 0..) |w, i| { diff --git a/zig/src/families/nemotron/lesson_route.zig b/zig/src/families/nemotron/lesson_route.zig deleted file mode 100644 index f806c76abcb..00000000000 --- a/zig/src/families/nemotron/lesson_route.zig +++ /dev/null @@ -1,121 +0,0 @@ -//! How rows meet lessons in both gate kernels: the decision row scores each router, later rows carry those that clear. -const std = @import("std"); - -pub const max_slots = 64; // latch slots: a stream's replay id (a sequence's on CUDA), the trainer's the last -pub const max_blocks = @import("learn_shape.zig").max_blocks; -pub const trainer_slot = max_slots - 1; -pub const max_segments = 8; - -/// A stream without a decision row: none of its rows carry a lesson. -pub const none: i64 = std.math.maxInt(i32); - -/// No segments: no row carries a lesson. -pub const off: Route = .{}; - -/// Which lessons act on a reply, a bit a block. -pub const Acting = std.bit_set.Integer(max_blocks); - -/// A training example's decision row and the lessons acting after it (`whole`: on every row, as weight edits do). -pub const Turn = struct { decide: u32, bits: Acting = .empty, whole: bool = false }; - -/// A slot's latch flags (`latch`: u32 [max_slots, max_blocks]) set to `bits`, as a training pass reads them. -pub fn flag(latch: []u32, slot: u32, bits: Acting) void { - for (latch[slot * max_blocks ..][0..max_blocks], 0..) |*f, b| f.* = @intFromBool(bits.isSet(b)); -} - -/// A training pass over one example's `rows` rows: its latch is set before the pass (the trainer's slot). -pub fn trained(rows: usize, turn: Turn) Route { - var r: Route = .{ .known = 1, .whole = @intFromBool(turn.whole) }; - r.add(0, rows, 0, turn.decide, trainer_slot); - return r; -} - -pub const Route = extern struct { - count: u32 = 0, - known: u32 = 0, // 1: every latch was set before the pass, so rows after a decision row in it may act (training) - whole: u32 = 0, // 1: lessons edit the weights and act on every row (a training pass's flagged ones, else all) - pad: u32 = 0, - seg: [max_segments][4]i32 = std.mem.zeroes([max_segments][4]i32), - - /// The pass's rows `first`..`first + rows`, a stream's rows from position `pos`, its decision row at `decide`. - pub fn add(r: *Route, first: usize, rows: usize, pos: usize, decide: i64, slot: u32) void { - std.debug.assert(r.count < max_segments); - const at: i64 = if (decide == none) none else @as(i64, @intCast(first)) + decide - @as(i64, @intCast(pos)); - r.seg[r.count] = .{ @intCast(first), @intCast(rows), @intCast(std.math.clamp(at, -1, none)), @intCast(slot) }; - r.count += 1; - } - - /// The pass's rows `first`..`first + rows`, a stream past its decision row: its latch alone decides. - pub fn later(r: *Route, first: usize, rows: usize, slot: u32) void { - r.add(first, rows, 1, 0, slot); - } - - /// Segment s's decision row, when it lies in this pass (then the stream's latch is set after it). - pub fn decision(r: *const Route, s: usize) ?usize { - const g = r.seg[s]; - return if (g[2] >= g[0] and g[2] < g[0] + g[1]) @intCast(g[2]) else null; - } -}; - -test "a stream's rows carry a lesson only after its decision row" { - var r: Route = .{}; - r.add(0, 10, 100, 104, 3); // decision at position 104: pass row 4 - r.add(10, 2, 200, 150, 5); // decided in an earlier pass - r.add(12, 3, 7, none, 6); - try std.testing.expectEqual(@as(?usize, 4), r.decision(0)); - try std.testing.expectEqual(@as(?usize, null), r.decision(1)); - try std.testing.expect(r.seg[1][2] < r.seg[1][0]); - try std.testing.expect(r.seg[2][2] >= r.seg[2][0] + r.seg[2][1]); -} - -/// A pass's rows the pocket acts on, segment by segment in pass order: runs of rows between untaught streams' rows. -pub const Runs = struct { - first: usize = 0, // the open run's first row - rows: usize = 0, // and its rows so far - - /// The run a segment of `rows` rows closes, if any: an untaught segment ends the open run and is left out. - pub fn next(r: *Runs, rows: usize, untaught: bool) ?[2]usize { - if (!untaught) { - r.rows += rows; - return null; - } - const closed = r.last(); - r.* = .{ .first = r.first + r.rows + rows }; - return closed; - } - - /// The open run, once every segment is in. - pub fn last(r: *const Runs) ?[2]usize { - return if (r.rows > 0) .{ r.first, r.rows } else null; - } -}; - -test "the pocket's runs leave out the rows of streams that read the model as shipped" { - var r: Runs = .{}; - try std.testing.expectEqual(@as(?[2]usize, null), r.next(3, false)); - try std.testing.expectEqual(@as(?[2]usize, .{ 0, 3 }), r.next(2, true)); - try std.testing.expectEqual(@as(?[2]usize, null), r.next(4, true)); - try std.testing.expectEqual(@as(?[2]usize, null), r.next(1, false)); - try std.testing.expectEqual(@as(?[2]usize, null), r.next(2, false)); - try std.testing.expectEqual(@as(?[2]usize, .{ 9, 3 }), r.last()); - var all: Runs = .{}; - try std.testing.expectEqual(@as(?[2]usize, null), all.next(5, true)); - try std.testing.expectEqual(@as(?[2]usize, null), all.last()); -} - -/// The kept lessons (blocks below `blocks`) whose router scores reach what they need. -pub fn latched(score: []const f32, need: []const f32, blocks: usize) Acting { - var bits: Acting = .empty; - for (0..blocks) |b| if (need[b] > 0 and score[b] >= need[b]) bits.set(b); - return bits; -} - -test "a kept lesson acts on a reply only once its router score reaches what it needs" { - var score: [max_blocks]f32 = @splat(0); - var need: [max_blocks]f32 = @splat(0); - score[0..4].* = .{ 2.5, 1.2, 0, 3 }; - need[0..2].* = .{ 2, 1.5 }; - const four = latched(&score, &need, 4); - try std.testing.expect(four.isSet(0) and four.count() == 1); - try std.testing.expectEqual(@as(usize, 0), latched(&score, &need, 0).count()); -} diff --git a/zig/src/families/nemotron/pocket_clock.zig b/zig/src/families/nemotron/pocket_clock.zig deleted file mode 100644 index f4b539472b0..00000000000 --- a/zig/src/families/nemotron/pocket_clock.zig +++ /dev/null @@ -1,37 +0,0 @@ -//! Where a pocket lesson's round spends its time: wall seconds, trainer passes and rows of each phase, logged a round. -const std = @import("std"); - -/// A round's phases: examples read, inputs fitted, outputs fitted, the held-out loss read between steps, judging. -pub const Part = enum { read, fit, values, judge, check }; -const parts = std.enums.values(Part).len; - -/// Passes a trainer ran and the rows they held, counted as it steps. -pub const Count = struct { passes: usize = 0, rows: usize = 0 }; - -pub const Clock = struct { - seconds: [parts]f64 = @splat(0), - passes: [parts]usize = @splat(0), - rows: [parts]usize = @splat(0), - round: usize = 1, - - pub fn add(c: *Clock, part: Part, seconds: f64, before: Count, after: Count) void { - const i = @backingInt(part); - c.seconds[i] += seconds; - c.passes[i] += after.passes - before.passes; - c.rows[i] += after.rows - before.rows; - } - - /// The round's line, then the counts cleared for the next round. - pub fn end(c: *Clock) void { - const s = c.seconds; - var total: f64 = 0; - for (s) |x| total += x; - std.log.info("slide pocket: round {d} took {d:.1} s: read {d:.1} s ({d} passes, {d} rows), fit {d:.1} s, values {d:.1} s ({d} passes, {d} rows), judge {d:.1} s ({d} passes), check {d:.1} s ({d} passes)", .{ c.round, total, s[0], c.passes[0], c.rows[0], s[1], s[2], c.passes[2], c.rows[2], s[3], c.passes[3], s[4], c.passes[4] }); - c.* = .{ .round = c.round + 1 }; - } -}; - -/// Seconds on the awake clock. -pub fn now(io: std.Io) f64 { - return @as(f64, @floatFromInt(std.Io.Clock.awake.now(io).toNanoseconds())) / 1e9; -} diff --git a/zig/src/families/nemotron/pocket_dump.zig b/zig/src/families/nemotron/pocket_dump.zig deleted file mode 100644 index b1f5d152a6a..00000000000 --- a/zig/src/families/nemotron/pocket_dump.zig +++ /dev/null @@ -1,40 +0,0 @@ -//! A lesson's read rows written out for offline study (TF_SLIDE_POCKET_DUMP=dir): inputs, labels and examples. -const std = @import("std"); -const platform = @import("sys"); - -/// `bytes` written to `path`. -fn put(path: [:0]const u8, bytes: []const u8) !void { - const f = platform.c.fopen(path, "wb") orelse return error.DumpOpen; - defer _ = platform.c.fclose(f); - if (platform.c.fwrite(bytes.ptr, 1, bytes.len, f) != bytes.len) return error.DumpWrite; -} - -/// Pocket `p`'s read rows under `dir` for `tag`: bf16 [read, slots, D], then their labels and examples as text. -pub fn write(p: anytype, dir: []const u8, tag: usize, d: usize) !void { - const a = p.gpa; - var path: [1024]u8 = undefined; - try put(try std.mem.printSentinel(&path, "{s}/fact-{d}-rows.bf16", .{ dir, tag }, 0), std.mem.sliceAsBytes(p.rows.items)); - var text: std.ArrayList(u8) = .empty; - defer text.deinit(a); - try text.print(a, "{d} {d}", .{ p.moe.items.len, d }); - for (p.moe.items) |l| try text.print(a, " {d}", .{l}); - try text.append(a, '\n'); - var exs: usize = 0; - for (p.labels.items) |l| { - const ex = p.pickRead(l.ex).?.ex; - const key: i32 = if (l.key) |k| @backingInt(k) else -1; - try text.print(a, "{d} {d} {d} {d} {d} {d}\n", .{ @backingInt(l.kind), key, l.ex, l.row, ex.ids[l.row], if (l.row > 0) ex.ids[l.row - 1] else 0 }); - exs = @max(exs, l.ex + 1); - } - try put(try std.mem.printSentinel(&path, "{s}/fact-{d}-labels.txt", .{ dir, tag }, 0), text.items); - text.clearRetainingCapacity(); - for (0..exs) |i| { - const got = p.pickRead(i).?; - const ex = got.ex; - try text.print(a, "{d} {d} {d} {d} {d} {d}", .{ i, @backingInt(got.kind), ex.start, ex.decide, ex.subject, ex.value }); - for (ex.ids) |id| try text.print(a, " {d}", .{id}); - try text.append(a, '\n'); - } - try put(try std.mem.printSentinel(&path, "{s}/fact-{d}-examples.txt", .{ dir, tag }, 0), text.items); - std.log.info("slide pocket: the lesson's {d} read rows written to {s} for study", .{ p.labels.items.len, dir }); -} diff --git a/zig/src/families/nemotron/pocket_fit.zig b/zig/src/families/nemotron/pocket_fit.zig deleted file mode 100644 index 02c9d994934..00000000000 --- a/zig/src/families/nemotron/pocket_fit.zig +++ /dev/null @@ -1,286 +0,0 @@ -//! A pocket neuron's input weights by Adam on squared hinges: at least 1 on its fact's rows, below zero elsewhere. -const std = @import("std"); -const subspace = @import("subspace.zig"); - -pub const margin: f32 = 0.25; // how far below zero a fact's neuron sits on rows it stays silent on -pub const fit_steps = 500; // Adam steps fitting a neuron's input weights -pub const fit_rate: f32 = 0.01; // their step, the inputs scaled to unit length - -/// A read row to the open fact: a key row of a learned, held-out or other prompt, any other row, or left free. -pub const Kind = enum(u8) { fact, held, steady, other, none }; - -/// One MoE layer's fit: how its neuron's input product sits on each kind of row. -pub const Fit = struct { - fact_least: f32 = 0, // the lowest over the fact's own questions - fact_on: f32 = 0, // the share of them at 0.5 or more - held_mean: f32 = 0, - held_on: f32 = 0, - steady_most: f32 = 0, // the highest over other prompts' first reply rows - other_most: f32 = 0, // the highest over every other row read - fires: usize = 0, // rows it must stay silent on where it is above zero -}; - -/// Slot j's neuron fitted on its read rows, copied side by side first (a failure: zero, its slot last in line). -pub fn fitLayer(gpa: std.mem.Allocator, rows: []const u16, kinds: []const Kind, slots: usize, j: usize, d: usize, u: []f32, out: *Fit) void { - const own = gpa.alloc(u16, kinds.len * d) catch { - out.* = .{ .fires = std.math.maxInt(usize) }; - return; - }; - defer gpa.free(own); - const xs = gpa.alloc([]const u16, kinds.len) catch { - out.* = .{ .fires = std.math.maxInt(usize) }; - return; - }; - defer gpa.free(xs); - for (xs, 0..) |*x, i| { - @memcpy(own[i * d ..][0..d], rows[(i * slots + j) * d ..][0..d]); - x.* = own[i * d ..][0..d]; - } - out.* = fit(gpa, xs, kinds, d, u, false, fit_steps, 0) catch blk: { - @memset(u, 0); - break :blk .{ .fires = std.math.maxInt(usize) }; - }; -} - -/// Fits `u` on `xs` (from `u` if `warm`): at least 1 on fact rows, at most -margin elsewhere; first `fixed` rows kept. -pub fn fit(gpa: std.mem.Allocator, xs: []const []const u16, kinds: []const Kind, d: usize, u: []f32, warm: bool, steps: usize, fixed: usize) !Fit { - const n = kinds.len; - var scale: f32 = 0; - for (xs) |x| scale += @sqrt(squares(x)); - scale /= @floatFromInt(@max(n, 1)); - const inv = 1 / scale; - var counts: [5]f32 = @splat(0); - for (kinds) |k| counts[@backingInt(k)] += 1; - const w = try gpa.alloc(f32, 8 * d); - defer gpa.free(w); - @memset(w, 0); - const mean_fact = w[0..d]; - const mean_rest = w[d..][0..d]; - const m = w[2 * d ..][0..d]; - const v = w[3 * d ..][0..d]; - const g = w[4 * d ..][0..d]; - const parts = w[5 * d ..][0 .. 3 * d]; // each kind's rows on the wrong side, their hinges' sum: fact, steady, other - if (warm) { - for (u) |*o| o.* *= scale; - } else { - // a start: the fact's mean less the mean of the rows it stays silent on, sized so the fact's mean is 1 - for (kinds, xs) |k, x| switch (k) { - .fact => axpyRow(mean_fact, inv / @max(counts[0], 1), x), - .steady, .other => axpyRow(mean_rest, inv / @max(counts[2] + counts[3], 1), x), - .held, .none => {}, - }; - for (u, mean_fact, mean_rest) |*o, a, b| o.* = a - b; - const at_fact = subspace.dot(u, mean_fact); - if (at_fact > 0) for (u) |*o| { - o.* /= at_fact; - }; - } - const basis = try gpa.alloc(f32, 2 * fixed * d); - defer gpa.free(basis); - const own = basis[fixed * d ..]; - for (0..fixed) |i| for (own[i * d ..][0..d], xs[i]) |*o, b| { - o.* = bf(b) * inv; - }; - const rank = orthonormal(basis[0 .. fixed * d], own, d); - for (1..steps + 1) |s| { - // each kind weighed by its rows on the wrong side only: a few rows that still slip are pushed as hard as many - @memset(parts, 0); - var wrong: [3]f32 = @splat(0); - for (kinds, xs) |k, x| { - const z = dotRow(u, x) * inv; - switch (k) { - .fact => if (z < 1) { - wrong[0] += 1; - axpyRow(parts[0..d], -2 * (1 - z), x); - }, - .steady, .other => if (z > -margin) { - const at: usize = if (k == .steady) 1 else 2; - wrong[at] += 1; - axpyRow(parts[at * d ..][0..d], 2 * (z + margin), x); - }, - .held, .none => {}, - } - } - @memset(g, 0); - for (0..3) |at| subspace.axpy(g, inv / @max(wrong[at], 1), parts[at * d ..][0..d]); - const tt: f32 = @floatFromInt(s); - for (u, m, v, g) |ui, *mi, *vi, *gi| { - const gg = gi.* + 2e-4 * ui; - mi.* = 0.9 * mi.* + 0.1 * gg; - vi.* = 0.999 * vi.* + 0.001 * gg * gg; - gi.* = fit_rate * (mi.* / (1 - std.math.pow(f32, 0.9, tt))) / (@sqrt(vi.* / (1 - std.math.pow(f32, 0.999, tt))) + 1e-8); - } - // the step, less its part along the fixed rows' span - for (0..rank) |j| { - const b = basis[j * d ..][0..d]; - subspace.axpy(g, -subspace.dot(g, b), b); - } - for (u, g) |*ui, st| ui.* -= st; - } - var f: Fit = .{ .fact_least = std.math.inf(f32), .steady_most = -std.math.inf(f32), .other_most = -std.math.inf(f32) }; - for (kinds, xs) |k, x| { - const zi = dotRow(u, x) * inv; - switch (k) { - .fact => { - f.fact_least = @min(f.fact_least, zi); - f.fact_on += @floatFromInt(@intFromBool(zi >= 0.5)); - }, - .held => { - f.held_mean += if (zi > 0) zi * zi else 0; - f.held_on += @floatFromInt(@intFromBool(zi >= 0.5)); - }, - .steady => { - f.steady_most = @max(f.steady_most, zi); - f.fires += @intFromBool(zi > 0); - }, - .other => { - f.other_most = @max(f.other_most, zi); - f.fires += @intFromBool(zi > 0); - }, - .none => {}, - } - } - f.fact_on /= @max(counts[0], 1); - f.held_on /= @max(counts[1], 1); - f.held_mean /= @max(counts[1], 1); - for (u) |*o| o.* /= scale; - return f; -} - -const V = @Vector(8, f32); - -/// Eight bf16 values widened to f32, exactly. -inline fn widen8(b: []const u16) V { - const raw: @Vector(8, u32) = @as(@Vector(8, u16), b[0..8].*); - return @bitCast(raw << @splat(16)); -} - -fn bf(b: u16) f32 { - return @bitCast(@as(u32, b) << 16); -} - -/// a . b for f32 `a` and bf16 `b`: four sums of eight lanes, so no add waits on the one before it. -fn dotRow(a: []const f32, b: []const u16) f32 { - var acc: [4]V = @splat(@splat(0)); - var i: usize = 0; - while (i + 32 <= a.len) : (i += 32) { - inline for (&acc, 0..) |*x, k| x.* += @as(V, a[i + 8 * k ..][0..8].*) * widen8(b[i + 8 * k ..]); - } - while (i + 8 <= a.len) : (i += 8) acc[0] += @as(V, a[i..][0..8].*) * widen8(b[i..]); - var s = @reduce(.Add, (acc[0] + acc[1]) + (acc[2] + acc[3])); - while (i < a.len) : (i += 1) s += a[i] * bf(b[i]); - return s; -} - -/// y += c b for bf16 `b`. -fn axpyRow(y: []f32, c: f32, b: []const u16) void { - const cv: V = @splat(c); - var i: usize = 0; - while (i + 8 <= y.len) : (i += 8) y[i..][0..8].* = @as(V, y[i..][0..8].*) + cv * widen8(b[i..]); - while (i < y.len) : (i += 1) y[i] += c * bf(b[i]); -} - -/// b . b for bf16 `b`. -fn squares(b: []const u16) f32 { - var acc: V = @splat(0); - var i: usize = 0; - while (i + 8 <= b.len) : (i += 8) { - const x = widen8(b[i..]); - acc += x * x; - } - var s = @reduce(.Add, acc); - while (i < b.len) : (i += 1) s += bf(b[i]) * bf(b[i]); - return s; -} - -/// An orthonormal basis of `rows` ([k, d]) into `basis` by Gram-Schmidt run twice, rows in the span left out; its rank. -fn orthonormal(basis: []f32, rows: []const f32, d: usize) usize { - var rank: usize = 0; - for (0..rows.len / d) |i| { - const q = basis[rank * d ..][0..d]; - @memcpy(q, rows[i * d ..][0..d]); - const before = @sqrt(subspace.dot(q, q)); - for (0..2) |_| for (0..rank) |j| { - const b = basis[j * d ..][0..d]; - subspace.axpy(q, -subspace.dot(q, b), b); - }; - const len = @sqrt(subspace.dot(q, q)); - if (len <= 1e-3 * before) continue; - for (q) |*e| e.* /= len; - rank += 1; - } - return rank; -} - -pub fn dotBf16(a: []const f32, b: []const u16) f32 { - var s: f32 = 0; - for (a, b) |x, y| s += x * @as(f32, @bitCast(@as(u32, y) << 16)); - return s; -} - -pub fn normBf16(b: []const u16) f32 { - var s: f32 = 0; - for (b) |y| { - const f: f32 = @bitCast(@as(u32, y) << 16); - s += f * f; - } - return @sqrt(s); -} - -test "a neuron fires on its fact's rows and stays at zero on the rest; fitted again, it goes quiet on a new fact's" { - const gpa = std.testing.allocator; - const d = 64; - var prng = std.Random.DefaultPrng.init(9); - const r = prng.random(); - // a shared offset every row has (as hidden states do), and a direction each fact's rows lean along - var common: [d]f32 = undefined; - var fact_dir: [d]f32 = undefined; - var new_dir: [d]f32 = undefined; - for (&common, &fact_dir, &new_dir) |*c, *f, *g| { - c.* = 1 + r.floatNorm(f32) * 0.1; - f.* = r.floatNorm(f32); - g.* = r.floatNorm(f32); - } - const n_fact = 12; - const n_rest = 200; - const n_new = 12; - const rows = try gpa.alloc(u16, (n_fact + n_rest + n_new) * d); - defer gpa.free(rows); - for (0..n_fact + n_rest + n_new) |i| { - const lean: ?*const [d]f32 = if (i < n_fact) &fact_dir else if (i >= n_fact + n_rest) &new_dir else null; - for (0..d) |k| { - var v = common[k] + r.floatNorm(f32) * 0.5; - if (lean) |dir| v += 1.5 * dir[k]; - rows[i * d + k] = @truncate(@as(u32, @bitCast(v)) >> 16); - } - } - const xs = try gpa.alloc([]const u16, n_fact + n_rest); - defer gpa.free(xs); - const kinds = try gpa.alloc(Kind, n_fact + n_rest); - defer gpa.free(kinds); - for (xs, kinds, 0..) |*x, *k, i| { - x.* = rows[i * d ..][0..d]; - k.* = if (i < n_fact) .fact else .other; - } - var u: [d]f32 = undefined; - const first = try fit(gpa, xs, kinds, d, &u, false, fit_steps, 0); - try std.testing.expectEqual(@as(f32, 1), first.fact_on); - try std.testing.expectEqual(@as(usize, 0), first.fires); - // the new fact's rows, which nothing told it about, are where it is fitted again to stay quiet - const all = try gpa.alloc([]const u16, n_fact + n_rest + n_new); - defer gpa.free(all); - const kinds2 = try gpa.alloc(Kind, n_fact + n_rest + n_new); - defer gpa.free(kinds2); - for (all, kinds2, 0..) |*x, *k, i| { - x.* = rows[i * d ..][0..d]; - k.* = if (i < n_fact) .fact else if (i < n_fact + n_rest) .other else .steady; - } - const before = try gpa.dupe(f32, &u); - defer gpa.free(before); - const again = try fit(gpa, all, kinds2, d, &u, true, fit_steps / 2, n_fact); - try std.testing.expectEqual(@as(f32, 1), again.fact_on); - try std.testing.expectEqual(@as(usize, 0), again.fires); - try std.testing.expect(again.steady_most <= 0); - // its own rows were held fixed: each reads as it did before the refit - for (all[0..n_fact]) |x| try std.testing.expectApproxEqAbs(dotBf16(before, x), dotBf16(&u, x), 1e-3); -} diff --git a/zig/src/families/nemotron/pocket_forget.zig b/zig/src/families/nemotron/pocket_forget.zig deleted file mode 100644 index 014a0b571ae..00000000000 --- a/zig/src/families/nemotron/pocket_forget.zig +++ /dev/null @@ -1,158 +0,0 @@ -//! A fact deleted on request: its neurons' inputs zeroed, their layers rounded as a save writes them, kept to put back. -const std = @import("std"); -const pocket = @import("pocket.zig"); - -/// What the last delete changed, bit for bit as it was: whole layers' neurons and counts, every neuron's record. -pub const Kept = struct { - held: bool = false, // a delete not yet written by a save nor put back - stale: bool = false, // put back in memory, but a layer's upload failed: kept until the device takes them all - slots: std.ArrayList(usize) = .empty, // the pocket slots it changed - up: std.ArrayList(f32) = .empty, // [slots, neurons, D]: their input weights before - down: std.ArrayList(f32) = .empty, // [slots, neurons, D]: their outputs before - used: std.ArrayList(usize) = .empty, // [slots]: their counts before - learned: std.ArrayList(pocket.Learned) = .empty, // the session's neuron records before - learned_before: usize = 0, - marks: usize = 0, // retired lessons before - - pub fn deinit(k: *Kept, gpa: std.mem.Allocator) void { - inline for (.{ "slots", "up", "down", "used", "learned" }) |f| @field(k, f).deinit(gpa); - } - - fn clear(k: *Kept) void { - inline for (.{ "slots", "up", "down", "used", "learned" }) |f| @field(k, f).clearRetainingCapacity(); - k.held = false; - k.stale = false; - } -}; - -/// Whether a delete waits to be written: a save then writes the pocket even when nothing is left in it. -pub fn pending(p: anytype) bool { - return p.forgot.held; -} - -/// Whether a put-back is in memory but not yet on the device: replies are refused until `unforget` lands it. -pub fn stale(p: anytype) bool { - return p.forgot.stale; -} - -/// The last delete written into the shards: nothing is left to put back. -pub fn settle(p: anytype) void { - p.forgot.clear(); -} - -/// Neurons `gone` names that hold anything silenced, their layers rounded, freed at the top; how many held anything. -pub fn forget(p: anytype, t: anytype, host: anytype, gone: []const [2]u16) !usize { - try p.load(t, host); - const d = t.config().hidden; - const n = pocket.neurons * d; - const k = &p.forgot; - // a put-back the device has not taken yet is never dropped for a new delete - if (k.stale) return error.PutBackNotOnDevice; - k.clear(); - var held: usize = 0; - for (gone) |g| { - const slot = std.mem.indexOfScalar(usize, p.moe.items, g[0]) orelse continue; - if (g[1] >= p.used.items[slot] or std.mem.allEqual(f32, p.neuron(p.up.items, slot, g[1], d), 0)) continue; - held += 1; - if (std.mem.indexOfScalar(usize, k.slots.items, slot) == null) try k.slots.append(p.gpa, slot); - } - // a replaced fact's neurons are zero already: nothing changes, nothing is kept - if (held == 0) return 0; - for (k.slots.items) |slot| { - try k.up.appendSlice(p.gpa, p.up.items[slot * n ..][0..n]); - try k.down.appendSlice(p.gpa, p.down.items[slot * n ..][0..n]); - try k.used.append(p.gpa, p.used.items[slot]); - } - try k.learned.appendSlice(p.gpa, p.learned.items); - // everything that can fail before the pocket moves is done here; anything that fails after puts it all back - try p.retired_lessons.ensureUnusedCapacity(p.gpa, p.learned.items.len); // a lesson at most for each record - k.learned_before = p.learned_before; - k.marks = p.retired_lessons.items.len; - k.held = true; - cut(p, t, host, gone) catch |e| { - // put back whole; if the device cannot take it, that is the failure to report, the snapshot kept - _ = unforget(p, t, host) catch |back| { - std.log.warn("slide pocket: a delete failed ({t}), and its put-back did not reach the device ({t})", .{ e, back }); - return back; - }; - return e; - }; - std.log.info("slide pocket: {d} neurons of a deleted fact zeroed in {d} layers", .{ held, k.slots.items.len }); - return held; -} - -/// The cut itself, after the snapshot: input weights zeroed, records out, layers rounded, freed and uploaded. -fn cut(p: anytype, t: anytype, host: anytype, gone: []const [2]u16) !void { - const d = t.config().hidden; - const n = pocket.neurons * d; - const k = &p.forgot; - for (gone) |g| { - const slot = std.mem.indexOfScalar(usize, p.moe.items, g[0]) orelse continue; - if (g[1] >= p.used.items[slot]) continue; - // its input weights zeroed, so it never fires; its output stays, so the 4-bit groups it shares keep every bit - @memset(p.neuron(p.up.items, slot, g[1], d), 0); - // its record goes, so no later fact on the neuron is refitted as this one; its lesson's answers retire - var i: usize = 0; - while (i < p.learned.items.len) { - const e = p.learned.items[i]; - if (e.slot != slot or e.neuron != g[1]) { - i += 1; - continue; - } - if (std.mem.indexOfScalar(u32, p.retired_lessons.items, e.lesson) == null) p.retired_lessons.appendAssumeCapacity(e.lesson); - _ = p.learned.orderedRemove(i); - if (i < p.learned_before) p.learned_before -= 1; - } - } - for (k.slots.items) |slot| { - // the layer as its next save writes it, so the checks after this read what the shards will hold - try host.pocketRound(p.up.items[slot * n ..][0..n], p.down.items[slot * n ..][0..n]); - try settled(p.gpa, host, p.up.items[slot * n ..][0..n], p.down.items[slot * n ..][0..n]); - // neurons at the top whose input weights are zero are free; one below a kept neuron stays taken - while (p.used.items[slot] > 0 and std.mem.allEqual(f32, p.neuron(p.up.items, slot, p.used.items[slot] - 1, d), 0)) p.used.items[slot] -= 1; - try p.upload(t, host, slot); - } -} - -/// A rounded layer that a save would round to the same bits, else error.LayerRoundsAgain, so the delete is put back. -fn settled(gpa: std.mem.Allocator, host: anytype, up: []const f32, down: []const f32) !void { - const again = try gpa.alloc(f32, up.len + down.len); - defer gpa.free(again); - @memcpy(again[0..up.len], up); - @memcpy(again[up.len..], down); - try host.pocketRound(again[0..up.len], again[up.len..]); - const same = std.mem.eql(u8, std.mem.sliceAsBytes(again[0..up.len]), std.mem.sliceAsBytes(up)) and std.mem.eql(u8, std.mem.sliceAsBytes(again[up.len..]), std.mem.sliceAsBytes(down)); - if (!same) return error.LayerRoundsAgain; -} - -/// The last delete undone bit for bit; a layer the device does not take keeps the snapshot, and a call again retries. -pub fn unforget(p: anytype, t: anytype, host: anytype) !usize { - const k = &p.forgot; - if (!k.held) return 0; - try p.load(t, host); - try p.learned.ensureTotalCapacity(p.gpa, k.learned.items.len); - // the pocket whole as it was before any layer goes to the forward, so a failed upload leaves no layer half put back - const n = pocket.neurons * t.config().hidden; - for (k.slots.items, 0..) |slot, j| { - @memcpy(p.up.items[slot * n ..][0..n], k.up.items[j * n ..][0..n]); - @memcpy(p.down.items[slot * n ..][0..n], k.down.items[j * n ..][0..n]); - p.used.items[slot] = k.used.items[j]; - } - p.learned.clearRetainingCapacity(); - p.learned.appendSliceAssumeCapacity(k.learned.items); - p.learned_before = k.learned_before; - p.retired_lessons.shrinkRetainingCapacity(k.marks); - const back = k.slots.items.len; - var failed: ?anyerror = null; - for (k.slots.items) |slot| p.upload(t, host, slot) catch |e| { - failed = failed orelse e; - }; - if (failed) |e| { - k.stale = true; - std.log.warn("slide pocket: a deleted fact's {d} layers are put back in memory, but not all on the device ({t}): replies are refused until they are", .{ back, e }); - return error.PutBackNotOnDevice; - } - k.clear(); - std.log.info("slide pocket: a deleted fact's {d} layers put back as they were", .{back}); - return back; -} diff --git a/zig/src/families/nemotron/pocket_forget_test.zig b/zig/src/families/nemotron/pocket_forget_test.zig deleted file mode 100644 index 5500a6ef658..00000000000 --- a/zig/src/families/nemotron/pocket_forget_test.zig +++ /dev/null @@ -1,464 +0,0 @@ -//! A delete on a pocket of three facts: their neurons zeroed and rounded, freed at the top, put back bit for bit. -const std = @import("std"); -const cfg = @import("config.zig"); -const pocket = @import("pocket.zig"); -const forgetting = @import("pocket_forget.zig"); -const whole = @import("whole.zig"); -const examples = @import("lesson_examples.zig"); -const Shards = @import("pocket_shards.zig").Io(struct { - pub const shard_edit = @import("../../core/shard_edit.zig"); - pub const safetensors = @import("../../core/safetensors.zig"); - pub const affine4_host = @import("../../core/affine4_host.zig"); -}); - -const d = 64; -const layers = 4; // every MoE layer but the last holds a pocket: slots 0, 1 and 2 -const width = pocket.neurons * d; - -/// The trainer as the pocket reads it: only the model's shape. -const Trainer = struct { - c: cfg.Config, - - pub fn config(t: *const Trainer) cfg.Config { - return t.c; - } -}; - -const P = pocket.Pocket(Trainer); - -/// The backend: the pocket as the shards loaded it, and each layer's live copy as the forward reads it. -const Device = struct { - loaded_up: [layers][width]f32 = @splat(@splat(0)), - loaded_down: [layers][width]f32 = @splat(@splat(0)), - loaded_used: [layers]usize = @splat(0), - up: [layers][width]f32 = @splat(@splat(0)), - down: [layers][width]f32 = @splat(@splat(0)), - used: [layers]usize = @splat(0), - uploads: usize = 0, - saves: usize = 0, - gpa: std.mem.Allocator = std.testing.allocator, // what rounding allocates from - fail_at: usize = 0, // the upload, counted from one, that fails once (0: none) - fail_from: usize = 0, // the upload, counted from one, from which every upload fails (0: none) - failing: bool = false, // every upload fails - - pub fn pocketRead(h: *Device, l: usize, up: []f32, down: []f32) usize { - @memcpy(up, &h.loaded_up[l]); - @memcpy(down, &h.loaded_down[l]); - h.up[l] = h.loaded_up[l]; - h.down[l] = h.loaded_down[l]; - h.used[l] = h.loaded_used[l]; - return h.loaded_used[l]; - } - - pub fn pocket(h: *Device, l: usize, up: []const f32, down: []const f32, used: usize) !void { - if (h.failing or h.uploads + 1 == h.fail_at or (h.fail_from > 0 and h.uploads + 1 >= h.fail_from)) { - h.uploads += 1; - return error.UploadFailed; - } - @memcpy(&h.up[l], up); - @memcpy(&h.down[l], down); - h.used[l] = used; - h.uploads += 1; - } - - pub fn pocketRound(h: *Device, up: []f32, down: []f32) !void { - return Shards.round(h.gpa, d, up, down); - } -}; - -/// The learner's host as a save reaches it: `Device` above, and a write into the shards that counts itself. -const SaveHost = struct { - pub const Ctx = *Device; - - pub fn seconds(_: std.Io) f64 { - return 0; - } - - pub fn pocket(h: Ctx, l: usize, up: []const f32, down: []const f32, used: usize) !void { - return h.pocket(l, up, down, used); - } - - pub fn pocketRead(h: Ctx, l: usize, up: []f32, down: []f32) usize { - return h.pocketRead(l, up, down); - } - - pub fn pocketSave(h: Ctx, _: std.mem.Allocator, _: std.Io, _: []const usize, _: usize, _: []f32, _: []f32) !usize { - h.saves += 1; - return 0; - } -}; - -/// The learner as `whole.save` reads it: a pocket lesson kept, and its pocket. -const Learner = struct { - pub const Host = SaveHost; - method: whole.Method = .pocket, - pocketed: bool = false, - kept_rounds: u32 = 1, - pockets: P = .{ .gpa = std.testing.allocator, .mode = .auto }, - trainer: ?*Trainer, - b: *Device, - gpa: std.mem.Allocator = std.testing.allocator, - io: std.Io = std.testing.io, - owned: examples.Lesson = .{}, - - pub fn recalls(_: *Learner, _: []const examples.Example, _: bool) !bool { - return true; - } -}; - -/// Three facts as saved: A at (0, 0) and (1, 0); B at (0, 1) and (2, 0); C at (0, 2) and (1, 1), lessons 0, 1, 2. -fn three(h: *Device, p: *P, t: *Trainer) !void { - var prng = std.Random.DefaultPrng.init(11); - const r = prng.random(); - const held = [_][3]usize{ .{ 0, 0, 0 }, .{ 1, 0, 0 }, .{ 0, 1, 1 }, .{ 2, 0, 1 }, .{ 0, 2, 2 }, .{ 1, 1, 2 } }; - for (held) |x| { - for (h.loaded_up[x[0]][x[1] * d ..][0..d], h.loaded_down[x[0]][x[1] * d ..][0..d]) |*u, *v| { - u.* = r.floatNorm(f32) * 0.05; - v.* = r.floatNorm(f32) * 0.2; - } - h.loaded_used[x[0]] = @max(h.loaded_used[x[0]], x[1] + 1); - } - // the shards hold 4-bit values: the pocket as a save left it - for (0..layers) |l| try Shards.round(std.testing.allocator, d, &h.loaded_up[l], &h.loaded_down[l]); - try p.load(t, h); - for (held, 0..) |x, i| try p.learned.append(p.gpa, .{ .slot = x[0], .neuron = x[1], .key = .reply, .start = i, .count = 1, .subject = 0, .lesson = @intCast(x[2]) }); - p.learned_before = 4; // C, the last lesson, found A's and B's -} - -fn trainer() Trainer { - var c: cfg.Config = .{ .hidden = d, .vocab = 16, .layers = layers, .mamba_heads = 1, .mamba_head_dim = 1, .groups = 1, .state = 1, .conv_kernel = 4, .heads = 1, .kv_heads = 1, .head_dim = 1, .experts = 1, .top_k = 1, .expert_width = 64, .shared_width = 64, .routed_scaling = 1, .eps = 1e-5 }; - for (0..layers) |l| c.kinds[l] = .moe; - return .{ .c = c }; -} - -const b_neurons = [_][2]u16{ .{ 0, 1 }, .{ 2, 0 } }; - -test "a deleted fact's input weights go to zero, every output bit stays, its layers rounded as a save writes them" { - var t = trainer(); - var h: Device = .{}; - var p: P = .{ .gpa = std.testing.allocator, .mode = .auto }; - defer p.deinit(); - try three(&h, &p, &t); - // a lesson since the last save moved C's outputs in layer 0 off the 4-bit grid - for (p.neuron(p.down.items, 0, 2, d)) |*v| v.* *= 1.001; - const before_up = try std.testing.allocator.dupe(f32, p.up.items); - defer std.testing.allocator.free(before_up); - // what layer 0 is to hold: B's input weights zeroed, then the layer rounded on its own - var want_up: [width]f32 = p.up.items[0..width].*; - var want_down: [width]f32 = p.down.items[0..width].*; - @memset(want_up[1 * d ..][0..d], 0); - try Shards.round(std.testing.allocator, d, &want_up, &want_down); - try std.testing.expectEqual(@as(usize, 2), try forgetting.forget(&p, &t, &h, &b_neurons)); - try std.testing.expect(forgetting.pending(&p)); - try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(&want_up), std.mem.sliceAsBytes(p.up.items[0..width])); - try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(&want_down), std.mem.sliceAsBytes(p.down.items[0..width])); - try std.testing.expect(std.mem.allEqual(f32, p.neuron(p.up.items, 2, 0, d), 0)); - // layer 2 as saved: B's input weights zero, every output bit as it was, B's own too, so no 4-bit group moves - try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(&h.loaded_down[2]), std.mem.sliceAsBytes(p.down.items[2 * width ..][0..width])); - // A's and C's input weights keep every bit; layer 1 was not touched at all - for ([_][2]usize{ .{ 0, 0 }, .{ 0, 2 }, .{ 1, 0 }, .{ 1, 1 } }) |x| try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(before_up[(x[0] * pocket.neurons + x[1]) * d ..][0..d]), std.mem.sliceAsBytes(p.neuron(p.up.items, x[0], x[1], d))); - try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(&h.loaded_down[1]), std.mem.sliceAsBytes(p.down.items[width..][0..width])); - // layer 0's neuron 1 sits below C's, so it stays taken; layer 2 is empty again - try std.testing.expectEqualSlices(usize, &.{ 3, 2, 0 }, p.used.items); - // the forward reads exactly the pocket, and only the two layers changed were sent - try std.testing.expectEqual(@as(usize, 2), h.uploads); - try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(p.down.items[0..width]), std.mem.sliceAsBytes(&h.down[0])); - try std.testing.expectEqual(@as(usize, 0), h.used[2]); - // B's records are gone, so no later fact on its freed neuron is refitted as B; its lesson's answers retire - try std.testing.expectEqual(@as(usize, 4), p.learned.items.len); - for (p.learned.items) |e| try std.testing.expect(e.lesson != 1); - try std.testing.expectEqual(@as(usize, 2), p.learned_before); - try std.testing.expectEqualSlices(u32, &.{1}, p.retired_lessons.items); - forgetting.settle(&p); - try std.testing.expect(!forgetting.pending(&p)); -} - -test "a delete put back restores every bit it changed, in the pocket and in the forward" { - var t = trainer(); - var h: Device = .{}; - var p: P = .{ .gpa = std.testing.allocator, .mode = .auto }; - defer p.deinit(); - try three(&h, &p, &t); - // C's outputs off the grid, as a lesson not yet saved leaves them: the delete's rounding moves them - for (p.neuron(p.down.items, 0, 2, d)) |*v| v.* *= 1.001; - try p.upload(&t, &h, 0); - const gpa = std.testing.allocator; - const up = try gpa.dupe(f32, p.up.items); - defer gpa.free(up); - const down = try gpa.dupe(f32, p.down.items); - defer gpa.free(down); - const used = try gpa.dupe(usize, p.used.items); - defer gpa.free(used); - const learned = try gpa.dupe(pocket.Learned, p.learned.items); - defer gpa.free(learned); - const live = h; - try std.testing.expectEqual(@as(usize, 2), try forgetting.forget(&p, &t, &h, &b_neurons)); - try std.testing.expectEqual(@as(usize, 2), try forgetting.unforget(&p, &t, &h)); - try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(up), std.mem.sliceAsBytes(p.up.items)); - try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(down), std.mem.sliceAsBytes(p.down.items)); - try std.testing.expectEqualSlices(usize, used, p.used.items); - try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(learned), std.mem.sliceAsBytes(p.learned.items)); - try std.testing.expectEqual(@as(usize, 4), p.learned_before); - try std.testing.expectEqual(@as(usize, 0), p.retired_lessons.items.len); - for (0..layers - 1) |l| { - try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(&live.up[l]), std.mem.sliceAsBytes(&h.up[l])); - try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(&live.down[l]), std.mem.sliceAsBytes(&h.down[l])); - try std.testing.expectEqual(live.used[l], h.used[l]); - } - try std.testing.expect(!forgetting.pending(&p)); - // with nothing to put back, a second put-back changes nothing - const sent = h.uploads; - try std.testing.expectEqual(@as(usize, 0), try forgetting.unforget(&p, &t, &h)); - try std.testing.expectEqual(sent, h.uploads); - try std.testing.expectEqual(@as(usize, 6), p.learned.items.len); -} - -test "a replaced fact's neurons are zero already: nothing to delete, nothing changed or kept" { - var t = trainer(); - var h: Device = .{}; - var p: P = .{ .gpa = std.testing.allocator, .mode = .auto }; - defer p.deinit(); - try three(&h, &p, &t); - // a newer fact replaced A: its neurons zeroed where they sit, their places taken - try p.retire(&t, &h, &.{ .{ 0, 0 }, .{ 1, 0 } }); - const gpa = std.testing.allocator; - const up = try gpa.dupe(f32, p.up.items); - defer gpa.free(up); - const down = try gpa.dupe(f32, p.down.items); - defer gpa.free(down); - const sent = h.uploads; - try std.testing.expectEqual(@as(usize, 0), try forgetting.forget(&p, &t, &h, &.{ .{ 0, 0 }, .{ 1, 0 } })); - try std.testing.expect(!forgetting.pending(&p)); - try std.testing.expectEqual(sent, h.uploads); - try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(up), std.mem.sliceAsBytes(p.up.items)); - try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(down), std.mem.sliceAsBytes(p.down.items)); - try std.testing.expectEqual(@as(usize, 6), p.learned.items.len); -} - -test "deleting every fact empties the pocket, and the delete still waits for a save to write it" { - var t = trainer(); - var h: Device = .{}; - var p: P = .{ .gpa = std.testing.allocator, .mode = .auto }; - defer p.deinit(); - try three(&h, &p, &t); - try std.testing.expectEqual(@as(usize, 6), try forgetting.forget(&p, &t, &h, &.{ .{ 0, 0 }, .{ 1, 0 }, .{ 0, 1 }, .{ 2, 0 }, .{ 0, 2 }, .{ 1, 1 } })); - try std.testing.expect(p.empty()); - try std.testing.expect(forgetting.pending(&p)); - for (0..layers - 1) |l| try std.testing.expect(std.mem.allEqual(f32, &h.up[l], 0)); - try std.testing.expectEqualSlices(u32, &.{ 0, 1, 2 }, p.retired_lessons.items); - try std.testing.expectEqual(@as(usize, 0), p.learned_before); -} - -test "a save after the last fact is deleted writes the emptied pocket; an untaught one stays unwritten" { - var t = trainer(); - var h: Device = .{}; - // a model never taught: nothing in the pocket, nothing written - var untaught: Learner = .{ .trainer = &t, .b = &h }; - defer untaught.pockets.deinit(); - try untaught.pockets.load(&t, &h); - try std.testing.expect(try whole.save(&untaught)); - try std.testing.expectEqual(@as(usize, 0), h.saves); - var l: Learner = .{ .trainer = &t, .b = &h }; - defer l.pockets.deinit(); - try three(&h, &l.pockets, &t); - _ = try forgetting.forget(&l.pockets, &t, &h, &.{ .{ 0, 0 }, .{ 1, 0 }, .{ 0, 1 }, .{ 2, 0 }, .{ 0, 2 }, .{ 1, 1 } }); - try std.testing.expect(try whole.save(&l)); - try std.testing.expectEqual(@as(usize, 1), h.saves); - try std.testing.expect(!forgetting.pending(&l.pockets)); -} - -/// The pocket's state a delete may change, copied: its weights, counts, records and retired lessons. -const Copy = struct { - up: []f32, - down: []f32, - used: []usize, - learned: []pocket.Learned, - learned_before: usize, - retired: []u32, - - fn of(p: *const P) !Copy { - const a = std.testing.allocator; - return .{ .up = try a.dupe(f32, p.up.items), .down = try a.dupe(f32, p.down.items), .used = try a.dupe(usize, p.used.items), .learned = try a.dupe(pocket.Learned, p.learned.items), .learned_before = p.learned_before, .retired = try a.dupe(u32, p.retired_lessons.items) }; - } - - fn expectSame(c: Copy, p: *const P) !void { - try c.expectFields(p); - try std.testing.expect(!forgetting.pending(p)); - } - - /// The pocket in memory as copied, its snapshot kept or not. - fn expectFields(c: Copy, p: *const P) !void { - try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(c.up), std.mem.sliceAsBytes(p.up.items)); - try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(c.down), std.mem.sliceAsBytes(p.down.items)); - try std.testing.expectEqualSlices(usize, c.used, p.used.items); - try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(c.learned), std.mem.sliceAsBytes(p.learned.items)); - try std.testing.expectEqual(c.learned_before, p.learned_before); - try std.testing.expectEqualSlices(u32, c.retired, p.retired_lessons.items); - } - - fn free(c: Copy) void { - const a = std.testing.allocator; - a.free(c.up); - a.free(c.down); - a.free(c.used); - a.free(c.learned); - a.free(c.retired); - } -}; - -/// The forward's layers as the device holds them, for the pocket's slots. -fn expectLive(before: *const Device, now: *const Device) !void { - for (0..layers - 1) |l| { - try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(&before.up[l]), std.mem.sliceAsBytes(&now.up[l])); - try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(&before.down[l]), std.mem.sliceAsBytes(&now.down[l])); - try std.testing.expectEqual(before.used[l], now.used[l]); - } -} - -test "an allocation or an upload that fails anywhere in a delete leaves the pocket and the forward as they were" { - var t = trainer(); - // each allocation of the delete in turn fails (the pocket's and the rounding's), until it goes through - var failures: usize = 0; - while (true) : (failures += 1) { - var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{}); - const h = try std.testing.allocator.create(Device); - defer std.testing.allocator.destroy(h); - h.* = .{ .gpa = failing.allocator() }; - var p: P = .{ .gpa = failing.allocator(), .mode = .auto }; - defer p.deinit(); - try three(h, &p, &t); - const before = try Copy.of(&p); - defer before.free(); - const live = try std.testing.allocator.create(Device); - defer std.testing.allocator.destroy(live); - live.* = h.*; - failing.fail_index = failing.alloc_index + failures; - if (forgetting.forget(&p, &t, h, &b_neurons)) |n| { - try std.testing.expectEqual(@as(usize, 2), n); - break; - } else |e| try std.testing.expectEqual(error.OutOfMemory, e); - try before.expectSame(&p); - try expectLive(live, h); - } - try std.testing.expect(failures >= 5); - // an upload that fails once, at either changed layer: the pocket and the forward put back - for ([_]usize{ 1, 2 }) |at| { - const h = try std.testing.allocator.create(Device); - defer std.testing.allocator.destroy(h); - h.* = .{}; - var p: P = .{ .gpa = std.testing.allocator, .mode = .auto }; - defer p.deinit(); - try three(h, &p, &t); - const before = try Copy.of(&p); - defer before.free(); - const live = try std.testing.allocator.create(Device); - defer std.testing.allocator.destroy(live); - live.* = h.*; - h.fail_at = h.uploads + at; - try std.testing.expectError(error.UploadFailed, forgetting.forget(&p, &t, h, &b_neurons)); - try before.expectSame(&p); - try expectLive(live, h); - // and a retry goes through - try std.testing.expectEqual(@as(usize, 2), try forgetting.forget(&p, &t, h, &b_neurons)); - } - // a device that takes no upload: put back in memory, the snapshot kept and the pocket stale until one lands - const h = try std.testing.allocator.create(Device); - defer std.testing.allocator.destroy(h); - h.* = .{}; - var p: P = .{ .gpa = std.testing.allocator, .mode = .auto }; - defer p.deinit(); - try three(h, &p, &t); - const before = try Copy.of(&p); - defer before.free(); - const live = try std.testing.allocator.create(Device); - defer std.testing.allocator.destroy(live); - live.* = h.*; - h.failing = true; - try std.testing.expectError(error.PutBackNotOnDevice, forgetting.forget(&p, &t, h, &b_neurons)); - try before.expectFields(&p); - try std.testing.expect(forgetting.stale(&p) and forgetting.pending(&p)); - h.failing = false; - try std.testing.expectEqual(@as(usize, 2), try forgetting.unforget(&p, &t, h)); - try before.expectSame(&p); - try expectLive(live, h); -} - -test "a put-back the device stops taking after one layer is cut keeps its snapshot, refuses, and lands once it can" { - var t = trainer(); - const h = try std.testing.allocator.create(Device); - defer std.testing.allocator.destroy(h); - h.* = .{}; - var l: Learner = .{ .trainer = &t, .b = h }; - defer l.pockets.deinit(); - try three(h, &l.pockets, &t); - const before = try Copy.of(&l.pockets); - defer before.free(); - const live = try std.testing.allocator.create(Device); - defer std.testing.allocator.destroy(live); - live.* = h.*; - // the first changed layer (0) takes its cut; from the second upload on, the device takes nothing, put-back too - h.fail_from = h.uploads + 2; - try std.testing.expectError(error.PutBackNotOnDevice, forgetting.forget(&l.pockets, &t, h, &b_neurons)); - // memory is as it was and the snapshot is kept, while the device still holds layer 0 cut and layer 2 as it was - try before.expectFields(&l.pockets); - try std.testing.expect(whole.stale(&l) and forgetting.pending(&l.pockets)); - try std.testing.expect(std.mem.allEqual(f32, h.up[0][1 * d ..][0..d], 0)); - try std.testing.expect(!std.mem.allEqual(f32, live.up[0][1 * d ..][0..d], 0)); - try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(&live.up[2]), std.mem.sliceAsBytes(&h.up[2])); - // until it lands, another delete is refused and a retry fails the same way, the snapshot kept - try std.testing.expectError(error.PutBackNotOnDevice, forgetting.forget(&l.pockets, &t, h, &b_neurons)); - try std.testing.expectError(error.PutBackNotOnDevice, whole.heal(&l)); - try std.testing.expect(whole.stale(&l)); - try before.expectFields(&l.pockets); - // the device takes uploads again: the retry lands every layer, and nothing is left to put back - h.fail_from = 0; - try whole.heal(&l); - try std.testing.expect(!whole.stale(&l)); - try before.expectSame(&l.pockets); - try expectLive(live, h); -} - -test "a delete whose cut layer would round to other values when saved is put back whole, nothing changed" { - var t = trainer(); - var h: Device = .{}; - var p: P = .{ .gpa = std.testing.allocator, .mode = .auto }; - defer p.deinit(); - try three(&h, &p, &t); - var prng = std.Random.DefaultPrng.init(3); - const r = prng.random(); - // slot 0's neurons far from zero next to their spread, until its cut layer would move when a save rounds it again - var cut_up: [width]f32 = undefined; - var cut_down: [width]f32 = undefined; - var moves = false; - for (0..20) |_| { - const spread = std.math.pow(f32, 10, -4 + 6 * r.float(f32)); - const offset = spread * 256 * r.float(f32) * @as(f32, if (r.boolean()) 1 else -1); - for (p.up.items[0..width], p.down.items[0..width]) |*u, *v| { - u.* = offset + spread * r.floatNorm(f32); - v.* = -offset + spread * r.floatNorm(f32); - } - @memcpy(&cut_up, p.up.items[0..width]); - @memcpy(&cut_down, p.down.items[0..width]); - @memset(cut_up[1 * d ..][0..d], 0); // B's neuron at slot 0 - try Shards.round(std.testing.allocator, d, &cut_up, &cut_down); - const once_up = cut_up; - const once_down = cut_down; - try Shards.round(std.testing.allocator, d, &cut_up, &cut_down); - moves = !std.mem.eql(u8, std.mem.sliceAsBytes(&once_up), std.mem.sliceAsBytes(&cut_up)) or !std.mem.eql(u8, std.mem.sliceAsBytes(&once_down), std.mem.sliceAsBytes(&cut_down)); - if (moves) break; - } - try std.testing.expect(moves); - try p.upload(&t, &h, 0); - const gpa = std.testing.allocator; - const up = try gpa.dupe(f32, p.up.items); - defer gpa.free(up); - const down = try gpa.dupe(f32, p.down.items); - defer gpa.free(down); - const live = h; - try std.testing.expectError(error.LayerRoundsAgain, forgetting.forget(&p, &t, &h, &b_neurons)); - try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(up), std.mem.sliceAsBytes(p.up.items)); - try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(down), std.mem.sliceAsBytes(p.down.items)); - for (0..layers - 1) |l| try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(&live.up[l]), std.mem.sliceAsBytes(&h.up[l])); - try std.testing.expect(!forgetting.pending(&p)); - try std.testing.expectEqual(@as(usize, 6), p.learned.items.len); -} diff --git a/zig/src/families/nemotron/pocket_joint.zig b/zig/src/families/nemotron/pocket_joint.zig deleted file mode 100644 index 6bbe409f9c2..00000000000 --- a/zig/src/families/nemotron/pocket_joint.zig +++ /dev/null @@ -1,46 +0,0 @@ -//! Earlier facts on the open fact's subject fitted with it: MEMIT-Merge's one value a subject, a fact at a time. -const std = @import("std"); - -/// The earlier subject neurons the open fact shares its subject with, their replayed answers, their outputs as now. -pub fn find(p: anytype, d: usize) !void { - p.joint.clearRetainingCapacity(); - p.joint_down.clearRetainingCapacity(); - p.joint_answers.clearRetainingCapacity(); - if (!p.joining or p.split[1] == 0 or p.subjects.items.len == 0) return; - var group: std.ArrayList(u32) = .empty; - defer group.deinit(p.gpa); - for (p.learned.items[0..p.learned_before]) |e| { - if (e.key != .subject or std.mem.indexOfScalar(u32, p.subjects.items, e.subject) == null) continue; - if (std.mem.indexOfScalar(u32, p.retired_lessons.items, e.lesson) != null) continue; - if (std.mem.indexOfScalar(u32, group.items, e.lesson) == null) try group.append(p.gpa, e.lesson); - } - const replay: []const @TypeOf(p.answered[0]) = if (p.steady.len > 2) p.steady[2] else &.{}; - for (replay, 0..) |ex, i| { - if (i >= p.replay_lessons.len or std.mem.indexOfScalar(u32, group.items, p.replay_lessons[i]) == null) continue; - if (p.keyRow(ex, .subject) != null) try p.joint_answers.append(p.gpa, ex); - } - // without their answers to hold them, earlier outputs would only bend to the new fact - if (p.joint_answers.items.len == 0) return; - for (p.learned.items[0..p.learned_before]) |e| if (e.key == .subject and std.mem.indexOfScalar(u32, group.items, e.lesson) != null) { - try p.joint.append(p.gpa, .{ .slot = e.slot, .neuron = e.neuron, .key = .subject }); - try p.joint_down.appendSlice(p.gpa, p.neuron(p.down.items, e.slot, e.neuron, d)); - }; - std.log.info("slide pocket: {d} neurons of {d} earlier facts on its subject fitted with it, on {d} of their answers", .{ p.joint.items.len, group.items.len, p.joint_answers.items.len }); -} - -/// Their outputs as the fit starts, after the open fact's (which start at zero). -pub fn seed(p: anytype, d: usize) void { - const k = p.taken.items.len; - @memcpy(p.v.adam.items[k * d ..][0 .. p.joint.items.len * d], p.joint_down.items); -} - -/// The earlier neurons as they were before the open fact fitted them (its lesson undone). -pub fn putBack(p: anytype, t: anytype, host: anytype, d: usize) !void { - for (p.joint.items, 0..) |x, j| { - @memcpy(p.neuron(p.down.items, x.slot, x.neuron, d), p.joint_down.items[j * d ..][0..d]); - try p.upload(t, host, x.slot); - } - p.joint.clearRetainingCapacity(); - p.joint_down.clearRetainingCapacity(); - p.joint_answers.clearRetainingCapacity(); -} diff --git a/zig/src/families/nemotron/pocket_pack.zig b/zig/src/families/nemotron/pocket_pack.zig deleted file mode 100644 index ebed647bb02..00000000000 --- a/zig/src/families/nemotron/pocket_pack.zig +++ /dev/null @@ -1,42 +0,0 @@ -//! The pocket's passes with their sequences side by side: as many as one pass of the trainer holds, run together. -const std = @import("std"); -const train_mode = @import("train_mode.zig"); -const lesson_route = @import("lesson_route.zig"); -const Example = @import("lesson_examples.zig").Example; - -pub const Seq = train_mode.Seq; -pub const Result = train_mode.Result; -const Mode = train_mode.Mode; - -/// How many of `seqs`, from the first, one pass of trainer t holds: as many as fit, at least one. -pub fn fits(t: anytype, seqs: []const Seq) usize { - if (!t.packs()) return @min(seqs.len, 1); - var rows: usize = 0; - var n: usize = 0; - while (n < seqs.len and n < t.spans.len) : (n += 1) { - rows += seqs[n].ids.len - 1 - seqs[n].skip; - if (rows > t.pack and n > 0) break; - } - return n; -} - -/// The sequence an example makes, its pocket unscaled and nothing nudged. -pub fn seq(ex: Example) Seq { - return .{ .ids = ex.ids, .start = ex.start, .decide = ex.decide }; -} - -/// The turn every pocket pass takes: lessons of the model itself, no router deciding. -pub const turn: lesson_route.Turn = .{ .decide = 0, .bits = lesson_route.Acting.empty, .whole = true }; - -/// Each of `xs` read in `mode` in as few passes as hold them, each one's result into `out`. -pub fn read(gpa: std.mem.Allocator, t: anytype, xs: []const Example, mode: Mode, out: []Result) !void { - const seqs = try gpa.alloc(Seq, xs.len); - defer gpa.free(seqs); - for (seqs, xs) |*s, ex| s.* = seq(ex); - var at: usize = 0; - while (at < seqs.len) { - const n = fits(t, seqs[at..]); - try t.pass(seqs[at..][0..n], mode, turn, out[at..][0..n]); - at += n; - } -} diff --git a/zig/src/families/nemotron/pocket_prefix.zig b/zig/src/families/nemotron/pocket_prefix.zig deleted file mode 100644 index ca854f38eee..00000000000 --- a/zig/src/families/nemotron/pocket_prefix.zig +++ /dev/null @@ -1,100 +0,0 @@ -//! A pocket fact's answers' prompts run once: their rows before any of its neurons fires never change while it learns. -const std = @import("std"); -const pack = @import("pocket_pack.zig"); -const train_mode = @import("train_mode.zig"); -const dotBf16 = @import("pocket_fit.zig").dotBf16; - -const Seq = train_mode.Seq; -const Span = train_mode.Span; - -const least = 16; // rows a prefix must hold to be worth a slot - -/// An answer's prefix: its rows before any open neuron fires (once a whole pass shows them), and its slot once drawn. -const Kept = struct { seen: bool = false, skip: usize = 0, slot: ?u32 = null }; - -/// The open fact's answers' prefixes (its own answers first, then those that are to stay). -pub const Prefixes = struct { - list: std.ArrayList(Kept) = .empty, - slots: u32 = 0, - skipped: usize = 0, // rows its steps did not run again - inputs: u64 = 0, // the pocket's input weights the prefixes were found under - - pub fn deinit(s: *Prefixes, gpa: std.mem.Allocator) void { - s.list.deinit(gpa); - } - - /// A fact's `n` answers begun, no prefix known. - pub fn begin(s: *Prefixes, gpa: std.mem.Allocator, n: usize) !void { - s.list.clearRetainingCapacity(); - try s.list.appendNTimes(gpa, .{}, n); - s.slots = 0; - s.skipped = 0; - s.inputs = 0; - } -}; - -/// A round of outputs begun: the prefixes found kept while the pocket's input weights are as they were found under. -pub fn round(p: anytype, s: *Prefixes) void { - var h = std.hash.Wyhash.init(0); - h.update(std.mem.sliceAsBytes(p.up.items)); - h.update(std.mem.sliceAsBytes(p.used.items)); - const now = h.final(); - if (now == s.inputs) return; - for (s.list.items) |*k| k.* = .{}; - s.slots = 0; - s.inputs = now; -} - -/// The slots freed with their states (a further round runs its answers' prefixes again from their next draw). -pub fn release(t: anytype, s: *Prefixes) !void { - try t.prefixSlots(0); - for (s.list.items) |*k| k.slot = null; - s.slots = 0; -} - -/// The drawn answers (`which`: their indexes) set to skip prefixes in slots; those shown but not yet kept primed first. -pub fn use(t: anytype, s: *Prefixes, seqs: []Seq, which: []const usize) !void { - if (!t.packs()) return; - var fresh: [32]Seq = undefined; - if (seqs.len > fresh.len) return error.BadPass; - var n: usize = 0; - for (seqs, which) |*q, w| { - const k = &s.list.items[w]; - if (k.slot == null and k.seen and k.skip >= least and s.slots < @TypeOf(t.prefixes).most) { - k.slot = s.slots; - s.slots += 1; - fresh[n] = .{ .ids = q.ids[0 .. k.skip + 1], .start = k.skip, .decide = k.skip - 1, .slot = k.slot.? }; - n += 1; - } - if (k.slot) |slot| { - q.skip = k.skip; - q.slot = slot; - s.skipped += k.skip; - } - } - if (n == 0) return; - try t.prefixSlots(s.slots); - var got: [32]train_mode.Result = undefined; - var at: usize = 0; - while (at < n) { - const m = pack.fits(t, fresh[at..n]); - try t.pass(fresh[at..][0..m], .prime, pack.turn, got[0..m]); - at += m; - } -} - -/// Answer `which` (`sq` at `sp`, run whole): its rows before an open neuron fires, its decision, answer and nudges. -pub fn learn(p: anytype, t: anytype, s: *Prefixes, sq: Seq, sp: Span, which: usize) void { - const k = &s.list.items[which]; - if (k.seen or sq.skip > 0) return; - k.seen = true; - const d = t.config().hidden; - var limit = @min(sq.decide, sq.start - 1); - for (sq.nudge.layers, sq.nudge.rows) |mask, row| if (mask != 0) { - limit = @min(limit, row); - }; - k.skip = rows: for (0..limit) |r| { - for (p.taken.items) |x| if (dotBf16(p.neuron(p.up.items, x.slot, x.neuron, d), t.normed(p.moe.items[x.slot], sp.row(r))) > 0) break :rows r; - for (p.joint.items) |x| if (dotBf16(p.neuron(p.up.items, x.slot, x.neuron, d), t.normed(p.moe.items[x.slot], sp.row(r))) > 0) break :rows r; - } else limit; -} diff --git a/zig/src/families/nemotron/probe.zig b/zig/src/families/nemotron/probe.zig deleted file mode 100644 index 1175275c7a6..00000000000 --- a/zig/src/families/nemotron/probe.zig +++ /dev/null @@ -1,186 +0,0 @@ -//! A measure, not a lesson: how far vectors fitted at one row of a few layers bring a fact's held-out answers back. -const std = @import("std"); -const examples = @import("lesson_examples.zig"); -const lesson_route = @import("lesson_route.zig"); -const subspace = @import("subspace.zig"); - -const Example = examples.Example; -const Acting = lesson_route.Acting; - -/// The row a setup's vectors go on: the reply's first (the assistant header) or the question's subject. -pub const Row = enum { decide, subject }; - -const steps = 30; // Adam steps a setup is fitted for -const reach: f32 = 0.05; // each step's size against the residual's -const decay: f32 = 0.05; // the vectors' squared size against the residual's, added to the loss -const furthest: f32 = 3; // a vector's size at most, against the residual's - -/// A probe over trainer T (Metal's: its residual and nudges). -pub fn Probe(comptime T: type) type { - return struct { - const Self = @This(); - const Setup = struct { row: Row, layers: u64 }; - - gpa: std.mem.Allocator, - answered: []const Example = &.{}, - held: []const Example = &.{}, - setups: std.ArrayList(Setup) = .empty, - setup: usize = 0, - round: usize = 0, - at: usize = 0, - judging: bool = false, - loss: f32 = 0, - first: f32 = 0, - final: f32 = 0, // the answers' loss at the last fitting round - back: usize = 0, // held-out answers that came back token for token - size: std.ArrayList(f32) = .empty, // [layers]: the row's mean residual length after each layer - state: std.ArrayList(f32) = .empty, // [4, layers, D]: the vectors, their Adam moments, a round's gradient - - pub fn init(gpa: std.mem.Allocator) Self { - return .{ .gpa = gpa }; - } - - pub fn deinit(p: *Self) void { - p.setups.deinit(p.gpa); - p.size.deinit(p.gpa); - p.state.deinit(p.gpa); - } - - /// A lesson's setups: the subject's row at MoE layers 13 to 25, then in windows of three MoE layers, two apart. - pub fn begin(p: *Self, t: *T, answered: []const Example, held: []const Example) !void { - const c = t.config(); - p.answered = answered; - p.held = held; - p.setups.clearRetainingCapacity(); - var moe: [64]usize = undefined; - var count_moe: usize = 0; - var mid: u64 = 0; - for (0..c.layers - 1) |l| if (c.kinds[l] == .moe) { - moe[count_moe] = l; - count_moe += 1; - if (l >= 13 and l <= 25) mid |= @as(u64, 1) << @intCast(l); - }; - try p.setups.append(p.gpa, .{ .row = .subject, .layers = mid }); - var w: usize = 0; - while (w + 3 <= count_moe) : (w += 2) { - var mask: u64 = 0; - for (moe[w..][0..3]) |l| mask |= @as(u64, 1) << @intCast(l); - try p.setups.append(p.gpa, .{ .row = .subject, .layers = mask }); - } - p.setup = 0; - try p.start(t); - } - - fn start(p: *Self, t: *T) !void { - const c = t.config(); - p.round = 0; - p.at = 0; - p.loss = 0; - p.judging = false; - p.back = 0; - p.size.clearRetainingCapacity(); - try p.size.appendNTimes(p.gpa, 0, c.layers); - p.state.clearRetainingCapacity(); - try p.state.appendNTimes(p.gpa, 0, 4 * c.layers * c.hidden); - } - - fn row(s: Setup, ex: Example) ?usize { - return switch (s.row) { - .decide => ex.decide, - .subject => if (ex.subject > 0 and ex.subject < ex.start) ex.subject else null, - }; - } - - /// One pass; true once every setup has been fitted and judged. - pub fn step(p: *Self, t: *T, acting: Acting) !bool { - if (p.setup == p.setups.items.len) return true; - const c = t.config(); - const d = c.hidden; - const n = c.layers * d; - const s = p.setups.items[p.setup]; - const vecs = p.state.items[0..n]; - const grad = p.state.items[3 * n ..][0..n]; - const list = if (p.judging) p.held else p.answered; - while (p.at < list.len) { - const ex = list[p.at]; - p.at += 1; - const r = row(s, ex) orelse continue; - t.nudge = .{ .layers = .{ s.layers, 0, 0 }, .rows = .{ r, 0, 0 } }; - @memcpy(t.delta.slice(f32, n), vecs); - const got = try t.step(ex.ids, ex.start, .target, .{ .decide = ex.decide, .bits = acting, .whole = true }); - p.loss += got.loss; - if (p.judging) { - p.back += @intFromBool(got.recalled); - return false; - } - for (0..c.layers) |l| if (s.layers >> @intCast(l) & 1 != 0) { - for (grad[l * d ..][0..d], t.push.slice(f32, n)[l * d ..][0..d]) |*g, x| g.* += x; - if (p.round == 0) p.size.items[l] += norm(t.residual(l + 1, r)); - }; - return false; - } - const used = count(s, list); - const mean = p.loss / @as(f32, @floatFromInt(@max(used, 1))); - p.loss = 0; - p.at = 0; - if (p.judging) { - var len: f32 = 0; - var layers: usize = 0; - for (0..c.layers) |l| if (s.layers >> @intCast(l) & 1 != 0) { - len += @sqrt(subspace.dot(vecs[l * d ..][0..d], vecs[l * d ..][0..d])) / p.size.items[l]; - layers += 1; - }; - const last = 63 - @clz(s.layers); - std.log.info("slide probe: the {t}'s row, {d} MoE layers from {d} to {d}: the answers' loss {d:.3} to {d:.3} in {d} steps, vectors {d:.2} of the residual each; held-out {d} of {d} come back, their loss {d:.3}", .{ s.row, layers, @ctz(s.layers), last, p.first, p.final, steps, len / @as(f32, @floatFromInt(@max(layers, 1))), p.back, used, mean }); - p.setup += 1; - if (p.setup < p.setups.items.len) try p.start(t); - return false; - } - if (p.round == 0) { - p.first = mean; - for (p.size.items) |*x| x.* /= @floatFromInt(@max(used, 1)); - } - p.round += 1; - p.final = mean; - if (p.round > steps) { - p.judging = true; - return false; - } - const m = p.state.items[n..][0..n]; - const v = p.state.items[2 * n ..][0..n]; - const tt: f32 = @floatFromInt(p.round); - for (0..c.layers) |l| if (s.layers >> @intCast(l) & 1 != 0) { - const size = p.size.items[l]; - const lr = reach * size / @sqrt(@as(f32, @floatFromInt(d))); - const x = vecs[l * d ..][0..d]; - for (x, m[l * d ..][0..d], v[l * d ..][0..d], grad[l * d ..][0..d]) |*xi, *mi, *vi, gi| { - const g = gi / @as(f32, @floatFromInt(@max(used, 1))) + 2 * decay * xi.* / (size * size); - mi.* = 0.9 * mi.* + 0.1 * g; - vi.* = 0.999 * vi.* + 0.001 * g * g; - xi.* -= lr * (mi.* / (1 - std.math.pow(f32, 0.9, tt))) / (@sqrt(vi.* / (1 - std.math.pow(f32, 0.999, tt))) + 1e-8); - } - const len = @sqrt(subspace.dot(x, x)); - if (len > furthest * size) for (x) |*xi| { - xi.* *= furthest * size / len; - }; - }; - @memset(grad, 0); - return false; - } - - fn count(s: Setup, list: []const Example) usize { - var k: usize = 0; - for (list) |ex| k += @intFromBool(row(s, ex) != null); - return k; - } - }; -} - -fn norm(b: []const u16) f32 { - var s: f32 = 0; - for (b) |x| { - const f: f32 = @bitCast(@as(u32, x) << 16); - s += f * f; - } - return @sqrt(s); -} diff --git a/zig/src/families/nemotron/router.zig b/zig/src/families/nemotron/router.zig deleted file mode 100644 index e221c50c6c1..00000000000 --- a/zig/src/families/nemotron/router.zig +++ /dev/null @@ -1,260 +0,0 @@ -//! A lesson's router: Fisher scores per layer, the best averaged; it acts past a bar read off left-out questions. -const std = @import("std"); -const shape = @import("learn_shape.zig"); -const subspace = @import("subspace.zig"); - -const n = shape.candidates; - -const ridge = 0.1; // of the scatter's mean diagonal: questions are few against 64 directions -const most_reads = 12; // layers a router averages: past the best dozen, weaker layers blur the fact's questions back in -const odd_share = 4; // one fact question in this many may word itself apart from the rest and go untaken - -pub const Fit = struct { - dir: []f32, // [layers, n]: each layer's direction, unit, in its candidates' terms - weight: []f32, // [layers]: each layer's share of the average over the other prompts' spread there (0: unread) - mean: []f32, // [layers]: the other prompts' mean score there - need: f32, // the average a reply's decision row must reach for the lesson to act on it - reads: u32, // layers with a share - fact_low: f32, // the average most fact questions left out of the fit reached (all but the oddest quarter) - fact_least: f32, // the lowest any of them reached - steady_high: f32, // the highest a steady prompt left out of the fit reached - - pub fn deinit(f: *Fit, gpa: std.mem.Allocator) void { - gpa.free(f.dir); - gpa.free(f.weight); - gpa.free(f.mean); - } - - /// Whether a fact question the fit never saw still scores above every steady prompt it never saw. - pub fn apart(f: *const Fit) bool { - return f.fact_low > f.steady_high; - } - - /// Router row `i` of `rows` (rows[l]: layer l's decision rows along its candidates) as the lesson scores it. - pub fn score(f: *const Fit, rows: []const []const f32, i: usize) f32 { - var s: f32 = 0; - for (rows, 0..) |r, l| { - if (f.weight[l] == 0) continue; - s += f.weight[l] * (subspace.dot(f.dir[l * n ..][0..n], r[i * n ..][0..n]) - f.mean[l]); - } - return s; - } -}; - -/// Sums over a set of rows, from which a mean and scatter come with any one row left out. -const Stats = struct { - count: f64 = 0, - sum: [n]f64 = @splat(0), - sq: [n * n]f64 = @splat(0), - - fn of(rows: []const f32) Stats { - var s: Stats = .{}; - for (0..rows.len / n) |r| s.add(rows[r * n ..][0..n], 1); - return s; - } - - fn add(s: *Stats, p: []const f32, w: f64) void { - s.count += w; - for (0..n) |i| { - s.sum[i] += w * p[i]; - for (0..n) |j| s.sq[i * n + j] += w * p[i] * p[j]; - } - } -}; - -/// Fisher's direction (unit) between two sets: (scatter + ridge)^-1 (mean difference). -fn fisher(pos: *const Stats, neg: *const Stats, out: []f32) !void { - var mean: [2][n]f64 = undefined; - const sets = [2]*const Stats{ pos, neg }; - var a: [n * n]f64 = @splat(0); - for (sets, 0..) |s, k| { - for (0..n) |i| mean[k][i] = s.sum[i] / s.count; - for (0..n) |i| for (0..n) |j| { - a[i * n + j] += s.sq[i * n + j] / s.count - mean[k][i] * mean[k][j]; - }; - } - var trace: f64 = 0; - for (0..n) |i| trace += a[i * n + i]; - for (0..n) |i| a[i * n + i] += ridge * trace / n + 1e-12; - var d: [n]f64 = undefined; - for (&d, mean[0], mean[1]) |*x, p, q| x.* = p - q; - try subspace.solve(&a, n, &d); - var size: f64 = 0; - for (d) |x| size += x * x; - for (out, d) |*o, x| o.* = @floatCast(x / @sqrt(@max(size, 1e-30))); -} - -/// One layer's direction from every row, and each row's score along the direction fitted without it. -fn layer(facts: []const f32, steady: []const f32, dir: []f32, fact_s: []f32, steady_s: []f32) !void { - const pos = Stats.of(facts); - const neg = Stats.of(steady); - try fisher(&pos, &neg, dir); - var d: [n]f32 = undefined; - for (fact_s, 0..) |*s, i| { - const p = facts[i * n ..][0..n]; - var less = pos; - less.add(p, -1); - try fisher(&less, &neg, &d); - s.* = subspace.dot(&d, p); - } - for (steady_s, 0..) |*s, j| { - const p = steady[j * n ..][0..n]; - var less = neg; - less.add(p, -1); - try fisher(&pos, &less, &d); - s.* = subspace.dot(&d, p); - } -} - -/// The steady rows' mean and spread of `s`, with row `skip` left out. -fn spread(s: []const f32, skip: ?usize) [2]f32 { - var sum: f64 = 0; - var sq: f64 = 0; - var count: f64 = 0; - for (s, 0..) |x, j| if (j != skip) { - sum += x; - sq += x * x; - count += 1; - }; - const m = sum / count; - return .{ @floatCast(m), @floatCast(@sqrt(@max(sq / count - m * m, 0)) + 1e-9) }; -} - -/// Each layer's share from fact scores `z` [layers, facts] less `skip`: top layers by median, above the steady mean. -fn shares(gpa: std.mem.Allocator, z: []const f32, layers: usize, nf: usize, skip: ?usize, out: []f32) !void { - const col = try gpa.alloc(f32, nf); - defer gpa.free(col); - const sep = try gpa.alloc(f32, layers); - defer gpa.free(sep); - for (0..layers) |l| { - var m: usize = 0; - for (0..nf) |i| if (i != skip) { - col[m] = z[l * nf + i]; - m += 1; - }; - std.mem.sort(f32, col[0..m], {}, std.sort.asc(f32)); - sep[l] = col[m / 2]; - } - const sorted = try gpa.dupe(f32, sep); - defer gpa.free(sorted); - std.mem.sort(f32, sorted, {}, std.sort.desc(f32)); - const bar = sorted[@min(most_reads, layers) - 1]; - var total: f32 = 0; - for (out, sep) |*w, x| { - w.* = if (x >= bar and x > 0) x else 0; - total += w.*; - } - for (out) |*w| w.* = if (total > 0) w.* / total else 0; -} - -/// The router from each layer's decision rows: facts[l] and steady[l] the same questions at every layer, [count, n]. -pub fn fit(gpa: std.mem.Allocator, facts: []const []const f32, steady: []const []const f32) !Fit { - const layers = facts.len; - const nf = facts[0].len / n; - const ns = steady[0].len / n; - if (nf < 2 or ns < 3) return error.TooFewQuestions; - const dir = try gpa.alloc(f32, layers * n); - errdefer gpa.free(dir); - const weight = try gpa.alloc(f32, layers); - errdefer gpa.free(weight); - const mean = try gpa.alloc(f32, layers); - errdefer gpa.free(mean); - const fact_s = try gpa.alloc(f32, layers * nf); - defer gpa.free(fact_s); - const steady_s = try gpa.alloc(f32, layers * ns); - defer gpa.free(steady_s); - const Share = struct { - fn run(from: usize, step: usize, ctx: anytype, out: *?anyerror) void { - var l = from; - while (l < ctx.layers) : (l += step) layer(ctx.facts[l], ctx.steady[l], ctx.dir[l * n ..][0..n], ctx.fact_s[l * ctx.nf ..][0..ctx.nf], ctx.steady_s[l * ctx.ns ..][0..ctx.ns]) catch |e| { - out.* = e; - }; - } - }; - const ctx = .{ .layers = layers, .facts = facts, .steady = steady, .dir = dir, .fact_s = fact_s, .steady_s = steady_s, .nf = nf, .ns = ns }; - var threads: [16]?std.Thread = @splat(null); - var errs: [16]?anyerror = @splat(null); - const k = @min(threads.len, layers); - for (threads[0..k], 0..) |*t, i| t.* = std.Thread.spawn(.{}, Share.run, .{ i, k, ctx, &errs[i] }) catch null; - for (threads[0..k], 0..) |t, i| if (t) |th| th.join() else Share.run(i, k, ctx, &errs[i]); - for (errs[0..k]) |e| if (e) |x| return x; - // every score standardised by the steady prompts' at its layer: a steady prompt's without its own - const z_fact = try gpa.alloc(f32, layers * nf); - defer gpa.free(z_fact); - const z_steady = try gpa.alloc(f32, layers * ns); - defer gpa.free(z_steady); - const spread_all = try gpa.alloc([2]f32, layers); - defer gpa.free(spread_all); - for (0..layers) |l| { - const s = steady_s[l * ns ..][0..ns]; - spread_all[l] = spread(s, null); - for (0..nf) |i| z_fact[l * nf + i] = (fact_s[l * nf + i] - spread_all[l][0]) / spread_all[l][1]; - for (0..ns) |j| { - const own = spread(s, j); - z_steady[l * ns + j] = (s[j] - own[0]) / own[1]; - } - } - // each left-out question's average over the layers chosen without it - const w = try gpa.alloc(f32, layers); - defer gpa.free(w); - const fact_avg = try gpa.alloc(f32, nf); - defer gpa.free(fact_avg); - for (fact_avg, 0..) |*avg, i| { - try shares(gpa, z_fact, layers, nf, i, w); - avg.* = 0; - for (0..layers) |l| avg.* += w[l] * z_fact[l * nf + i]; - } - try shares(gpa, z_fact, layers, nf, null, w); - var high: f32 = -std.math.inf(f32); - for (0..ns) |j| { - var avg: f32 = 0; - for (0..layers) |l| avg += w[l] * z_steady[l * ns + j]; - high = @max(high, avg); - } - std.mem.sort(f32, fact_avg, {}, std.sort.asc(f32)); - const low = fact_avg[nf / odd_share]; - var reads: u32 = 0; - for (0..layers) |l| { - weight[l] = w[l] / spread_all[l][1]; - mean[l] = spread_all[l][0]; - reads += @intFromBool(w[l] > 0); - } - // half way across the gap between left-out facts and steady prompts; on overlap, what most facts reach - const need = if (low > high) (low + high) / 2 else low; - return .{ .dir = dir, .weight = weight, .mean = mean, .need = need, .reads = reads, .fact_low = low, .fact_least = fact_avg[0], .steady_high = high }; -} - -test "a router clears questions it never saw about its fact, and steady prompts it never saw stay below it" { - const gpa = std.testing.allocator; - var prng = std.Random.DefaultPrng.init(11); - const r = prng.random(); - const layers = 6; - const nf = 8; - const ns = 60; - var facts: [layers][]f32 = undefined; - var steady: [layers][]f32 = undefined; - // facts share a direction the steady rows lack; every row then made unit - for (0..layers) |l| { - facts[l] = try gpa.alloc(f32, nf * n); - steady[l] = try gpa.alloc(f32, ns * n); - for (facts[l], 0..) |*x, i| x.* = r.floatNorm(f32) * 0.3 + @as(f32, if (i % n == l) 3 else 0); - for (steady[l]) |*x| x.* = r.floatNorm(f32) * 0.3; - for ([_][]f32{ facts[l], steady[l] }) |rows| for (0..rows.len / n) |q| { - const row = rows[q * n ..][0..n]; - const size = @sqrt(subspace.dot(row, row)); - for (row) |*x| x.* /= size; - }; - } - defer for (0..layers) |l| { - gpa.free(facts[l]); - gpa.free(steady[l]); - }; - var f = try fit(gpa, &facts, &steady); - defer f.deinit(gpa); - try std.testing.expect(f.apart()); - try std.testing.expect(f.need > f.steady_high and f.need < f.fact_low); - try std.testing.expectEqual(@as(u32, layers), f.reads); - // the fit's own rows: every fact above the bar, every steady prompt below it - for (0..nf) |i| try std.testing.expect(f.score(&facts, i) >= f.need); - for (0..ns) |j| try std.testing.expect(f.score(&steady, j) < f.need); -} diff --git a/zig/src/families/nemotron/subspace.zig b/zig/src/families/nemotron/subspace.zig deleted file mode 100644 index 4fe16eb109e..00000000000 --- a/zig/src/families/nemotron/subspace.zig +++ /dev/null @@ -1,216 +0,0 @@ -//! Small dense linear algebra for a lesson's directions: orthonormal rows, and where one set of rows outweighs another. -const std = @import("std"); - -const V = @Vector(8, f32); - -pub fn dot(x: []const f32, y: []const f32) f32 { - var acc: V = @splat(0); - var i: usize = 0; - while (i + 8 <= x.len) : (i += 8) acc += @as(V, x[i..][0..8].*) * @as(V, y[i..][0..8].*); - var s = @reduce(.Add, acc); - while (i < x.len) : (i += 1) s += x[i] * y[i]; - return s; -} - -/// y += c x. -pub fn axpy(y: []f32, c: f32, x: []const f32) void { - const cv: V = @splat(c); - var i: usize = 0; - while (i + 8 <= y.len) : (i += 8) y[i..][0..8].* = @as(V, y[i..][0..8].*) + cv * @as(V, x[i..][0..8].*); - while (i < y.len) : (i += 1) y[i] += c * x[i]; -} - -/// Rows of `m` made orthonormal in place, each against those before it twice over; a row that vanishes becomes zero. -pub fn orthonormal(m: []f32, rows: usize, len: usize) void { - for (0..rows) |j| { - const row = m[j * len ..][0..len]; - const size = @sqrt(dot(row, row)); - for (0..2) |_| for (0..j) |i| { - const prev = m[i * len ..][0..len]; - axpy(row, -dot(row, prev), prev); - }; - const left = @sqrt(dot(row, row)); - if (!(left > 1e-4 * size)) { - @memset(row, 0); - continue; - } - for (row) |*v| v.* /= left; - } -} - -/// Each row of `m` (rows x len) with its parts along the orthonormal rows of `basis` taken out, twice over. -pub fn remove(m: []f32, rows: usize, basis: []const f32, count: usize, len: usize) void { - for (0..rows) |q| { - const row = m[q * len ..][0..len]; - for (0..2) |_| for (0..count) |u| { - const dir = basis[u * len ..][0..len]; - axpy(row, -dot(row, dir), dir); - }; - } -} - -/// The k orthonormal directions (rows of out) where `more` (n x n) outweighs `less`: more v = mu (less + lambda) v. -pub fn outweigh(gpa: std.mem.Allocator, more: []const f64, less: []const f64, n: usize, k: usize, out: []f32) !void { - const l = try gpa.dupe(f64, less); - defer gpa.free(l); - var trace: f64 = 0; - for (0..n) |i| trace += l[i * n + i]; - const lambda = 1e-3 * trace / @as(f64, @floatFromInt(n)) + 1e-12; - for (0..n) |i| l[i * n + i] += lambda; - try cholesky(l, n); - const s = try gpa.alloc(f64, n * n); - defer gpa.free(s); - const t = try gpa.alloc(f64, n * n); - defer gpa.free(t); - @memcpy(t, more); - for (0..n) |col| lower(l, n, t, col); - for (0..n) |i| for (0..n) |j| { - s[i * n + j] = t[j * n + i]; - }; - for (0..n) |col| lower(l, n, s, col); - const vecs = try gpa.alloc(f64, n * n); - defer gpa.free(vecs); - jacobi(s, n, vecs); - const vals = try gpa.alloc(f64, n); - defer gpa.free(vals); - for (vals, 0..) |*v, i| v.* = s[i * n + i]; - const order = try gpa.alloc(usize, n); - defer gpa.free(order); - for (order, 0..) |*o, i| o.* = i; - std.mem.sort(usize, order, vals, struct { - fn bigger(v: []const f64, a: usize, b: usize) bool { - return v[a] > v[b]; - } - }.bigger); - const w = try gpa.alloc(f64, n); - defer gpa.free(w); - for (0..k) |q| { - for (w, 0..) |*x, i| x.* = vecs[i * n + order[q]]; - upper(l, n, w); - for (out[q * n ..][0..n], w) |*o, x| o.* = @floatCast(x); - } - orthonormal(out, k, n); -} - -/// x = a^-1 b for a symmetric positive definite a (n x n, overwritten by its Cholesky factor). -pub fn solve(a: []f64, n: usize, b: []f64) !void { - try cholesky(a, n); - solveFactored(a, n, b); -} - -/// x = a^-1 b given a's Cholesky factor (as `factor` leaves it). -pub fn solveFactored(l: []const f64, n: usize, b: []f64) void { - for (0..n) |i| { - var v = b[i]; - for (0..i) |k| v -= l[i * n + k] * b[k]; - b[i] = v / l[i * n + i]; - } - upper(l, n, b); -} - -/// a = L L^T in place, for solveFactored. -pub fn factor(a: []f64, n: usize) !void { - try cholesky(a, n); -} - -/// a = L L^T in place (L in the lower triangle, the upper zeroed); a must be symmetric positive definite. -fn cholesky(a: []f64, n: usize) !void { - for (0..n) |j| { - var d = a[j * n + j]; - for (0..j) |k| d -= a[j * n + k] * a[j * n + k]; - if (!(d > 0)) return error.NotPositiveDefinite; - const root = @sqrt(d); - a[j * n + j] = root; - for (j + 1..n) |i| { - var v = a[i * n + j]; - for (0..j) |k| v -= a[i * n + k] * a[j * n + k]; - a[i * n + j] = v / root; - } - for (j + 1..n) |k| a[j * n + k] = 0; - } -} - -/// Column `col` of m (n x n) replaced by L^-1 times it. -fn lower(l: []const f64, n: usize, m: []f64, col: usize) void { - for (0..n) |i| { - var v = m[i * n + col]; - for (0..i) |k| v -= l[i * n + k] * m[k * n + col]; - m[i * n + col] = v / l[i * n + i]; - } -} - -/// w replaced by L^-T w. -fn upper(l: []const f64, n: usize, w: []f64) void { - var i = n; - while (i > 0) { - i -= 1; - var v = w[i]; - for (i + 1..n) |k| v -= l[k * n + i] * w[k]; - w[i] = v / l[i * n + i]; - } -} - -/// A symmetric a (n x n) brought to its eigenvalues on the diagonal by Jacobi rotations; vecs' columns: eigenvectors. -fn jacobi(a: []f64, n: usize, vecs: []f64) void { - @memset(vecs, 0); - for (0..n) |i| vecs[i * n + i] = 1; - for (0..60) |_| { - var off: f64 = 0; - var all: f64 = 0; - for (0..n) |i| for (0..n) |j| { - all += a[i * n + j] * a[i * n + j]; - if (i != j) off += a[i * n + j] * a[i * n + j]; - }; - if (off <= 1e-24 * all) return; - for (0..n) |p| for (p + 1..n) |q| { - const apq = a[p * n + q]; - if (apq == 0) continue; - const theta = (a[q * n + q] - a[p * n + p]) / (2 * apq); - const t = std.math.sign(theta) / (@abs(theta) + @sqrt(theta * theta + 1)) + @as(f64, if (theta == 0) 1 else 0); - const c = 1 / @sqrt(t * t + 1); - const s = t * c; - for (0..n) |k| { - const akp = a[k * n + p]; - const akq = a[k * n + q]; - a[k * n + p] = c * akp - s * akq; - a[k * n + q] = s * akp + c * akq; - } - for (0..n) |k| { - const apk = a[p * n + k]; - const aqk = a[q * n + k]; - a[p * n + k] = c * apk - s * aqk; - a[q * n + k] = s * apk + c * aqk; - } - for (0..n) |k| { - const vkp = vecs[k * n + p]; - const vkq = vecs[k * n + q]; - vecs[k * n + p] = c * vkp - s * vkq; - vecs[k * n + q] = s * vkp + c * vkq; - } - }; - } -} - -test "orthonormal rows, and the direction one set of rows outweighs another along" { - const len = 64; - var avoid: [3 * len]f32 = undefined; - var seek: [2 * len]f32 = undefined; - var prng = std.Random.DefaultPrng.init(7); - for (&avoid) |*v| v.* = prng.random().float(f32) - 0.5; - for (&seek) |*v| v.* = prng.random().float(f32) - 0.5; - orthonormal(&avoid, 3, len); - remove(&seek, 2, &avoid, 3, len); - orthonormal(&seek, 2, len); - for (0..2) |q| { - const row = seek[q * len ..][0..len]; - try std.testing.expectApproxEqAbs(@as(f32, 1), dot(row, row), 1e-4); - for (0..3) |u| try std.testing.expectApproxEqAbs(@as(f32, 0), dot(row, avoid[u * len ..][0..len]), 1e-4); - } - // more is large on axis 0 and 1, less is large on axis 1: the best single direction is axis 0 - var more = [_]f64{ 4, 0, 0, 0, 4, 0, 0, 0, 1 }; - var less = [_]f64{ 1, 0, 0, 0, 9, 0, 0, 0, 1 }; - var out: [3]f32 = undefined; - try outweigh(std.testing.allocator, &more, &less, 3, 1, &out); - try std.testing.expectApproxEqAbs(@as(f32, 1), @abs(out[0]), 1e-4); - try std.testing.expectApproxEqAbs(@as(f32, 0), out[1], 1e-4); -} diff --git a/zig/src/families/nemotron/train_mode.zig b/zig/src/families/nemotron/train_mode.zig deleted file mode 100644 index d6b4a69dfc5..00000000000 --- a/zig/src/families/nemotron/train_mode.zig +++ /dev/null @@ -1,47 +0,0 @@ -//! What a training step does, for both backends' trainers. - -/// A step's loss, its gradient (and Adam: `learn`), inputs only (`reads`), or the gradient at a nudged row (`target`). -pub const Mode = enum { loss, grad, learn, avoid, seek, project, keys, target, prime }; - -/// Whether a step only reads the site inputs (sketches, projections or keys), with no loss. -pub fn reads(mode: Mode) bool { - return switch (mode) { - .avoid, .seek, .project, .keys, .prime => true, - else => false, - }; -} - -/// Where a `target` step nudges and reads the gradient: three rows, each after its mask's layers, row i's in third i. -pub const Nudge = struct { layers: [3]u64 = @splat(0), rows: [3]usize = @splat(0) }; - -/// The answer's mean loss, and whether each of its tokens was the likeliest at its row. -pub const Result = struct { loss: f32, recalled: bool }; - -/// A pass's sequence: tokens, answer start, decision row, pocket scale, nudges, and `skip` rows from prefix `slot`. -pub const Seq = struct { ids: []const u32, start: usize, decide: usize, scale: f32 = 1, nudge: Nudge = .{}, skip: usize = 0, slot: u32 = 0 }; - -/// Where each sequence of a pass sits: its first row, its rows (ids less the last and the skipped), its prefix. -pub const Span = struct { - at: usize, - rows: usize, - skip: usize = 0, - slot: u32 = 0, - - /// The pass's row holding the sequence's row r (r at least `skip`). - pub fn row(sp: Span, r: usize) usize { - return sp.at + r - sp.skip; - } -}; - -/// A sequence's rows that predict its answer: the first in the pass, where they sit among the head's rows, how many. -pub const Answer = struct { first: usize, at: usize, rows: usize }; - -/// Each sequence's answer rows, packed for the head (no other row's loss or gradient there is anything but zero). -pub fn answers(seqs: []const Seq, spans: []const Span, out: []Answer) usize { - var at: usize = 0; - for (seqs, spans, out) |sq, sp, *a| { - a.* = .{ .first = sp.row(sq.start - 1), .at = at, .rows = sq.ids.len - sq.start }; - at += a.rows; - } - return at; -} diff --git a/zig/src/families/qwen27/decode_round.zig b/zig/src/families/qwen27/decode_round.zig index 3db4d341fd4..59bda260091 100644 --- a/zig/src/families/qwen27/decode_round.zig +++ b/zig/src/families/qwen27/decode_round.zig @@ -7,6 +7,8 @@ const forward = @import("forward.zig"); const Ref = @import("projection.zig").Ref; /// Layers a verify encodes before committing them, so the GPU starts while the CPU encodes the rest. const commit_every = 4; +/// Passes past this many rows are prompt chunks (128 rows and up), 3.5% slower on Metal 4 with qk: Metal 3 takes them. +const metal4_rows = 64; const wts = @import("gpu_weights.zig"); const attn = @import("attention.zig"); const abi = @import("gdn_contract.zig"); @@ -14,6 +16,7 @@ const GdnPool = @import("gdn_pool_gpu.zig").Pool; const GdnHook = @import("gdn_hook.zig").Hook; const GdnPlan = @import("gdn_plan.zig").Plan; const Round = @import("round_plan.zig").Round; +const fingerprint = @import("round_fingerprint.zig").fingerprint; const Taps = @import("taps.zig").Taps; const image_rows = @import("image_rows.zig"); const mrope = @import("core").qwen_vl.rope; @@ -30,6 +33,12 @@ pub fn gpuFailed(cb: mtl.CommandBuffer, what: []const u8) bool { return true; } +/// The flat kernels or the general ones, for every round after this; TF_Q27_FLAT_GLUE=0 keeps the general ones. +pub fn setFlatGlue(on: bool) void { + @import("core_delta").flat_glue = on; + @import("core").tree_round_gpu.chunked_picks = on; +} + pub const Runner = struct { allocator: std.mem.Allocator, residency: ?mtl.ResidencySet.Follow = null, @@ -55,6 +64,8 @@ pub const Runner = struct { tail: ?forward.Tail = null, accepted_chain: bool = false, last_gpu_seconds: f64 = 0, + /// Verify passes take the model's Metal 4 context when it has one; an A/B tool turns it off for one runner. + metal4: bool = true, gpu_seconds: f64 = 0, // with a trace attached: every pass's GPU-busy seconds, its spans' and share's buffers too trace: ?*@import("core").gpu_profile.Trace = null, // TF_Q27_PROFILE's: each pass run while it is enabled is a round current_round: ?*const Round = null, @@ -87,6 +98,7 @@ pub const Runner = struct { } fn build(a: std.mem.Allocator, m: *Model, slots: u32, capacity: u32, ready: u32, paged: bool) !Runner { + setFlatGlue(try @import("sys").environment.read(bool, "TF_Q27_FLAT_GLUE", @import("core_delta").flat_glue)); if (slots == 0 or slots > attn.planning.max_streams or capacity == 0 or m.frame.capacity % 16 != 0 or ready == 0 or ready > slots) return error.BadRoundCapacity; const geometry = try attn.planning.Geometry.fromConfig(m.config, m.device.tensorUnits()); const linear_index = try a.alloc(u32, m.config.layers); @@ -305,7 +317,7 @@ pub const Runner = struct { const spanned = if (r.trace) |t| t.spanned else 0; // a profiled pass's spans commit buffers of their own const handed = if (r.model.ane) |share| share.gpu_seconds else 0; var stages = forward.Stages{ .model = r.model, .rows = @intCast(round.ids.len), .hooks = .{ .ptr = r, .gdn = gdnForward, .attention = attentionForward, .tap = if (r.capture_taps) tap else null, .keys = if (r.keysOnly(head)) keysForward else null }, .head = head, .tail = r.tail, .images = placed.images, .reduce = r.reduce, .picks = r.picks }; - r.last_gpu_seconds = @import("core").segments.runCommitting(r.model.device, &.{r.model.queue}, r.model.config.layers, .concurrent, &stages, commit_every) catch |err| { + r.last_gpu_seconds = @import("core").segments.runCommitting(r.model.device, &.{r.passQueue(round.ids.len)}, r.model.config.layers, .concurrent, &stages, commit_every) catch |err| { r.failed = true; return err; }; @@ -328,6 +340,13 @@ pub const Runner = struct { } else r.active = fingerprint(round); } + /// The model's Metal 4 queue, unless the pass is a prompt chunk or needs Metal 3: a trace, the Neural Engine, seams + fn passQueue(r: *const Runner, rows: usize) mtl.Queue { + const c = r.model.metal4 orelse return r.model.queue; + if (!r.metal4 or rows > metal4_rows or c.broken or r.trace != null or r.model.ane != null or r.reduce != null) return r.model.queue; + return c.asQueue(); + } + pub fn keep(r: *Runner, round: *const Round, paths: []const []const u32) !void { const active = r.active orelse return error.RoundNotReady; if (r.failed or !std.mem.eql(u8, &active, &fingerprint(round))) return error.RoundNotReady; @@ -481,7 +500,7 @@ pub const Runner = struct { fn metadata(r: *Runner) @import("gdn_pool_gpu.zig").Metadata { const f = &r.model.frame; - return .{ .parents = f.get(.parents), .windows = f.get(.windows), .row_slots = f.get(.row_slots), .segments = f.get(.segments), .keeps = f.get(.keeps), .kept_rows = f.get(.kept_rows), .slot_steps = f.get(.slot_steps) }; + return .{ .parents = f.get(.parents), .windows = f.get(.windows), .row_slots = f.get(.row_slots), .segments = f.get(.segments), .keeps = f.get(.keeps), .kept_rows = f.get(.kept_rows), .slot_steps = f.get(.slot_steps), .flows = f.get(.flows) }; } pub fn promptRows(r: *const Runner, requested: u32) u32 { @@ -576,21 +595,3 @@ fn allocation(a: std.mem.Allocator, device: mtl.Device, owned: *std.ArrayList(mt }; return b; } - -fn fingerprint(round: *const Round) [32]u8 { - var hash = std.crypto.hash.sha2.Sha256.init(.{}); - hash.update(std.mem.sliceAsBytes(round.ids)); - hash.update(std.mem.sliceAsBytes(round.slots)); - hash.update(std.mem.sliceAsBytes(round.feed_positions)); - hash.update(std.mem.sliceAsBytes(round.draw_positions)); - hash.update(std.mem.sliceAsBytes(round.firsts)); - for (round.windows) |window| { - hash.update(std.mem.asBytes(&window.start)); - hash.update(std.mem.asBytes(&window.taps)); - hash.update(std.mem.sliceAsBytes(window.parents)); - hash.update(std.mem.sliceAsBytes(window.conv)); - } - var out: [32]u8 = undefined; - hash.final(&out); - return out; -} diff --git a/zig/src/families/qwen27/dflash/round_gpu.zig b/zig/src/families/qwen27/dflash/round_gpu.zig index a9ff9aec597..74c01eb802b 100644 --- a/zig/src/families/qwen27/dflash/round_gpu.zig +++ b/zig/src/families/qwen27/dflash/round_gpu.zig @@ -29,7 +29,7 @@ pub const Matcher = struct { @memcpy(m.buffers[1].slice(i32, parents.len), parents); @memcpy(m.buffers[3].slice(u32, eos.len), eos); const shape = contract.Match{ .rows = @intCast(ids.len), .vocab = vocab, .budget = budget, .eos_count = @intCast(eos.len) }; - try m.ops.argmax(e, logits, .{ .buf = m.buffers[2] }, .{ .rows = shape.rows, .vocab = vocab, .stride = vocab }); + try m.ops.argmaxChunks(e, logits, .{ .buf = m.buffers[2] }, .{ .rows = shape.rows, .vocab = vocab, .stride = vocab }); e.barrier(); try m.ops.match(e, .{ .buf = m.buffers[0] }, .{ .buf = m.buffers[1] }, .{ .buf = m.buffers[2] }, if (eos.len == 0) null else .{ .buf = m.buffers[3] }, .{ .buf = m.buffers[4] }, shape); e.barrier(); diff --git a/zig/src/families/qwen27/gdn.zig b/zig/src/families/qwen27/gdn.zig index 003a8b9cdad..b49d08797e0 100644 --- a/zig/src/families/qwen27/gdn.zig +++ b/zig/src/families/qwen27/gdn.zig @@ -55,6 +55,7 @@ pub const Buffers = struct { keeps: Span, kept_rows: Span, slot_steps: Span, + flows: ?Span = null, pub fn check(b: Buffers, sizes: abi.Bytes, kinds: abi.WeightKinds, p: abi.Params, plan: Plan) !void { try b.qkv.check(sizes.qkv); @@ -105,6 +106,7 @@ pub const Round = struct { tree_mode: TreeMode = .auto, compact: bool, slot_kernel: usize, // which tree_slots kernel holds the plan's peak of live states + column_kernel: ?usize = null, // which column scan holds them, if the plan's trees fit one pub fn init(shape: abi.Shape, kinds: abi.WeightKinds, p: abi.Params, plan: Plan, b: Buffers, pipelines: Pipelines) !Round { if (plan.parents.len != p.rows or plan.segments.len == 0 or plan.keeps.len != plan.segments.len or (plan.compact and plan.slot_steps.len != p.rows)) return error.BadGdnPlan; @@ -114,10 +116,25 @@ pub const Round = struct { for (pipelines.tree_slots) |pipeline| if (pipeline.simdWidth() != 32 or pipeline.maxThreads() < 128) return error.UnsupportedGdnPipeline; const slots = @import("core_delta").slotKernel(plan.slot_peak); if (plan.compact) for (plan.segments) |segment| try @import("core").tree_slots.validate(plan.parents[segment.first..][0..segment.rows], plan.slot_steps[segment.first..][0..segment.rows], segment.first, @import("core_delta").slot_kernels[slots]); - return .{ .slot_kernel = slots, .compact = plan.compact, .p = p, .b = b, .pipelines = pipelines, .segments = plan.segments.len, .conv_width = shape.conv }; + const columns = if (plan.flowing and pipelines.columns != null and b.flows != null) @import("core_delta").columnKernel(plan.slot_peak) else null; + return .{ .slot_kernel = slots, .column_kernel = columns, .compact = plan.compact, .p = p, .b = b, .pipelines = pipelines, .segments = plan.segments.len, .conv_width = shape.conv }; + } + + /// All-bf16 weights and four taps over 128-wide heads, the shape the vector conv reads. + fn usesVectors(r: Round) bool { + return @import("core_delta").flat_glue and r.pipelines.pre_vectors != null and r.p.dk == 128 and r.p.dv == 128 and r.p.taps == 4 and r.p.weight_flags & 7 == 0; } pub fn prepare(r: Round, e: metal.ComputeEncoder) void { + if (r.usesVectors()) { + e.setPipeline(r.pipelines.pre_vectors.?); + bind(e, .{ r.b.qkv, r.b.a, r.b.b, r.b.history, r.b.conv_weight, r.b.a_log, r.b.dt, r.b.windows, r.b.row_slots }, 0); + e.setValue(r.p, 9); + bind(e, .{ r.b.query, r.b.key, r.b.value, r.b.decay, r.b.mixing }, 10); + e.dispatchGroups(.{ .width = 1, .height = 2 * r.p.nk + r.p.nv, .depth = r.p.rows }, .{ .width = 32, .height = 1, .depth = 1 }); + e.barrier(); + return; + } e.setPipeline(r.pipelines.pre); bind(e, .{ r.b.qkv, r.b.a, r.b.b, r.b.history, r.b.conv_weight, r.b.a_log, r.b.dt, r.b.windows, r.b.row_slots }, 0); e.setValue(r.p, 9); @@ -141,17 +158,30 @@ pub const Round = struct { return r.p.dk == 128 and r.compact and r.tree_mode != .snapshot; } + /// A shared round's windows step their state in the slot scan, so only a lone tree takes the columns. + fn usesColumns(r: Round) bool { + return @import("core_delta").flat_glue and r.usesSlots() and r.p.dv == 128 and r.p.advance == 0 and r.column_kernel != null; + } + pub fn forward(r: Round, e: metal.ComputeEncoder) void { - e.setPipeline(if (r.usesSlots()) r.pipelines.tree_slots[r.slot_kernel] else r.pipelines.tree); - bind(e, .{ r.b.query, r.b.key, r.b.value, r.b.decay, r.b.mixing, r.b.state, r.b.parents, r.b.segments }, 0); - e.setValue(r.p, 8); - bind(e, .{ r.b.recurrent, r.b.snapshots }, 9); - if (r.usesSlots()) { - r.b.slot_steps.bind(e, 11); - r.b.state.bind(e, 12); - (r.b.before orelse r.b.state).bind(e, 13); + if (r.usesColumns()) { + e.setPipeline(r.pipelines.columns.?[r.column_kernel.?]); + bind(e, .{ r.b.query, r.b.key, r.b.value, r.b.decay, r.b.mixing, r.b.state, r.b.segments }, 0); + e.setValue(r.p, 7); + bind(e, .{ r.b.recurrent, r.b.flows.? }, 8); + e.dispatchGroups(.{ .width = 1, .height = r.p.dv / 4, .depth = r.p.nv * r.segments }, .{ .width = 32, .height = 1, .depth = 1 }); + } else { + e.setPipeline(if (r.usesSlots()) r.pipelines.tree_slots[r.slot_kernel] else r.pipelines.tree); + bind(e, .{ r.b.query, r.b.key, r.b.value, r.b.decay, r.b.mixing, r.b.state, r.b.parents, r.b.segments }, 0); + e.setValue(r.p, 8); + bind(e, .{ r.b.recurrent, r.b.snapshots }, 9); + if (r.usesSlots()) { + r.b.slot_steps.bind(e, 11); + r.b.state.bind(e, 12); + (r.b.before orelse r.b.state).bind(e, 13); + } + r.stateGrid(e); } - r.stateGrid(e); e.barrier(); e.setPipeline(r.pipelines.post); bind(e, .{ r.b.recurrent, r.b.z, r.b.norm }, 0); diff --git a/zig/src/families/qwen27/gdn_hook.zig b/zig/src/families/qwen27/gdn_hook.zig index 944fd7aa307..5ac1d0244ee 100644 --- a/zig/src/families/qwen27/gdn_hook.zig +++ b/zig/src/families/qwen27/gdn_hook.zig @@ -41,5 +41,5 @@ fn refs(weight: Weights.Gdn, frame: *Frame) !pool_gpu.Refs { } fn devicePlan(plan: Plan, frame: *Frame) pool_gpu.DevicePlan { - return .{ .host = plan, .metadata = .{ .parents = frame.get(.parents), .windows = frame.get(.windows), .row_slots = frame.get(.row_slots), .segments = frame.get(.segments), .keeps = frame.get(.keeps), .kept_rows = frame.get(.kept_rows), .slot_steps = frame.get(.slot_steps) } }; + return .{ .host = plan, .metadata = .{ .parents = frame.get(.parents), .windows = frame.get(.windows), .row_slots = frame.get(.row_slots), .segments = frame.get(.segments), .keeps = frame.get(.keeps), .kept_rows = frame.get(.kept_rows), .slot_steps = frame.get(.slot_steps), .flows = frame.get(.flows) } }; } diff --git a/zig/src/families/qwen27/gdn_plan.zig b/zig/src/families/qwen27/gdn_plan.zig index 9a7db9d386c..0834c8d834b 100644 --- a/zig/src/families/qwen27/gdn_plan.zig +++ b/zig/src/families/qwen27/gdn_plan.zig @@ -15,6 +15,8 @@ pub const Plan = struct { keeps: []abi.Keep, kept_rows: []u32, slot_steps: []tree_slots.Step = &.{}, + flows: []u32 = &.{}, // the slot steps as the column scan reads them + flowing: bool = false, // every window is one tree, so `flows` holds its steps compact: bool = false, slot_peak: usize = 0, // the most register slots any window's schedule holds live @@ -52,6 +54,9 @@ pub const Plan = struct { const slot_steps = try gpa.alloc(tree_slots.Step, rows); errdefer gpa.free(slot_steps); @memset(slot_steps, .{ .row = 0, .read_slot = -1, .write_slot = 0 }); + const flows = try gpa.alloc(u32, rows); + errdefer gpa.free(flows); + var flowing = true; var compact = true; var slot_peak: usize = 0; var first: u32 = 0; @@ -66,6 +71,7 @@ pub const Plan = struct { }, else => return err, }); + if (compact) flowing = tree_slots.flows(slot_steps[first..][0..n], flows[first..][0..n]) and flowing; @memset(slots[first..][0..n], input.state_slot); for (input.window.conv, 0..) |index, at| windows[first * p.taps + at] = if (index < p.taps - 1) index else index + first; for (input.path, 0..) |row, at| kept_rows[keep_first + at] = first + row; @@ -74,7 +80,7 @@ pub const Plan = struct { first += n; keep_first += @intCast(input.path.len); } - return .{ .gpa = gpa, .parents = parents, .windows = windows, .row_slots = slots, .segments = segments, .keeps = keeps, .kept_rows = kept_rows, .slot_steps = slot_steps, .compact = compact, .slot_peak = slot_peak }; + return .{ .gpa = gpa, .parents = parents, .windows = windows, .row_slots = slots, .segments = segments, .keeps = keeps, .kept_rows = kept_rows, .slot_steps = slot_steps, .flows = flows, .flowing = flowing and compact, .compact = compact, .slot_peak = slot_peak }; } pub fn deinit(plan: *Plan) void { @@ -85,6 +91,7 @@ pub const Plan = struct { plan.gpa.free(plan.keeps); plan.gpa.free(plan.kept_rows); plan.gpa.free(plan.slot_steps); + plan.gpa.free(plan.flows); plan.* = undefined; } }; diff --git a/zig/src/families/qwen27/gdn_pool_gpu.zig b/zig/src/families/qwen27/gdn_pool_gpu.zig index 5d8931162d3..919a973617c 100644 --- a/zig/src/families/qwen27/gdn_pool_gpu.zig +++ b/zig/src/families/qwen27/gdn_pool_gpu.zig @@ -22,8 +22,14 @@ pub const Metadata = struct { keeps: Ref, kept_rows: Ref, slot_steps: Ref, + flows: ?Ref = null, pub fn upload(m: Metadata, plan: Plan) !void { + if (m.flows) |r| { + const bytes = std.mem.sliceAsBytes(plan.flows); + if (r.offset > r.buffer.length() or bytes.len > r.buffer.length() - r.offset) return error.ShortGdnMetadata; + @memcpy(r.buffer.contents()[r.offset..][0..bytes.len], bytes); + } inline for (.{ "parents", "windows", "row_slots", "segments", "keeps", "kept_rows", "slot_steps" }) |name| { const r = @field(m, name); const bytes = std.mem.sliceAsBytes(@field(plan, name)); @@ -322,6 +328,7 @@ pub const Pool = struct { .keeps = try refSpan(m.keeps, plan.keeps.len * @sizeOf(abi.Keep)), .kept_rows = try refSpan(m.kept_rows, plan.kept_rows.len * 4), .slot_steps = try refSpan(m.slot_steps, plan.slot_steps.len * @sizeOf(@import("core").tree_slots.Step)), + .flows = if (m.flows) |r| try refSpan(r, plan.flows.len * 4) else null, }; var result = try gdn.Round.init(pool.budget.shape, refs.scalars.kinds, p, plan, b, pool.kernels.pipelines); result.tree_mode = pool.tree_mode; diff --git a/zig/src/families/qwen27/gpu_frame.zig b/zig/src/families/qwen27/gpu_frame.zig index 1efb68fd2b3..f868187e096 100644 --- a/zig/src/families/qwen27/gpu_frame.zig +++ b/zig/src/families/qwen27/gpu_frame.zig @@ -4,7 +4,7 @@ const mtl = @import("metal"); const Config = @import("config.zig").Config; const Ref = @import("projection.zig").Ref; -pub const Field = enum { ids, dims, positions, hidden, residual, input, sums, mixed, mixer_out, output, z, a, b, query, key, value, norm_query, norm_key, q_gate, gate, up, activated, act_sums, logits, drawn, eps, parents, windows, row_slots, segments, keeps, kept_rows, rotated_key, takes, slot_steps, router, picks, route_weights, offsets, order, sorted_weights, sorted_rows, expert_gate, expert_up, expert_act, expert_out, expert_sums }; +pub const Field = enum { ids, dims, positions, hidden, residual, input, sums, mixed, mixer_out, output, z, a, b, query, key, value, norm_query, norm_key, q_gate, gate, up, activated, act_sums, logits, drawn, eps, parents, windows, row_slots, segments, keeps, kept_rows, rotated_key, takes, slot_steps, router, picks, route_weights, offsets, order, sorted_weights, sorted_rows, expert_gate, expert_up, expert_act, expert_out, expert_sums, flows }; /// A prompt pass's rows at most (a chain); rounds with trees and every logits row stay within `logit_rows`. pub const max_rows = 2048; @@ -36,7 +36,7 @@ pub fn allocationSizes(config: Config, capacity: u32) [std.enums.values(Field).l slots * 4, slots * 4, (config.experts + 1) * 4, slots * 4, slots * 4, slots * config.hidden * 2, slots * config.moe_intermediate * 2, slots * config.moe_intermediate * 2, slots * config.moe_intermediate * 2, - slots * config.hidden * 2, slots * @max(config.hidden, config.moe_intermediate) / 64 * 4, + slots * config.hidden * 2, slots * @max(config.hidden, config.moe_intermediate) / 64 * 4, capacity * 4, }; } diff --git a/zig/src/families/qwen27/gpu_weights.zig b/zig/src/families/qwen27/gpu_weights.zig index 1383e224463..a76b803e82d 100644 --- a/zig/src/families/qwen27/gpu_weights.zig +++ b/zig/src/families/qwen27/gpu_weights.zig @@ -385,11 +385,40 @@ pub fn load(allocator: std.mem.Allocator, device: mtl.Device, checkpoint: *const for (layers, 0..) |*l, i| l.* = try b.layer(s, i); const embed = try b.quant("model.embed_tokens", g.vocab, g.hidden, ws.embed); const norm = try b.tensor("model.norm.weight", .bf16, &.{c.hidden}); - const head = try b.linear(&.{.{ .module = "lm_head", .n = g.vocab, .w = ws.head, .span = s.vocabRows() }}, g.hidden); - if (device.tensorUnits()) try laneOrder(allocator, device, layers, head); + var head = try b.linear(&.{.{ .module = "lm_head", .n = g.vocab, .w = ws.head, .span = s.vocabRows() }}, g.hidden); + if (device.tensorUnits()) { + if (try qkLayout(allocator, device)) markPlain(layers, &head); + try laneOrder(allocator, device, layers, head); + } return .{ .allocator = allocator, .layers = layers, .embed = embed, .norm = norm, .head = head, .owned = owned, .runs = runs }; } +/// Whether 4-bit g64 matrices stay in weight_layout for qk: a GPU that builds qk, unless TF_Q27_QK=0. +pub fn qkLayout(allocator: std.mem.Allocator, device: mtl.Device) !bool { + if (!try @import("sys").environment.read(bool, "TF_Q27_QK", true)) return false; + if (lane.qk.available(allocator, device)) return true; + std.log.info("qwen27: this GPU's runtime compiler does not build qk; projections take tf_lane_reg", .{}); + return false; +} + +/// qk reads 4-bit g64 matrices as `projection.prepare` leaves them, so they skip the reorder and keep no copy. +fn markPlain(layers: []Layer, head: *Linear) void { + for (layers) |*l| { + switch (l.mixer) { + .linear => |*g| for ([_]*Linear{ &g.qkv, &g.zba, &g.out }) |p| plainOne(p), + .attention => |*t| for ([_]*Linear{ &t.q, &t.kv, &t.out }) |p| plainOne(p), + } + plainOne(&l.gu); + plainOne(&l.down); + } + plainOne(head); +} + +/// Mixed stacks keep their members in reg order: quantRuns takes them a row a launch on the lane kernels. +fn plainOne(p: *Linear) void { + if (p.runs.len == 0 and p.raw == null and p.bits == 4 and p.group == 64 and p.n % 32 == 0) p.plain = true; +} + /// Tensor-unit projections leave load in lane_projection.reg_layout, the order quant_gpu's reg kernel reads. fn laneOrder(a: std.mem.Allocator, device: mtl.Device, layers: []const Layer, head: Linear) !void { var jobs: std.ArrayList(lane.Order) = .empty; @@ -402,13 +431,13 @@ fn laneOrder(a: std.mem.Allocator, device: mtl.Device, layers: []const Layer, he for (list) |p| try regJobs(a, &jobs, p); } try regJobs(a, &jobs, head); - try lane.regOrder(device, jobs.items); + if (jobs.items.len > 0) try lane.regOrder(device, jobs.items); } /// Only 4-bit g64 matrices take the reg kernel; other widths keep lane_projection.weight_layout. fn regJobs(a: std.mem.Allocator, jobs: *std.ArrayList(lane.Order), p: Linear) std.mem.Allocator.Error!void { for (p.runs) |r| try regJobs(a, jobs, r.linear); - if (p.runs.len == 0 and p.bits == 4 and p.group == 64 and p.n % 32 == 0) try jobs.append(a, .{ .w = .{ .buf = p.words.buffer, .off = p.words.offset }, .n = p.n, .k = p.k }); + if (p.runs.len == 0 and !p.plain and p.bits == 4 and p.group == 64 and p.n % 32 == 0) try jobs.append(a, .{ .w = .{ .buf = p.words.buffer, .off = p.words.offset }, .n = p.n, .k = p.k }); } /// A borrowed quantized tensor as the row kernels' matrix. diff --git a/zig/src/families/qwen27/model.zig b/zig/src/families/qwen27/model.zig index 91c82ae970e..48c1096bf62 100644 --- a/zig/src/families/qwen27/model.zig +++ b/zig/src/families/qwen27/model.zig @@ -19,6 +19,8 @@ pub const Model = struct { allocator: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, + /// Verify passes' own Metal 4 queue, where this Mac has one and TF_Q27_METAL4 allows it (see metal4Wanted). + metal4: ?*mtl.metal4.Context = null, /// This rank's share of the family's weights; `local` shapes are what this graph builds, `global` the file's. shard: cfg.Shard, /// The local config, so downstream shapes are the rank's own. @@ -79,7 +81,7 @@ pub const Model = struct { share_fits: ?*const fn (u64) bool, later: bool, ) !*Model { - if (platform.getenv("TF_PROMPT_ROWS")) |raw| { + if ((platform.environment.Process{}).get("TF_PROMPT_ROWS")) |raw| { const n = std.fmt.parseInt(u32, raw, 10) catch 0; if (n < 16 or n > 2048 or n % 16 != 0) { try platform.environment.check("TF_PROMPT_ROWS", raw); @@ -117,6 +119,12 @@ pub const Model = struct { validation.end(); m.queue = try m.device.queue(); errdefer m.queue.deinit(); + m.metal4 = null; + if (try metal4Wanted(m.device)) m.metal4 = mtl.metal4.Context.create(a, m.device) catch |err| blk: { + std.log.info("qwen27: verify passes stay on Metal 3: {s}", .{@errorName(err)}); + break :blk null; + }; + errdefer if (m.metal4) |ctx| ctx.destroy(); m.checkpoint = core.checkpoint_metal.Checkpoint.init(a); errdefer m.checkpoint.deinit(); const headers = timing.span(.checkpoint_headers); @@ -158,7 +166,7 @@ pub const Model = struct { m.share_pending = false; defer m.checkpoint.closeFiles(); const c = m.config; - const columns = try ane_policy.columns(if (platform.c.getenv("TF_ANE_COLUMNS")) |v| std.mem.span(v) else null); + const columns = try ane_policy.columns((platform.environment.Process{}).get("TF_ANE_COLUMNS")); // The share is a whole MLP's columns: a rank holds half of them, so tensor parallel keeps prompts on the GPU. const share = m.shard.ranks == 1 and ane_policy.requestedOnChip(columns, m.device.tensorUnits()) and !c.moe() and mtl.ane.available() and m.weights.uniformMlp(); if (m.shard.ranks != 1) std.log.info("qwen27: tensor parallel rank {d}/{d} runs prompts on the GPU alone", .{ m.shard.rank, m.shard.ranks }); @@ -195,6 +203,7 @@ pub const Model = struct { } pub fn deinit(m: *Model) void { + if (m.metal4) |c| c.destroy(); if (m.ane) |share| share.deinit(); m.frame.deinit(); if (m.moe) |*k| k.deinit(); @@ -208,9 +217,14 @@ pub const Model = struct { } }; +/// Metal 4 on chips with tensor units, where it was measured; TF_Q27_METAL4=0 turns it off and 1 on elsewhere. +fn metal4Wanted(device: mtl.Device) !bool { + return @import("sys").environment.read(bool, "TF_Q27_METAL4", device.tensorUnits()); +} + /// A prompt pass's requested rows, before the runner's frame and attention limits. pub fn promptRows(c: cfg.Config, generation: u32) u32 { - const value = if (std.c.getenv("TF_PROMPT_ROWS")) |v| std.mem.span(v) else null; + const value = (platform.environment.Process{}).get("TF_PROMPT_ROWS"); return @import("prompt_rows.zig").requested(generation, c.moe(), value); } diff --git a/zig/src/families/qwen27/projection.zig b/zig/src/families/qwen27/projection.zig index 7d32bb6798d..b0a01493711 100644 --- a/zig/src/families/qwen27/projection.zig +++ b/zig/src/families/qwen27/projection.zig @@ -7,7 +7,21 @@ const lane = @import("core").lane_projection; pub const Ref = struct { buffer: mtl.Buffer, offset: usize = 0 }; /// A device matrix; `runs` non-empty means fused members of different widths. `gn`: the checkpoint's rows (0 = `n`). -pub const Linear = struct { words: Ref, pairs: Ref, n: u32, k: u32, tile: u32, slices: u32, raw: ?row.Weights = null, bits: u8 = 4, group: u32 = 64, runs: []const Run = &.{}, gn: usize = 0 }; +pub const Linear = struct { + words: Ref, + pairs: Ref, + n: u32, + k: u32, + tile: u32, + slices: u32, + raw: ?row.Weights = null, + bits: u8 = 4, + group: u32 = 64, + runs: []const Run = &.{}, + gn: usize = 0, + plain: bool = false, // 4-bit g64 words left in lane_projection.weight_layout for qk, not reordered for tf_lane_reg + reg_copy: ?Ref = null, // the same words in reg_layout beside them, which only the A/B tools make +}; /// One product inside a mixed fused matrix, writing output columns [first, first + linear.n). pub const Run = struct { linear: Linear, first: u32 }; /// Staged tensors: `gn` the part's rows when `weight.shape[0]` is a slice, `whole` its tensor's rows as a block. diff --git a/zig/src/families/qwen27/quant_gpu.zig b/zig/src/families/qwen27/quant_gpu.zig index 0fa62a37792..cdceafecd59 100644 --- a/zig/src/families/qwen27/quant_gpu.zig +++ b/zig/src/families/qwen27/quant_gpu.zig @@ -6,12 +6,16 @@ const row = @import("core").row_projection; const sources = @import("qwen_runtime_sources"); const projection = @import("projection.zig"); const profile = @import("core").gpu_profile; +const qk = lane.qk; pub const Ref = projection.Ref; /// Group sums the input's producer wrote: XS[group * stride + row], in the lane projection's order. pub const Sums = struct { ref: Ref, stride: u32 }; -pub const Key = struct { kind: Kind, n: u32 = 0, k: u32, slices: u32 = 0, tile: u32 = 0, tmr: u32 = 0, edge: bool = false, skip: u32 = 0, cut: [2]u32 = .{ 0, 0 }, bits: u8 = 4, group: u32 = 64, long: bool = false, xs: bool = true }; -pub const Kind = enum { projection, xsum, norm, input_norm, mlp, ane_input, mlp_ane, add_ane }; +/// Whether plain matrices take qk; off, a reg copy takes tf_lane_reg, else tf_lane_pair: every choice, the same words. +pub var qk_rows: bool = true; + +pub const Key = struct { kind: Kind, n: u32 = 0, k: u32, slices: u32 = 0, tile: u32 = 0, tmr: u32 = 0, edge: bool = false, skip: u32 = 0, cut: [2]u32 = .{ 0, 0 }, bits: u8 = 4, group: u32 = 64, long: bool = false, xs: bool = true, cooperative: bool = false }; +pub const Kind = enum { projection, xsum, norm, input_norm, mlp, mlp_rows, ane_input, mlp_ane, add_ane }; /// Whether prompt chunks take one dispatch a projection (`Kernels.long_prompt`): Ultras with tensor units only. pub fn longPrompt(name: []const u8, tensor_units: bool) bool { @@ -70,6 +74,8 @@ pub const Kernels = struct { prep_words: ?mtl.Buffer = null, /// tf_sq_prep_s's sums for a chunk-pair projection's prompt rows, written just before it. sum_words: ?mtl.Buffer = null, + /// qk's pipelines, made at the first plain matrix's quant. + qks: ?qk.Pipelines = null, pub fn setResident(k: *Kernels, hook: ?mtl.ResidencySet.Follow) void { var it = k.lanes.valueIterator(); @@ -100,6 +106,7 @@ pub const Kernels = struct { var lane_it = k.lanes.valueIterator(); while (lane_it.next()) |p| p.deinit(); k.lanes.deinit(k.allocator); + if (k.qks) |*q| q.deinit(); var it = k.cache.valueIterator(); while (it.next()) |p| p.deinit(); k.cache.deinit(k.allocator); @@ -117,6 +124,7 @@ pub const Kernels = struct { .norm => "custom_kernel_q27_norm_xs_bfloat16_t_bfloat16_t_bfloat16_t_floatc_int32_t_bfloat16_t_bfloat16_t_float", .input_norm => "custom_kernel_q27_norm_input_bfloat16_t_bfloat16_t_floatc_int32_t_bfloat16_t_float", .mlp => "custom_kernel_q27_mlp_xs_bfloat16_t_bfloat16_t_int32_t_bfloat16_t_float", + .mlp_rows => "q27_mlp_rows", .ane_input => "q27_ane_input", .mlp_ane => "q27_mlp_ane", .add_ane => "q27_add_ane", @@ -155,18 +163,21 @@ pub const Kernels = struct { skip: u32, cut: [2]u32, long: bool, + /// A plain matrix with no reg copy: tf_lane_pair, which reads weight_layout and writes tf_lane_reg's words. + cooperative: bool, ) !std.AutoHashMapUnmanaged(Key, lane.Projection).GetOrPutResult { - const reg = p.bits == 4 and p.group == 64; + const reg = p.bits == 4 and p.group == 64 and !cooperative; const key = Key{ .kind = .projection, .n = p.n, .k = p.k, - .slices = if (reg) sk else p.slices, + .slices = if (reg or cooperative) sk else p.slices, .skip = skip, .cut = cut, .bits = p.bits, .group = p.group, .long = long, + .cooperative = cooperative, }; const half = p.n / 64; const ranges = [_][2]usize{ .{ skip, half - skip }, .{ half + skip, half - skip } }; @@ -183,8 +194,9 @@ pub const Kernels = struct { .output = if (cut[1] > 0) .f32 else .bf16, .precompute_sums = reg or (p.bits == 8 and p.group == 64), .reg = reg, + .cooperative = cooperative, .row_blocks = long and !reg, - .rows = if (long) lane.max_reg_rows else if (reg) lane.reg_rows else 16, + .rows = if (long) lane.max_reg_rows else if (reg or cooperative) lane.reg_rows else 16, }); k.joined(entry.value_ptr); } @@ -195,7 +207,12 @@ pub const Kernels = struct { pub fn prepareDecode(k: *Kernels, p: projection.Linear) !void { if (p.runs.len > 0 or p.raw != null or p.tile != 32 or k.prompt) return; // decoded rows never take the long key (longKey needs prompt rows) - _ = try k.laneEntry(p, p.slices, 0, .{ 0, 0 }, false); + if (p.plain and qk_rows) { + if (k.qks == null) k.qks = qk.Pipelines.init(k.allocator, k.device); + for ([_]u32{ 8, 16 }) |block| _ = try k.qks.?.get(p.slices, block); + return; + } + _ = try k.laneEntry(p, p.slices, 0, .{ 0, 0 }, false, p.plain and p.reg_copy == null); } fn quantOne(k: *Kernels, input_encoder: mtl.ComputeEncoder, p: projection.Linear, x: Ref, xs: ?Sums, dims: Ref, y: Ref, rows: u32, skip: u32, cut: [2]u32) !void { @@ -262,14 +279,23 @@ pub const Kernels = struct { } const reg = p.bits == 4 and p.group == 64; if (!reg and (skip > 0 or cut[1] > 0)) return error.BadCoreProjectionRows; - const long = if (reg) longKey(k.long_prompt, k.prompt, rows) else k.long_prompt and k.prompt and rows > 16; - const sums: ?Sums = if (reg or (p.bits == 8 and p.group == 64)) xs else null; - const entry = try k.laneEntry(p, sk, skip, cut, long); + if (reg and p.plain and qk_rows and skip == 0 and cut[1] == 0) { + try k.quantQk(e, p, x, xs, y, rows, sk); + try span.end(); + return; + } + // A plain matrix off qk: tf_lane_reg on its reg copy when it has one, else the cooperative kernel. + const on_reg = reg and (!p.plain or p.reg_copy != null); + const words = if (p.plain) p.reg_copy orelse p.words else p.words; + // long key: reg rows past 128; 8-bit past 16 as whole-prompt row blocks; cooperative never + const long = if (on_reg) longKey(k.long_prompt, k.prompt, rows) else !reg and k.long_prompt and k.prompt and rows > 16; + const sums: ?Sums = if (on_reg or (p.bits == 8 and p.group == 64)) xs else null; + const entry = try k.laneEntry(p, sk, skip, cut, long, reg and !on_reg); const step = entry.value_ptr.max_rows; var first: u32 = 0; while (first < rows) : (first += step) { const xr = lane.Ref{ .buf = x.buffer, .off = x.offset + @as(usize, first) * p.k * 2 }; - const w = lane.Ref{ .buf = p.words.buffer, .off = p.words.offset }; + const w = lane.Ref{ .buf = words.buffer, .off = words.offset }; const sb = lane.Ref{ .buf = p.pairs.buffer, .off = p.pairs.offset }; const yr = lane.Ref{ .buf = y.buffer, .off = y.offset + @as(usize, first) * p.n * @as(usize, if (cut[1] > 0) 4 else 2) }; if (sums) |s| try entry.value_ptr.encodeSums(e, xr, w, sb, .{ .ref = .{ .buf = s.ref.buffer, .off = s.ref.offset + @as(usize, first) * 4 }, .stride = s.stride }, yr, @min(rows - first, step)) else try entry.value_ptr.encode(e, xr, w, sb, yr, @min(rows - first, step)); @@ -277,6 +303,23 @@ pub const Kernels = struct { try span.end(); } + /// qk on a plain matrix, 128 rows a dispatch, on the producer's group sums or else the reg entry's tf_lane_sums. + fn quantQk(k: *Kernels, e: mtl.ComputeEncoder, p: projection.Linear, x: Ref, xs: ?Sums, y: Ref, rows: u32, sk: u32) !void { + if (k.qks == null) k.qks = qk.Pipelines.init(k.allocator, k.device); + const own = if (xs == null) try k.laneEntry(p, sk, 0, .{ 0, 0 }, false, false) else null; + const w = lane.Ref{ .buf = p.words.buffer, .off = p.words.offset }; + const sb = lane.Ref{ .buf = p.pairs.buffer, .off = p.pairs.offset }; + var first: u32 = 0; + while (first < rows) : (first += lane.reg_rows) { + const take = @min(rows - first, lane.reg_rows); + const xr = lane.Ref{ .buf = x.buffer, .off = x.offset + @as(usize, first) * p.k * 2 }; + const yr = lane.Ref{ .buf = y.buffer, .off = y.offset + @as(usize, first) * p.n * 2 }; + const sums: lane.Sums = if (xs) |s| .{ .ref = .{ .buf = s.ref.buffer, .off = s.ref.offset + @as(usize, first) * 4 }, .stride = s.stride } else try own.?.value_ptr.encodeOwnSums(e, xr, take); + try k.qks.?.encode(e, p.n, p.k, sk, xr, w, sb, sums, yr, take); + if (xs == null) e.barrier(); + } + } + /// A mixed stack: each member its own product into its columns; row kernels write the fused rows at a stride. fn quantRuns(k: *Kernels, input_encoder: mtl.ComputeEncoder, p: projection.Linear, x: Ref, xs: ?Sums, dims: Ref, y: Ref, rows: u32, skip: u32, cut: [2]u32) !void { if (skip > 0 or cut[1] > 0 or rows == 0) return error.BadCoreProjectionRows; @@ -488,6 +531,17 @@ pub const Kernels = struct { const e = span.encoder; const xs_on = k.device.tensorUnits(); + if (@import("core_delta").flat_glue) { + const pipeline = try k.get(.{ .kind = .mlp_rows, .k = width, .n = width, .xs = xs_on }); + if (pipeline.maxThreads() >= 256) { + e.setPipeline(pipeline); + bind(e, .{ gate, up, dims, out, xs }); + e.setValue(width, 5); + e.dispatchGroups(mtl.Size.of(width / 64, padded(rows) / 16, 1), mtl.Size.of(256, 1, 1)); + try span.end(); + return; + } + } e.setPipeline(try k.get(.{ .kind = .mlp, .k = width, .n = width, .xs = xs_on })); bind(e, .{ gate, up, dims, out, xs }); e.dispatchGroups(mtl.Size.of(width / 64, if (xs_on) padded(rows) else rows, 1), mtl.Size.of(64, 1, 1)); @@ -516,7 +570,7 @@ pub fn specializedSource(a: std.mem.Allocator, key: Key) ![]u8 { .xsum => sources.xsum, .norm => sources.norm_xs, .input_norm => sources.norm_input, - .mlp => sources.mlp_xs, + .mlp, .mlp_rows => sources.mlp_xs, .ane_input, .mlp_ane, .add_ane => sources.mlp_ane, }; const mark = std.mem.indexOf(u8, template, "Q27_SPECIALIZE") orelse return error.BadKernelSource; @@ -524,7 +578,7 @@ pub fn specializedSource(a: std.mem.Allocator, key: Key) ![]u8 { .projection => unreachable, .xsum => try std.fmt.allocPrint(a, "constexpr int K={d}, GS=64;", .{key.k}), .norm, .input_norm => try std.fmt.allocPrint(a, "constexpr int K={d};", .{key.k}), - .mlp => try std.fmt.allocPrint(a, "constexpr int N={d};", .{key.n}), + .mlp, .mlp_rows => try std.fmt.allocPrint(a, "constexpr int N={d};", .{key.n}), .ane_input, .mlp_ane, .add_ane => try std.fmt.allocPrint(a, "constant constexpr int H={d}, N={d}, A={d};", .{ key.k, key.n, key.tile }), }; defer a.free(definitions); diff --git a/zig/src/families/qwen27/round_fingerprint.zig b/zig/src/families/qwen27/round_fingerprint.zig new file mode 100644 index 00000000000..25bbdd0c784 --- /dev/null +++ b/zig/src/families/qwen27/round_fingerprint.zig @@ -0,0 +1,21 @@ +//! The byte identity of a queued Qwen27 round. +const std = @import("std"); +const Round = @import("round_plan.zig").Round; + +pub fn fingerprint(round: *const Round) [32]u8 { + var hash = std.crypto.hash.sha2.Sha256.init(.{}); + hash.update(std.mem.sliceAsBytes(round.ids)); + hash.update(std.mem.sliceAsBytes(round.slots)); + hash.update(std.mem.sliceAsBytes(round.feed_positions)); + hash.update(std.mem.sliceAsBytes(round.draw_positions)); + hash.update(std.mem.sliceAsBytes(round.firsts)); + for (round.windows) |window| { + hash.update(std.mem.asBytes(&window.start)); + hash.update(std.mem.asBytes(&window.taps)); + hash.update(std.mem.sliceAsBytes(window.parents)); + hash.update(std.mem.sliceAsBytes(window.conv)); + } + var out: [32]u8 = undefined; + hash.final(&out); + return out; +} diff --git a/zig/src/families/qwen3_5/backend.zig b/zig/src/families/qwen3_5/backend.zig index 1236bebc1ce..6ffe0fedd3c 100644 --- a/zig/src/families/qwen3_5/backend.zig +++ b/zig/src/families/qwen3_5/backend.zig @@ -253,4 +253,5 @@ pub const draw = draws.draw; test { _ = draws; + _ = @import("model.zig"); } diff --git a/zig/src/families/qwen3_5/backend/hip/engine/native.zig b/zig/src/families/qwen3_5/backend/hip/engine/native.zig index 9b3467cfd59..d9d1d32f8fc 100644 --- a/zig/src/families/qwen3_5/backend/hip/engine/native.zig +++ b/zig/src/families/qwen3_5/backend/hip/engine/native.zig @@ -171,10 +171,7 @@ fn prepare( a, problem, "{s}", - .{try hip.admission.badSetting(a, if (err == error.BadReserve) error.BadReserve else error.BadLimit, .{ - .reserve = @import("sys").getenv("TENSORFOLD_MEMORY_RESERVE_GIB"), - .limit = @import("sys").getenv("TENSORFOLD_HIP_MEMORY_LIMIT_GB"), - })}, + .{try hip.admission.badSetting(a, if (err == error.BadReserve) error.BadReserve else error.BadLimit, hip.admission.envTexts())}, ), error.HostMemoryUnavailable => steps.refuseAll( a, diff --git a/zig/src/families/qwen3_5/cuda_cache.zig b/zig/src/families/qwen3_5/cuda_cache.zig index 7c3c98e1762..1675ac8aa5e 100644 --- a/zig/src/families/qwen3_5/cuda_cache.zig +++ b/zig/src/families/qwen3_5/cuda_cache.zig @@ -3,6 +3,7 @@ const std = @import("std"); const cuda = @import("cuda"); const geometry = @import("cuda_geometry.zig"); const engine = @import("cuda_engine.zig"); +const platform = @import("sys"); const Engine = engine.Engine; const DeviceBuffer = cuda.DeviceBuffer; @@ -21,7 +22,7 @@ pub fn keepLate() bool { var on: ?bool = null; }; if (S.on) |v| return v; - const v = if (std.c.getenv("TF_QWEN_KEEP_LATE")) |x| std.mem.eql(u8, std.mem.span(x), "1") else false; + const v = platform.environment.read(bool, "TF_QWEN_KEEP_LATE", false) catch false; S.on = v; return v; } @@ -71,16 +72,20 @@ pub const Paged = struct { /// TF_QWEN_KV_PAGE_TEST=n: each cache's own buffer read through a table of n-position pages in reverse order (checks). pub fn pageTest() !usize { - const v = std.c.getenv("TF_QWEN_KV_PAGE_TEST") orelse return 0; - return parsePageTest(std.mem.span(v)); + const n = try platform.environment.read(u64, "TF_QWEN_KV_PAGE_TEST", 0); + return if (n == 0) 0 else parsePageTestValue(n); } -pub fn parsePageTest(v: []const u8) !usize { - const n = std.fmt.parseInt(usize, v, 10) catch return error.BadQwenPageTest; +pub fn parsePageTestValue(n: usize) !usize { if (!validPageTokens(n)) return error.BadQwenPageTest; return n; } +pub fn parsePageTest(v: []const u8) !usize { + const n = std.fmt.parseInt(usize, v, 10) catch return error.BadQwenPageTest; + return parsePageTestValue(n); +} + pub fn validPageTokens(n: usize) bool { return n > 0 and n <= std.math.maxInt(c_int); } @@ -413,6 +418,14 @@ fn freePaged(gpa: std.mem.Allocator, p: *Paged) void { if (p.own_ids) gpa.free(p.ids); } +test "TF_QWEN_KEEP_LATE and TF_QWEN_KV_PAGE_TEST: the platform parses unset, valid and malformed text" { + try std.testing.expectEqual(@as(?u64, null), try platform.environment.parse("TF_QWEN_KEEP_LATE", null)); + try std.testing.expectEqual(@as(?u64, 1), try platform.environment.parse("TF_QWEN_KEEP_LATE", "1")); + try std.testing.expectError(error.InvalidEnvironment, platform.environment.parse("TF_QWEN_KEEP_LATE", "on")); + try std.testing.expectEqual(@as(?u64, 512), try platform.environment.parse("TF_QWEN_KV_PAGE_TEST", "512")); + try std.testing.expectError(error.InvalidEnvironment, platform.environment.parse("TF_QWEN_KV_PAGE_TEST", "0")); +} + test "KV page dimensions: diagnostic rows fit the signed kernel argument" { try std.testing.expectEqual(@as(usize, 48), try parsePageTest("48")); try std.testing.expectError(error.BadQwenPageTest, parsePageTest("0")); diff --git a/zig/src/families/qwen3_5/cuda_cost_adapter.zig b/zig/src/families/qwen3_5/cuda_cost_adapter.zig index e2f1796d4a7..11b766fb1a6 100644 --- a/zig/src/families/qwen3_5/cuda_cost_adapter.zig +++ b/zig/src/families/qwen3_5/cuda_cost_adapter.zig @@ -5,6 +5,7 @@ const E = @import("cuda_engine.zig"); const warm = @import("cuda_warm.zig"); const profile = @import("cuda_startup_profile.zig"); const costs = @import("cuda_window_costs.zig"); +const platform = @import("sys"); pub const file_identity = @import("cuda_cost_identity.zig"); pub const Kind = enum { dflash, mtp }; @@ -38,7 +39,7 @@ pub fn identity(l: anytype, d: anytype, reserved: ?*E.Cache) !costs.Keys { const checkpoint = std.fmt.bytesToHex(stamp, .lower); const target_hex = std.fmt.bytesToHex(target, .lower); const parts = [_][]const u8{ "qwen35-cuda/wall-chain-greedy-v2", gpu, release, geometry, policy, taps, @tagName(l.cost_kind), draft, facts, &checkpoint, &target_hex }; - const trace = if (@import("sys").getenv("TF_COST_KEY_TRACE")) |v| std.mem.eql(u8, v, "1") else false; + const trace = try platform.environment.read(bool, "TF_COST_KEY_TRACE", false); if (trace) { const names = [_][]const u8{ "profile", "gpu", "driver", "geometry", "policy", "target-taps", "draft-kind", "draft-config", "draft-facts", "draft-checkpoint", "target-checkpoint" }; for (names, parts) |name_, bytes| tracePart(name_, bytes); @@ -150,3 +151,9 @@ fn tracePart(name: []const u8, bytes: []const u8) void { const hex = std.fmt.bytesToHex(digest, .lower); std.log.info("window cost key part {s} {s}", .{ name, hex[0..12] }); } + +test "TF_COST_KEY_TRACE: the platform parses unset, valid and malformed text" { + try std.testing.expectEqual(@as(?u64, null), try platform.environment.parse("TF_COST_KEY_TRACE", null)); + try std.testing.expectEqual(@as(?u64, 1), try platform.environment.parse("TF_COST_KEY_TRACE", "1")); + try std.testing.expectError(error.InvalidEnvironment, platform.environment.parse("TF_COST_KEY_TRACE", "on")); +} diff --git a/zig/src/families/qwen3_5/cuda_draft.zig b/zig/src/families/qwen3_5/cuda_draft.zig index 5c9d057ab8d..b7f77b8a4f4 100644 --- a/zig/src/families/qwen3_5/cuda_draft.zig +++ b/zig/src/families/qwen3_5/cuda_draft.zig @@ -172,7 +172,7 @@ pub const Draft = struct { /// The target's measured window cost, published after the complete reset-cache width sweep. pub fn setCost(d: *Draft, rows: u32, ms: f64) void { - if (platform.c.getenv("TF_TIMING") != null) std.debug.print("[timing] window {d} rows {d:.2} ms (a hold level {d:.2})\n", .{ rows, ms, d.step_ms }); + if (platform.environment.read(bool, "TF_TIMING", false) catch false) std.debug.print("[timing] window {d} rows {d:.2} ms (a hold level {d:.2})\n", .{ rows, ms, d.step_ms }); if (d.n_costs < d.costs.len) { d.costs[d.n_costs] = .{ .width = rows, .ms = ms }; d.n_costs += 1; @@ -440,7 +440,7 @@ pub const Draft = struct { fn factsFn(p: *anyopaque) dr.Facts { const d = cast(p); // TF_NO_TREES=1: chains only (for comparing) - return .{ .fixed_block = d.c.kind == .dflash2, .depth = @intCast(d.c.block - 1), .step_ms = d.step_ms, .prior = &draft_prior.prior, .plain_guard = true, .batched = true, .stream_bytes = d.c.ringBytes() + d.target_taps + d.scratch_one, .trees = platform.c.getenv("TF_NO_TREES") == null, .window_costs = d.costs[0..d.n_costs], .lane_costs = d.costs[0..d.n_costs], .copy_match = factsCopyMatch(d), .tree_nodes = @intCast(if (d.c.block == 16) d.tree_nodes else 0) }; + return .{ .fixed_block = d.c.kind == .dflash2, .depth = @intCast(d.c.block - 1), .step_ms = d.step_ms, .prior = &draft_prior.prior, .plain_guard = true, .batched = true, .stream_bytes = d.c.ringBytes() + d.target_taps + d.scratch_one, .trees = !(platform.environment.read(bool, "TF_NO_TREES", false) catch false), .window_costs = d.costs[0..d.n_costs], .lane_costs = d.costs[0..d.n_costs], .copy_match = factsCopyMatch(d), .tree_nodes = @intCast(if (d.c.block == 16) d.tree_nodes else 0) }; } fn openFn(p: *anyopaque, s: *Stream) anyerror!void { @@ -549,7 +549,7 @@ pub fn factsCopyMatch(d: anytype) i64 { /// TF_TIMING=1: each call's wall time on stderr. pub fn timing(what: []const u8, io: std.Io, t0: std.Io.Timestamp) void { - if (platform.c.getenv("TF_TIMING") == null) return; + if (!(platform.environment.read(bool, "TF_TIMING", false) catch false)) return; const now = std.Io.Clock.awake.now(io); const ns: f64 = @floatFromInt(t0.durationTo(now).toNanoseconds()); const at: f64 = @floatFromInt(@mod(now.toNanoseconds(), 1_000_000_000_000)); @@ -591,3 +591,9 @@ test "a drafter config with a zero divisor is refused, and any admitted rank's s const c = try Config.parse(gpa, wide, target); try std.testing.expect(Draft.stagedLen(c.rank) >= Draft.hp_at + (c.block - 1) * c.rank * 2); } + +test "TF_TIMING: the platform parses unset, valid and malformed text" { + try std.testing.expectEqual(@as(?u64, null), try platform.environment.parse("TF_TIMING", null)); + try std.testing.expectEqual(@as(?u64, 1), try platform.environment.parse("TF_TIMING", "1")); + try std.testing.expectError(error.InvalidEnvironment, platform.environment.parse("TF_TIMING", "on")); +} diff --git a/zig/src/families/qwen3_5/cuda_draft_tree.zig b/zig/src/families/qwen3_5/cuda_draft_tree.zig index 0475cca0ae5..e5897d2c221 100644 --- a/zig/src/families/qwen3_5/cuda_draft_tree.zig +++ b/zig/src/families/qwen3_5/cuda_draft_tree.zig @@ -11,10 +11,16 @@ pub const lanesOf = walker.lanesOf; /// A grown tree's nodes at most: walker.nodes under the engine's window, 0 under TF_NO_TREES. pub fn nodes() !usize { - return walker.nodes(engine.most_window, platform.c.getenv("TF_NO_TREES") != null); + return walker.nodes(engine.most_window, try platform.environment.read(bool, "TF_NO_TREES", false)); } /// walker.grow under the engine's window. pub fn grow(c: Candidates, pending: u32, rows: usize, most: usize, tokens: []u32, parents: []i32, own: []f64) usize { return walker.grow(engine.most_window, c, pending, rows, most, tokens, parents, own); } + +test "TF_NO_TREES: the platform parses unset, valid and malformed text" { + try @import("std").testing.expectEqual(@as(?u64, null), try platform.environment.parse("TF_NO_TREES", null)); + try @import("std").testing.expectEqual(@as(?u64, 1), try platform.environment.parse("TF_NO_TREES", "1")); + try @import("std").testing.expectError(error.InvalidEnvironment, platform.environment.parse("TF_NO_TREES", "on")); +} diff --git a/zig/src/families/qwen3_5/cuda_mtp.zig b/zig/src/families/qwen3_5/cuda_mtp.zig index 7be3a015faa..6aa5907b493 100644 --- a/zig/src/families/qwen3_5/cuda_mtp.zig +++ b/zig/src/families/qwen3_5/cuda_mtp.zig @@ -118,10 +118,10 @@ pub const Mtp = struct { if (!e.g.moe()) return error.NotRouted; const d = try gpa.create(Mtp); errdefer gpa.destroy(d); - d.* = .{ .gpa = gpa, .io = io, .e = e, .w = undefined, .mod = undefined, .dmod = undefined, .fns = undefined, .ring_fns = undefined, .scratch = undefined, .capacity = capacity, .depth = default_depth, .trees = platform.c.getenv("TF_MTP_TREES") != null, .tap = .{@intCast(e.g.layers - 1)}, .taps_in = 0, .hin = 0, .hn = 0, .emb = 0, .en = 0, .h = 0, .r = 0, .x = 0, .qraw = 0, .q = 0, .kraw = 0, .kb = 0, .vb = 0, .att = 0, .xs = 0, .logits = 0, .words = 0, .picks = 0, .lane_state = 0, .lane_k = 0, .lane_v = 0, .anc = 0, .ids = 0, .tok = 0, .staged = undefined, .tab = 0 }; + d.* = .{ .gpa = gpa, .io = io, .e = e, .w = undefined, .mod = undefined, .dmod = undefined, .fns = undefined, .ring_fns = undefined, .scratch = undefined, .capacity = capacity, .depth = default_depth, .trees = try platform.environment.read(bool, "TF_MTP_TREES", false), .tap = .{@intCast(e.g.layers - 1)}, .taps_in = 0, .hin = 0, .hn = 0, .emb = 0, .en = 0, .h = 0, .r = 0, .x = 0, .qraw = 0, .q = 0, .kraw = 0, .kb = 0, .vb = 0, .att = 0, .xs = 0, .logits = 0, .words = 0, .picks = 0, .lane_state = 0, .lane_k = 0, .lane_v = 0, .anc = 0, .ids = 0, .tok = 0, .staged = undefined, .tab = 0 }; d.depth = try platform.environment.read(u32, "TF_MTP_DRAFTS", default_depth); d.depth = @min(@max(d.depth, 1), most_window - 1); - if (platform.c.getenv("TF_MTP_BATCH")) |v| d.batch = !std.mem.eql(u8, std.mem.span(v), "0"); + d.batch = try platform.environment.read(bool, "TF_MTP_BATCH", true); d.mod = try cuda.Module.load(e.d, cuda.kernels.qwen36_mtp); errdefer d.mod.unload(); d.dmod = try cuda.Module.load(e.d, cuda.kernels.qwen35_draft); @@ -160,7 +160,7 @@ pub const Mtp = struct { } pub fn setCost(d: *Mtp, rows: u32, ms: f64) void { - if (platform.c.getenv("TF_TIMING") != null) std.debug.print("[timing] window {d} rows {d:.2} ms (a draft level {d:.2})\n", .{ rows, ms, d.step_ms }); + if (platform.environment.read(bool, "TF_TIMING", false) catch false) std.debug.print("[timing] window {d} rows {d:.2} ms (a draft level {d:.2})\n", .{ rows, ms, d.step_ms }); if (d.n_costs < d.costs.len) { d.costs[d.n_costs] = .{ .width = rows, .ms = ms }; d.n_costs += 1; @@ -474,7 +474,7 @@ pub const Mtp = struct { }; } ctx.held_n = n; - if (platform.c.getenv("TF_TIMING") != null) std.debug.print("[timing] lanes {d} levels {d}\n", .{ n, l.levels() }); + if (platform.environment.read(bool, "TF_TIMING", false) catch false) std.debug.print("[timing] lanes {d} levels {d}\n", .{ n, l.levels() }); } // the Drafter contract @@ -562,3 +562,9 @@ pub const Mtp = struct { /// Acceptance by depth until a stream has its own (the frozen engine's chains kept about three of four). const prior = [_]f64{ 0.7, 0.55, 0.45, 0.4, 0.35, 0.3, 0.3 }; + +test "TF_MTP_TREES: the platform parses unset, valid and malformed text" { + try std.testing.expectEqual(@as(?u64, null), try platform.environment.parse("TF_MTP_TREES", null)); + try std.testing.expectEqual(@as(?u64, 1), try platform.environment.parse("TF_MTP_TREES", "1")); + try std.testing.expectError(error.InvalidEnvironment, platform.environment.parse("TF_MTP_TREES", "on")); +} diff --git a/zig/src/families/qwen3_5/cuda_pages.zig b/zig/src/families/qwen3_5/cuda_pages.zig index cc50afddd88..100ccd0557c 100644 --- a/zig/src/families/qwen3_5/cuda_pages.zig +++ b/zig/src/families/qwen3_5/cuda_pages.zig @@ -4,6 +4,7 @@ const cuda = @import("cuda"); const kv = @import("core").kv_pool; const engine = @import("cuda_engine.zig"); const caches = @import("cuda_cache.zig"); +const platform = @import("sys"); const Engine = engine.Engine; const Cache = caches.Cache; @@ -193,8 +194,7 @@ pub const Pages = struct { /// TF_QWEN_POOL_LOG=1: the pool's census after a prompt pass (the agent replay's memory readings). pub fn log(p: *const Pages, prompt: usize, cached: usize) void { - const v = std.c.getenv("TF_QWEN_POOL_LOG") orelse return; - if (!std.mem.eql(u8, std.mem.span(v), "1")) return; + if (!(platform.environment.read(bool, "TF_QWEN_POOL_LOG", false) catch false)) return; const n = p.pool.census(); std.log.info("qwen3_5 pool after a prompt of {d} (resumed at {d}): {d} pages leased, {d} held by the prompt cache, {d} free of {d}", .{ prompt, cached, n.leased, n.kept, n.free, n.total }); } @@ -277,3 +277,9 @@ test "Qwen pages default: TF_QWEN_KV_PAGES_ALL unset keeps the engine's stream a try std.testing.expect(pagedOnlyOf("1")); for ([_][]const u8{ "0", "", "true", "01", " 1 " }) |v| try std.testing.expect(!pagedOnlyOf(v)); } + +test "TF_QWEN_POOL_LOG: the platform parses unset, valid and malformed text" { + try std.testing.expectEqual(@as(?u64, null), try platform.environment.parse("TF_QWEN_POOL_LOG", null)); + try std.testing.expectEqual(@as(?u64, 1), try platform.environment.parse("TF_QWEN_POOL_LOG", "1")); + try std.testing.expectError(error.InvalidEnvironment, platform.environment.parse("TF_QWEN_POOL_LOG", "on")); +} diff --git a/zig/src/families/qwen3_5/cuda_pocket.zig b/zig/src/families/qwen3_5/cuda_pocket.zig index e52074f4f71..5fc87cc2515 100644 --- a/zig/src/families/qwen3_5/cuda_pocket.zig +++ b/zig/src/families/qwen3_5/cuda_pocket.zig @@ -2,6 +2,7 @@ const std = @import("std"); const cuda = @import("cuda"); const to = @import("cuda_train_ops.zig"); +const platform = @import("sys"); /// A layer's neurons on the device: fp32 [cap, hidden] gate rows, up rows and outputs; the first `used` live. pub const Rows = struct { gate: cuda.DeviceBuffer, up: cuda.DeviceBuffer, down: cuda.DeviceBuffer, cap: usize, used: usize = 0 }; @@ -117,10 +118,10 @@ pub const Pockets = struct { var learned: usize = 0; var off: std.ArrayList([2]usize) = .empty; defer off.deinit(p.gpa); - if (@import("sys").c.getenv("TF_Q27_POCKET_OFF")) |list| { - const all = std.mem.eql(u8, std.mem.span(list), "all"); + if (try platform.environment.path("TF_Q27_POCKET_OFF", platform.environment.Process.get(.{}, "TF_Q27_POCKET_OFF"))) |list| { + const all = std.mem.eql(u8, list, "all"); if (all) for (host, 0..) |slot, l| if (slot) |h| for (0..h.n) |j| try off.append(p.gpa, .{ l, j }); - var it = std.mem.tokenizeAny(u8, if (all) "" else std.mem.span(list), ", "); + var it = std.mem.tokenizeAny(u8, if (all) "" else list, ", "); while (it.next()) |pair| { const c = std.mem.indexOfScalar(u8, pair, ':') orelse return error.UnexpectedTensor; try off.append(p.gpa, .{ try std.fmt.parseInt(usize, pair[0..c], 10), try std.fmt.parseInt(usize, pair[c + 1 ..], 10) }); @@ -209,3 +210,10 @@ fn staged(d: *const cuda.Driver, values: []const f32) !cuda.DeviceBuffer { try d.check(d.api.cuMemcpyHtoD_v2(out.ptr, host.bytes.ptr, bytes.len), "pocket staged upload"); return out; } + +test "TF_Q27_POCKET_OFF: the platform parses unset, valid and malformed text" { + try std.testing.expectEqual(@as(?u64, null), try platform.environment.parse("TF_Q27_POCKET_OFF", null)); + try std.testing.expectEqual(@as(u64, 0), (try platform.environment.parse("TF_Q27_POCKET_OFF", "all")).?); + try std.testing.expectEqual(@as(u64, 0), (try platform.environment.parse("TF_Q27_POCKET_OFF", "1:2")).?); + try std.testing.expectError(error.InvalidEnvironment, platform.environment.parse("TF_Q27_POCKET_OFF", "no\ncontrol")); +} diff --git a/zig/src/families/qwen3_5/cuda_round_timing.zig b/zig/src/families/qwen3_5/cuda_round_timing.zig index 05fe0226236..8354515bdc9 100644 --- a/zig/src/families/qwen3_5/cuda_round_timing.zig +++ b/zig/src/families/qwen3_5/cuda_round_timing.zig @@ -1,6 +1,7 @@ //! Enabled-only numeric frame receipts join actual CUDA forward buckets to the shared core's accepted paths. const std = @import("std"); const be = @import("lanes").backend; +const platform = @import("sys"); pub const Shape = @import("cuda_shapes.zig").Shape; pub const Trace = struct { const Frame = struct { first: usize, windows: usize, offered: usize, bucket: usize, ms: f64 }; @@ -8,7 +9,7 @@ pub const Trace = struct { len: usize = 0, pub fn enabled() bool { - return std.c.getenv("TF_TIMING") != null; + return platform.environment.read(bool, "TF_TIMING", false) catch false; } pub fn create(a: std.mem.Allocator, on: bool) !?*Trace { diff --git a/zig/src/families/qwen3_5/cuda_train.zig b/zig/src/families/qwen3_5/cuda_train.zig index 8844e195865..66efea9e84c 100644 --- a/zig/src/families/qwen3_5/cuda_train.zig +++ b/zig/src/families/qwen3_5/cuda_train.zig @@ -1,5 +1,6 @@ //! The 27B's Living Weights trainer: packed passes through Forward.chunks and the loss back to the lowest nudged layer. const std = @import("std"); +const platform = @import("sys"); const cuda = @import("cuda"); const core = @import("core"); const living = @import("living"); @@ -247,7 +248,7 @@ pub const Trainer = struct { /// The rows the backward still needs, each nudged sequence's from its first nudged row on (null: every row). fn tailRows(t: *Trainer, rows: usize) ?to.Tail { if (!t.k.wide) return null; - if (@import("sys").c.getenv("TF_Q27_TAIL")) |v| if (std.mem.eql(u8, std.mem.span(v), "off")) return null; + if ((platform.environment.read(u64, "TF_Q27_TAIL", 1) catch 1) == 0) return null; const list = t.tails.slice(i32, pack_rows); const mask = t.tails.host.bytes[pack_rows * 4 ..][0..pack_rows]; @memset(mask[0..rows], 0); @@ -564,3 +565,9 @@ test "Save recovery: dense constructor pending work drains or exits before any o if (!cuda.kernels.available) return error.SkipZigTest; try @import("cuda_train_init_test.zig").pendingFailure(Trainer.initWithWeights); } + +test "TF_Q27_TAIL: the platform parses unset, valid and malformed text" { + try std.testing.expectEqual(@as(?u64, null), try platform.environment.parse("TF_Q27_TAIL", null)); + try std.testing.expectEqual(@as(?u64, 0), try platform.environment.parse("TF_Q27_TAIL", "off")); + try std.testing.expectError(error.InvalidEnvironment, platform.environment.parse("TF_Q27_TAIL", "on")); +} diff --git a/zig/src/families/qwen3_5/cuda_train_ops.zig b/zig/src/families/qwen3_5/cuda_train_ops.zig index 1dc9d43ec9b..f56479d35d9 100644 --- a/zig/src/families/qwen3_5/cuda_train_ops.zig +++ b/zig/src/families/qwen3_5/cuda_train_ops.zig @@ -1,6 +1,7 @@ //! The 27B's input gradients for Living Weights as calls on one stream. const std = @import("std"); const cuda = @import("cuda"); +const platform = @import("sys"); /// A 4-bit matrix [n, k] in MLX's layout: words [n, k / 8], bf16 scales and biases [n, k / group]. pub const Q4 = struct { w: u64, s: u64, b: u64, n: usize, k: usize, group: usize = 64 }; @@ -51,7 +52,7 @@ pub const Kernels = struct { pub fn load(d: *const cuda.Driver) !Kernels { if (!cuda.kernels.available) return error.BuiltWithoutKernels; - const narrow = if (@import("sys").c.getenv("TF_Q27_GEMM")) |v| std.mem.eql(u8, std.mem.span(v), "narrow") else false; + const narrow = (try platform.environment.read(?u64, "TF_Q27_GEMM", null)) != null; var k: Kernels = .{ .own = try cuda.Module.load(d, cuda.kernels.qwen27_train), .attn = undefined, .train = undefined, .fo = undefined, .fa = undefined, .ft = undefined, .wide = !narrow }; errdefer k.own.unload(); k.attn = try cuda.Module.load(d, cuda.kernels.attn_train); @@ -418,3 +419,11 @@ test "splits stay within the K rows and fill small products" { try std.testing.expect(splitsFor(16, 5120, 248320) > 1); try std.testing.expectEqual(@as(usize, 1), splitsFor(16, 5120, 512)); } + +test "TF_Q27_GEMM: the platform parses unset, valid and malformed text" { + try std.testing.expectEqual(@as(?u64, null), try platform.environment.parse("TF_Q27_GEMM", null)); + try std.testing.expectEqual(@as(?u64, 0), try platform.environment.parse("TF_Q27_GEMM", "narrow")); + try std.testing.expectEqual(@as(?u64, null), try platform.environment.value(?u64, "TF_Q27_GEMM", null, null)); + try std.testing.expect((try platform.environment.value(?u64, "TF_Q27_GEMM", "narrow", null)) != null); + try std.testing.expectError(error.InvalidEnvironment, platform.environment.parse("TF_Q27_GEMM", "wide")); +} diff --git a/zig/src/families/qwen3_5/model.zig b/zig/src/families/qwen3_5/model.zig index 4dee28f796a..2062429e32c 100644 --- a/zig/src/families/qwen3_5/model.zig +++ b/zig/src/families/qwen3_5/model.zig @@ -7,6 +7,11 @@ const shards = @import("../../core/checkpoint.zig"); const weights = @import("weights.zig"); const kernels = @import("kernels.zig"); +/// The language model's tensors pack into their own buffer, not the file span between them that holds the vision tower. +fn never(_: []const u8, _: usize) bool { + return false; +} + pub const Model = struct { gpa: std.mem.Allocator, device: mtl.Device, @@ -30,7 +35,7 @@ pub const Model = struct { errdefer m.checkpoint.deinit(); const files = try shards.shardFiles(gpa, io, dir); defer shards.freeShardFiles(gpa, files); - for (files) |path| try m.checkpoint.addFileSelected(m.device, path, "", "language_model."); + for (files) |path| try m.checkpoint.addFileSplit(m.device, path, "", "language_model.", never); m.weights = try weights.load(&m.checkpoint, config.tied); m.kernels = try kernels.load(m.device); return m; @@ -44,3 +49,36 @@ pub const Model = struct { m.gpa.destroy(m); } }; + +test "the language model's tensors are held without the vision tower stored between them" { + if (comptime !@hasDecl(mtl.Device, "init")) return error.SkipZigTest; + const device = mtl.Device.init() catch return error.SkipZigTest; + defer device.deinit(); + const gpa = std.testing.allocator; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + // the order a Qwen3.5 checkpoint stores: a language-model tensor, the vision tower, then the next one + const header = + \\{"language_model.a":{"dtype":"BF16","shape":[2],"data_offsets":[0,4]}, + \\ "vision_tower.x":{"dtype":"U8","shape":[4096],"data_offsets":[4,4100]}, + \\ "language_model.b":{"dtype":"BF16","shape":[3],"data_offsets":[4100,4106]}} + ; + var data: [8 + header.len + 4106]u8 = undefined; + std.mem.writeInt(u64, data[0..8], header.len, .little); + @memcpy(data[8..][0..header.len], header); + for (data[8 + header.len ..], 0..) |*b, i| b.* = @truncate(i); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "model.safetensors", .data = &data }); + const path = try std.fmt.allocPrintSentinel(gpa, ".zig-cache/tmp/{s}/model.safetensors", .{tmp.sub_path}, 0); + defer gpa.free(path); + var span = ckpt.Checkpoint.init(gpa); + defer span.deinit(); + try span.addFileSelected(device, path, "", "language_model."); + try std.testing.expectEqual(@as(usize, 4106), span.residentBytes()); + var packed_ = ckpt.Checkpoint.init(gpa); + defer packed_.deinit(); + try packed_.addFileSplit(device, path, "", "language_model.", never); + try std.testing.expectEqual(@as(usize, ckpt.alignment + 6), packed_.residentBytes()); + try std.testing.expect(!packed_.has("vision_tower.x")); + inline for (.{ "language_model.a", "language_model.b" }) |name| + try std.testing.expectEqualSlices(u16, (try span.get(name)).host(u16), (try packed_.get(name)).host(u16)); +} diff --git a/zig/src/hip/admission.zig b/zig/src/hip/admission.zig index e3a0946d4bb..dd612d46e85 100644 --- a/zig/src/hip/admission.zig +++ b/zig/src/hip/admission.zig @@ -55,10 +55,7 @@ pub fn budget(gpa: Allocator, io: std.Io, ctx: Context) !Pool { const integrated = (try ctx.attribute(.integrated)) != 0; const card = try ctx.memInfo(); const own: MemInfo = .{ .total = card.total, .available = card.free }; - const env: Env = .{ - .reserve = getenv("TENSORFOLD_MEMORY_RESERVE_GIB"), - .limit = getenv("TENSORFOLD_HIP_MEMORY_LIMIT_GB"), - }; + const env = envTexts(); if (windows) { // WDDM reports the whole budget through the driver: no host text, no dedicated-VRAM file. const p = try plan(false, own, null, null, env); @@ -79,6 +76,12 @@ pub const Source = enum { card, carve_out, host }; /// The reserve and cap variables' text, unset as null. pub const Env = struct { reserve: ?[]const u8 = null, limit: ?[]const u8 = null }; +/// The two settings' texts, registered in platform/environment.zig; `plan` refuses them against the runtime bounds. +pub fn envTexts() Env { + const e = @import("sys").environment; + return .{ .reserve = e.rawText("TENSORFOLD_MEMORY_RESERVE_GIB"), .limit = e.rawText("TENSORFOLD_HIP_MEMORY_LIMIT_GB") }; +} + pub const Plan = struct { pool: Pool, source: Source }; pub const PlanError = error{ HostMemoryUnavailable, BadReserve, BadLimit }; @@ -173,10 +176,6 @@ fn announce(p: Plan) void { std.log.info("HIP memory budget from {s}: {d:.1} of {d:.1} GiB free, {d:.1} GiB reserve", .{ what, f, t, r }); } -fn getenv(name: [:0]const u8) ?[]const u8 { - return std.mem.span(std.c.getenv(name) orelse return null); -} - /// A /proc file's text, streamed: procfs reports size 0, and a positional read (readFileAlloc) stops there. pub fn procText(a: Allocator, io: std.Io, path: []const u8) ?[]u8 { var file = std.Io.Dir.cwd().openFile(io, path, .{}) catch return null; @@ -253,3 +252,12 @@ test "a carve-out needs the card's total to be the dedicated VRAM: not past it, const shared = plan(true, .{ .total = 60 * g, .available = 59 * g }, big, g / 2, .{ .reserve = "1" }); try std.testing.expectError(error.BadReserve, shared); // shared memory keeps its floor of 2 } + +test "HIP memory settings: the platform parses unset, valid and malformed text" { + const e = @import("sys").environment; + for ([_][:0]const u8{ "TENSORFOLD_MEMORY_RESERVE_GIB", "TENSORFOLD_HIP_MEMORY_LIMIT_GB" }) |name| { + try std.testing.expectEqual(@as(f64, 7), try e.value(f64, name, null, 7)); + try std.testing.expectEqual(@as(f64, 2.5), try e.value(f64, name, "2.5", 7)); + try std.testing.expectError(error.InvalidEnvironment, e.check(name, "none")); + } +} diff --git a/zig/src/main.zig b/zig/src/main.zig index c02baa6f216..8f81487374c 100644 --- a/zig/src/main.zig +++ b/zig/src/main.zig @@ -276,6 +276,7 @@ pub fn main(init: std.process.Init) !void { const arena = init.arena.allocator(); const argv = try init.minimal.args.toSlice(arena); if (cluster.cli.wants(@ptrCast(argv[1..]))) std.process.exit(try cluster.cli.main(init, argv[1..])); + if (cluster.validate.wants(@ptrCast(argv[1..]))) std.process.exit(try cluster.validate.main(init, argv[1..])); if (checkpoint_cli.wants(@ptrCast(argv[1..]))) std.process.exit(try checkpoint_cli.main(init, argv[1..])); const o = try parseArgs(arena, argv); cli_chunks = o.chunks; diff --git a/zig/src/metal/command.zig b/zig/src/metal/command.zig index 769e0995674..937d0e7b79e 100644 --- a/zig/src/metal/command.zig +++ b/zig/src/metal/command.zig @@ -1,7 +1,8 @@ -//! Command queues, command buffers and compute encoders (serial or concurrent dispatch). +//! Command queues, command buffers and compute encoders (serial or concurrent dispatch), on Metal 3 or Metal 4. const std = @import("std"); const objc = @import("objc.zig"); const types = @import("types.zig"); +const metal4 = @import("metal4.zig"); const Buffer = @import("device.zig").Buffer; const Pipeline = @import("library.zig").Pipeline; const SharedEvent = @import("sync.zig").SharedEvent; @@ -14,6 +15,8 @@ const Size = types.Size; pub const Queue = struct { id: Id, + /// A Metal 4 context's queue: its command buffers come from the context, which owns them and the queue. + m4: ?*metal4.Context = null, pub fn deviceId(self: Queue) Id { return objc.msg(Id, self.id, "device", .{}); @@ -21,11 +24,13 @@ pub const Queue = struct { /// A command buffer that retains what it references (autoreleased: keep a pool around it). pub fn commandBuffer(self: Queue) CommandBuffer { + if (self.m4) |c| return c.commandBuffer(); return .{ .id = objc.msg(Id, self.id, "commandBuffer", .{}) }; } /// A command buffer that does not retain its resources: the caller keeps them alive until it completes. pub fn commandBufferUnretained(self: Queue) CommandBuffer { + if (self.m4) |c| return c.commandBuffer(); return .{ .id = objc.msg(Id, self.id, "commandBufferWithUnretainedReferences", .{}) }; } @@ -39,38 +44,46 @@ pub const Queue = struct { } pub fn deinit(self: Queue) void { - objc.release(self.id); + if (self.m4 == null) objc.release(self.id); } }; pub const CommandBuffer = struct { id: Id, + m4: ?*metal4.Context = null, + slot: u8 = 0, pub fn compute(self: CommandBuffer, dispatch: types.DispatchType) ComputeEncoder { + if (self.m4) |c| return .{ .id = c.encoder(self.id), .m4 = c, .serial = dispatch == .serial }; return .{ .id = objc.msg(Id, self.id, "computeCommandEncoderWithDispatchType:", .{@backingInt(dispatch)}) }; } /// A blit encoder on this buffer, for copies between buffers on the GPU. pub fn blit(self: CommandBuffer) BlitEncoder { + if (self.m4 != null) @panic("metal 4: no blit encoders; copies stay on Metal 3"); return .{ .id = objc.msg(Id, self.id, "blitCommandEncoder", .{}) }; } /// The GPU waits here until `event` reaches `value`. pub fn waitFor(self: CommandBuffer, event: SharedEvent, value: u64) void { + if (self.m4 != null) @panic("metal 4: events between command buffers stay on Metal 3"); objc.msg(void, self.id, "encodeWaitForEvent:value:", .{ event.id, value }); } /// The GPU sets `event` to `value` once the work before this point completes. pub fn signal(self: CommandBuffer, event: SharedEvent, value: u64) void { + if (self.m4 != null) @panic("metal 4: events between command buffers stay on Metal 3"); objc.msg(void, self.id, "encodeSignalEvent:value:", .{ event.id, value }); } /// waitFor and signal with a GPU-only event. pub fn waitForEvent(self: CommandBuffer, event: Event, value: u64) void { + if (self.m4 != null) @panic("metal 4: events between command buffers stay on Metal 3"); objc.msg(void, self.id, "encodeWaitForEvent:value:", .{ event.id, value }); } pub fn signalEvent(self: CommandBuffer, event: Event, value: u64) void { + if (self.m4 != null) @panic("metal 4: events between command buffers stay on Metal 3"); objc.msg(void, self.id, "encodeSignalEvent:value:", .{ event.id, value }); } @@ -80,22 +93,25 @@ pub const CommandBuffer = struct { pub fn commit(self: CommandBuffer) void { @import("pass_metrics.zig").commit(); + if (self.m4) |c| return c.commit(self.slot); objc.msg(void, self.id, "commit", .{}); } pub fn wait(self: CommandBuffer) void { const metrics = @import("pass_metrics.zig"); const start = metrics.time(); - objc.msg(void, self.id, "waitUntilCompleted", .{}); + if (self.m4) |c| c.wait(self.slot) else objc.msg(void, self.id, "waitUntilCompleted", .{}); if (start != 0) metrics.wait(start, self.gpuSeconds()); } pub fn status(self: CommandBuffer) types.CommandBufferStatus { + if (self.m4) |c| return c.status(self.slot); return @fromBackingInt(@intCast(objc.msg(usize, self.id, "status", .{}))); } /// The error text when the command buffer failed, else null. pub fn failure(self: CommandBuffer) ?[*:0]const u8 { + if (self.m4) |c| return c.failure(self.slot); if (self.status() != .@"error") return null; return objc.errorText(objc.msg(?Id, self.id, "error", .{})); } @@ -106,19 +122,23 @@ pub const CommandBuffer = struct { } pub fn gpuStart(self: CommandBuffer) f64 { + if (self.m4) |c| return c.start[self.slot]; return objc.msg(f64, self.id, "GPUStartTime", .{}); } pub fn gpuEnd(self: CommandBuffer) f64 { + if (self.m4) |c| return c.end[self.slot]; return objc.msg(f64, self.id, "GPUEndTime", .{}); } + /// A Metal 4 context owns its command buffers, so they need no retain. pub fn retain(self: CommandBuffer) CommandBuffer { + if (self.m4 != null) return self; return .{ .id = objc.retain(self.id) }; } pub fn release(self: CommandBuffer) void { - objc.release(self.id); + if (self.m4 == null) objc.release(self.id); } }; @@ -141,8 +161,12 @@ pub const BlitEncoder = struct { pub const ComputeEncoder = struct { id: Id, + m4: ?*metal4.Context = null, + /// Metal 4 encoders run their dispatches side by side, so a serial one puts a barrier after each. + serial: bool = false, pub fn deviceId(self: ComputeEncoder) Id { + if (self.m4) |c| return c.device.id; return objc.msg(Id, self.id, "device", .{}); } @@ -151,11 +175,13 @@ pub const ComputeEncoder = struct { } pub fn setBuffer(self: ComputeEncoder, buffer: Buffer, offset: usize, index: usize) void { + if (self.m4) |c| return c.bind(buffer, offset, index); objc.msg(void, self.id, "setBuffer:offset:atIndex:", .{ buffer.id, offset, index }); } /// Small constants copied into the command stream (at most 4 KB). pub fn setBytes(self: ComputeEncoder, bytes: []const u8, index: usize) void { + if (self.m4) |c| return c.constant(bytes, index); objc.msg(void, self.id, "setBytes:length:atIndex:", .{ bytes.ptr, bytes.len, index }); } @@ -170,29 +196,47 @@ pub const ComputeEncoder = struct { /// Whole threadgroups: `groups` of `threads` each. pub fn dispatchGroups(self: ComputeEncoder, groups: Size, threads: Size) void { objc.msg(void, self.id, "dispatchThreadgroups:threadsPerThreadgroup:", .{ groups, threads }); + self.dispatched(); } /// Whole threadgroups of `threads` each, their counts (3 u32) read from `args` at `offset` when the dispatch runs. pub fn dispatchIndirect(self: ComputeEncoder, args: Buffer, offset: usize, threads: Size) void { + if (self.m4) |c| { + c.dispatchIndirect(self.id, args, offset, threads); + return self.dispatched(); + } objc.msg(void, self.id, "dispatchThreadgroupsWithIndirectBuffer:indirectBufferOffset:threadsPerThreadgroup:", .{ args.id, offset, threads }); } /// A grid of `grid` threads in groups of `threads` (edge groups may be partial), as MLX dispatches. pub fn dispatchThreads(self: ComputeEncoder, grid: Size, threads: Size) void { objc.msg(void, self.id, "dispatchThreads:threadsPerThreadgroup:", .{ grid, threads }); + self.dispatched(); + } + + fn dispatched(self: ComputeEncoder) void { + const c = self.m4 orelse return; + c.pending = true; + if (self.serial) c.barrier(self.id); } /// Later dispatches see every buffer write before this point (concurrent encoders). pub fn barrier(self: ComputeEncoder) void { + if (self.m4) |c| return c.barrier(self.id); objc.msg(void, self.id, "memoryBarrierWithScope:", .{types.BarrierScope.buffers}); } /// Declare a resource used through indirect commands or argument buffers. pub fn useResource(self: ComputeEncoder, buffer: Buffer, usage: usize) void { + if (self.m4) |c| { + _ = c.resident(buffer); + return; + } objc.msg(void, self.id, "useResource:usage:", .{ buffer.id, usage }); } pub fn execute(self: ComputeEncoder, icb: IndirectCommandBuffer, first: usize, count: usize) void { + if (self.m4 != null) @panic("metal 4: indirect command buffers stay on Metal 3"); objc.msg(void, self.id, "executeCommandsInBuffer:withRange:", .{ icb.id, types.Range{ .location = first, .length = count } }); } @@ -202,11 +246,13 @@ pub const ComputeEncoder = struct { /// The command buffer this encoder was opened from, for the event ops a seam encodes BETWEEN encoders. pub fn commandBuffer(self: ComputeEncoder) CommandBuffer { + if (self.m4 != null) @panic("metal 4: seams stay on Metal 3"); return .{ .id = objc.msg(Id, self.id, "commandBuffer", .{}) }; } /// Whether this encoder dispatches serially or concurrently: a seam reopens it in the same mode. pub fn dispatchType(self: ComputeEncoder) types.DispatchType { + if (self.m4 != null) return if (self.serial) .serial else .concurrent; return @fromBackingInt(@intCast(objc.msg(usize, self.id, "dispatchType", .{}))); } }; diff --git a/zig/src/metal/device.zig b/zig/src/metal/device.zig index 769a1b7e994..573d1e2f965 100644 --- a/zig/src/metal/device.zig +++ b/zig/src/metal/device.zig @@ -38,6 +38,7 @@ pub const Buffer = struct { } pub fn deinit(self: Buffer) void { + @import("metal4.zig").released(self.id); // a Metal 4 context's residency set lets go of it too objc.release(self.id); } }; diff --git a/zig/src/metal/metal.zig b/zig/src/metal/metal.zig index e1da53b0a32..33a49b696d2 100644 --- a/zig/src/metal/metal.zig +++ b/zig/src/metal/metal.zig @@ -30,6 +30,7 @@ pub const clock = @import("clock.zig"); pub const pass_metrics = @import("pass_metrics.zig"); pub const counters = @import("counters.zig"); pub const ane = @import("ane.zig"); +pub const metal4 = @import("metal4.zig"); test { std.testing.refAllDecls(@This()); diff --git a/zig/src/metal/metal4.zig b/zig/src/metal/metal4.zig new file mode 100644 index 00000000000..6859f810372 --- /dev/null +++ b/zig/src/metal/metal4.zig @@ -0,0 +1,385 @@ +//! Metal 4 for one model's passes: its own queue, command allocator, argument table, constants ring and residency set. +const std = @import("std"); +const objc = @import("objc.zig"); +const types = @import("types.zig"); +const command = @import("command.zig"); +const Buffer = @import("device.zig").Buffer; +const Device = @import("device.zig").Device; + +const Id = objc.Id; + +/// Apple's unfair lock; off Apple an empty stand-in, since other builds still analyze this file and never run it. +const darwin = @import("builtin").os.tag.isDarwin(); +const Lock = if (darwin) std.c.os_unfair_lock else struct {}; +fn hold(lock: *Lock) void { + if (darwin) std.c.os_unfair_lock_lock(lock); +} +fn drop(lock: *Lock) void { + if (darwin) std.c.os_unfair_lock_unlock(lock); +} + +/// Command buffers a context reuses; a 64-layer pass committing every 4 layers takes 16. +pub const max_buffers = 32; +/// The ring setBytes copies into, since Metal 4 has no setBytes: a pass waits for the last, so the ring may wrap. +const ring_bytes: usize = 8 << 20; +const stage_dispatch: usize = 1 << 27; // MTLStageDispatch +const visibility_device: usize = 1; // MTL4VisibilityOptionDevice: a barrier flushes to the device's coherence point +const wait_ms: u64 = 120_000; +const block_is_global: c_int = 1 << 28; // BLOCK_IS_GLOBAL: copying or releasing a handler leaves it where it is + +extern "c" var _NSConcreteGlobalBlock: [32]?*anyopaque; + +const Descriptor = extern struct { reserved: c_ulong = 0, size: c_ulong }; + +/// A block literal: Metal calls `invoke` with a commit's feedback once its work ends, on a thread of its own. +const Handler = extern struct { + isa: *anyopaque, + flags: c_int = block_is_global, + reserved: c_int = 0, + invoke: *const fn (*Handler, Id) callconv(.c) void, + descriptor: *const Descriptor, + context: *Context, + slot: usize, +}; + +const handler_descriptor = Descriptor{ .size = @sizeOf(Handler) }; + +const State = enum { free, open, committed }; + +pub const Context = struct { + gpa: std.mem.Allocator, + device: Device, + queue: Id, + allocator: Id, + table: Id, + event: Id, + set: Id, + ring: Buffer, + ring_address: u64, + ring_bytes: [*]u8, + bump: usize = 0, + buffers: [max_buffers]Id = undefined, + handlers: [max_buffers]Handler = undefined, + state: [max_buffers]State = @splat(.free), + ticks: [max_buffers]u64 = @splat(0), + done: [max_buffers]std.atomic.Value(u64) = @splat(.init(0)), + failed: [max_buffers]bool = @splat(false), + start: [max_buffers]f64 = @splat(0), + end: [max_buffers]f64 = @splat(0), + used: usize = 0, + tick: u64 = 0, + /// A wait timed out: the GPU may still read this context's buffers, so passes go back to Metal 3. + broken: bool = false, + /// Each buffer in the set by its id, with its GPU address. + known: std.AutoHashMapUnmanaged(usize, u64) = .empty, + dirty: bool = false, + /// A dispatch since the encoder's last barrier: without one a barrier orders nothing new. + pending: bool = false, + lock: Lock = .{}, + freed: std.ArrayList(Id) = .empty, + frees: std.atomic.Value(usize) = .init(0), + + /// A context on `device`, or error.NoMetal4 where this macOS or GPU makes no Metal 4 queue. + pub fn create(gpa: std.mem.Allocator, device: Device) !*Context { + if (!device.responds("newMTL4CommandQueue")) return error.NoMetal4; + const queue = objc.msg(?Id, device.id, "newMTL4CommandQueue", .{}) orelse return error.NoMetal4; + errdefer objc.release(queue); + const allocator = objc.msg(?Id, device.id, "newCommandAllocator", .{}) orelse return error.NoMetal4; + errdefer objc.release(allocator); + const d = objc.msg(Id, objc.msg(Id, objc.class("MTL4ArgumentTableDescriptor"), "alloc", .{}), "init", .{}); + defer objc.release(d); + objc.msg(void, d, "setMaxBufferBindCount:", .{@as(usize, 31)}); + var err: ?Id = null; + const table = objc.msg(?Id, device.id, "newArgumentTableWithDescriptor:error:", .{ d, &err }) orelse return error.NoMetal4; + errdefer objc.release(table); + const event = objc.msg(?Id, device.id, "newSharedEvent", .{}) orelse return error.NoMetal4; + errdefer objc.release(event); + const set = (try device.residencySet(1024)).id; + errdefer objc.release(set); + const ring = try device.buffer(ring_bytes, types.ResourceOptions.shared | types.ResourceOptions.untracked); + errdefer ring.deinit(); + const c = try gpa.create(Context); + errdefer gpa.destroy(c); + c.* = .{ .gpa = gpa, .device = device, .queue = queue, .allocator = allocator, .table = table, .event = event, .set = set, .ring = ring, .ring_address = ring.gpuAddress(), .ring_bytes = ring.contents() }; + var made: usize = 0; + errdefer for (c.buffers[0..made]) |cb| objc.release(cb); + while (made < max_buffers) : (made += 1) { + c.buffers[made] = objc.msg(?Id, device.id, "newCommandBuffer", .{}) orelse return error.NoMetal4; + c.handlers[made] = .{ .isa = @ptrCast(&_NSConcreteGlobalBlock), .invoke = feedback, .descriptor = &handler_descriptor, .context = c, .slot = made }; + } + try register(c); + objc.msg(void, set, "addAllocation:", .{ring.id}); + objc.msg(void, set, "commit", .{}); + objc.msg(void, queue, "addResidencySet:", .{set}); + return c; + } + + /// Waits for every commit, then releases the context and what its set held. + pub fn destroy(c: *Context) void { + c.waitAll(); + unregister(c); + for (c.buffers, c.state) |cb, state| { + if (state == .open) objc.msg(void, cb, "endCommandBuffer", .{}); + objc.release(cb); + } + objc.msg(void, c.queue, "removeResidencySet:", .{c.set}); + objc.release(c.set); + c.ring.deinit(); + objc.release(c.event); + objc.release(c.table); + objc.release(c.allocator); + objc.release(c.queue); + c.known.deinit(c.gpa); + c.freed.deinit(c.gpa); + c.gpa.destroy(c); + } + + /// The context as a queue: its command buffers and encoders take this file's paths. + pub fn asQueue(c: *Context) command.Queue { + return .{ .id = c.queue, .m4 = c }; + } + + /// The next command buffer, begun; with nothing in flight, freed buffers leave the set and the allocator restarts. + pub fn commandBuffer(c: *Context) command.CommandBuffer { + if (c.used == max_buffers) c.waitAll(); + if (c.idle()) { + c.drainFrees(); + c.reset(); + } + if (c.used == max_buffers) @panic("metal 4: every command buffer of the context is open"); + const s = c.used; + c.used += 1; + objc.msg(void, c.buffers[s], "beginCommandBufferWithAllocator:", .{c.allocator}); + c.state[s] = .open; + return .{ .id = c.buffers[s], .m4 = c, .slot = @intCast(s) }; + } + + fn idle(c: *const Context) bool { + for (c.state[0..c.used], c.ticks[0..c.used], c.done[0..c.used]) |state, tick, *done| { + if (state == .committed and done.load(.acquire) < tick) return false; + } + return true; + } + + /// One command buffer encodes at a time, so an open one here was dropped by an encoding error and never commits. + fn reset(c: *Context) void { + for (c.buffers[0..c.used], c.state[0..c.used]) |cb, *state| { + if (state.* == .open) objc.msg(void, cb, "endCommandBuffer", .{}); + state.* = .free; + } + objc.msg(void, c.allocator, "reset", .{}); + c.used = 0; + } + + pub fn commit(c: *Context, s: u8) void { + if (c.dirty) { + objc.msg(void, c.set, "commit", .{}); + c.dirty = false; + } + const cb = c.buffers[s]; + objc.msg(void, cb, "endCommandBuffer", .{}); + c.tick += 1; + c.ticks[s] = c.tick; + c.failed[s] = false; + c.state[s] = .committed; + // Metal calls an options object's handlers for one commit only, so each commit takes new options. + const options = objc.msg(Id, objc.msg(Id, objc.class("MTL4CommitOptions"), "alloc", .{}), "init", .{}); + defer objc.release(options); + objc.msg(void, options, "addFeedbackHandler:", .{@as(*anyopaque, @ptrCast(&c.handlers[s]))}); + const list = [1]Id{cb}; + objc.msg(void, c.queue, "commit:count:options:", .{ @as([*]const Id, &list), @as(usize, 1), options }); + objc.msg(void, c.queue, "signalEvent:value:", .{ c.event, c.tick }); + } + + /// Blocks until slot `s`'s commit ended and its feedback arrived; a timeout breaks the context. + pub fn wait(c: *Context, s: u8) void { + if (c.state[s] != .committed or c.broken) return; + const tick = c.ticks[s]; + if (c.done[s].load(.acquire) >= tick) return; + if (!objc.msg(bool, c.event, "waitUntilSignaledValue:timeoutMS:", .{ tick, wait_ms })) return c.timeOut(); + var tries: usize = 0; + while (c.done[s].load(.acquire) < tick) : (tries += 1) { + if (tries == 50_000_000) return c.timeOut(); // the feedback trails the event by microseconds + std.Thread.yield() catch {}; + } + } + + pub fn waitAll(c: *Context) void { + for (0..c.used) |s| c.wait(@intCast(s)); + } + + fn timeOut(c: *Context) void { + c.broken = true; + std.log.err("metal 4: a command buffer did not finish in {d} s; passes go back to Metal 3", .{wait_ms / 1000}); + } + + pub fn status(c: *const Context, s: u8) types.CommandBufferStatus { + if (c.state[s] != .committed) return .not_enqueued; + if (c.broken) return .@"error"; + if (c.done[s].load(.acquire) < c.ticks[s]) return .committed; + return if (c.failed[s]) .@"error" else .completed; + } + + /// Valid once waited: Metal's own error was logged when its feedback arrived. + pub fn failure(c: *const Context, s: u8) ?[*:0]const u8 { + if (c.state[s] != .committed) return null; + if (c.broken) return "a Metal 4 command buffer did not finish"; + return if (c.failed[s]) "a Metal 4 command buffer failed (Metal's error is logged above)" else null; + } + + /// `buffer`'s GPU address; it joins the set on first use, since a Metal 4 queue reaches only what sets hold. + pub fn resident(c: *Context, buffer: Buffer) u64 { + const key = @intFromPtr(buffer.id); + if (c.known.get(key)) |address| return address; + const address = buffer.gpuAddress(); + hold(&c.lock); + c.known.put(c.gpa, key, address) catch {}; // without room it joins again on its next use, which changes nothing + drop(&c.lock); + objc.msg(void, c.set, "addAllocation:", .{buffer.id}); + c.dirty = true; + return address; + } + + /// Any thread, as a buffer is released: the set's reference keeps it alive until an idle command buffer drops it. + fn forget(c: *Context, id: Id) void { + hold(&c.lock); + defer drop(&c.lock); + if (!c.known.contains(@intFromPtr(id))) return; + c.freed.append(c.gpa, id) catch return; // without room the set keeps it until the context goes + _ = c.frees.fetchAdd(1, .release); + } + + fn drainFrees(c: *Context) void { + if (c.frees.load(.acquire) == 0) return; + hold(&c.lock); + defer drop(&c.lock); + for (c.freed.items) |id| { + objc.msg(void, c.set, "removeAllocation:", .{id}); + _ = c.known.remove(@intFromPtr(id)); + } + c.freed.clearRetainingCapacity(); + c.frees.store(0, .release); + objc.msg(void, c.set, "commit", .{}); + } + + /// An encoder on `cb` whose dispatches read their buffers from the context's argument table. + pub fn encoder(c: *Context, cb: Id) Id { + const e = objc.msg(Id, cb, "computeCommandEncoder", .{}); + objc.msg(void, e, "setArgumentTable:", .{c.table}); + c.pending = false; + return e; + } + + pub fn bind(c: *Context, buffer: Buffer, offset: usize, index: usize) void { + objc.msg(void, c.table, "setAddress:atIndex:", .{ c.resident(buffer) + offset, index }); + } + + /// setBytes: the bytes go into the ring and the table takes their address. + pub fn constant(c: *Context, bytes: []const u8, index: usize) void { + if (c.bump + bytes.len > ring_bytes) c.bump = 0; + @memcpy(c.ring_bytes[c.bump..][0..bytes.len], bytes); + objc.msg(void, c.table, "setAddress:atIndex:", .{ c.ring_address + c.bump, index }); + c.bump += (bytes.len + 63) & ~@as(usize, 63); + } + + pub fn dispatchIndirect(c: *Context, e: Id, args: Buffer, offset: usize, threads: types.Size) void { + objc.msg(void, e, "dispatchThreadgroupsWithIndirectBuffer:threadsPerThreadgroup:", .{ c.resident(args) + offset, threads }); + } + + /// Later dispatches see every write before this point, as memoryBarrierWithScope does on Metal 3. + pub fn barrier(c: *Context, e: Id) void { + if (!c.pending) return; + c.pending = false; + objc.msg(void, e, "barrierAfterEncoderStages:beforeEncoderStages:visibilityOptions:", .{ stage_dispatch, stage_dispatch, visibility_device }); + } +}; + +fn feedback(h: *Handler, report: Id) callconv(.c) void { + const c = h.context; + const s = h.slot; + if (objc.msg(?Id, report, "error", .{})) |err| { + c.failed[s] = true; + std.log.err("metal 4: a command buffer failed on the GPU: {s}", .{objc.errorText(err)}); + } + c.start[s] = objc.msg(f64, report, "GPUStartTime", .{}); + c.end[s] = objc.msg(f64, report, "GPUEndTime", .{}); + c.done[s].store(c.ticks[s], .release); +} + +pub fn waitForFence(e: Id, fence: Id) void { + objc.msg(void, e, "waitForFence:beforeEncoderStages:", .{ fence, stage_dispatch }); +} + +pub fn updateFence(e: Id, fence: Id) void { + objc.msg(void, e, "updateFence:afterEncoderStages:", .{ fence, stage_dispatch }); +} + +var registry_lock: Lock = .{}; +var registry: [8]?*Context = @splat(null); +var live = std.atomic.Value(usize).init(0); + +fn register(c: *Context) !void { + hold(®istry_lock); + defer drop(®istry_lock); + for (®istry) |*entry| if (entry.* == null) { + entry.* = c; + _ = live.fetchAdd(1, .release); + return; + }; + return error.TooManyMetal4Contexts; +} + +fn unregister(c: *Context) void { + hold(®istry_lock); + defer drop(®istry_lock); + for (®istry) |*entry| if (entry.* == c) { + entry.* = null; + _ = live.fetchSub(1, .release); + }; +} + +/// Buffer.deinit's hook: a buffer about to be released leaves each context's set once that context is idle. +pub fn released(id: Id) void { + if (live.load(.acquire) == 0) return; + hold(®istry_lock); + defer drop(®istry_lock); + for (registry) |entry| if (entry) |c| c.forget(id); +} + +test "a Metal 4 context runs commits back to back, reports each one's feedback and drops freed buffers" { + const library = @import("library.zig"); + const device = Device.init() catch return error.SkipZigTest; + defer device.deinit(); + const c = Context.create(std.testing.allocator, device) catch return error.SkipZigTest; + defer c.destroy(); + const source = "#include \nusing namespace metal;\nkernel void add(device const float* x [[buffer(0)]], device float* y [[buffer(1)]], constant float& k [[buffer(2)]], uint i [[thread_position_in_grid]]) { y[i] = x[i] + k; }"; + const lib = try library.Library.fromSource(device, source, library.CompileOptions.mlx()); + defer lib.deinit(); + const pipeline = try library.Pipeline.init(device, lib, "add", false); + defer pipeline.deinit(); + const options = types.ResourceOptions.shared | types.ResourceOptions.untracked; + const x = try device.buffer(1024 * 4, options); + defer x.deinit(); + for (x.slice(f32, 1024), 0..) |*v, i| v.* = @floatFromInt(i); + const y = try device.buffer(1024 * 4, options); + for (0..3) |round| { // each commit takes new commit options, or the second one never reports back + const cb = c.asQueue().commandBuffer(); + const e = cb.compute(.concurrent); + e.setPipeline(pipeline); + e.setBuffer(x, 0, 0); + e.setBuffer(y, 0, 1); + e.setValue(@as(f32, @floatFromInt(round)), 2); + e.dispatchThreads(types.Size.of(1024, 1, 1), types.Size.of(256, 1, 1)); + e.end(); + cb.commit(); + cb.wait(); + try std.testing.expect(cb.failure() == null and cb.status() == .completed); + try std.testing.expect(cb.gpuSeconds() > 0); + try std.testing.expectEqual(@as(f32, @floatFromInt(1023 + round)), y.slice(f32, 1024)[1023]); + } + const freed = @intFromPtr(y.id); + y.deinit(); + try std.testing.expect(c.known.contains(freed)); + _ = c.asQueue().commandBuffer(); // nothing in flight: the freed buffer leaves the set + try std.testing.expect(!c.known.contains(freed) and c.known.contains(@intFromPtr(x.id))); +} diff --git a/zig/src/native/drama_host.zig b/zig/src/native/drama_host.zig index 6c21778743e..93362401c6b 100644 --- a/zig/src/native/drama_host.zig +++ b/zig/src/native/drama_host.zig @@ -13,6 +13,7 @@ const Limit = if (is_cuda) @import("drama_limit.zig").Limit else struct { fn deinit(_: *@This()) void {} }; const Warm = if (is_cuda) struct {} else d3.residency.Warm; +const Voice = @import("drama_host_voice.zig").For(Host); const Session = struct { e: *d3.Engine, t: *d3.tts.Tts, @@ -66,6 +67,7 @@ const Host = struct { closing: bool = false, failed: completion.State = .{}, refs: Refs = .{}, + voices: @import("drama_host_voice.zig").Queue = .{}, const vtable: api.Engine.VTable = .{ .info = info, .submit = submitText, @@ -75,6 +77,7 @@ const Host = struct { .memory = memory, .keepalive = if (is_cuda) null else keepalive, .drain = drain, + .encode_voice = Voice.encode, }; fn self(p: *anyopaque) *Host { return @ptrCast(@alignCast(p)); @@ -163,6 +166,7 @@ const Host = struct { if (is_cuda) h.sessions[0].e.ctx.makeCurrent() catch { h.lock(); h.closing = true; + Voice.refuse(h); h.unlock(); while (true) { h.lock(); @@ -174,6 +178,7 @@ const Host = struct { }; while (true) { h.lock(); + if (Voice.step(h)) continue; const work = h.queue.next() orelse { if (h.closing or h.failed.closed) { h.unlock(); @@ -356,14 +361,7 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, _: []const u8, try o.silence.validate(); const h = try gpa.create(Host); errdefer gpa.destroy(h); - h.* = .{ - .gpa = gpa, - .io = io, - .limit = undefined, - .queue = try rounds.Queue.init(o.lanes), - .info_ = .{}, - .silence = o.silence, - }; + h.* = .{ .gpa = gpa, .io = io, .limit = undefined, .queue = try rounds.Queue.init(o.lanes), .info_ = .{}, .silence = o.silence }; if (is_cuda) h.refs = .{ .gpa = gpa, .capacity = o.reference_entries }; try h.limit.init(gpa, io, o.device); errdefer h.limit.deinit(); diff --git a/zig/src/native/drama_host_voice.zig b/zig/src/native/drama_host_voice.zig new file mode 100644 index 00000000000..dc6aaf49a54 --- /dev/null +++ b/zig/src/native/drama_host_voice.zig @@ -0,0 +1,87 @@ +//! A reference WAV file's codes for POST /v1/voices, encoded on the speech host's own thread by an idle lane's codec. +const std = @import("std"); +const api = @import("engine_api"); + +/// One waiting encode; the asking thread sleeps on `done` under the host's mutex. +const Ask = struct { + gpa: std.mem.Allocator, + wav: []const u8, + codes: [][10]i32 = &.{}, + err: ?api.EncodeVoiceError = null, + done: bool = false, + cond: std.Io.Condition = .init, +}; + +/// Asks waiting for the host thread: one at a time, in arrival order. +pub const Queue = struct { turn: std.Io.Mutex = .init, ask: ?*Ask = null }; + +/// Errors of the file itself: the request's to fix, so the engine stays open. +fn input(err: anyerror) bool { + for ([_]anyerror{ error.NotWav, error.BadWav, error.UnsupportedWav, error.BadReference, error.EmptyAudio }) |e| if (err == e) return true; + return false; +} + +pub fn For(comptime Host: type) type { + return struct { + /// The engine's encode_voice: hands the file to the host thread and waits for its codes. + pub fn encode(p: *anyopaque, gpa: std.mem.Allocator, wav: []const u8) api.EncodeVoiceError![][10]i32 { + const h: *Host = @ptrCast(@alignCast(p)); + h.voices.turn.lockUncancelable(h.io); + defer h.voices.turn.unlock(h.io); + var ask: Ask = .{ .gpa = gpa, .wav = wav }; + h.mutex.lockUncancelable(h.io); + defer h.mutex.unlock(h.io); + if (h.closing or h.failed.closed) return error.Closed; + h.voices.ask = &ask; + h.wake.signal(h.io); + while (!ask.done) ask.cond.waitUncancelable(h.io, &h.mutex); + return ask.err orelse ask.codes; + } + + /// On the host thread with its mutex held: runs a waiting encode on an idle lane; true: done, mutex released. + pub fn step(h: *Host) bool { + const ask = h.voices.ask orelse return false; + if (h.closing or h.failed.closed) { + refuse(h); + h.mutex.unlock(h.io); + return true; + } + const lane = for (h.jobs[0..h.queue.lanes], 0..) |job, i| { + if (job == null) break i; + } else return false; // every lane busy: the ask waits for one to finish + h.voices.ask = null; + h.mutex.unlock(h.io); + const t = h.sessions[lane].t; + const outcome: ?api.EncodeVoiceError = if (t.encodeWav(ask.wav)) |codes| copy: { + defer t.c.gpa.free(codes); + ask.codes = ask.gpa.dupe([10]i32, codes) catch break :copy error.OutOfMemory; + break :copy null; + } else |err| if (err == error.OutOfMemory) error.OutOfMemory else if (input(err)) error.BadWav else fail: { + std.log.warn("drama3: reference encode failed, closing the speech engine: {s}", .{@errorName(err)}); + break :fail error.Failed; + }; + h.mutex.lockUncancelable(h.io); + if (outcome) |e| if (e == error.Failed) { + h.failed.closed = true; // a device error: as in advance, the engine stops serving + }; + ask.err = outcome; + ask.done = true; + ask.cond.signal(h.io); + h.mutex.unlock(h.io); + return true; + } + + /// With the host's mutex held and the engine closing: a waiting encode gets Closed. + pub fn refuse(h: *Host) void { + const ask = h.voices.ask orelse return; + h.voices.ask = null; + ask.err = error.Closed; + ask.done = true; + ask.cond.signal(h.io); + } + }; +} + +test { + _ = @import("drama_host_voice_test.zig"); +} diff --git a/zig/src/native/drama_host_voice_test.zig b/zig/src/native/drama_host_voice_test.zig new file mode 100644 index 00000000000..2c6b3e6a1e0 --- /dev/null +++ b/zig/src/native/drama_host_voice_test.zig @@ -0,0 +1,109 @@ +//! The speech host's encode hand-off over a fake host: idle lanes answer, busy ones wait, a bad file keeps it open. +const std = @import("std"); +const Queue = @import("drama_host_voice.zig").Queue; +const t = std.testing; + +const Tts = struct { + c: struct { gpa: std.mem.Allocator } = .{ .gpa = t.allocator }, + fail: ?anyerror = null, + calls: usize = 0, + + pub fn encodeWav(tts: *Tts, wav: []const u8) ![][10]i32 { + tts.calls += 1; + if (tts.fail) |e| return switch (e) { + error.NotWav => error.NotWav, + error.UnsupportedWav => error.UnsupportedWav, + else => error.LaunchFailed, + }; + const codes = try tts.c.gpa.alloc([10]i32, wav.len); + for (codes, wav) |*row, byte| row.* = @splat(byte); + return codes; + } +}; + +const Host = struct { + io: std.Io = t.io, + mutex: std.Io.Mutex = .init, + wake: std.Io.Condition = .init, + closing: bool = false, + failed: struct { closed: bool = false } = .{}, + jobs: [2]?u8 = @splat(null), + queue: struct { lanes: usize = 2 } = .{}, + tts: [2]Tts = @splat(.{}), + sessions: [2]struct { t: *Tts } = undefined, + voices: Queue = .{}, + + fn lock(h: *Host) void { + h.mutex.lockUncancelable(h.io); + } + fn unlock(h: *Host) void { + h.mutex.unlock(h.io); + } +}; +const Voice = @import("drama_host_voice.zig").For(Host); + +const Asked = struct { + h: *Host, + out: @import("engine_api").EncodeVoiceError![][10]i32 = &.{}, + fn run(a: *Asked) void { + a.out = Voice.encode(a.h, t.allocator, "ab"); + } +}; + +/// One encode from another thread, answered by this one as the host loop would. +fn ask(h: *Host) ![][10]i32 { + var asked: Asked = .{ .h = h }; + const thread = try std.Thread.spawn(.{}, Asked.run, .{&asked}); + while (true) { + h.lock(); + if (h.voices.ask != null and Voice.step(h)) break; + h.unlock(); + std.Thread.yield() catch {}; + } + thread.join(); + return asked.out; +} + +test "drama voice encode: an idle lane answers; a bad file keeps the engine open, a device error closes it" { + var h: Host = .{}; + for (&h.sessions, &h.tts) |*s, *tts| s.* = .{ .t = tts }; + h.jobs[0] = 1; // lane 0 busy: lane 1 encodes + const codes = try ask(&h); + defer t.allocator.free(codes); + try t.expectEqualSlices([10]i32, &.{ @splat('a'), @splat('b') }, codes); + try t.expectEqual(@as(usize, 1), h.tts[1].calls); + h.tts[1].fail = error.NotWav; + try t.expectError(error.BadWav, ask(&h)); + h.tts[1].fail = error.UnsupportedWav; + try t.expectError(error.BadWav, ask(&h)); + try t.expect(!h.failed.closed); + h.tts[1].fail = error.LaunchFailed; + const level = t.log_level; + t.log_level = .err; // the closing warning is the expected outcome here + defer t.log_level = level; + try t.expectError(error.Failed, ask(&h)); + try t.expect(h.failed.closed); + try t.expectError(error.Closed, Voice.encode(&h, t.allocator, "ab")); + try t.expectEqual(@as(usize, 0), h.tts[0].calls); +} + +test "drama voice encode: every lane busy keeps the ask waiting; closing answers it" { + var h: Host = .{}; + for (&h.sessions, &h.tts) |*s, *tts| s.* = .{ .t = tts }; + h.jobs = .{ 1, 2 }; + var asked: Asked = .{ .h = &h }; + const thread = try std.Thread.spawn(.{}, Asked.run, .{&asked}); + while (true) { + h.lock(); + defer h.unlock(); + if (h.voices.ask != null) break; + } + h.lock(); + try t.expect(!Voice.step(&h)); // nothing ran: the mutex is still held + h.closing = true; + Voice.refuse(&h); + h.unlock(); + thread.join(); + try t.expectError(error.Closed, asked.out); + try t.expectEqual(@as(usize, 0), h.tts[0].calls + h.tts[1].calls); +} diff --git a/zig/src/native/qwen27_lanes.zig b/zig/src/native/qwen27_lanes.zig index b94e4c22320..d8e910312b2 100644 --- a/zig/src/native/qwen27_lanes.zig +++ b/zig/src/native/qwen27_lanes.zig @@ -278,7 +278,7 @@ pub const Metal = struct { var at = first; while (at < first + rows) : (at += contract.max_rows) { const n = @min(first + rows - at, contract.max_rows); - try b.ops.argmax(e, .{ .buf = logits.buffer, .off = logits.offset + at * vocab * 2 }, .{ .buf = b.picks, .off = at * @sizeOf(contract.Pick) }, .{ .rows = @intCast(n), .vocab = vocab, .stride = vocab }); + try b.ops.argmaxChunks(e, .{ .buf = logits.buffer, .off = logits.offset + at * vocab * 2 }, .{ .buf = b.picks, .off = at * @sizeOf(contract.Pick) }, .{ .rows = @intCast(n), .vocab = vocab, .stride = vocab }); } e.end(); cb.commit(); diff --git a/zig/src/platform/environment.zig b/zig/src/platform/environment.zig index 56a6426a21e..3016e2d0a3d 100644 --- a/zig/src/platform/environment.zig +++ b/zig/src/platform/environment.zig @@ -3,7 +3,7 @@ const std = @import("std"); const sys = @import("sys.zig"); pub const Error = error{InvalidEnvironment}; -pub const Scope = enum { common, cuda, metal, xpu, slide, hooks, dsv41, gemma4, drama3, glm, flashnext }; +pub const Scope = enum { common, cuda, metal, xpu, slide, hooks, dsv41, gemma4, drama3, glm, flashnext, nemotron, minimax_m3 }; pub const Kind = enum { u32, u64, size, percent, positive, device, segments, mib, bit_width, word, prompt, flag, toggle, real, positive_real, signed_real, range, path }; pub const Rule = struct { name: [:0]const u8, @@ -31,6 +31,9 @@ pub fn isReal(kind: Kind) bool { } pub const rules = [_]Rule{ + .{ .name = "TF_Q27_METAL4", .scope = .metal, .kind = .flag, .forms = "0 or 1" }, + .{ .name = "TF_Q27_FLAT_GLUE", .scope = .metal, .kind = .flag, .forms = "0 or 1" }, + .{ .name = "TF_Q27_QK", .scope = .metal, .kind = .flag, .forms = "0 or 1" }, .{ .name = "TF_CACHE_EVICT", .scope = .common, .kind = .word, .words = &.{ "main", "decayed_resume" }, .forms = "main or decayed_resume (default main)" }, .{ .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)" }, @@ -45,6 +48,7 @@ pub const rules = [_]Rule{ .{ .name = "TENSORFOLD_RESTORE_PREFETCH_MS", .scope = .common, .kind = .u64, .trim = " \t", .first_digit = true, .forms = "whole unsigned 64-bit milliseconds (capped at 1099511627776)" }, .{ .name = "TENSORFOLD_TOOL_ID_KEY_FILE", .scope = .common, .kind = .path, .forms = "a path without control characters to a file only its owner can read, holding at least 32 key bytes" }, .{ .name = "TENSORFOLD_CUDA_KERNELS", .scope = .cuda, .kind = .path, .forms = "a captured kernel set's folder without control characters, or native for the engine's own kernels" }, + .{ .name = "TF_NCCL_LIB", .scope = .cuda, .kind = .path, .forms = "an NCCL library path without control characters, or blank for libnccl.so.2" }, .{ .name = "TF_CUDA_DEVICE", .scope = .cuda, .kind = .device, .trim = " ", .forms = "a whole GPU ordinal from 0 to 4294967295, or empty for the default" }, .{ .name = "TF_CUDA_SEGMENTS", .scope = .cuda, .kind = .segments, .trim = " ", .forms = "a whole number from 1 to 4, or empty for the default" }, .{ .name = "TF_CUDA_CARVEOUT", .scope = .cuda, .kind = .flag, .forms = "0 or 1" }, @@ -53,6 +57,20 @@ pub const rules = [_]Rule{ .{ .name = "TF_DSPINE_WINDOW", .scope = .cuda, .kind = .size, .min = 16, .max = 8192, .forms = "a whole row count from 16 to 8192, at most the DSpine drafter's own sliding_window" }, .{ .name = "TF_DRAFT_NODES", .scope = .cuda, .kind = .size, .forms = "a whole nonnegative native-size node count (capped by the drafter's window)" }, .{ .name = "TF_QMMF_HALF_BELOW", .scope = .cuda, .kind = .size, .forms = "a whole nonnegative native-size block count (0 disables half tiles)" }, + // Qwen 3.5 CUDA and HIP settings, read through this table: + .{ .name = "TENSORFOLD_MEMORY_RESERVE_GIB", .scope = .cuda, .kind = .real, .forms = "a finite GiB amount (the HIP admission's floor and the memory's size still bound it)" }, + .{ .name = "TENSORFOLD_HIP_MEMORY_LIMIT_GB", .scope = .cuda, .kind = .real, .forms = "a finite GiB amount (the HIP admission still fits its byte count in a 64-bit size)" }, + .{ .name = "TF_QWEN_KEEP_LATE", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (default 0)" }, + .{ .name = "TF_QWEN_KV_PAGE_TEST", .scope = .cuda, .kind = .size, .min = 1, .max = 2147483647, .forms = "a whole page size from 1 to 2147483647 (unset: off)" }, + .{ .name = "TF_COST_KEY_TRACE", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (default 0)" }, + .{ .name = "TF_TIMING", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (default 0)" }, + .{ .name = "TF_NO_TREES", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (default 0; 1 keeps the CUDA drafter's chains only)" }, + .{ .name = "TF_MTP_TREES", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (default 0)" }, + .{ .name = "TF_MTP_BATCH", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (default 1; 0 keeps one stream at a time)" }, + .{ .name = "TF_QWEN_POOL_LOG", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (default 0)" }, + .{ .name = "TF_Q27_POCKET_OFF", .scope = .cuda, .kind = .path, .forms = "all, or a list of layer:neuron pairs without control characters (default off)" }, + .{ .name = "TF_Q27_TAIL", .scope = .cuda, .kind = .word, .words = &.{"off"}, .forms = "off (default: each nudged sequence's tail rows)" }, + .{ .name = "TF_Q27_GEMM", .scope = .cuda, .kind = .word, .words = &.{"narrow"}, .forms = "narrow (default: 128x128 tiles)" }, .{ .name = "TENSORFOLD_PROMPT_CACHE_KEEP_OTHERS", .scope = .cuda, .kind = .flag, .forms = "0 or 1" }, .{ .name = "TF_PROMPT_INTERMEDIATE", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (default 0)" }, .{ .name = "TENSORFOLD_LFM2_KV_PAGES", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (unset leases pool pages)" }, @@ -211,6 +229,15 @@ pub const rules = [_]Rule{ .{ .name = "TF_FLASHNEXT_KV_PAGE_TEST", .scope = .flashnext, .kind = .size, .forms = "a page size the kernels take, whole blocks of the indexer's ratio up to the window (unset: off)" }, .{ .name = "TF_FLASHNEXT_CONFIDENCE", .scope = .flashnext, .kind = .signed_real, .forms = "a finite number (default -0.4)" }, .{ .name = "TF_FLASHNEXT_PROMPT", .scope = .flashnext, .kind = .word, .words = &.{"rows"}, .forms = "rows for the rows path (unset or blank keeps the plain path)" }, + // Family rank and prompt settings below are read through their own family's startup scope. + .{ .name = "TF_GLM_INDEX_CUDA", .scope = .glm, .kind = .word, .words = &.{ "1", "0", "scores" }, .forms = "1 (both kernels), 0 (neither) or scores (scores only; unset or blank is both)" }, + .{ .name = "TF_GLM_KV_HOST_GIB", .scope = .glm, .kind = .real, .forms = "a finite GiB amount of at least 0 (unset or blank uses one full window and 16 rows a page)" }, + .{ .name = "TF_GLM_RANK", .scope = .glm, .kind = .u64, .forms = "a whole rank index from 0 to 4294967295 (unset with TF_GLM_WORLD gives one rank)" }, + .{ .name = "TF_GLM_WORLD", .scope = .glm, .kind = .u64, .forms = "a whole rank count from 1 to 4294967295 (unset with TF_GLM_RANK gives one rank)" }, + .{ .name = "TF_NEMOTRON_RANK", .scope = .nemotron, .kind = .u64, .forms = "a whole rank index from 0 to 4294967295 (unset with TF_NEMOTRON_WORLD gives one rank)" }, + .{ .name = "TF_NEMOTRON_WORLD", .scope = .nemotron, .kind = .u64, .forms = "a whole rank count from 1 to 4294967295 (unset with TF_NEMOTRON_RANK gives one rank)" }, + .{ .name = "TF_MINIMAX_RANK", .scope = .minimax_m3, .kind = .u64, .forms = "a whole rank index, 0 or 1 at two ranks (unset with TF_MINIMAX_WORLD gives one rank)" }, + .{ .name = "TF_MINIMAX_WORLD", .scope = .minimax_m3, .kind = .u64, .forms = "a whole rank count, 2 on CUDA (unset with TF_MINIMAX_RANK gives one rank)" }, }; pub fn rule(name: []const u8) Rule { @@ -298,6 +325,11 @@ pub fn describe(a: std.mem.Allocator, name: []const u8, raw: []const u8) ![]cons return std.fmt.allocPrint(a, "{s}=\"{f}\": expected {s}", .{ name, std.zig.fmtString(raw), rule(name).forms }); } +/// A registered setting's raw text, for readers that parse it against runtime bounds the table cannot name. +pub fn rawText(name: [:0]const u8) ?[]const u8 { + return sys.getenv(name); +} + /// A direct family/tool entry point gets the same refusal even when it has no server problem buffer. fn checked(name: [:0]const u8, raw: ?[]const u8) Error!?u64 { return parse(name, raw) catch { @@ -374,6 +406,8 @@ pub const Flags = struct { drama3: bool = false, glm: bool = false, flashnext: bool = false, + nemotron: bool = false, + minimax_m3: bool = false, device: ?u32 = null, segments: ?u32 = null, carveout: bool = false, @@ -391,6 +425,8 @@ pub const Flags = struct { .drama3 => f.drama3, .glm => f.glm, .flashnext => f.flashnext, + .nemotron => f.nemotron, + .minimax_m3 => f.minimax_m3, }; } }; diff --git a/zig/src/platform/environment_test.zig b/zig/src/platform/environment_test.zig index 16ac23c2e2a..8ad640caaa5 100644 --- a/zig/src/platform/environment_test.zig +++ b/zig/src/platform/environment_test.zig @@ -3,7 +3,7 @@ const std = @import("std"); const e = @import("environment.zig"); const t = std.testing; const a = t.allocator; -const all: e.Flags = .{ .cuda = true, .metal = true, .xpu = true, .slide = true, .hooks = true, .dsv41 = true, .gemma4 = true, .drama3 = true, .glm = true, .flashnext = true }; +const all: e.Flags = .{ .cuda = true, .metal = true, .xpu = true, .slide = true, .hooks = true, .dsv41 = true, .gemma4 = true, .drama3 = true, .glm = true, .flashnext = true, .nemotron = true, .minimax_m3 = true }; const Env = struct { name: []const u8, raw: ?[]const u8, @@ -36,6 +36,12 @@ 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_Q27_METAL4", .raw = "0", .n = 0 }, + .{ .name = "TF_Q27_METAL4", .raw = "1", .n = 1 }, + .{ .name = "TF_Q27_FLAT_GLUE", .raw = "0", .n = 0 }, + .{ .name = "TF_Q27_FLAT_GLUE", .raw = "1", .n = 1 }, + .{ .name = "TF_Q27_QK", .raw = "0", .n = 0 }, + .{ .name = "TF_Q27_QK", .raw = "1", .n = 1 }, .{ .name = "TF_CACHE_EVICT", .raw = "main", .n = 0 }, .{ .name = "TF_CACHE_EVICT", .raw = "decayed_resume", .n = 1 }, .{ .name = "TF_FLASHNEXT_BATCH_DRAWS", .raw = "0", .n = 0 }, @@ -67,6 +73,28 @@ const valid = [_]Case{ .{ .name = "TENSORFOLD_UNIFIED_HOST_COUNTS", .raw = "0", .n = 0 }, .{ .name = "TENSORFOLD_UNIFIED_HOST_COUNTS", .raw = "1", .n = 1 }, .{ .name = "TF_MTP_DRAFTS", .raw = "0", .n = 0 }, + .{ .name = "TF_QWEN_KEEP_LATE", .raw = "0", .n = 0 }, + .{ .name = "TF_QWEN_KEEP_LATE", .raw = "1", .n = 1 }, + .{ .name = "TF_QWEN_KV_PAGE_TEST", .raw = "1", .n = 1 }, + .{ .name = "TF_QWEN_KV_PAGE_TEST", .raw = "2147483647", .n = 2147483647 }, + .{ .name = "TF_COST_KEY_TRACE", .raw = "0", .n = 0 }, + .{ .name = "TF_COST_KEY_TRACE", .raw = "1", .n = 1 }, + .{ .name = "TF_TIMING", .raw = "0", .n = 0 }, + .{ .name = "TF_TIMING", .raw = "1", .n = 1 }, + .{ .name = "TF_NO_TREES", .raw = "0", .n = 0 }, + .{ .name = "TF_NO_TREES", .raw = "1", .n = 1 }, + .{ .name = "TF_MTP_TREES", .raw = "0", .n = 0 }, + .{ .name = "TF_MTP_TREES", .raw = "1", .n = 1 }, + .{ .name = "TF_MTP_BATCH", .raw = "0", .n = 0 }, + .{ .name = "TF_MTP_BATCH", .raw = "1", .n = 1 }, + .{ .name = "TF_QWEN_POOL_LOG", .raw = "0", .n = 0 }, + .{ .name = "TF_QWEN_POOL_LOG", .raw = "1", .n = 1 }, + .{ .name = "TF_Q27_GEMM", .raw = "narrow", .n = 0 }, + .{ .name = "TF_Q27_TAIL", .raw = "off", .n = 0 }, + .{ .name = "TF_Q27_POCKET_OFF", .raw = "all", .n = 0 }, + .{ .name = "TENSORFOLD_MEMORY_RESERVE_GIB", .raw = "1", .n = 4607182418800017408 }, + .{ .name = "TENSORFOLD_HIP_MEMORY_LIMIT_GB", .raw = "2", .n = 4611686018427387904 }, + .{ .name = "TF_MTP_DRAFTS", .raw = "4294967295", .n = std.math.maxInt(u32) }, .{ .name = "TF_DSPINE_WINDOW", .raw = "16", .n = 16 }, .{ .name = "TF_DSPINE_WINDOW", .raw = "4096", .n = 4096 }, @@ -125,12 +153,17 @@ const valid = [_]Case{ .{ .name = "TF_SLIDE_TAP_CHECK", .raw = "1", .n = 1 }, .{ .name = "TF_SLIDE_POCKET_DUMP", .raw = "/tmp/pocket rows", .n = 0 }, .{ .name = "TENSORFOLD_CUDA_KERNELS", .raw = "/tmp/captured set", .n = 0 }, + .{ .name = "TF_NCCL_LIB", .raw = "/fixture/nccl/libnccl.so.2", .n = 0 }, .{ .name = "TF_SLIDE_FORGET_FAIL", .raw = " 0 ", .n = 0 }, .{ .name = "TF_DSV41_SMALL", .raw = "1", .n = 1 }, .{ .name = "TF_DSV41_ASSETS", .raw = "deepseek assets", .n = 0 }, .{ .name = "TF_DSV41_ENGRAM_DIR", .raw = "engram-rows", .n = 0 }, .{ .name = "TF_DSV41_ENGRAM_VERIFY", .raw = "full", .n = 1 }, .{ .name = "TF_DSV41_ENGRAM_CACHE", .raw = "0", .n = 0 }, + .{ .name = "TF_NEMOTRON_RANK", .raw = "1", .n = 1 }, + .{ .name = "TF_NEMOTRON_WORLD", .raw = "2", .n = 2 }, + .{ .name = "TF_MINIMAX_RANK", .raw = "1", .n = 1 }, + .{ .name = "TF_MINIMAX_WORLD", .raw = "2", .n = 2 }, }; test "environment: valid forms remain raw numbers before existing consumer clamps and defaults" { @@ -167,7 +200,14 @@ test "environment: range, enum, whitespace and native prompt geometry refusals a .{ "XPU_A8_BITS", "16" }, .{ "TF_SLIDE_POCKET_KEY", "AUTO" }, .{ "TF_DRAMA_PREFILL_ROWS", "4096x" }, .{ "TF_DRAMA_REFERENCE_CACHE", "4294967296" }, .{ "TF_DSPINE_WINDOW", "0" }, .{ "TF_DSPINE_WINDOW", "15" }, - .{ "TF_DSPINE_WINDOW", "8193" }, + .{ "TF_DSPINE_WINDOW", "8193" }, .{ "TF_QWEN_KV_PAGE_TEST", "2147483648" }, + .{ "TF_QWEN_KV_PAGE_TEST", "0" }, .{ "TF_Q27_GEMM", "wide" }, + .{ "TF_Q27_GEMM", "NARROW" }, .{ "TF_Q27_TAIL", "on" }, + .{ "TF_Q27_TAIL", "OFF" }, .{ "TF_Q27_POCKET_OFF", "no\ncontrol" }, + .{ "TF_QWEN_KEEP_LATE", "2" }, .{ "TF_TIMING", "2" }, + .{ "TF_NO_TREES", "true" }, .{ "TF_MTP_TREES", "yes" }, + .{ "TF_MTP_BATCH", "off" }, .{ "TF_QWEN_POOL_LOG", "true" }, + .{ "TF_COST_KEY_TRACE", "on" }, }) |c| try t.expectError(error.InvalidEnvironment, e.parse(c[0], c[1])); try t.expectEqual(@as(?u64, null), try e.parse("TF_CUDA_DEVICE", " ")); try t.expectEqual(@as(?u64, 0), try e.parse("TF_Q27_COPY_ROWS", "+0")); diff --git a/zig/src/qwen27_bank_test.zig b/zig/src/qwen27_bank_test.zig index f9f92db2831..df7efdd9904 100644 --- a/zig/src/qwen27_bank_test.zig +++ b/zig/src/qwen27_bank_test.zig @@ -158,7 +158,10 @@ const Fixture = struct { } fn deinit(f: *Fixture) void { f.pool.deinit(); - inline for (@typeInfo(gpu.Metadata).@"struct".field_names) |name| @field(f.metadata, name).buffer.deinit(); + inline for (@typeInfo(gpu.Metadata).@"struct".field_names) |name| { + const ref = if (comptime std.mem.eql(u8, name, "flows")) @field(f.metadata, name).? else @field(f.metadata, name); + ref.buffer.deinit(); + } f.scratch.deinit(); f.output.deinit(); } diff --git a/zig/src/qwen27_keep_test.zig b/zig/src/qwen27_keep_test.zig index 5bb0fb3f31e..3b02501b189 100644 --- a/zig/src/qwen27_keep_test.zig +++ b/zig/src/qwen27_keep_test.zig @@ -47,7 +47,10 @@ test "qwen27 speed: shared in-place verify then empty and full keeps restore sta const buffer = metal.Buffer{ .id = 100 + i, .data = try a.alignedAlloc(u8, .@"16", bytes) }; @field(metadata, field) = .{ .buffer = buffer }; } - defer inline for (@typeInfo(gpu.Metadata).@"struct".field_names) |field| a.free(@field(metadata, field).buffer.data); + defer inline for (@typeInfo(gpu.Metadata).@"struct".field_names) |field| { + const ref = if (comptime std.mem.eql(u8, field, "flows")) @field(metadata, field).? else @field(metadata, field); + a.free(ref.buffer.data); + }; const state = try pool.committed(0, 0, true); @memset(@constCast(state), 0x12); const other = try pool.committed(0, 1, true); diff --git a/zig/src/server/auth_scope.zig b/zig/src/server/auth_scope.zig index d6db0ca0f42..fb81ae6e699 100644 --- a/zig/src/server/auth_scope.zig +++ b/zig/src/server/auth_scope.zig @@ -75,13 +75,22 @@ pub fn allows(scopes: Scopes, method: []const u8, raw_path: []const u8) bool { if (scopes.admin) return true; const route = routePath(raw_path); if (std.mem.eql(u8, method, "GET")) { - if ((scopes.inference or scopes.read) and oneOf(route, &listing)) return true; + if ((scopes.inference or scopes.read) and (oneOf(route, &listing) or modelId(route) != null)) return true; return scopes.read and oneOf(route, &reading); } const put = std.mem.eql(u8, method, "PUT") and putRoute(route); return scopes.inference and (std.mem.eql(u8, method, "POST") or put) and oneOf(route, &inferring); } +/// The id in GET /v1/models/{id} or /models/{id}, still escaped; a path ending in /models stays the listing's alias. +pub fn modelId(route: []const u8) ?[]const u8 { + if (std.mem.endsWith(u8, route, "/models")) return null; + for ([_][]const u8{ "/v1/models/", "/models/" }) |head| { + if (route.len > head.len and std.mem.startsWith(u8, route, head)) return route[head.len..]; + } + return null; +} + /// A key that may open a Responses WebSocket: admin, or inference (each create is checked again over the socket). pub fn allowsUpgrade(scopes: Scopes) bool { return scopes.admin or scopes.inference; diff --git a/zig/src/server/auth_scope_http_test.zig b/zig/src/server/auth_scope_http_test.zig index 31555f49d0d..427cd91d751 100644 --- a/zig/src/server/auth_scope_http_test.zig +++ b/zig/src/server/auth_scope_http_test.zig @@ -244,8 +244,10 @@ test "auth scopes HTTP: inference and read are separate grants and full keys kee var arena = std.heap.ArenaAllocator.init(t.allocator); defer arena.deinit(); const a = arena.allocator(); - for ([_][]const u8{ "/models", "/v1/models", "/v1/models/?x=1" }) |path| for ([_][]const u8{ "read-secret", "infer-secret" }) |key| + for ([_][]const u8{ "/models", "/v1/models", "/v1/models/?x=1", "/v1/models/m", "/models/m/" }) |path| for ([_][]const u8{ "read-secret", "infer-secret" }) |key| try expectStatus(try h.ask(a, "GET", path, key, ""), 200); + try expectStatus(try h.ask(a, "GET", "/v1/models/other", "read-secret", ""), 404); + try expectStatus(try h.ask(a, "GET", "/v1/models/m", "", ""), 401); for ([_][]const u8{ "/metrics", "/v1/metrics", "/v1/load", "/memory", "/v1/memory", "/stats", "/dashboard" }) |path| { try expectStatus(try h.ask(a, "GET", path, "read-secret", ""), 200); try expectStatus(try h.ask(a, "GET", path, "infer-secret", ""), 403); diff --git a/zig/src/server/auth_scope_test.zig b/zig/src/server/auth_scope_test.zig index 47c79080cae..997d04f6225 100644 --- a/zig/src/server/auth_scope_test.zig +++ b/zig/src/server/auth_scope_test.zig @@ -105,6 +105,23 @@ test "auth scopes: route grants are exact and every other method or resource is try t.expect(!scope.allows(.{}, "GET", "/v1/models")); } +test "auth scopes: one model's entry is granted with the listing, by GET only, and a /models suffix stays refused" { + const infer: scope.Scopes = .{ .inference = true }; + const read: scope.Scopes = .{ .read = true }; + const both: scope.Scopes = .{ .inference = true, .read = true }; + for ([_][]const u8{ "/v1/models/m", "/models/m", "/v1/models/org/m", "/v1/models/org%2Fm", "/models/m/?x=1" }) |path| { + try t.expect(scope.allows(read, "GET", path) and scope.allows(infer, "GET", path)); + for ([_][]const u8{ "POST", "DELETE", "PUT", "HEAD", "OPTIONS" }) |method| try t.expect(!scope.allows(both, method, path)); + try t.expect(!scope.allows(.{}, "GET", path)); + } + for ([_][]const u8{ "/v1/models/m/models", "/models/models", "/x/models/m", "/v2/models/m" }) |path| + try t.expect(!scope.allows(both, "GET", path)); + try t.expectEqualStrings("org/m", scope.modelId("/v1/models/org/m").?); + try t.expectEqualStrings("org%2Fm", scope.modelId("/models/org%2Fm").?); + for ([_][]const u8{ "/v1/models", "/models", "/v1/models/", "/v1/models/m/models", "/v1/modelsx" }) |route| + try t.expect(scope.modelId(route) == null); +} + fn denial(scopes: scope.Scopes, text: []const u8) !?scope.Denial { var arena = std.heap.ArenaAllocator.init(t.allocator); defer arena.deinit(); diff --git a/zig/src/server/benchmark_server.zig b/zig/src/server/benchmark_server.zig index 8b1c6a31e06..035c5707a1c 100644 --- a/zig/src/server/benchmark_server.zig +++ b/zig/src/server/benchmark_server.zig @@ -46,10 +46,10 @@ pub fn argv(a: Allocator, plan: Plan) ![]const []const u8 { return out.items; } -/// The parent's variables without the API key, request log, seed salt and upload token; no live line or update check. +/// Parent variables minus the API key, request log, journal, seed salt and upload token; no live line or update check. pub fn environ(a: Allocator, parent: *const std.process.Environ.Map) !std.process.Environ.Map { var env = try parent.clone(a); - for ([_][]const u8{ "TENSORFOLD_API_KEY", "TENSORFOLD_REQUEST_LOG", "TENSORFOLD_SEED_SALT", "TENSORFOLD_BENCHMARK_TOKEN" }) |k| _ = env.orderedRemove(k); + for ([_][]const u8{ "TENSORFOLD_API_KEY", "TENSORFOLD_REQUEST_LOG", "TENSORFOLD_REQUEST_JOURNAL", "TENSORFOLD_SEED_SALT", "TENSORFOLD_BENCHMARK_TOKEN" }) |k| _ = env.orderedRemove(k); try env.put("TENSORFOLD_NO_LIVE", "1"); try env.put("TENSORFOLD_NO_UPDATE_CHECK", "1"); try env.put("HF_HUB_OFFLINE", "1"); diff --git a/zig/src/server/benchmark_server_test.zig b/zig/src/server/benchmark_server_test.zig index b1c12fc09b3..f10ff7f3bef 100644 --- a/zig/src/server/benchmark_server_test.zig +++ b/zig/src/server/benchmark_server_test.zig @@ -51,9 +51,9 @@ test "the child's environment drops the key, log, salt and token and turns off t defer arena.deinit(); const a = arena.allocator(); var parent: std.process.Environ.Map = .init(a); - for ([_][]const u8{ "TENSORFOLD_API_KEY", "TENSORFOLD_REQUEST_LOG", "TENSORFOLD_SEED_SALT", "TENSORFOLD_BENCHMARK_TOKEN", "PATH" }) |k| try parent.put(k, "x"); + for ([_][]const u8{ "TENSORFOLD_API_KEY", "TENSORFOLD_REQUEST_LOG", "TENSORFOLD_REQUEST_JOURNAL", "TENSORFOLD_SEED_SALT", "TENSORFOLD_BENCHMARK_TOKEN", "PATH" }) |k| try parent.put(k, "x"); const env = try server.environ(a, &parent); - for ([_][]const u8{ "TENSORFOLD_API_KEY", "TENSORFOLD_REQUEST_LOG", "TENSORFOLD_SEED_SALT", "TENSORFOLD_BENCHMARK_TOKEN" }) |k| try std.testing.expect(env.get(k) == null); + for ([_][]const u8{ "TENSORFOLD_API_KEY", "TENSORFOLD_REQUEST_LOG", "TENSORFOLD_REQUEST_JOURNAL", "TENSORFOLD_SEED_SALT", "TENSORFOLD_BENCHMARK_TOKEN" }) |k| try std.testing.expect(env.get(k) == null); for ([_][]const u8{ "TENSORFOLD_NO_LIVE", "TENSORFOLD_NO_UPDATE_CHECK", "HF_HUB_OFFLINE" }) |k| try std.testing.expectEqualStrings("1", env.get(k).?); try std.testing.expectEqualStrings("x", env.get("PATH").?); } diff --git a/zig/src/server/chat.zig b/zig/src/server/chat.zig index f8851faba6b..3eb1098fd7f 100644 --- a/zig/src/server/chat.zig +++ b/zig/src/server/chat.zig @@ -5,6 +5,7 @@ const json = @import("json"); const errors = @import("errors.zig"); const fields_mod = @import("fields.zig"); const reply_text = @import("reply_text.zig"); +const recipient_reply = @import("recipient_reply.zig"); const tool_stream = @import("tool_stream.zig"); const prompt_mod = @import("prompt.zig"); const images = @import("images.zig"); @@ -27,6 +28,7 @@ pub const Prompt = union(enum) { text: []const u8, ids: []const u32 }; pub const Input = struct { /// The client itself asked for thinking off (no server, template or route default counts): it must be honored. explicit_off: bool = false, + trace: ?*@import("request_trace.zig").Trace = null, // the request's journal records; null when the journal is off /// The server's own request (a compaction summary, a lesson's wordings): it never takes --instruct-sampling's set. own: bool = false, messages: Value = .{ .array = &.{} }, @@ -120,13 +122,6 @@ test "Server recovery: token staging allocation failure ends the loop without co } } -/// Python's ``bool(fields.get(key))`` on the sampling fields. -fn flag(f: Value, key: []const u8) ?bool { - const v = f.get(key) orelse return null; - if (v == .null) return null; - return v.truthy(); -} - /// A request rendered and checked but not submitted; it holds the preparing count until generate or release. pub const Prepared = struct { input: Input, @@ -160,13 +155,13 @@ pub fn prepare(srv: *Server, cx: *Cx, input: Input, gone: anytype) Failure!Prepa if (preparing) _ = srv.preparing.fetchAdd(1, .acq_rel); errdefer srv.release(preparing, null); if (gone.check()) return error.Cancelled; - const thinking = input.prompt == null and (flag(f, "enable_thinking") orelse srv.config.enable_thinking); + const thinking = input.prompt == null and (fields_mod.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 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.clear_thinking = fields_mod.flag(f, "clear_thinking"); cx.template_fields = f; const rendered = try prompt_mod.prepare(srv, cx, input, thinking, effort); if (gone.check()) return error.Cancelled; @@ -230,7 +225,8 @@ pub fn prepare(srv: *Server, cx: *Cx, input: Input, gone: anytype) Failure!Prepa request.logprobs = input.logprobs; request.prompt_logprobs = input.prompt_logprobs; if (try engine_refusal.of(srv.engine, cx, &request)) |message| return cx.refuse(message); - return .{ .input = input, .request = request, .prompt_len = rendered.ids.len, .received = received, .thinking = thinking, .reasoning = reasoning, .effort = effort, .sampled = sampling != null, .drafts = drafts, .token_ids = flag(f, "return_token_ids") orelse false, .stops = stops_opt, .preparing = preparing, .frames = rendered.frames }; + if (input.trace) |trace| trace.prepared(&request, thinking, effort); + return .{ .input = input, .request = request, .prompt_len = rendered.ids.len, .received = received, .thinking = thinking, .reasoning = reasoning, .effort = effort, .sampled = sampling != null, .drafts = drafts, .token_ids = fields_mod.flag(f, "return_token_ids") orelse false, .stops = stops_opt, .preparing = preparing, .frames = rendered.frames }; } /// Submit a prepared request and collect its reply; ``sink`` hears the stream (null: not streamed). @@ -273,9 +269,10 @@ pub fn generate(srv: *Server, cx: *Cx, prepared: Prepared, sink: ?Sink, gone: an }; srv.release(preparing, null); // a background request waits only while a foreground one prepares preparing = false; - var gen: Generation = .{ .srv = srv, .a = a, .box = &box, .id = id, .asked = input.cancel, .reply_id = input.id, .seed = if (request.sampling) |v| v.seed else null, .sink = sink, .thinking = prepared.reasoning or (srv.text.vtable.format != .kimi and srv.info.capability(.reasoning) and reply_text.isChannel(srv.markers)), .chat = input.prompt == null, .stops = .{ .strings = stops_opt.strings }, .ignore_eos = stops_opt.ignore_eos, .max_tokens = request.max_tokens, .tools = input.tools, .token_ids = prepared.token_ids, .lp = if (request.logprobs != null) .{ .positions = if (sink) |s| s.tokens != null else false } else null, .loop_stop = request.loop_stop, .single = flag(input.fields, "tool_call_single") orelse false, .recover = input.prompt == null and request.structure == null }; + var gen: Generation = .{ .srv = srv, .a = a, .box = &box, .id = id, .asked = input.cancel, .reply_id = input.id, .seed = if (request.sampling) |v| v.seed else null, .sink = sink, .thinking = prepared.reasoning or (srv.text.vtable.format != .kimi and srv.info.capability(.reasoning) and reply_text.isChannel(srv.markers)), .chat = input.prompt == null, .stops = .{ .strings = stops_opt.strings }, .ignore_eos = stops_opt.ignore_eos, .max_tokens = request.max_tokens, .tools = input.tools, .token_ids = prepared.token_ids, .lp = if (request.logprobs != null) .{ .positions = if (sink) |s| s.tokens != null else false } else null, .loop_stop = request.loop_stop, .single = fields_mod.flag(input.fields, "tool_call_single") orelse false, .recover = input.prompt == null and request.structure == null }; defer srv.noteRequest(prepared.prompt_len, cached_tokens.within(box.cached, prepared.prompt_len), gen.collected.items.len, box.stats.drafted, box.stats.accepted, box.stats.rounds, received, gen.first_ns, gen.last_ns, box.stats.prefill_seconds, if (box.stats.prefill_seconds != null) box.stats.queued_seconds else null); errdefer if (!gen.engine_done) gen.cancel(); // the engine writes to the mailbox until it says finished + if (srv.recipients and input.prompt == null) gen.recipient = try recipient_reply.Reading.of(a, srv.text, request.prompt, input.tools, prepared.reasoning); const result: Failure!Reply = blk: { if (sink) |s| if (s.begin) |begin| begin(s.ctx, prepared.prompt_len) catch break :blk error.Cancelled; if (sink != null and input.tools.len > 0 and srv.text.vtable.format != .kimi) gen.calls = tool_stream.Streamer.init(a, input.tools) catch |e| break :blk e; diff --git a/zig/src/server/chat_generation.zig b/zig/src/server/chat_generation.zig index 3868f69293c..69fb3c771b3 100644 --- a/zig/src/server/chat_generation.zig +++ b/zig/src/server/chat_generation.zig @@ -4,6 +4,7 @@ const api = @import("engine_api"); const json = @import("json"); const chat = @import("chat.zig"); const reply_text = @import("reply_text.zig"); +const recipient_reply = @import("recipient_reply.zig"); const tool_stream = @import("tool_stream.zig"); const tool_parse = @import("tool_parse.zig"); const tool_lfm2 = @import("tool_lfm2.zig"); @@ -55,6 +56,7 @@ pub const Generation = struct { token_ids: bool, // "return_token_ids": the response's tensorfold block carries the reply's token ids tools: []const Value, calls: ?tool_stream.Streamer = null, + recipient: ?recipient_reply.Reading = null, // a chat whose reply is messages to recipients (Muse Spark's) collected: std.ArrayList(u32) = .empty, visible: reply_text.Incremental = .{}, kimi: ?@import("kimi_reply.zig").Stream = null, @@ -151,10 +153,10 @@ pub const Generation = struct { const text = try @import("tool_minimax.zig").dsml(g.a, raw_visible, g.tools); // MiniMax-M3's calls as DSML var answer = text; var thought: []const u8 = ""; - if (g.thinking) { + if (g.thinking or g.recipient != null) { const original_close = try g.visible.closeOf(g.a, reply_text.decodeText, g.srv.text, g.srv.close_id); const close = try @import("tool_minimax.zig").closeAfterRewrite(g.a, raw_visible, g.tools, original_close); - const split = try reply_text.splitThinkingAt(g.a, text, false, g.srv.markers, close); + const split = if (g.recipient) |*r| try r.split(g.a, text, .streaming) else try reply_text.splitThinkingAt(g.a, text, false, g.srv.markers, close); thought = g.streamed_reasoning.after(reply_text.pyStrip(split.reasoning), true); // the whole reply strips it if (thought.len > 0) try g.streamed_reasoning.set(g.a, reply_text.pyStrip(split.reasoning), thought); answer = split.answer; @@ -303,11 +305,12 @@ pub const Generation = struct { const text = if (close.len > 0) try std.mem.concat(a, u8, &.{ visible, close }) else visible; var content: []const u8 = text; var reasoning: ?[]const u8 = null; + const read = g.thinking or g.recipient != null; // the reply's split text is its content if (native) |n| { const r = reply_text.pyStrip(n.reasoning); reasoning = if (r.len > 0) r else null; - } else if (g.thinking) { - const split = try reply_text.splitThinkingAt(a, text, true, g.srv.markers, close_at.?); + } else if (read) { + const split = if (g.recipient) |*r| try r.split(a, text, if (std.mem.eql(u8, reason, "length")) .cut else if (g.stops.matched(raw) != null) .stopped else .ended) else try reply_text.splitThinkingAt(a, text, true, g.srv.markers, close_at.?); const r = reply_text.pyStrip(split.reasoning); reasoning = if (r.len > 0) r else null; content = split.answer; @@ -325,17 +328,17 @@ pub const Generation = struct { const thought = g.streamed_reasoning.text.items; if (reasoning) |r| if (std.mem.startsWith(u8, r, thought) and r.len > thought.len) try g.emit(sink, try deltaOf(a, "reasoning_content", r[thought.len..])); - const shown = if (g.calls != null) try tool_stream.endProse(a, content, if (g.thinking) content else text, g.tools, reason, g.single) else content; + const shown = if (g.calls != null) try tool_stream.endProse(a, content, if (read) content else text, g.tools, reason, g.single) else content; const sent = g.streamed.text.items; const rest = if (std.mem.startsWith(u8, shown, sent) and shown.len > sent.len) shown[sent.len..] else ""; if (rest.len > 0) try g.emit(sink, .{ .string = rest }); if (g.calls) |*c| { // the streamer reads the closers as markup the model wrote, so the call ends with the same deltas var out: std.ArrayList(Value) = .empty; - const final_text = if (g.thinking) content else text; + const final_text = if (read) content else text; if (std.mem.eql(u8, reason, "length")) { try c.finishCut(final_text, &out); - } else if (close.len > 0 or c.streamed) { + } else if (close.len > 0 or c.streamed or g.recipient != null) { try c.finish(final_text, &out); } for (out.items) |d| try g.emit(sink, d); diff --git a/zig/src/server/cli.zig b/zig/src/server/cli.zig index 4a384032bfc..cd80de16cad 100644 --- a/zig/src/server/cli.zig +++ b/zig/src/server/cli.zig @@ -52,7 +52,7 @@ pub const flags = [_]Flag{ .{ .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{ +} ++ @import("drama_cfg.zig").flags ++ @import("admission_cli.zig").flags ++ @import("connection_cli.zig").flags ++ @import("voice_cli.zig").flags ++ [_]Flag{ .{ .name = "--alias", .kind = .append, .native = true }, .{ .name = "--name-priority", .kind = .append, .native = true }, .{ .name = "--api-key", .kind = .append, .native = true }, @@ -165,7 +165,7 @@ pub const flags = [_]Flag{ }; /// The variables this binary honours as the Python engine does, then the CUDA build's or the Metal build's. -pub const env = [_][]const u8{ "TENSORFOLD_API_KEY", "TENSORFOLD_NO_LIVE", "TENSORFOLD_SEED_SALT", "TENSORFOLD_REQUEST_LOG", "TENSORFOLD_TOOL_ID_KEY_FILE", "TENSORFOLD_PHASE_METRICS", "TENSORFOLD_LIBPDFIUM", "TENSORFOLD_MAX_PDF_PAGES", "TENSORFOLD_DEVICE_CHECK", "HF_HOME", "HF_HUB_CACHE", "BRAVE_SEARCH_API_KEY" } ++ +pub const env = [_][]const u8{ "TENSORFOLD_API_KEY", "TENSORFOLD_NO_LIVE", "TENSORFOLD_SEED_SALT", "TENSORFOLD_REQUEST_LOG", "TENSORFOLD_REQUEST_JOURNAL", "TENSORFOLD_TOOL_ID_KEY_FILE", "TENSORFOLD_PHASE_METRICS", "TENSORFOLD_LIBPDFIUM", "TENSORFOLD_MAX_PDF_PAGES", "TENSORFOLD_DEVICE_CHECK", "HF_HOME", "HF_HUB_CACHE", "BRAVE_SEARCH_API_KEY" } ++ (if (cuda_build) [_][]const u8{ "TF_CUDA_DEVICE", "TF_CUDA_SEGMENTS", "TENSORFOLD_CUDA_KERNELS", "TENSORFOLD_MEMORY_RESERVE_GIB", "TENSORFOLD_CUDA_MEMORY_LIMIT_GB", "TENSORFOLD_P2P_DIAGNOSTICS", "TENSORFOLD_P2P_PROBE" } else [_][]const u8{}) ++ (if (builtin.os.tag == .macos) [_][]const u8{"TF_Q27_PROFILE"} else [_][]const u8{}); pub const Args = struct { @@ -194,6 +194,7 @@ pub const Args = struct { max_frames: ?u32 = null, silence: api.speech_guard.Config = .{}, cfg: @import("drama_cfg.zig").Flags = .{}, + voice: @import("voice_cli.zig").Flags = .{}, redraw: @import("speech_redraw.zig").Policy = .{}, speed_up: ?[]const u8 = null, // speed-up mode: this Mac's settings for the two-Mac link (Flash Next and the GLMs) prompt_cache_gib: ?f64 = null, // kept prompt states' budget (0: none; null: what 70% of RAM leaves past the loaded server) @@ -418,6 +419,7 @@ fn apply(a: Allocator, out: *Args, name: []const u8, value: ?[]const u8, u: *Usa } if (try cudaFlag(a, out, name, v, u) or try gpuFlag(a, out, name, v, u)) return; if (try @import("cli_recall.zig").flag(a, out, name, v, u)) return; + if (@import("voice_cli.zig").apply(&out.voice, name)) return; if (out.cfg.set(name, v) catch return fail(u, a, "--cfg-gamma must be 0 (off) or 1 (unguided) through 5", .{})) return; if (@import("cli_fsr.zig").apply(out, name, v) catch |err| return fail(u, a, "argument {s}: {s}", .{ name, @errorName(err) })) return; if (is(name, "--voices")) { diff --git a/zig/src/server/device/profile_test.zig b/zig/src/server/device/profile_test.zig index e59ba49b047..2a3a78cd940 100644 --- a/zig/src/server/device/profile_test.zig +++ b/zig/src/server/device/profile_test.zig @@ -76,6 +76,37 @@ test "device profile: a scan saves, reads back whole, and stays until the hardwa try t.expectEqual(@as(?profile.Due, .hardware), (try scan.current(a, t.io, file, more, newer, "x", false, false)).scanned); } +test "device profile: a changed Mac wired limit refreshes the saved budget" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const root = try folder(a); + defer std.Io.Dir.cwd().deleteTree(t.io, root) catch {}; + const file = try std.fs.path.join(a, &.{ root, ".tensorfold", "device.json" }); + const mac = try parse.macos(a, "aarch64", fx.m1_max_wired); + const bin: scan.Binary = .{ .version = "test", .offer = .{ .version = "test", .backends = &.{"metal"} } }; + const original = try scan.current(a, t.io, file, mac, bin, "2026-11-13T01:00:00Z", false, true); + try t.expect(original.saved and original.support.budget > 0); + const unchanged = try scan.current(a, t.io, file, mac, bin, "2026-11-13T02:00:00Z", false, true); + try t.expectEqual(@as(?profile.Due, null), unchanged.scanned); + try t.expect(scan.fresh(a, t.io, file, mac, bin.version) != null); + + var limited = mac; + limited.gpu_wired_limit = bin.offer.margin; + const stale = scan.fresh(a, t.io, file, limited, bin.version); + const lower = try scan.current(a, t.io, file, limited, bin, "2026-11-13T03:00:00Z", false, true); + try t.expectEqual(@as(?profile.Due, .hardware), lower.scanned); + try t.expect(stale == null); + try t.expect(lower.saved); + try t.expectEqual(limited.gpu_wired_limit, lower.doc.machine.gpu_wired_limit); + try t.expectEqual(@as(u64, 0), lower.support.budget); + try t.expect(scan.fresh(a, t.io, file, limited, bin.version) != null); + + const restored = try scan.current(a, t.io, file, mac, bin, "2026-11-13T04:00:00Z", false, true); + try t.expectEqual(@as(?profile.Due, .hardware), restored.scanned); + try t.expectEqual(original.support.budget, restored.support.budget); +} + test "device profile: a driver that does not answer keeps the OS's listing and a quick scan" { var arena: std.heap.ArenaAllocator = .init(t.allocator); defer arena.deinit(); diff --git a/zig/src/server/device/scan.zig b/zig/src/server/device/scan.zig index 6bcac9fc537..c239aa2a191 100644 --- a/zig/src/server/device/scan.zig +++ b/zig/src/server/device/scan.zig @@ -24,12 +24,19 @@ pub const Current = struct { saved: bool = false, }; +fn rescanReason(old: ?profile.Doc, quick: Machine, version: []const u8, asked: bool, want_full: bool) ?profile.Due { + const saved = old orelse return .missing; + const fp = machine.fingerprint(quick); + if (profile.due(saved, &fp, version, asked, want_full)) |why| return why; + if (quick.os == .macos and saved.machine.gpu_wired_limit != quick.gpu_wired_limit) return .hardware; + return null; +} + /// `quick` is this call's own listing (read.quick); `full` asks the driver when the profile is only a quick one. pub fn current(a: Allocator, io: std.Io, file: ?[]const u8, quick: Machine, bin: Binary, now: []const u8, asked: bool, full: bool) !Current { - const fp = machine.fingerprint(quick); const old = if (file) |f| profile.load(a, io, f) else null; const ask = full and bin.driver != null and quick.os != .macos; - const why = profile.due(old, &fp, bin.version, asked, ask) orelse { + const why = rescanReason(old, quick, bin.version, asked, ask) orelse { const doc = old.?; return .{ .doc = doc, .support = try support.derive(a, doc.machine, bin.offer) }; }; @@ -41,6 +48,7 @@ pub fn current(a: Allocator, io: std.Io, file: ?[]const u8, quick: Machine, bin: kind = .full; }; const s = try support.derive(a, m, bin.offer); + const fp = machine.fingerprint(quick); const doc: profile.Doc = .{ .scanned_at = now, .binary_version = bin.version, .fingerprint = try a.dupe(u8, &fp), .scan = kind, .machine = m, .support = s }; var saved = false; if (file) |f| { @@ -52,9 +60,8 @@ pub fn current(a: Allocator, io: std.Io, file: ?[]const u8, quick: Machine, bin: /// The saved profile when it is current for this machine and binary; null otherwise. Never scans or writes. pub fn fresh(a: Allocator, io: std.Io, file: ?[]const u8, quick: Machine, version: []const u8) ?profile.Doc { - const fp = machine.fingerprint(quick); const old = profile.load(a, io, file orelse return null) orelse return null; - return if (profile.due(old, &fp, version, false, false) == null) old else null; + return if (rescanReason(old, quick, version, false, false) == null) old else null; } /// The driver's GPUs in its own order (CUDA's ordinals), in place of the OS's listing of that vendor; the rest after. diff --git a/zig/src/server/drama_voice.zig b/zig/src/server/drama_voice.zig index 7f6ba7aacd1..be06690f5c7 100644 --- a/zig/src/server/drama_voice.zig +++ b/zig/src/server/drama_voice.zig @@ -31,7 +31,12 @@ pub fn parse(a: Allocator, bytes: []const u8) ![]const prompt.Reference { .ok => |v| v, else => return error.BadVoice, }; - if (!std.mem.eql(u8, doc.strField("format") orelse "", "drama3-http-voice/1")) return error.BadVoice; + return parseDoc(a, doc); +} + +/// A parsed voice file, or an inline voice object, checked as a catalog file is. +pub fn parseDoc(a: Allocator, doc: json.Value) ![]const prompt.Reference { + if (doc != .object or !std.mem.eql(u8, doc.strField("format") orelse "", "drama3-http-voice/1")) return error.BadVoice; const source = doc.get("source") orelse return error.MissingAttestation; const kind = source.strField("kind") orelse return error.MissingAttestation; if (!std.mem.eql(u8, kind, "synthetic") and !std.mem.eql(u8, kind, "self") and !std.mem.eql(u8, kind, "consented")) return error.MissingAttestation; @@ -61,10 +66,13 @@ pub fn parse(a: Allocator, bytes: []const u8) ![]const prompt.Reference { /// A checked file's optional one-line `description`, shown in the listing. fn describe(a: Allocator, bytes: []const u8) ![]const u8 { - const doc = switch (try json.parse(a, bytes)) { + return describeDoc(switch (try json.parse(a, bytes)) { .ok => |v| v, else => return error.BadVoice, - }; + }); +} + +pub fn describeDoc(doc: json.Value) ![]const u8 { if (doc.get("description") == null) return ""; const s = doc.strField("description") orelse return error.BadVoice; if (s.len > 200 or !std.unicode.utf8ValidateSlice(s)) return error.BadVoice; diff --git a/zig/src/server/drama_voice_routes.zig b/zig/src/server/drama_voice_routes.zig new file mode 100644 index 00000000000..64da74c2456 --- /dev/null +++ b/zig/src/server/drama_voice_routes.zig @@ -0,0 +1,97 @@ +//! POST /v1/voices and DELETE /v1/voices/NAME under --manage-voices: attested catalog voices added and deleted live. +const std = @import("std"); +const json = @import("json"); +const prompt = @import("drama_prompt"); +const errors = @import("errors.zig"); +const http_body = @import("http_body.zig"); +const routes = @import("routes.zig"); +const voice = @import("drama_voice.zig"); +const tool = @import("drama_voice_tool.zig"); +const Server = @import("server.zig").Server; +const Conn = @import("http_conn.zig").Conn; +const Value = json.Value; +const Allocator = std.mem.Allocator; + +const unattested = "a voice needs source.kind synthetic, self or consented and a source.note"; +const bad_voice = "a voice needs 1 to 4 references, each a transcript a speech request accepts and its codes"; + +/// One frame stands in for the codes, so a request the catalog would refuse never reaches the encoder. +const placeholder = [1][10]i32{@splat(0)}; + +fn refuse(conn: *Conn, a: Allocator, code: u16, message: []const u8) void { + const o = json.newObject(a) catch return; + o.put(a, "message", .{ .string = message }) catch return; + o.put(a, "type", .{ .string = if (code >= 500) "server_error" else "invalid_request_error" }) catch return; + const wrapped = json.newObject(a) catch return; + wrapped.put(a, "error", .{ .object = o }) catch return; + routes.sendValue(conn, a, code, .{ .object = wrapped }); +} + +const Made = struct { file: []const u8, refs: []const prompt.Reference, description: []const u8 }; + +/// The attested voice file a request describes: a voice file's own fields, or a WAV with its transcript. +fn made(srv: *Server, a: Allocator, body: Value) !Made { + const description = voice.describeDoc(body) catch return error.BadDescription; + const source = body.get("source") orelse .null; + const kind = source.strField("kind") orelse ""; + const note = source.strField("note") orelse ""; + const audio = body.get("audio") orelse .null; + if (audio == .null) { + const refs = try voice.parseDoc(a, body); + return .{ .file = try tool.document(a, kind, note, description, refs), .refs = refs, .description = description }; + } + if (body.get("references") != null) return error.AudioAndReferences; + if (audio != .string) return error.BadAudio; + const text = body.strField("text") orelse return error.BadVoice; + _ = try tool.document(a, kind, note, description, &.{.{ .transcript = text, .codes = &placeholder }}); + const decoder = std.base64.standard.Decoder; + const wav = try a.alloc(u8, decoder.calcSizeForSlice(audio.string) catch return error.BadAudio); + decoder.decode(wav, audio.string) catch return error.BadAudio; + const encode = srv.engine.vtable.encode_voice orelse return error.NoEncoder; + const codes = try encode(srv.engine.ctx, a, wav); + if (codes.len == 0 or codes.len > voice.max_frames) return error.BadWav; + const refs = try a.dupe(prompt.Reference, &.{.{ .transcript = text, .codes = codes }}); + return .{ .file = try tool.document(a, kind, note, description, refs), .refs = refs, .description = description }; +} + +pub fn post(srv: *Server, conn: *Conn, a: Allocator) void { + var cx: errors.Cx = .{ .a = a }; + const body = http_body.readJson(conn, &cx) catch |e| return if (e == error.OutOfMemory) refuse(conn, a, 500, "out of memory") else refuse(conn, a, 400, cx.message); + const name = body.strField("name") orelse ""; + if (body != .object or !voice.validName(name)) return refuse(conn, a, 400, "name must be 1 to 64 letters, digits, '-' or '_', starting with a letter or digit, and not default"); + const voice_file = made(srv, a, body) catch |e| return switch (e) { + error.MissingAttestation => refuse(conn, a, 400, unattested), + error.BadVoice => refuse(conn, a, 400, bad_voice), + error.BadDescription => refuse(conn, a, 400, "description must be UTF-8 text of at most 200 bytes"), + error.AudioAndReferences => refuse(conn, a, 400, "send audio with its text, or a voice file's references, not both"), + error.BadAudio => refuse(conn, a, 400, "audio must be a WAV file in standard base64"), + error.BadWav => refuse(conn, a, 400, "audio must be a RIFF WAVE file (PCM 8, 16, 24 or 32-bit, or float32) of up to 30 seconds"), + error.NoEncoder => refuse(conn, a, 400, "this engine does not encode reference audio: send a voice file's references"), + error.Closed => refuse(conn, a, 503, "the speech engine is closed"), + error.OutOfMemory => refuse(conn, a, 500, "out of memory"), + else => refuse(conn, a, 500, "the reference audio could not be encoded"), + }; + const added = srv.voices.put(name, voice_file.file, voice_file.refs, voice_file.description) catch |e| return switch (e) { + error.TooManyVoices => refuse(conn, a, 409, "the catalog holds its most voices: delete one first"), + error.OutOfMemory => refuse(conn, a, 500, "out of memory"), + else => refuse(conn, a, 500, "the voice file could not be written to --voices"), + }; + const reply = json.newObject(a) catch return; + reply.put(a, "id", .{ .string = name }) catch return; + reply.put(a, "description", .{ .string = voice_file.description }) catch return; + reply.put(a, "added", .{ .bool = added }) catch return; + routes.sendValue(conn, a, if (added) 201 else 200, .{ .object = reply }); +} + +pub fn delete(srv: *Server, conn: *Conn, a: Allocator, name: []const u8) void { + srv.voices.remove(name, srv.config.voice.default) catch |e| return switch (e) { + error.UnknownVoice => refuse(conn, a, 404, "no such voice in the catalog"), + error.DefaultVoice => refuse(conn, a, 409, "the configured --default-voice cannot be deleted"), + error.OutOfMemory => refuse(conn, a, 500, "out of memory"), + else => refuse(conn, a, 500, "the voice file could not be removed from --voices"), + }; + const reply = json.newObject(a) catch return; + reply.put(a, "id", .{ .string = name }) catch return; + reply.put(a, "deleted", .{ .bool = true }) catch return; + routes.sendValue(conn, a, 200, .{ .object = reply }); +} diff --git a/zig/src/server/drama_voice_store.zig b/zig/src/server/drama_voice_store.zig new file mode 100644 index 00000000000..fb6a5143c96 --- /dev/null +++ b/zig/src/server/drama_voice_store.zig @@ -0,0 +1,141 @@ +//! The served voice catalog: --voices DIR at startup, then admin adds and deletes, read under one lock. +const std = @import("std"); +const json = @import("json"); +const prompt = @import("drama_prompt"); +const voice = @import("drama_voice.zig"); +const Allocator = std.mem.Allocator; +const Voice = voice.Voice; + +/// Readers copy what they need under the lock, so a change frees the old catalog at once and no request sees it go. +pub const Store = struct { + gpa: Allocator = undefined, + io: std.Io = undefined, + /// --voices DIR: where added voices are written and deleted ones removed; null keeps changes in memory. + dir: ?[]const u8 = null, + mutex: std.Io.Mutex = .init, + arena: ?*std.heap.ArenaAllocator = null, + voices: []const Voice = &.{}, + + /// The catalog in `dir`, sorted by name, as startup loads it. + pub fn load(s: *Store, dir: []const u8) !void { + var scratch: std.heap.ArenaAllocator = .init(s.gpa); + defer scratch.deinit(); + try s.swap(try voice.load(scratch.allocator(), s.io, dir)); + } + + pub fn deinit(s: *Store) void { + if (s.arena) |arena| free(s.gpa, arena); + s.arena = null; + s.voices = &.{}; + } + + /// The references `requested` selects (as drama_voice.select), copied into `a`. + pub fn select(s: *Store, a: Allocator, default: []const u8, requested: []const u8) ![]const prompt.Reference { + s.mutex.lockUncancelable(s.io); + defer s.mutex.unlock(s.io); + const refs = try voice.select(s.voices, default, requested); + const copy = try a.alloc(prompt.Reference, refs.len); + for (refs, copy) |ref, *out| out.* = .{ .transcript = try a.dupe(u8, ref.transcript), .codes = try a.dupe([10]i32, ref.codes) }; + return copy; + } + + /// GET /v1/voices's reply, its names and descriptions copied into `a`. + pub fn listing(s: *Store, a: Allocator) !json.Value { + s.mutex.lockUncancelable(s.io); + defer s.mutex.unlock(s.io); + const copy = try a.alloc(Voice, s.voices.len); + for (s.voices, copy) |v, *out| out.* = .{ .name = try a.dupe(u8, v.name), .references = &.{}, .description = try a.dupe(u8, v.description) }; + return voice.listing(a, copy); + } + + pub fn count(s: *Store) usize { + s.mutex.lockUncancelable(s.io); + defer s.mutex.unlock(s.io); + return s.voices.len; + } + + /// Adds or replaces `name`, first writing `file` (its attested voice file) when there is a directory; true: added. + pub fn put(s: *Store, name: []const u8, file: []const u8, refs: []const prompt.Reference, description: []const u8) !bool { + if (!voice.validName(name)) return error.BadVoiceName; + s.mutex.lockUncancelable(s.io); + defer s.mutex.unlock(s.io); + var next: std.ArrayList(Voice) = .empty; + defer next.deinit(s.gpa); + for (s.voices) |v| if (!std.mem.eql(u8, v.name, name)) try next.append(s.gpa, v); + const added = next.items.len == s.voices.len; + if (added and next.items.len >= max_voices) return error.TooManyVoices; + try next.append(s.gpa, .{ .name = name, .references = refs, .description = description }); + if (s.dir) |dir| try write(s.gpa, s.io, dir, name, file); + try s.swap(next.items); + return added; + } + + /// Deletes `name`, and its file when there is a directory; the configured default voice stays. + pub fn remove(s: *Store, name: []const u8, default: []const u8) !void { + if (!voice.validName(name)) return error.UnknownVoice; + if (std.mem.eql(u8, name, default)) return error.DefaultVoice; + s.mutex.lockUncancelable(s.io); + defer s.mutex.unlock(s.io); + var next: std.ArrayList(Voice) = .empty; + defer next.deinit(s.gpa); + for (s.voices) |v| if (!std.mem.eql(u8, v.name, name)) try next.append(s.gpa, v); + if (next.items.len == s.voices.len) return error.UnknownVoice; + if (s.dir) |dir| try unlink(s.io, dir, name); + try s.swap(next.items); + } + + /// The catalog becomes a sorted copy of `voices` and the old one is freed; the caller holds the lock or is alone. + pub fn swap(s: *Store, voices: []const Voice) !void { + const arena = try s.gpa.create(std.heap.ArenaAllocator); + arena.* = .init(s.gpa); + errdefer free(s.gpa, arena); + const a = arena.allocator(); + const copy = try a.alloc(Voice, voices.len); + for (voices, copy) |v, *out| { + const refs = try a.alloc(prompt.Reference, v.references.len); + for (v.references, refs) |ref, *r| r.* = .{ .transcript = try a.dupe(u8, ref.transcript), .codes = try a.dupe([10]i32, ref.codes) }; + out.* = .{ .name = try a.dupe(u8, v.name), .references = refs, .description = try a.dupe(u8, v.description) }; + } + std.mem.sort(Voice, copy, {}, struct { + fn less(_: void, left: Voice, right: Voice) bool { + return std.mem.lessThan(u8, left.name, right.name); + } + }.less); + if (s.arena) |old| free(s.gpa, old); + s.arena = arena; + s.voices = copy; + } +}; + +pub const max_voices = 256; + +fn free(gpa: Allocator, arena: *std.heap.ArenaAllocator) void { + arena.deinit(); + gpa.destroy(arena); +} + +/// NAME.json through a fresh hidden temporary in the same directory, renamed over any older file. +fn write(a: Allocator, io: std.Io, path: []const u8, name: []const u8, file: []const u8) !void { + var dir = try std.Io.Dir.cwd().openDir(io, path, .{}); + defer dir.close(io); + var nonce: [8]u8 = undefined; + io.random(&nonce); + const temp = try std.fmt.allocPrint(a, ".{s}.json.{x}", .{ name, std.mem.readInt(u64, &nonce, .native) }); + defer a.free(temp); + const final = try std.fmt.allocPrint(a, "{s}.json", .{name}); + defer a.free(final); + try dir.writeFile(io, .{ .sub_path = temp, .data = file, .flags = .{ .exclusive = true } }); + errdefer dir.deleteFile(io, temp) catch {}; + try dir.rename(temp, dir, final, io); +} + +fn unlink(io: std.Io, path: []const u8, name: []const u8) !void { + var dir = try std.Io.Dir.cwd().openDir(io, path, .{}); + defer dir.close(io); + var buf: [80]u8 = undefined; + dir.deleteFile(io, try std.fmt.bufPrint(&buf, "{s}.json", .{name})) catch |e| if (e != error.FileNotFound) return e; +} + +test { + _ = @import("drama_voice_store_test.zig"); +} diff --git a/zig/src/server/drama_voice_store_test.zig b/zig/src/server/drama_voice_store_test.zig new file mode 100644 index 00000000000..5412312abd5 --- /dev/null +++ b/zig/src/server/drama_voice_store_test.zig @@ -0,0 +1,62 @@ +//! The voice catalog store: copies outlive changes, files follow the catalog, the default voice stays. +const std = @import("std"); +const voice = @import("drama_voice.zig"); +const Store = @import("drama_voice_store.zig").Store; +const t = std.testing; + +const tone = + \\{"format":"drama3-http-voice/1","source":{"kind":"synthetic","note":"Tone A."}, + \\"references":[{"text":"One cloud.","codes":[[1,2,3,4,5,6,7,8,9,10]]}]} +; +const bright = + \\{"format":"drama3-http-voice/1","source":{"kind":"synthetic","note":"Tone B."},"description":"Bright.", + \\"references":[{"text":"Two clouds.","codes":[[2,2,3,4,5,6,7,8,9,10]]}]} +; + +test "voice store: a request's copy outlives a delete, and files follow adds and deletes" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = t.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(t.io, .{ .sub_path = "tone.json", .data = tone }); + var store: Store = .{ .gpa = t.allocator, .io = t.io, .dir = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}", .{tmp.sub_path}) }; + defer store.deinit(); + try store.load(store.dir.?); + const held = try store.select(a, "default", "tone"); + try t.expect(try store.put("bright", bright, try voice.parse(a, bright), "Bright.")); + try t.expect(!try store.put("bright", bright, try voice.parse(a, bright), "Bright.")); + try store.remove("tone", "default"); + try t.expectEqualStrings("One cloud.", held[0].transcript); + try t.expectEqual(@as(i32, 1), held[0].codes[0][0]); + try t.expectError(error.UnknownVoice, store.select(a, "default", "tone")); + try t.expectEqual(@as(usize, 0), (try store.select(a, "default", "default")).len); + try t.expectError(error.FileNotFound, tmp.dir.access(t.io, "tone.json", .{})); + try t.expectEqualStrings(bright, try tmp.dir.readFileAlloc(t.io, "bright.json", a, .limited(voice.max_file_bytes))); + const listed = try @import("json").stringify(a, try store.listing(a), .{}); + try t.expect(std.mem.indexOf(u8, listed, "\"voices\": [\"default\", \"bright\"]") != null); + try t.expect(std.mem.indexOf(u8, listed, "\"description\": \"Bright.\"") != null); + try t.expectError(error.UnknownVoice, store.remove("tone", "default")); + try t.expectError(error.DefaultVoice, store.remove("bright", "bright")); + try t.expectError(error.BadVoiceName, store.put("default", bright, &.{}, "")); + // a restart reads back what the routes wrote + var again: Store = .{ .gpa = t.allocator, .io = t.io }; + defer again.deinit(); + try again.load(store.dir.?); + try t.expectEqual(@as(usize, 1), again.count()); + try t.expectEqualStrings("Two clouds.", (try again.select(a, "default", "bright"))[0].transcript); +} + +test "voice store: without a directory changes stay in memory, and the catalog is capped" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var store: Store = .{ .gpa = t.allocator, .io = t.io }; + defer store.deinit(); + const refs = try voice.parse(a, tone); + for (0..@import("drama_voice_store.zig").max_voices) |i| try t.expect(try store.put(try std.fmt.allocPrint(a, "v{d}", .{i}), tone, refs, "")); + try t.expectError(error.TooManyVoices, store.put("one-more", tone, refs, "")); + try t.expect(!try store.put("v7", tone, refs, "kept")); + try store.remove("v7", "default"); + try t.expect(try store.put("one-more", tone, refs, "")); +} diff --git a/zig/src/server/drama_voice_tool.zig b/zig/src/server/drama_voice_tool.zig index df985d69b0a..ea3b09f4511 100644 --- a/zig/src/server/drama_voice_tool.zig +++ b/zig/src/server/drama_voice_tool.zig @@ -62,7 +62,7 @@ pub fn run(a: Allocator, io: std.Io, err: *Writer, argv: []const []const u8) !u8 if (kind == null or note == null) return refuse(err, unattested); const refs = try a.alloc(prompt.Reference, texts.items.len); for (refs, texts.items) |*ref, text| ref.* = .{ .transcript = text, .codes = &placeholder }; - _ = document(a, kind.?, note.?, refs) catch |e| return refuse(err, switch (e) { + _ = document(a, kind.?, note.?, "", refs) catch |e| return refuse(err, switch (e) { error.MissingAttestation => unattested, error.BadVoice => "drama3-voice: refused, give 1 to 4 references, each a transcript a speech request accepts\n", else => return e, @@ -156,7 +156,7 @@ fn encode( if (bytes.len % @sizeOf([10]i32) != 0) return error.BadCodes; ref.codes = std.mem.bytesAsSlice([10]i32, bytes); } - try private.writeFile(io, .{ .sub_path = base, .data = try document(a, kind, note, refs), .flags = .{ .exclusive = true } }); + try private.writeFile(io, .{ .sub_path = base, .data = try document(a, kind, note, "", refs), .flags = .{ .exclusive = true } }); try private.rename(base, parent, base, io); return 0; } @@ -166,15 +166,19 @@ fn refuse(err: *Writer, message: []const u8) !u8 { return 2; } -/// The voice file's JSON, accepted by the catalog's own parser. -fn document(a: Allocator, kind: []const u8, note: []const u8, refs: []const prompt.Reference) ![]const u8 { +/// The voice file's JSON, with its listing `description` when not empty, accepted by the catalog's own parser. +pub fn document(a: Allocator, kind: []const u8, note: []const u8, description: []const u8, refs: []const prompt.Reference) ![]const u8 { var out: Writer.Allocating = .init(a); const w = &out.writer; try w.writeAll("{\"format\": \"drama3-http-voice/1\", \"source\": {\"kind\": "); try json.writeString(w, kind, .{ .ascii = false }); try w.writeAll(", \"note\": "); try json.writeString(w, note, .{ .ascii = false }); - try w.writeAll("},\n\"references\": ["); + if (description.len > 0) { + try w.writeAll("}, \"description\": "); + try json.writeString(w, description, .{ .ascii = false }); + } else try w.writeByte('}'); + try w.writeAll(",\n\"references\": ["); for (refs, 0..) |ref, r| { try w.writeAll(if (r == 0) "\n{\"text\": " else ",\n{\"text\": "); try json.writeString(w, ref.transcript, .{ .ascii = false }); @@ -188,6 +192,10 @@ fn document(a: Allocator, kind: []const u8, note: []const u8, refs: []const prom } try w.writeAll("\n]}\n"); _ = try voice.parse(a, out.written()); + if (description.len > 0) _ = try voice.describeDoc(switch (try json.parse(a, out.written())) { + .ok => |doc| doc, + else => return error.BadVoice, + }); return out.written(); } diff --git a/zig/src/server/fields.zig b/zig/src/server/fields.zig index aad8720a231..c1449a84bb3 100644 --- a/zig/src/server/fields.zig +++ b/zig/src/server/fields.zig @@ -22,6 +22,13 @@ pub fn typeName(v: Value) []const u8 { }; } +/// Python's ``bool(fields.get(key))`` on the sampling fields. +pub fn flag(f: Value, key: []const u8) ?bool { + const v = f.get(key) orelse return null; + if (v == .null) return null; + return v.truthy(); +} + /// ``fields.get`` on a body that is not an object fails as Python's AttributeError does. pub fn requireObject(cx: *Cx, v: Value) errors.Refused!void { if (v != .object) return cx.fail(.other, "'{s}' object has no attribute 'get'", .{typeName(v)}); diff --git a/zig/src/server/late_system.zig b/zig/src/server/late_system.zig new file mode 100644 index 00000000000..b63efe0052e --- /dev/null +++ b/zig/src/server/late_system.zig @@ -0,0 +1,14 @@ +//! The startup probe for a template's late system role. +const std = @import("std"); +const json = @import("json"); +const model_text = @import("model_text.zig"); +const Allocator = std.mem.Allocator; + +/// ``template_late_system``: "system" when the template keeps a later system message in place, else "user". +pub fn lateSystem(a: Allocator, text: model_text.Text) ![]const u8 { + const probe_text = "tensorfold-late-system-probe"; + const probe = (try json.parse(a, "[{\"role\": \"system\", \"content\": \"s\"}, {\"role\": \"user\", \"content\": \"u\"}, {\"role\": \"assistant\", \"content\": \"a\"}, {\"role\": \"system\", \"content\": \"tensorfold-late-system-probe\"}, {\"role\": \"user\", \"content\": \"v\"}]")).ok; + var problem: []const u8 = ""; + const rendered = text.render(a, probe, .{ .add_generation_prompt = false }, &problem) catch return "user"; + return if (std.mem.indexOf(u8, rendered.text, probe_text) != null) "system" else "user"; +} diff --git a/zig/src/server/models_id_test.zig b/zig/src/server/models_id_test.zig new file mode 100644 index 00000000000..345b69688a6 --- /dev/null +++ b/zig/src/server/models_id_test.zig @@ -0,0 +1,102 @@ +//! GET /v1/models/{id} through the dispatcher: the listing's entry by id or alias, escaped or raw, else a 404. +const std = @import("std"); +const json = @import("json"); +const Server = @import("server.zig").Server; +const Conn = @import("http_conn.zig").Conn; +const routes = @import("routes.zig"); +const discovery = @import("models_input_types_test.zig"); +const t = std.testing; + +const Reply = struct { status: []const u8, body: json.Value }; + +/// A GET of `path` as the dispatcher answers it: the status line and the JSON body. +fn get(a: std.mem.Allocator, srv: *Server, path: []const u8) !Reply { + var wire: discovery.Wire = .{ .out = .init(a) }; + var conn: Conn = .{ .fd = -1, .peer = "", .buf = &.{}, .gpa = a, .version = "HTTP/1.1", .method = "GET", .path = path, .write_hooks = .{ .ctx = &wire, .write = discovery.Wire.write } }; + routes.dispatch(srv, &conn, a); + const bytes = wire.out.written(); + const split = std.mem.indexOf(u8, bytes, "\r\n\r\n") orelse return error.NoReply; + return .{ .status = bytes[0..std.mem.indexOf(u8, bytes, "\r\n").?], .body = (try json.parse(a, bytes[split + 4 ..])).ok }; +} + +/// An entry's JSON with its created time zeroed: two reads may fall in different seconds. +fn timeless(a: std.mem.Allocator, entry: json.Value) ![]const u8 { + try entry.object.put(a, "created", .{ .int = "0" }); + return json.stringify(a, entry, .{}); +} + +fn served() Server { + var srv = discovery.server(null, true); + srv.config.model_ids = &.{ "model", "alias", "example-org/model", "50%off" }; + return srv; +} + +test "model discovery by id: the served name and every alias return the listing's own entry" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var srv = served(); + const listed = try discovery.listed(a, &srv); + for (srv.config.model_ids, listed) |id, entry| { + for ([_][]const u8{ "/v1/models/", "/models/" }) |head| { + const got = try get(a, &srv, try std.mem.concat(a, u8, &.{ head, id })); + try t.expectEqualStrings("HTTP/1.1 200 OK", got.status); + try t.expectEqualStrings(try timeless(a, entry), try timeless(a, got.body)); + } + } +} + +test "model discovery by id: an org/name id is found raw, escaped with %2F or %2f, and past a query or slash" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var srv = served(); + const paths = [_][]const u8{ + "/v1/models/example-org/model", "/v1/models/example-org%2Fmodel", "/models/example-org%2fmodel", + "/v1/models/%65xample-org/model", "/v1/models/example-org/model/?x=1", + }; + for (paths) |path| { + const got = try get(a, &srv, path); + try t.expectEqualStrings("HTTP/1.1 200 OK", got.status); + try t.expectEqualStrings("example-org/model", got.body.strField("id").?); + try t.expectEqualStrings("model", got.body.strField("object").?); + } + // a % that escapes no hex pair leaves the id as written; %25 is the escaped percent sign + for ([_][]const u8{ "/v1/models/50%off", "/v1/models/50%25off" }) |path| + try t.expectEqualStrings("50%off", (try get(a, &srv, path)).body.strField("id").?); +} + +test "model discovery by id: any other id is a 404 model_not_found naming the decoded id" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var srv = served(); + const cases = [_][2][]const u8{ + .{ "/v1/models/missing", "model 'missing' is not served here" }, + .{ "/v1/models/example-org%2Fmissing", "model 'example-org/missing' is not served here" }, + .{ "/models/MODEL", "model 'MODEL' is not served here" }, + .{ "/v1/models/example-org", "model 'example-org' is not served here" }, + }; + for (cases) |c| { + const got = try get(a, &srv, c[0]); + try t.expectEqualStrings("HTTP/1.1 404 Not Found", got.status); + const err = got.body.get("error").?; + try t.expectEqualStrings(c[1], err.strField("message").?); + try t.expectEqualStrings("invalid_request_error", err.strField("type").?); + try t.expectEqualStrings("model", err.strField("param").?); + try t.expectEqualStrings("model_not_found", err.strField("code").?); + } +} + +test "model discovery by id: a path ending in /models still lists every model" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var srv = served(); + for ([_][]const u8{ "/v1/models", "/models/", "/v1/models/model/models", "/models/models" }) |path| { + const got = try get(a, &srv, path); + try t.expectEqualStrings("HTTP/1.1 200 OK", got.status); + try t.expectEqualStrings("list", got.body.strField("object").?); + try t.expectEqual(srv.config.model_ids.len, got.body.get("data").?.array.len); + } +} diff --git a/zig/src/server/models_input_types_test.zig b/zig/src/server/models_input_types_test.zig index 2e39c9a92d0..8f0743b99c5 100644 --- a/zig/src/server/models_input_types_test.zig +++ b/zig/src/server/models_input_types_test.zig @@ -9,9 +9,9 @@ const messages = @import("messages.zig"); const images = @import("images.zig"); const t = std.testing; -const Wire = struct { +pub const Wire = struct { out: std.Io.Writer.Allocating, - fn write(ctx: *anyopaque, bytes: []const u8) error{Closed}!void { + pub 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; } @@ -41,7 +41,7 @@ fn noTemplate(_: *anyopaque) []const u8 { } /// 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 { +pub fn server(vision: ?api.Vision, video_decoder: bool) Server { var srv: Server = undefined; srv.io = t.io; srv.info = .{ .vision = vision }; @@ -57,7 +57,7 @@ fn server(vision: ?api.Vision, video_decoder: bool) Server { } /// GET /v1/models' `data`, as a client reads it. -fn listed(a: std.mem.Allocator, srv: *Server) ![]json.Value { +pub 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); diff --git a/zig/src/server/openai.zig b/zig/src/server/openai.zig index a3f7e333ec2..1b5987da538 100644 --- a/zig/src/server/openai.zig +++ b/zig/src/server/openai.zig @@ -20,6 +20,7 @@ const routes = @import("routes.zig"); const warm = @import("warm.zig"); const cortheon = @import("cortheon/cortheon.zig"); const cancel_ids = @import("cancel_ids.zig"); +const ClientOut = @import("openai_client.zig").ClientOut; const prompt_list = @import("prompt_list.zig"); const completion_prompt = @import("completion_prompt.zig"); const Server = @import("server.zig").Server; @@ -57,38 +58,6 @@ pub fn post(srv: *Server, conn: *Conn, a: Allocator, is_chat: bool) void { run(srv, a, client.out(), .{ .conn = conn }, is_chat, body); } -/// A chat reply written straight to the client. -const ClientOut = struct { - startup_at: ?u64 = null, - conn: *Conn, - a: Allocator, - - fn out(c: *ClientOut) Out { - return .{ .ctx = c, .vt = &.{ .open = open, .event = event, .reply = reply, .keepalive = keepalive } }; - } - - fn open(ctx: *anyopaque, _: usize) error{Closed}!void { - const c: *ClientOut = @ptrCast(@alignCast(ctx)); - return sse.open(c.conn); - } - - fn event(ctx: *anyopaque, payload: ?Value) error{Closed}!void { - const c: *ClientOut = @ptrCast(@alignCast(ctx)); - return if (payload) |p| sse.data(c.conn, c.a, p) else sse.done(c.conn); - } - - fn reply(ctx: *anyopaque, status: u16, payload: Value) void { - const c: *ClientOut = @ptrCast(@alignCast(ctx)); - routes.sendValue(c.conn, c.a, status, payload); - if (status == 200 and c.conn.response_complete and !c.conn.broken) @import("startup_receipt.zig").complete(c.startup_at, payload); - } - - fn keepalive(ctx: *anyopaque) error{Closed}!void { - const c: *ClientOut = @ptrCast(@alignCast(ctx)); - return sse.comment(c.conn); - } -}; - /// Whether the client has gone, read between rounds (Python's socket_cancellation). pub const Gone = @import("stream_live.zig").Gone; @@ -200,11 +169,16 @@ pub fn runNamed(srv: *Server, a: Allocator, out: Out, gone: Gone, is_chat: bool, 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, .skip_request_log = skip_request_log }; + // TENSORFOLD_REQUEST_JOURNAL: off, `observed` is `out` and the trace does nothing + var trace: @import("request_trace.zig").Trace = .{ .journal = srv.config.journal, .a = a, .id = id, .parent = out }; + defer trace.finish(); + const observed = trace.out(); + if (trace.begin(raw, is_chat, gone.conn.key_label orelse "")) return trace.refuse(id); 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); const body = errorBody(a, &cx, field) catch return; - out.vt.reply(out.ctx, cx.status(), wrapError(a, body) catch return); + observed.vt.reply(observed.ctx, cx.status(), wrapError(a, body) catch return); return; }; p.input.id = id; @@ -214,9 +188,10 @@ pub fn runNamed(srv: *Server, a: Allocator, out: Out, gone: Gone, is_chat: bool, cancel_ids.registry.add(srv.io, &names, &asked); defer cancel_ids.registry.remove(srv.io, &names, &asked); p.input.cancel = &asked.asked; - if (p.prompts.len > 0) return prompt_list.run(srv, a, out, gone, p, p.prompts, raw); + if (p.prompts.len > 0) return prompt_list.run(srv, a, observed, gone, p, p.prompts, raw); + if (srv.config.journal != null) p.input.trace = &trace; const turn = cortheon.begin(srv, a, raw, id, is_chat, &p.input); - var r: Run = .{ .srv = srv, .a = a, .out = out, .is_chat = is_chat, .plan = p, .id = id, .created = std.Io.Clock.real.now(srv.io).toSeconds(), .turn = turn, .call_ids = .{ .key = &srv.tool_ids, .body = raw } }; + var r: Run = .{ .srv = srv, .a = a, .out = observed, .is_chat = is_chat, .plan = p, .id = id, .created = std.Io.Clock.real.now(srv.io).toSeconds(), .turn = turn, .call_ids = .{ .key = &srv.tool_ids, .body = raw } }; if (p.stream) r.stream(gone, field) else r.whole(gone, field); } diff --git a/zig/src/server/openai_client.zig b/zig/src/server/openai_client.zig new file mode 100644 index 00000000000..3f3b31122ac --- /dev/null +++ b/zig/src/server/openai_client.zig @@ -0,0 +1,39 @@ +//! A chat reply written straight to the client: its own Out, an SSE stream or one JSON reply (openai.zig). +const std = @import("std"); +const sse = @import("sse.zig"); +const routes = @import("routes.zig"); +const Conn = @import("http_conn.zig").Conn; +const Value = @import("json").Value; +const Out = @import("openai.zig").Out; +const Allocator = std.mem.Allocator; + +pub const ClientOut = struct { + startup_at: ?u64 = null, + conn: *Conn, + a: Allocator, + + pub fn out(c: *ClientOut) Out { + return .{ .ctx = c, .vt = &.{ .open = open, .event = event, .reply = reply, .keepalive = keepalive } }; + } + + fn open(ctx: *anyopaque, _: usize) error{Closed}!void { + const c: *ClientOut = @ptrCast(@alignCast(ctx)); + return sse.open(c.conn); + } + + fn event(ctx: *anyopaque, payload: ?Value) error{Closed}!void { + const c: *ClientOut = @ptrCast(@alignCast(ctx)); + return if (payload) |p| sse.data(c.conn, c.a, p) else sse.done(c.conn); + } + + fn reply(ctx: *anyopaque, status: u16, payload: Value) void { + const c: *ClientOut = @ptrCast(@alignCast(ctx)); + routes.sendValue(c.conn, c.a, status, payload); + if (status == 200 and c.conn.response_complete and !c.conn.broken) @import("startup_receipt.zig").complete(c.startup_at, payload); + } + + fn keepalive(ctx: *anyopaque) error{Closed}!void { + const c: *ClientOut = @ptrCast(@alignCast(ctx)); + return sse.comment(c.conn); + } +}; diff --git a/zig/src/server/prompt.zig b/zig/src/server/prompt.zig index 763a683e4b9..a4c224a59d7 100644 --- a/zig/src/server/prompt.zig +++ b/zig/src/server/prompt.zig @@ -49,7 +49,7 @@ pub fn renderStarts(srv: *Server, cx: *Cx, messages: Value, tools: []const Value .tools = if (tools.len > 0) Value{ .array = @constCast(tools) } else null, .add_generation_prompt = generation, .enable_thinking = thinking, - .reasoning_effort = if (thinking) effort else cx.named_effort, // off: only an effort the request named + .reasoning_effort = if (thinking) effort else cx.named_effort orelse srv.off_effort, .clear_thinking = cx.clear_thinking, .tool_choice = cx.template_fields.get("tool_choice"), .response_format = cx.template_fields.get("response_format"), diff --git a/zig/src/server/recipient_cut_test.zig b/zig/src/server/recipient_cut_test.zig new file mode 100644 index 00000000000..6b619a25a0f --- /dev/null +++ b/zig/src/server/recipient_cut_test.zig @@ -0,0 +1,69 @@ +//! A recipient reply max_tokens cuts inside a call message: its cut call, whole and streamed, as #1299's GLM call. +const std = @import("std"); +const harness = @import("recipient_reply_test.zig"); +const Text = harness.Text; + +const head = "{\"model\":\"test-model\",\"messages\":[{\"role\":\"user\",\"content\":\"x\"}]," ++ + "\"tools\":[{\"type\":\"function\",\"function\":{\"name\":\"write_file\",\"parameters\":{\"type\":\"object\"," ++ + "\"properties\":{\"path\":{\"type\":\"string\"},\"content\":{\"type\":\"string\"},\"limit\":{\"type\":\"integer\"}}}}}]"; +const thought = " to=self<|message|>A file is needed.<|eom|>"; +const call = "<|start|>assistant to=write_file<|message|>"; +const path = "\n\nnotes.txt\n"; +const opened = path ++ "The history of"; +const rest = " the bicycle\n\n<|eot|>"; +const args = "{\"path\":\"notes.txt\",\"content\":\"The history of"; + +/// `cut` then `rest`, max_tokens at `cut`'s end: whole and streamed replies agree at every stride (null: unchecked). +fn expectCut(cut: []const u8, calls: usize, arguments: []const u8, content: ?[]const u8, extra: []const u8) !void { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var text: Text = .{}; + const n = (try text.tokens(a, cut)).len; + const body = try std.fmt.allocPrint(a, "{s},\"max_tokens\":{d}{s}", .{ head, n, extra }); + var whole = try harness.send(.{}, try std.mem.concat(a, u8, &.{ cut, rest }), 4096, try std.mem.concat(a, u8, &.{ body, "}" })); + defer whole.deinit(); + try std.testing.expectEqual(@as(u16, 200), whole.status); + for ([_]usize{ 1, 3, 7, 4096 }) |stride| { + var streamed = try harness.send(.{}, try std.mem.concat(a, u8, &.{ cut, rest }), stride, try std.mem.concat(a, u8, &.{ body, ",\"stream\":true}" })); + defer streamed.deinit(); + for ([_]*const harness.Shown{ &whole, &streamed }) |s| { + try std.testing.expectEqual(calls, s.calls); + try std.testing.expectEqualStrings(arguments, s.arguments.items); + if (content) |c| try std.testing.expectEqualStrings(c, s.content.items); + for ([_][]const u8{ "atem", "\n\na.txt" ++ + "\n\n<|eom|>"; + try expectCut(thought ++ first ++ call ++ opened, 2, "{\"path\":\"a.txt\"}" ++ args, "", ""); + // inside a value's closer, between parameters, inside a parameter's name and after the invoke closed + try expectCut(thought ++ call ++ opened ++ "\n\n12"; + try expectCut(thought ++ call ++ limit, 1, "{\"limit\":12", "", ""); +} + +test "recipient cut: a call cut before its invoke names the tool is the header's call" { + inline for (.{ "", "\nassistant to=write_fi", 0, "", "", ""); +} + +test "recipient cut: the one-call policy hides the cut call" { + try expectCut(thought ++ call ++ opened, 0, "", null, ",\"parallel_tool_calls\":false"); +} diff --git a/zig/src/server/recipient_reply.zig b/zig/src/server/recipient_reply.zig new file mode 100644 index 00000000000..c2fdcb4f5c1 --- /dev/null +++ b/zig/src/server/recipient_reply.zig @@ -0,0 +1,270 @@ +//! Replies written as messages to recipients: `<|start|>assistant to=R<|message|>body<|eom|>`, the last one `<|eot|>`. +const std = @import("std"); +const json = @import("json"); +const reply_text = @import("reply_text.zig"); +const tool_specs = @import("tool_specs.zig"); +const Allocator = std.mem.Allocator; +const Value = json.Value; +const Split = reply_text.Split; +const findTag = reply_text.findTag; + +const start = "<|start|>"; +const message = "<|message|>"; +const ends = [_][]const u8{ "<|eom|>", "<|eot|>" }; +const closers = ends ++ [_][]const u8{start}; +const block = ""; +const block_close = ""; +const invoke = "" } }; + var out: std.ArrayList(u8) = .empty; + var i: usize = 0; + outer: while (i < s.len) { + for (escapes) |e| if (std.mem.startsWith(u8, s[i..], e[0])) { + try out.appendSlice(a, e[1]); + i += e[0].len; + continue :outer; + }; + try out.append(a, s[i]); + i += 1; + } + return out.items; +} + +/// The offered tool's spelling of `name`, as tool_parse matches a call's name; null: not offered. +fn offered(a: Allocator, name: []const u8, tools: []const Value) Allocator.Error!?[]const u8 { + for (tools) |tool| { + const spelled = try tool_specs.toolName(a, tool); + if (spelled.len > 0 and std.ascii.eqlIgnoreCase(spelled, name)) return spelled; + } + return null; +} + +/// A call message as the `` markup tool_parse reads, a cut one left open; null: keep the model's text. +pub fn calls(a: Allocator, body: []const u8, recipient: []const u8, tools: []const Value, end: End) Allocator.Error!?[]const u8 { + if (tools.len == 0 or end == .stopped) return null; // no tools offered, or a stop string inside the call + const cut = end == .cut; + const lead = reply_text.pyLstrip(body); + if (!std.mem.startsWith(u8, lead, block) and !(cut and std.mem.startsWith(u8, block, lead))) return null; + var out: std.ArrayList(u8) = .empty; + var pos: usize = 0; + while (findTag(body, pos, invoke)) |s| { + const q = std.mem.indexOfPos(u8, body, s + invoke.len, "\">") orelse break; // its name is still being written + const name = (try offered(a, try unescape(a, body[s + invoke.len .. q]), tools)) orelse return null; + const close = std.mem.indexOfPos(u8, body, q, invoke_close); + const stop = close orelse body.len; + if (out.items.len > 0) try out.append(a, '\n'); + try out.print(a, "\n\n", .{name}); + var p = q + 2; + while (findTag(body[0..stop], p, parameter)) |ps| { + const pq = std.mem.indexOfPos(u8, body[0..stop], ps + parameter.len, "\">") orelse break; // a cut name + const pe = std.mem.indexOfPos(u8, body[0..stop], pq + 2, parameter_close); + const value = body[pq + 2 .. pe orelse stop - (if (cut) reply_text.partialTag(body[pq + 2 .. stop], parameter_close) else 0)]; + try out.print(a, "\n{s}", .{ try unescape(a, body[ps + parameter.len .. pq]), value }); + if (pe == null and cut) return out.items; // a cut value: its closers never came + try out.appendSlice(a, "\n\n"); + p = pe orelse stop; + } + if (close == null and cut) return out.items; // cut between its parameters + try out.appendSlice(a, "\n"); + pos = if (close) |c| c + invoke_close.len else stop; + if (cut and findTag(body, pos, invoke) == null and findTag(body, pos, block_close) == null) return out.items; // block open + try out.appendSlice(a, ""); + } + if (out.items.len == 0 and cut and findTag(body, 0, block_close) == null) { // cut before its invoke names it + const name = (try offered(a, recipient, tools)) orelse return null; + return try std.fmt.allocPrint(a, "\n\n", .{name}); + } + return if (out.items.len > 0) out.items else null; +} + +/// The open message of a reply being read: its kind, recipient and body start, how far it was scanned and sent. +const Open = struct { kind: Kind, recipient: []const u8, b0: usize, scan: usize, sent: usize = 0, begun: bool = false }; + +/// The longest closer less a byte: a closer that began before a scan's end is found from this far back. +const reach = blk: { + var n: usize = 0; + for (closers) |e| n = @max(n, e.len); + break :blk n - 1; +}; + +/// `bytes` after `out`'s; a full list moves to a buffer twice the size, the old left intact for earlier splits. +fn keep(a: Allocator, out: *std.ArrayList(u8), bytes: []const u8) Allocator.Error!void { + if (out.items.len + bytes.len > out.capacity) { + const cap = @max(256, 2 * (out.items.len + bytes.len)); + const mem = try a.alloc(u8, cap); + @memcpy(mem[0..out.items.len], out.items); + out.items = mem[0..out.items.len]; + out.capacity = cap; + } + out.appendSliceAssumeCapacity(bytes); +} + +/// A message's new text since the last call, its end's whitespace held back (the finished reply strips it). +fn grow(a: Allocator, out: *std.ArrayList(u8), o: *Open, text: []const u8) Allocator.Error!void { + const body = reply_text.pyRstrip(text); + var piece = body[@min(o.sent, body.len)..]; + o.sent = @max(o.sent, body.len); + if (!o.begun) { + piece = reply_text.pyLstrip(piece); + if (piece.len == 0) return; + o.begun = true; + if (out.items.len > 0) try keep(a, out, "\n\n"); + } + try keep(a, out, piece); +} + +/// How one chat's reply reads: the message its prompt left open, the request's tools and thinking switch. +pub const Reading = struct { + /// The prompt after its last `<|start|>` when no end follows it (`assistant`, or `assistant to=self<|message|>`). + lead: []const u8 = "", + tools: []const Value = &.{}, + /// Thinking on: `self` messages are the reasoning; off, they stay out of the reply. + reasoning: bool = true, + /// What a streamed reply's text gave so far: each call reads only the bytes after the last (the reply grows). + st: State = .{}, + + const State = struct { + ready: bool = false, + at: usize = 0, // the reply read up to here: closed messages before it, or the open message's body start + open: ?Open = null, + any: bool = false, // a message seen + first: bool = true, // the next header is the reply's first, which the prompt's lead begins + reasoning: std.ArrayList(u8) = .empty, + answer: std.ArrayList(u8) = .empty, + len: usize = 0, // the reply's length at the last call, and its last bytes (the same reply grew since) + tail: [32]u8 = undefined, + tail_n: usize = 0, + }; + + pub fn of(a: Allocator, text: anytype, prompt: []const u32, tools: []const Value, thinking: bool) Allocator.Error!Reading { + var r: Reading = .{ .tools = tools, .reasoning = thinking }; + const id = text.tokenId(start) orelse return r; + const at = std.mem.lastIndexOfScalar(u32, prompt, id) orelse return r; + const lead = try text.decode(a, prompt[at + 1 ..]); + for (ends) |e| if (std.mem.indexOf(u8, lead, e) != null) return r; + r.lead = lead; + return r; + } + + /// A fresh read: new lists (an earlier split's text stays as it was), the lead's open message if it has one. + fn restart(r: *Reading, a: Allocator) Allocator.Error!void { + r.st = .{ .ready = true }; + const m = findTag(r.lead, 0, message) orelse return; + var header = r.lead[0..m]; + if (std.mem.startsWith(u8, header, start)) header = header[start.len..]; + r.st.open = .{ .kind = kindOf(header), .recipient = try a.dupe(u8, recipientOf(header) orelse ""), .b0 = 0, .scan = 0 }; + r.st.any = true; + r.st.first = false; + } + + /// Whether `reply` is the last call's reply grown (else the read starts over). + fn grew(r: *const Reading, reply: []const u8) bool { + const st = &r.st; + if (!st.ready or reply.len < st.len) return false; + return std.mem.eql(u8, reply[st.len - st.tail_n .. st.len], st.tail[0..st.tail_n]); + } + + fn mark(r: *Reading, reply: []const u8) void { + r.st.len = reply.len; + r.st.tail_n = @min(reply.len, r.st.tail.len); + @memcpy(r.st.tail[0..r.st.tail_n], reply[reply.len - r.st.tail_n ..]); + } + + /// A reply with no header at its start (none in the prompt's lead): all of it is the answer, streamed as it comes. + fn plain(r: *const Reading, reply: []const u8, end: End) ?[]const u8 { + if (r.st.any) return null; + const p = reply_text.pyLstrip(reply); + if (std.mem.startsWith(u8, p, "<|") or std.mem.startsWith(u8, p, "to=")) return null; + if (end == .streaming and (p.len == 0 or std.mem.startsWith(u8, "<|", p) or std.mem.startsWith(u8, "to=", p))) return ""; + return reply_text.pyStrip(p); + } + + /// An open message's text into the split: reasoning and answer as they grow, a call once closed or at the end. + fn body(r: *Reading, a: Allocator, o: *Open, text: []const u8, done: bool, as: End) Allocator.Error!void { + switch (o.kind) { + .reasoning => if (r.reasoning) try grow(a, &r.st.reasoning, o, text), + .answer => try grow(a, &r.st.answer, o, text), + .call => if (done and !o.begun) try grow(a, &r.st.answer, o, (try calls(a, text, o.recipient, r.tools, as)) orelse text), + } + } + + /// (reasoning, answer) so far; a stream holds back open headers, calls and partial markers, so each split grows. + pub fn split(r: *Reading, a: Allocator, reply: []const u8, end: End) Allocator.Error!Split { + if (!r.grew(reply)) try r.restart(a); + defer r.mark(reply); + if (r.plain(reply, end)) |p| return .{ .reasoning = "", .answer = p }; + const st = &r.st; + while (true) { + if (st.open == null) { // the next header, the lead before the reply's first + const m = findTag(reply, st.at, message) orelse break; + var header = reply[st.at..m]; + if (st.first) header = try std.mem.concat(a, u8, &.{ r.lead, header }); + if (std.mem.startsWith(u8, header, start)) header = header[start.len..]; + st.first = false; + st.any = true; + st.open = .{ .kind = kindOf(header), .recipient = try a.dupe(u8, recipientOf(header) orelse ""), .b0 = m + message.len, .scan = m + message.len }; + st.at = m + message.len; + } + const o = &st.open.?; + var b1 = reply.len; + var next = reply.len; + var closed = false; + for (closers) |e| if (findTag(reply[0..b1], o.scan, e)) |at| { + b1 = at; + next = if (std.mem.eql(u8, e, start)) at else at + e.len; + closed = true; + }; + if (closed) { + try r.body(a, o, reply[o.b0..b1], true, .ended); + st.open = null; + st.at = next; + continue; + } + o.scan = @max(o.b0, reply.len -| reach); // a closer begun before the end is found next call + if (end == .streaming) { + var held: usize = 0; + for (closers) |e| held = @max(held, reply_text.partialTag(reply[o.b0..], e)); + try r.body(a, o, reply[o.b0 .. reply.len - held], false, end); + } else try r.body(a, o, reply[o.b0..], true, end); + break; + } + if (!st.any and end != .streaming) { // no message markup at all; a header the reply was cut in is no answer + const p = reply_text.pyStrip(reply); + return .{ .reasoning = "", .answer = if (std.mem.startsWith(u8, p, "to=")) "" else p }; + } + return .{ .reasoning = st.reasoning.items, .answer = st.answer.items }; + } +}; diff --git a/zig/src/server/recipient_reply_test.zig b/zig/src/server/recipient_reply_test.zig new file mode 100644 index 00000000000..d08480daa9e --- /dev/null +++ b/zig/src/server/recipient_reply_test.zig @@ -0,0 +1,431 @@ +//! Recipient replies (Muse Spark's template) split into reasoning, answer and calls, while Harmony replies keep theirs. +const std = @import("std"); +const api = @import("engine_api"); +const server = @import("root.zig"); +const json = server.json; +const model_text = @import("model_text.zig"); +const openai = @import("openai.zig"); +const recipient_reply = @import("recipient_reply.zig"); +const reply_text = @import("reply_text.zig"); +const tool_parse = @import("tool_parse.zig"); +const Conn = @import("http_conn.zig").Conn; + +const muse_markers = [_][]const u8{ "<|start|>", "<|message|>", "<|eom|>", "<|eot|>" }; +const harmony_markers = [_][]const u8{ "<|start|>", "<|message|>", "<|channel|>", "<|end|>", "<|return|>", "<|call|>" }; +const muse_eos = [_]u32{303}; // <|eot|> +const harmony_eos = [_]u32{304}; // <|return|> +const muse_template = "{%- set reasoning_effort_map = {'low': 8, 'xhigh': 512} -%}{{- '<|start|>assistant to=self<|message|>' -}}"; +const harmony_template = "{{- '<|start|>assistant<|channel|>commentary to=functions.' ~ name ~ '<|message|>' -}}"; +const all_bytes = blk: { + var all: [256]u8 = undefined; + for (&all, 0..) |*b, i| b.* = i; + break :blk all; +}; + +/// Bytes as tokens and each marker of the format as one token from 300; every prompt renders as `prompt`. +pub const Text = struct { + harmony: bool = false, + prompt: []const u8 = "prompt<|start|>assistant", // rendered after `effort=E;`, the effort the template heard + + fn text(t: *@This()) model_text.Text { + return .{ .ctx = t, .vtable = &.{ .encode = encode, .decode = decode, .token_id = tokenId, .token_string = tokenString, .vocab_size = vocabSize, .eos_ids = eosIds, .render = render, .template_source = templateSource } }; + } + + fn markers(t: *const Text) []const []const u8 { + return if (t.harmony) &harmony_markers else &muse_markers; + } + + fn piece(t: *const Text, id: u32) []const u8 { + return if (id >= 300) t.markers()[id - 300] else all_bytes[id..][0..1]; + } + + /// The reply's tokens: each marker the text spells is its token, every other byte its own. + pub fn tokens(t: *const Text, a: std.mem.Allocator, s: []const u8) ![]const u32 { + var out: std.ArrayList(u32) = .empty; + var i: usize = 0; + next: while (i < s.len) { + for (t.markers(), 0..) |m, k| if (std.mem.startsWith(u8, s[i..], m)) { + try out.append(a, @intCast(300 + k)); + i += m.len; + continue :next; + }; + try out.append(a, s[i]); + i += 1; + } + return out.items; + } + + fn encode(ctx: *anyopaque, a: std.mem.Allocator, input: []const u8, _: bool) model_text.Error![]u32 { + const t: *Text = @ptrCast(@alignCast(ctx)); + return @constCast(try t.tokens(a, input)); + } + + fn decode(ctx: *anyopaque, a: std.mem.Allocator, ids: []const u32) std.mem.Allocator.Error![]u8 { + const t: *Text = @ptrCast(@alignCast(ctx)); + var out: std.ArrayList(u8) = .empty; + for (ids) |id| try out.appendSlice(a, t.piece(id)); + return out.items; + } + + fn tokenId(ctx: *anyopaque, p: []const u8) ?u32 { + const t: *Text = @ptrCast(@alignCast(ctx)); + for (t.markers(), 0..) |m, k| if (std.mem.eql(u8, m, p)) return @as(u32, @intCast(300 + k)); + return null; + } + + fn tokenString(ctx: *anyopaque, a: std.mem.Allocator, id: u32) std.mem.Allocator.Error![]u8 { + return decode(ctx, a, &.{id}); + } + + fn vocabSize(_: *anyopaque) u32 { + return 310; + } + + fn eosIds(ctx: *anyopaque) []const u32 { + const t: *Text = @ptrCast(@alignCast(ctx)); + return if (t.harmony) &harmony_eos else &muse_eos; + } + + fn render(ctx: *anyopaque, a: std.mem.Allocator, _: json.Value, o: model_text.RenderOptions, _: *[]const u8) model_text.Error!model_text.Rendered { + const t: *Text = @ptrCast(@alignCast(ctx)); + return .{ .text = try std.mem.concat(a, u8, &.{ "effort=", o.reasoning_effort orelse "none", ";", t.prompt }) }; + } + + fn templateSource(ctx: *anyopaque) []const u8 { + const t: *Text = @ptrCast(@alignCast(ctx)); + return if (t.harmony) harmony_template else muse_template; + } +}; + +/// Answers `reply` in chunks of `stride` tokens. +pub const Script = struct { + reply: []const u32, + stride: usize, + eos: u32, + effort: [8]u8 = undefined, // the effort the submitted prompt was rendered with + effort_len: usize = 0, + + fn engine(e: *@This()) api.Engine { + return .{ .ctx = e, .vtable = &.{ .info = info, .submit = submit, .cancel = cancel, .status = status, .memory = memory } }; + } + + fn info(_: *anyopaque) api.Info { + return .{ .context_window = 4096 }; + } + + fn submit(ctx: *anyopaque, id: api.Id, request: *const api.Request, sink: api.Sink) api.SubmitError!void { + const e: *Script = @ptrCast(@alignCast(ctx)); + const named = request.prompt["effort=".len..]; + e.effort_len = std.mem.indexOfScalar(u32, named, ';').?; + for (named[0..e.effort_len], e.effort[0..e.effort_len]) |t, *b| b.* = @intCast(t); + sink.event(sink.ctx, id, &.{ .prefilled = 0 }); + var at: usize = 0; + while (at < e.reply.len) : (at = @min(at + e.stride, e.reply.len)) { + sink.event(sink.ctx, id, &.{ .tokens = e.reply[at..@min(at + e.stride, e.reply.len)] }); + } + const ended = e.reply.len > 0 and e.reply[e.reply.len - 1] == e.eos; + sink.event(sink.ctx, id, &.{ .finished = .{ .reason = if (ended) .stop else .length } }); + } + + fn cancel(_: *anyopaque, _: api.Id) void {} + + fn status(_: *anyopaque, out: *api.Status, _: []u32) void { + out.* = .{}; + } + + fn memory(_: *anyopaque, _: bool) ?api.Memory { + return null; + } +}; + +/// What a reply showed its client, whole or streamed: reasoning, content, the calls begun and their arguments. +pub const Shown = struct { + reasoning: std.ArrayList(u8) = .empty, + content: std.ArrayList(u8) = .empty, + arguments: std.ArrayList(u8) = .empty, + calls: usize = 0, + status: u16 = 0, + length: bool = false, // finish_reason "length" + effort: [8]u8 = undefined, + effort_len: usize = 0, + + fn out(s: *Shown) openai.Out { + return .{ .ctx = s, .vt = &.{ .open = open, .event = event, .reply = reply } }; + } + + pub fn deinit(s: *Shown) void { + for ([_]*std.ArrayList(u8){ &s.reasoning, &s.content, &s.arguments }) |l| l.deinit(std.testing.allocator); + } + + /// One message or delta object: its text fields appended, each call with an id counted, arguments appended. + fn take(s: *Shown, choice: json.Value, key: []const u8) !void { + if (choice.strField("finish_reason")) |f| s.length = s.length or std.mem.eql(u8, f, "length"); + const m = choice.get(key) orelse return; + const g = std.testing.allocator; + if (m.get("reasoning_content")) |v| if (v == .string) try s.reasoning.appendSlice(g, v.string); + if (m.get("content")) |v| if (v == .string) try s.content.appendSlice(g, v.string); + const list = m.get("tool_calls") orelse return; + if (list != .array) return; + for (list.array) |call| { + if (call.get("id") != null) s.calls += 1; + const f = call.get("function") orelse continue; + if (f.strField("arguments")) |args| try s.arguments.appendSlice(g, args); + } + } + + fn open(_: *anyopaque, _: usize) error{Closed}!void {} + + fn event(ctx: *anyopaque, payload: ?json.Value) error{Closed}!void { + const s: *Shown = @ptrCast(@alignCast(ctx)); + const p = payload orelse return; + const choices = p.get("choices") orelse return; + if (choices != .array or choices.array.len == 0) return; + s.take(choices.array[0], "delta") catch return error.Closed; + } + + fn reply(ctx: *anyopaque, status: u16, payload: json.Value) void { + const s: *Shown = @ptrCast(@alignCast(ctx)); + s.status = status; + const choices = payload.get("choices") orelse return; + if (choices != .array or choices.array.len == 0) return; + s.take(choices.array[0], "message") catch return; + } +}; + +/// `body` answered with `reply`'s tokens, `stride` at a time; the engine stops at the end token or after the reply. +pub fn send(settings: Text, reply: []const u8, stride: usize, body: []const u8) !Shown { + var text = settings; + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var backend: Script = .{ .reply = try text.tokens(a, reply), .stride = stride, .eos = Text.eosIds(&text)[0] }; + var srv = try server.Server.init(std.testing.allocator, std.testing.io, backend.engine(), text.text(), .{ + .served_name = "test-model", + .model_ids = &.{"test-model"}, + .enable_thinking = true, + .use_drafts = false, + }, null); + defer srv.deinit(); + const raw = (try json.parse(a, body)).ok; + var conn: Conn = .{ .fd = -1, .peer = "", .buf = &.{}, .gpa = a }; + var shown: Shown = .{}; + openai.run(srv, a, shown.out(), .{ .conn = &conn }, true, raw); + @memcpy(shown.effort[0..backend.effort_len], backend.effort[0..backend.effort_len]); + shown.effort_len = backend.effort_len; + return shown; +} + +const ask = "{\"model\":\"test-model\",\"messages\":[{\"role\":\"user\",\"content\":\"x\"}],\"max_tokens\":1024"; +const no_thinking = ",\"chat_template_kwargs\":{\"enable_thinking\":false}"; +const weather = ",\"tools\":[{\"type\":\"function\",\"function\":{\"name\":\"get_weather\",\"parameters\":{\"type\":\"object\"," ++ + "\"properties\":{\"city\":{\"type\":\"string\"},\"days\":{\"type\":\"integer\"}}}}}]"; + +fn atem(comptime city: []const u8, comptime days: []const u8) []const u8 { + return "\n\n" ++ city ++ + "\n" ++ days ++ "\n\n"; +} + +const chat_reply = " to=self<|message|>The sky question is simple.<|eom|><|start|>assistant to=user<|message|>Blue sky.<|eot|>"; +const call_reply = " to=self<|message|>Two forecasts are needed.<|eom|><|start|>assistant to=commentary<|message|>Checking both." ++ + "<|eom|><|start|>assistant to=get_weather<|message|>" ++ atem("Paris", "3") ++ "<|eom|><|start|>assistant to=get_weather" ++ + "<|message|>" ++ atem("Oslo", "1") ++ "<|eot|>"; +const harmony_reply = "<|channel|>analysis<|message|>Think.<|end|><|start|>assistant<|channel|>final<|message|>Blue sky.<|return|>"; + +test "recipient replies: detected from the markers and the template, never for Harmony's tokens" { + var muse: Text = .{}; + var harmony: Text = .{ .harmony = true }; + try std.testing.expect(recipient_reply.detect(muse.text())); + try std.testing.expect(!recipient_reply.detect(harmony.text())); +} + +test "recipient replies: a split while streaming only grows, holds calls back, and the finished split extends it" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const reply = call_reply[0 .. call_reply.len - "<|eot|>".len]; + var reading: recipient_reply.Reading = .{ .lead = "assistant", .tools = (try json.parse(a, weather[",\"tools\":".len..])).ok.array }; + const done = try reading.split(a, reply, .ended); + try std.testing.expectEqualStrings("Two forecasts are needed.", done.reasoning); + const xml = "\n\n\n{s}\n\n\n{s}\n\n" ++ + "\n"; + const want = try std.fmt.allocPrint(a, "Checking both.\n\n" ++ xml ++ "\n\n" ++ xml, .{ "Paris", "3", "Oslo", "1" }); + try std.testing.expectEqualStrings(want, done.answer); + var last: reply_text.Split = .{ .reasoning = "", .answer = "" }; + for (1..reply.len + 1) |n| { + const s = try reading.split(a, reply[0..n], .streaming); + try std.testing.expect(std.mem.startsWith(u8, s.reasoning, last.reasoning)); + try std.testing.expect(std.mem.startsWith(u8, s.answer, last.answer)); + try std.testing.expect(std.mem.indexOf(u8, s.answer, "<|") == null and std.mem.indexOf(u8, s.answer, "atem") == null); + try std.testing.expect(std.mem.startsWith(u8, done.answer, s.answer)); + last = s; + } + try std.testing.expect(std.mem.indexOf(u8, last.answer, "Oslo") == null); // the open call waits for the reply's end + try std.testing.expectEqualStrings("plain", (try reading.split(a, " plain ", .ended)).answer); +} + +test "recipient replies: atem calls become OpenAI calls with schema-typed arguments" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const tools = (try json.parse(a, weather[",\"tools\":".len..])).ok.array; + const body = atem("Rio de Janeiro", "4"); + const parsed = try tool_parse.parse(a, (try recipient_reply.calls(a, body, "get_weather", tools, .ended)).?, tools, null); + try std.testing.expectEqualStrings("", parsed.content); + const f = parsed.calls.?[0].get("function").?; + try std.testing.expectEqualStrings("get_weather", f.strField("name").?); + try std.testing.expectEqualStrings("{\"city\":\"Rio de Janeiro\",\"days\":4}", f.strField("arguments").?); + const amp = (try json.parse(a, "[{\"type\":\"function\",\"function\":{\"name\":\"a&b\"}}]")).ok.array; + const named = (try recipient_reply.calls(a, "\n\n", "a&b", amp, .ended)).?; + try std.testing.expectEqualStrings("\n\n\n", named); + try std.testing.expect((try recipient_reply.calls(a, "no calls here", "get_weather", tools, .ended)) == null); +} + +test "recipient replies: whole and streamed chats show the same reasoning, answer and calls" { + const cases = [_]struct { reply: []const u8, body: []const u8, content: []const u8, reasoning: []const u8, arguments: []const u8, calls: usize }{ + .{ .reply = chat_reply, .body = ask ++ "}", .content = "Blue sky.", .reasoning = "The sky question is simple.", .arguments = "", .calls = 0 }, + .{ .reply = call_reply, .body = ask ++ weather ++ "}", .content = "Checking both.", .reasoning = "Two forecasts are needed.", .arguments = "{\"city\":\"Paris\",\"days\":3}{\"city\":\"Oslo\",\"days\":1}", .calls = 2 }, + }; + for (cases) |c| { + var whole = try send(.{}, c.reply, 4096, c.body); + defer whole.deinit(); + try std.testing.expectEqual(@as(u16, 200), whole.status); + for ([_]usize{ 1, 7, 4096 }) |stride| { + const streamed_body = try std.mem.concat(std.testing.allocator, u8, &.{ c.body[0 .. c.body.len - 1], ",\"stream\":true}" }); + defer std.testing.allocator.free(streamed_body); + var streamed = try send(.{}, c.reply, stride, streamed_body); + defer streamed.deinit(); + for ([_]*const Shown{ &whole, &streamed }) |s| { + try std.testing.expectEqualStrings(c.content, s.content.items); + try std.testing.expectEqualStrings(c.reasoning, s.reasoning.items); + try std.testing.expectEqualStrings(c.arguments, s.arguments.items); + try std.testing.expectEqual(c.calls, s.calls); + } + } + } +} + +test "recipient replies: a Harmony reply keeps its final channel as content and analysis as reasoning" { + var whole = try send(.{ .harmony = true }, harmony_reply, 4096, ask ++ no_thinking ++ "}"); + defer whole.deinit(); + var streamed = try send(.{ .harmony = true }, harmony_reply, 1, ask ++ no_thinking ++ ",\"stream\":true}"); + defer streamed.deinit(); + for ([_]*const Shown{ &whole, &streamed }) |s| { + try std.testing.expectEqualStrings("Blue sky.", s.content.items); + try std.testing.expectEqualStrings("Think.", s.reasoning.items); + } +} + +test "recipient replies: a prompt that opened the self message keeps the reasoning that follows it" { + const opened: Text = .{ .prompt = "prompt<|start|>assistant to=self<|message|>" }; + const reply = "The sky question is simple.<|eom|><|start|>assistant to=user<|message|>Blue sky.<|eot|>"; + var whole = try send(opened, reply, 4096, ask ++ "}"); + defer whole.deinit(); + for ([_]usize{ 1, 7, 4096 }) |stride| { + var streamed = try send(opened, reply, stride, ask ++ ",\"stream\":true}"); + defer streamed.deinit(); + for ([_]*const Shown{ &whole, &streamed }) |s| { + try std.testing.expectEqualStrings("Blue sky.", s.content.items); + try std.testing.expectEqualStrings("The sky question is simple.", s.reasoning.items); + } + // cut while it still reasons: the reasoning so far, no answer + var cut = try send(opened, "Still weighing the sky", stride, ask ++ ",\"stream\":true}"); + defer cut.deinit(); + try std.testing.expectEqualStrings("Still weighing the sky", cut.reasoning.items); + try std.testing.expectEqualStrings("", cut.content.items); + } +} + +test "recipient replies: a call to no offered tool stays as the model wrote it, never as other markup" { + const time = ",\"tools\":[{\"type\":\"function\",\"function\":{\"name\":\"get_time\",\"parameters\":{\"type\":\"object\"}}}]"; + const want = comptime "Checking both.\n\n" ++ atem("Paris", "3") ++ "\n\n" ++ atem("Oslo", "1"); + for ([_][]const u8{ "", time }) |tools| { + const body = try std.mem.concat(std.testing.allocator, u8, &.{ ask, tools, "}" }); + defer std.testing.allocator.free(body); + var whole = try send(.{}, call_reply, 4096, body); + defer whole.deinit(); + for ([_]usize{ 1, 7, 4096 }) |stride| { + const streamed_body = try std.mem.concat(std.testing.allocator, u8, &.{ ask, tools, ",\"stream\":true}" }); + defer std.testing.allocator.free(streamed_body); + var streamed = try send(.{}, call_reply, stride, streamed_body); + defer streamed.deinit(); + for ([_]*const Shown{ &whole, &streamed }) |s| { + try std.testing.expectEqualStrings(want, s.content.items); + try std.testing.expectEqual(@as(usize, 0), s.calls); + } + } + } +} + +test "recipient replies: thinking off keeps self messages out of the reply and the template at its lowest effort" { + for ([_][]const u8{ no_thinking, ",\"reasoning_effort\":\"none\"" }) |off| { + const body = try std.mem.concat(std.testing.allocator, u8, &.{ ask, off, "}" }); + defer std.testing.allocator.free(body); + var whole = try send(.{}, chat_reply, 4096, body); + defer whole.deinit(); + const streamed_body = try std.mem.concat(std.testing.allocator, u8, &.{ ask, off, ",\"stream\":true}" }); + defer std.testing.allocator.free(streamed_body); + for ([_]usize{ 1, 7 }) |stride| { + var streamed = try send(.{}, chat_reply, stride, streamed_body); + defer streamed.deinit(); + for ([_]*const Shown{ &whole, &streamed }) |s| { + try std.testing.expectEqualStrings("Blue sky.", s.content.items); + try std.testing.expectEqualStrings("", s.reasoning.items); + try std.testing.expectEqualStrings("low", s.effort[0..s.effort_len]); + } + } + } + // thinking on: the template's default effort, or the named level nearest the request's + var on = try send(.{}, chat_reply, 4096, ask ++ "}"); + defer on.deinit(); + try std.testing.expectEqualStrings("none", on.effort[0..on.effort_len]); + try std.testing.expectEqualStrings("The sky question is simple.", on.reasoning.items); + var high = try send(.{}, chat_reply, 4096, ask ++ ",\"reasoning_effort\":\"high\"}"); + defer high.deinit(); + try std.testing.expectEqualStrings("xhigh", high.effort[0..high.effort_len]); +} + +test "recipient replies: a streamed read goes on from the last call and equals a fresh read at every length" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const tools = (try json.parse(a, weather[",\"tools\":".len..])).ok.array; + const spaced = " to=self<|message|>Think.\n\nMore.\n\n<|eom|><|start|>assistant to=user<|message|>Done. \n<|eot|>"; + for ([_][]const u8{ chat_reply, call_reply, " to=self<|message|>x<|eo", spaced }) |reply| for ([_][]const u8{ "assistant", "assistant to=self<|message|>" }) |lead| { + var going: recipient_reply.Reading = .{ .lead = lead, .tools = tools }; + for (1..reply.len + 1) |n| { + var fresh: recipient_reply.Reading = .{ .lead = lead, .tools = tools }; + const want = try fresh.split(a, reply[0..n], .streaming); + const got = try going.split(a, reply[0..n], .streaming); + try std.testing.expectEqualStrings(want.reasoning, got.reasoning); + try std.testing.expectEqualStrings(want.answer, got.answer); + for ([_][]const u8{ got.reasoning, got.answer }) |t| try std.testing.expect(t.len == 0 or !std.ascii.isWhitespace(t[t.len - 1])); + } + for ([_]recipient_reply.End{ .ended, .cut }) |end| { + var fresh: recipient_reply.Reading = .{ .lead = lead, .tools = tools }; + var done = going; + const want = try fresh.split(a, reply, end); + const got = try done.split(a, reply, end); + try std.testing.expectEqualStrings(want.reasoning, got.reasoning); + try std.testing.expectEqualStrings(want.answer, got.answer); + } + }; +} + +test "recipient replies: a reply with no markup streams as it comes; one that may still be a header waits" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var r: recipient_reply.Reading = .{ .lead = "assistant" }; + const reply = " Blue sky, mostly. "; + var last: []const u8 = ""; + for (1..reply.len + 1) |n| { + const s = (try r.split(a, reply[0..n], .streaming)).answer; + try std.testing.expect(std.mem.startsWith(u8, s, last) and std.mem.startsWith(u8, "Blue sky, mostly.", s)); + last = s; + } + try std.testing.expectEqualStrings("Blue sky, mostly", (try r.split(a, reply[0 .. reply.len - 2], .streaming)).answer); + try std.testing.expectEqualStrings("Blue sky, mostly.", (try r.split(a, reply, .ended)).answer); + var h: recipient_reply.Reading = .{ .lead = "assistant" }; + for ([_][]const u8{ " t", " to", " to=se", " <" }) |p| try std.testing.expectEqualStrings("", (try h.split(a, p, .streaming)).answer); + try std.testing.expectEqualStrings("hi", (try h.split(a, " to=user<|message|>hi", .streaming)).answer); +} diff --git a/zig/src/server/request_journal.zig b/zig/src/server/request_journal.zig new file mode 100644 index 00000000000..2a249f88383 --- /dev/null +++ b/zig/src/server/request_journal.zig @@ -0,0 +1,288 @@ +//! TENSORFOLD_REQUEST_JOURNAL: an opt-in, owner-only, rotated request journal; crashed requests are quarantined. +const std = @import("std"); +const platform = @import("sys"); +const json = @import("json"); +const log = @import("log.zig"); +const private = @import("request_log.zig").private; +const Allocator = std.mem.Allocator; +const Value = json.Value; +const Sha256 = std.crypto.hash.sha2.Sha256; +const c = platform.c; + +/// Past this a file becomes `.1`, each older file moves up one, and the oldest of `files` is removed. +pub const file_limit: usize = 64 << 20; +pub const files = 4; +/// The most one record holds: a larger body or reply is journaled by its size and SHA-256 only. +pub const record_limit: usize = 8 << 20; +/// A quarantine lapses a day after the crash that set it, unless cleared sooner; at most `quarantine_limit` hold. +pub const quarantine_s: i64 = 24 * 60 * 60; +pub const quarantine_limit = 4096; +/// Requests in flight at one crash are only flagged; one in flight at a second crash too is refused. +const refuse_at = 2; +const path_max = 4000; + +/// The API key's label, the route and the whole body: one key's crashed request never blocks another key's. +pub const Fingerprint = [32]u8; + +pub fn fingerprint(key: []const u8, chat: bool, body: Value) Fingerprint { + var buf: [4096]u8 = undefined; + var w: std.Io.Writer.Hashing(Sha256) = .init(&buf); + w.writer.print("tensorfold-quarantine-1\x00{s}\x00{s}\x00", .{ key, if (chat) "chat" else "completion" }) catch unreachable; + json.write(&w.writer, body, .{ .compact = true }) catch unreachable; // hashing drains never fail + w.writer.flush() catch unreachable; + return w.hasher.finalResult(); +} + +/// What serve prints when the journal can't be opened. +pub fn why(e: anyerror) []const u8 { + return switch (e) { + error.JournalBusy => "another server holds it (its .lock file is locked)", + error.JournalPermissions => "it or its .lock file is not a regular file only its owner can read and write", + error.JournalOpen => "it or its .lock file cannot be opened, or is a symbolic link", + error.JournalPath => "the path is empty or too long", + else => @errorName(e), + }; +} + +pub const Journal = struct { + gpa: Allocator, + io: std.Io, + path: [:0]const u8, + lock: c.fd_t, + fd: c.fd_t, + mutex: std.Io.Mutex = .init, + bytes: usize = 0, + limit: usize = file_limit, + lost: std.atomic.Value(u64) = .init(0), + blocked: std.AutoHashMapUnmanaged(Fingerprint, i64) = .empty, // the second each refusal lapses; fixed once open + + /// Takes `path.lock`, reads every kept file and quarantines the requests a crash left without a finish. + pub fn open(gpa: Allocator, io: std.Io, path: []const u8) !*Journal { + if (path.len == 0 or path.len > path_max or std.mem.indexOfScalar(u8, path, 0) != null) return error.JournalPath; + const j = try gpa.create(Journal); + errdefer gpa.destroy(j); + j.* = .{ .gpa = gpa, .io = io, .path = try gpa.dupeSentinel(u8, path, 0), .lock = -1, .fd = -1 }; + errdefer j.release(); + var buf: [path_max + 16]u8 = undefined; + j.lock = try openPrivate(try sibling(&buf, path, ".lock"), .{ .ACCMODE = .RDWR, .CREAT = true, .NOFOLLOW = true, .CLOEXEC = true }); + if (c.flock(j.lock, c.LOCK.EX | c.LOCK.NB) != 0) return error.JournalBusy; + j.fd = try openPrivate(j.path, .{ .ACCMODE = .RDWR, .APPEND = true, .CREAT = true, .NOFOLLOW = true, .CLOEXEC = true }); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + var r: Recovery = .{ .a = arena.allocator(), .gpa = gpa, .now = j.now() }; + var older: usize = files; + while (older > 1) { + older -= 1; + const fd = openPrivate(try sibling(&buf, path, suffix(older)), .{ .NOFOLLOW = true, .CLOEXEC = true }) catch continue; + defer _ = c.close(fd); + try r.scan(fd); + } + try r.scan(j.fd); + j.bytes = r.whole; + // a crash mid-write leaves a torn last line; the next record starts on a fresh one + if (r.size > r.whole and c.ftruncate(j.fd, @intCast(r.whole)) != 0) return error.JournalWrite; + try r.settle(j); + if (r.skipped > 0) log.line("request journal {s}: {d} unreadable record(s) passed over", .{ path, r.skipped }); + if (j.blocked.count() > 0) log.line("request journal {s}: {d} request(s) quarantined after crashes", .{ path, j.blocked.count() }); + return j; + } + + pub fn close(j: *Journal) void { + const lost = j.lost.load(.monotonic); + if (lost > 0) log.line("request journal {s}: {d} record(s) were not written", .{ j.path, lost }); + j.release(); + j.gpa.destroy(j); + } + + fn release(j: *Journal) void { + if (j.fd >= 0) _ = c.close(j.fd); + if (j.lock >= 0) _ = c.close(j.lock); + j.blocked.deinit(j.gpa); + j.gpa.free(j.path); + } + + /// A clean stop: requests still open now were not in flight at a crash. + pub fn stopped(j: *Journal) void { + var arena: std.heap.ArenaAllocator = .init(j.gpa); + defer arena.deinit(); + const o = j.record(arena.allocator(), "stop", null) catch return j.lose(); + j.append(arena.allocator(), .{ .object = o }); + } + + /// Whether this fingerprint crashed the server and is refused until it lapses or the operator clears it. + pub fn quarantined(j: *Journal, fp: Fingerprint) bool { + const until = j.blocked.get(fp) orelse return false; + return j.now() < until; + } + + pub fn record(j: *Journal, a: Allocator, kind: []const u8, id: ?[]const u8) Allocator.Error!*json.Object { + const o = try json.newObject(a); + try o.put(a, "version", .{ .int = "1" }); + try o.put(a, "kind", .{ .string = kind }); + if (id) |s| try o.put(a, "id", .{ .string = s }); + try o.put(a, "at", try json.intValue(a, j.now())); + return o; + } + + /// One record as one line in one write, with no sync; a failure or a full file loses the record, never the request. + pub fn append(j: *Journal, a: Allocator, value: Value) void { + var out: std.Io.Writer.Allocating = .init(a); + json.write(&out.writer, value, .{ .compact = true }) catch return j.lose(); + out.writer.writeByte('\n') catch return j.lose(); + const line = out.written(); + if (line.len > record_limit) return j.lose(); + j.mutex.lockUncancelable(j.io); + defer j.mutex.unlock(j.io); + if (j.fd >= 0 and j.bytes > 0 and j.bytes + line.len > j.limit) j.rotate(); + if (j.fd < 0) return j.lose(); + const n = c.write(j.fd, line.ptr, line.len); + if (n == @as(isize, @intCast(line.len))) { + j.bytes += line.len; + return; + } + if (n > 0) _ = c.ftruncate(j.fd, @intCast(j.bytes)); // no torn line for the next record to follow + j.lose(); + } + + /// The current file becomes `.1`, older ones move up, and a new one starts; a failure stops the journal. + fn rotate(j: *Journal) void { + _ = c.close(j.fd); + j.fd = -1; + var from: [path_max + 16]u8 = undefined; + var to: [path_max + 16]u8 = undefined; + var i: usize = files - 1; + while (i > 0) : (i -= 1) _ = c.rename(sibling(&from, j.path, suffix(i - 1)) catch return, sibling(&to, j.path, suffix(i)) catch return); + j.fd = openPrivate(j.path, .{ .ACCMODE = .WRONLY, .APPEND = true, .CREAT = true, .EXCL = true, .NOFOLLOW = true, .CLOEXEC = true }) catch -1; + j.bytes = 0; + } + + fn lose(j: *Journal) void { + if (j.lost.fetchAdd(1, .monotonic) == 0) log.line("request journal {s}: a record was not written (a full disk, an I/O error or a record past {d} MiB); requests go on", .{ j.path, record_limit >> 20 }); + } + + fn now(j: *const Journal) i64 { + return std.Io.Clock.real.now(j.io).toSeconds(); + } +}; + +fn suffix(n: usize) []const u8 { + return ([_][]const u8{ "", ".1", ".2", ".3", ".4", ".5", ".6", ".7", ".8" })[n]; +} + +fn sibling(buf: []u8, path: []const u8, tail: []const u8) ![:0]const u8 { + return std.fmt.bufPrintSentinel(buf, "{s}{s}", .{ path, tail }, 0) catch error.JournalPath; +} + +/// Opened only as a regular file no one but its owner can read or write; a link or a shared file is refused. +fn openPrivate(path: [*:0]const u8, flags: c.O) !c.fd_t { + const fd = c.open(path, flags, @as(c.mode_t, 0o600)); + if (fd < 0) return error.JournalOpen; + if (private(fd)) return fd; + _ = c.close(fd); + return error.JournalPermissions; +} + +/// The kept files read oldest first: starts still open at the end were in flight when the server last stopped. +const Recovery = struct { + a: Allocator, + gpa: Allocator, + now: i64, + pending: std.StringArrayHashMapUnmanaged(Fingerprint) = .empty, + crashes: std.AutoArrayHashMapUnmanaged(Fingerprint, Crashes) = .empty, + skipped: usize = 0, + size: usize = 0, + whole: usize = 0, // the last file's bytes up to and including its last newline + const Crashes = struct { n: u32 = 0, until: i64 = 0 }; + + fn scan(r: *Recovery, fd: c.fd_t) !void { + var line: std.ArrayList(u8) = .empty; + defer line.deinit(r.gpa); + var scratch: std.heap.ArenaAllocator = .init(r.gpa); + defer scratch.deinit(); + var chunk: [1 << 16]u8 = undefined; + var over = false; // past a record's size: the line is passed over + r.size = 0; + r.whole = 0; + while (true) { + const n = c.read(fd, &chunk, chunk.len); + if (n < 0) return error.JournalRead; + if (n == 0) break; + var rest: []const u8 = chunk[0..@intCast(n)]; + r.size += rest.len; + while (std.mem.indexOfScalar(u8, rest, '\n')) |at| { + if (!over) try line.appendSlice(r.gpa, rest[0..at]); + if (over) r.skipped += 1 else try r.entry(scratch.allocator(), line.items); + _ = scratch.reset(.retain_capacity); + line.clearRetainingCapacity(); + over = false; + rest = rest[at + 1 ..]; + r.whole = r.size - rest.len; + } + if (!over and line.items.len + rest.len > record_limit) { + over = true; + line.clearRetainingCapacity(); + } else if (!over) try line.appendSlice(r.gpa, rest); + } + } + + fn entry(r: *Recovery, a: Allocator, text: []const u8) !void { + if (text.len == 0) return; + const v = switch (try json.parse(a, text)) { + .ok => |v| v, + .err => return r.skip(), + }; + if (((v.get("version") orelse return r.skip()).int64() orelse return r.skip()) != 1) return r.skip(); + const kind = v.strField("kind") orelse return r.skip(); + if (eql(kind, "stop")) return r.pending.clearRetainingCapacity(); + if (eql(kind, "clear")) { + if (json.truthyField(v, "all")) return r.crashes.clearRetainingCapacity(); + _ = r.crashes.orderedRemove(hexOf(v) orelse return r.skip()); + return; + } + const id = v.strField("id") orelse return r.skip(); + if (eql(kind, "start")) return r.pending.put(r.a, try r.a.dupe(u8, id), hexOf(v) orelse return r.skip()); + if (!eql(kind, "finish") and !eql(kind, "quarantine")) return; + _ = r.pending.orderedRemove(id); + if (!eql(kind, "quarantine")) return; + const at = (v.get("at") orelse return r.skip()).int64() orelse return r.skip(); + try r.add(hexOf(v) orelse return r.skip(), at + quarantine_s); + } + + fn add(r: *Recovery, fp: Fingerprint, until: i64) !void { + if (until <= r.now) return; + const w = try r.crashes.getOrPut(r.a, fp); + if (!w.found_existing) w.value_ptr.* = .{}; + w.value_ptr.n += 1; + w.value_ptr.until = @max(w.value_ptr.until, until); + } + + /// The last session's open starts are quarantined, then every fingerprint in flight at two crashes is refused. + fn settle(r: *Recovery, j: *Journal) !void { + for (r.pending.keys(), r.pending.values()) |id, fp| { + const o = try j.record(r.a, "quarantine", id); + const hex = std.fmt.bytesToHex(fp, .lower); + try o.put(r.a, "fingerprint", .{ .string = try r.a.dupe(u8, &hex) }); + j.append(r.a, .{ .object = o }); + try r.add(fp, r.now + quarantine_s); + } + for (r.crashes.keys(), r.crashes.values()) |fp, w| { + if (w.n >= refuse_at and j.blocked.count() < quarantine_limit) try j.blocked.put(j.gpa, fp, w.until); + } + } + + fn skip(r: *Recovery) void { + r.skipped += 1; + } +}; + +fn hexOf(v: Value) ?Fingerprint { + const text = v.strField("fingerprint") orelse return null; + var fp: Fingerprint = undefined; + if (text.len != 64) return null; + _ = std.fmt.hexToBytes(&fp, text) catch return null; + return fp; +} + +fn eql(a: []const u8, b: []const u8) bool { + return std.mem.eql(u8, a, b); +} diff --git a/zig/src/server/request_journal_test.zig b/zig/src/server/request_journal_test.zig new file mode 100644 index 00000000000..83de76cc271 --- /dev/null +++ b/zig/src/server/request_journal_test.zig @@ -0,0 +1,461 @@ +//! The request journal on a fake engine: records, replay by the resolved seed, crash quarantine, rotation, failures. +const std = @import("std"); +const builtin = @import("builtin"); +const api = @import("engine_api"); +const json = @import("json"); +const platform = @import("sys"); +const journal_mod = @import("request_journal.zig"); +const Journal = journal_mod.Journal; +const Trace = @import("request_trace.zig").Trace; +const openai = @import("openai.zig"); +const Server = @import("server.zig").Server; +const Conn = @import("http_conn.zig").Conn; +const TestText = @import("stream_preflight_test.zig").TestText; +const t = std.testing; +const Allocator = std.mem.Allocator; +const Value = json.Value; + +/// Replies with the decimal digits of the seed it was given, so a replay without that seed reads differently. +const Fake = struct { + submitted: usize = 0, + fn engine(f: *Fake) api.Engine { + return .{ .ctx = f, .vtable = &.{ .info = info, .submit = submit, .cancel = cancel, .status = status, .memory = memory } }; + } + fn info(_: *anyopaque) api.Info { + return .{ .context_window = 4096 }; + } + fn submit(ctx: *anyopaque, id: api.Id, r: *const api.Request, sink: api.Sink) api.SubmitError!void { + const f: *Fake = @ptrCast(@alignCast(ctx)); + f.submitted += 1; + var buf: [24]u8 = undefined; + const text = std.fmt.bufPrint(&buf, "{d}", .{if (r.sampling) |s| s.seed else 7}) catch unreachable; + var ids: [24]u32 = undefined; + for (text, 0..) |b, i| ids[i] = b; + sink.event(sink.ctx, id, &.{ .prefilled = 0 }); + sink.event(sink.ctx, id, &.{ .tokens = ids[0..text.len] }); + 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; + } +}; + +/// The bytes a client would read: each payload serialized as the socket writers do. +const Wire = struct { + a: Allocator, + bytes: std.ArrayList(u8) = .empty, + status: u16 = 0, + last: Value = .null, + fn out(w: *Wire) openai.Out { + return .{ .ctx = w, .vt = &.{ .open = open, .event = event, .reply = reply } }; + } + fn open(ctx: *anyopaque, _: usize) error{Closed}!void { + const w: *Wire = @ptrCast(@alignCast(ctx)); + w.status = 200; + } + fn event(ctx: *anyopaque, payload: ?Value) error{Closed}!void { + const w: *Wire = @ptrCast(@alignCast(ctx)); + const p = payload orelse return w.bytes.appendSlice(w.a, "data: [DONE]\n\n") catch error.Closed; + w.last = p; + const text = json.stringify(w.a, p, .{}) catch return error.Closed; + w.bytes.appendSlice(w.a, std.mem.concat(w.a, u8, &.{ "data: ", text, "\n\n" }) catch return error.Closed) catch return error.Closed; + } + fn reply(ctx: *anyopaque, code: u16, payload: Value) void { + const w: *Wire = @ptrCast(@alignCast(ctx)); + w.status = code; + w.last = payload; + w.bytes.appendSlice(w.a, json.stringify(w.a, payload, .{}) catch return) catch {}; + } + fn tokens(w: *const Wire) []const u8 { + return w.last.get("tensorfold").?.strField("token_sha256").?; + } +}; + +const hello = "{\"model\":\"m\",\"messages\":[{\"role\":\"user\",\"content\":\"hello\"}],\"temperature\":1,\"max_tokens\":8"; + +fn serve(fake: *Fake, text: *TestText, journal: ?*Journal) !*Server { + return Server.init(t.allocator, t.io, fake.engine(), text.text(), .{ .served_name = "m", .model_ids = &.{"m"}, .enable_thinking = false, .use_drafts = false, .journal = journal }, null); +} + +fn ask(srv: *Server, a: Allocator, body: []const u8, key: ?[]const u8) !Wire { + var wire: Wire = .{ .a = a }; + var conn: Conn = .{ .fd = -1, .peer = "", .buf = &.{}, .gpa = a, .key_label = key }; + openai.run(srv, a, wire.out(), .{ .conn = &conn }, true, (try json.parse(a, body)).ok); + return wire; +} + +fn records(a: Allocator, path: []const u8) ![]Value { + const raw = try std.Io.Dir.cwd().readFileAlloc(t.io, path, a, .limited(1 << 26)); + var found: std.ArrayList(Value) = .empty; + var it = std.mem.splitScalar(u8, raw, '\n'); + while (it.next()) |line| if (line.len > 0) try found.append(a, (try json.parse(a, line)).ok); + return found.items; +} + +fn kinds(a: Allocator, path: []const u8, kind: []const u8) ![]Value { + var found: std.ArrayList(Value) = .empty; + for (try records(a, path)) |r| if (std.mem.eql(u8, r.strField("kind").?, kind)) try found.append(a, r); + return found.items; +} + +fn journalPath(a: Allocator, tmp: t.TmpDir, name: []const u8) ![]const u8 { + return std.fmt.allocPrint(a, ".zig-cache/tmp/{s}/{s}", .{ tmp.sub_path, name }); +} + +/// A request that began and never finished: the process died with it in flight. +fn inFlight(j: *Journal, a: Allocator, body: []const u8, key: []const u8) !void { + var wire: Wire = .{ .a = a }; + var trace: Trace = .{ .journal = j, .a = a, .id = try std.fmt.allocPrint(a, "chatcmpl-{d}", .{j.bytes}), .parent = wire.out() }; + try t.expect(!trace.begin((try json.parse(a, body)).ok, true, key)); +} + +test "request journal: whole and streamed replies keep their start, resolved seed and exact reply bytes" { + 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 journalPath(a, tmp, "requests.jsonl"); + const j = try Journal.open(t.allocator, t.io, path); + defer j.close(); + var fake: Fake = .{}; + var text: TestText = .{}; + const srv = try serve(&fake, &text, j); + defer srv.deinit(); + inline for (.{ "}", ",\"stream\":true}" }) |tail| { + const wire = try ask(srv, a, hello ++ ",\"seed\":1234" ++ tail, null); + try t.expectEqual(@as(u16, 200), wire.status); + const finishes = try kinds(a, path, "finish"); + const finish = finishes[finishes.len - 1]; + const id = finish.strField("id").?; + try t.expectEqualStrings("completed", finish.strField("outcome").?); + try t.expectEqual(tail.len > 1, finish.get("stream").?.bool); + const encoded = finish.strField("reply_base64").?; + const decoder = std.base64.standard.Decoder; + const bytes = try a.alloc(u8, try decoder.calcSizeForSlice(encoded)); + try decoder.decode(bytes, encoded); + try t.expectEqualStrings(wire.bytes.items, bytes); + try t.expectEqualStrings(wire.tokens(), finish.strField("token_sha256").?); + for (try records(a, path)) |r| if (std.mem.eql(u8, r.strField("id") orelse "", id)) { + const kind = r.strField("kind").?; + if (std.mem.eql(u8, kind, "prepared")) try t.expectEqual(@as(i64, 1234), r.get("seed").?.int64().?); + if (std.mem.eql(u8, kind, "start")) try t.expectEqual(@as(usize, 64), r.strField("fingerprint").?.len); + }; + } + try t.expectEqual(@as(usize, 2), (try kinds(a, path, "start")).len); + try t.expectEqual(@as(usize, 2), (try kinds(a, path, "prepared")).len); +} + +test "request journal: a two-prompt completion finishes whole and streamed with the merged reply" { + 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 journalPath(a, tmp, "requests.jsonl"); + const j = try Journal.open(t.allocator, t.io, path); + defer j.close(); + var fake: Fake = .{}; + var text: TestText = .{}; + const srv = try serve(&fake, &text, j); + defer srv.deinit(); + const base = "{\"model\":\"m\",\"prompt\":[\"abc\",\"def\"],\"seed\":1234,\"max_tokens\":8"; + inline for (.{ "}", ",\"stream\":true}" }) |tail| { + var wire: Wire = .{ .a = a }; + var conn: Conn = .{ .fd = -1, .peer = "", .buf = &.{}, .gpa = a }; + openai.run(srv, a, wire.out(), .{ .conn = &conn }, false, (try json.parse(a, base ++ tail)).ok); + try t.expectEqual(@as(u16, 200), wire.status); + const finishes = try kinds(a, path, "finish"); + const finish = finishes[finishes.len - 1]; + try t.expectEqualStrings("completed", finish.strField("outcome").?); + const encoded = finish.strField("reply_base64").?; + const decoder = std.base64.standard.Decoder; + const bytes = try a.alloc(u8, try decoder.calcSizeForSlice(encoded)); + try decoder.decode(bytes, encoded); + try t.expectEqualStrings(wire.bytes.items, bytes); + try t.expectEqual(@as(usize, 0), (try kinds(a, path, "prepared")).len); + } +} + +test "request journal: an unseeded request's drawn seed replays the same tokens, and a replay without it differs" { + 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 journalPath(a, tmp, "requests.jsonl"); + var fake: Fake = .{}; + var text: TestText = .{}; + const first = blk: { + const j = try Journal.open(t.allocator, t.io, path); + defer j.close(); + const srv = try serve(&fake, &text, j); + defer srv.deinit(); + break :blk try ask(srv, a, hello ++ "}", null); + }; + const start = (try kinds(a, path, "start"))[0]; + const seed = (try kinds(a, path, "prepared"))[0].get("seed").?; + try t.expect(start.get("seed").? == .null); + const body = start.get("body").?; + try body.object.put(a, "seed", seed); + const replay = try json.stringify(a, body, .{}); + const srv = try serve(&fake, &text, null); + defer srv.deinit(); + const again = try ask(srv, a, replay, null); + try t.expectEqualStrings(first.tokens(), again.tokens()); + const content = first.last.get("choices").?.array[0].get("message").?.strField("content").?; + try t.expectEqualStrings(content, again.last.get("choices").?.array[0].get("message").?.strField("content").?); + _ = body.object.orderedRemove("seed"); + const fresh = try ask(srv, a, try json.stringify(a, body, .{}), null); + try t.expect(!std.mem.eql(u8, first.tokens(), fresh.tokens())); // a fresh seed: one chance in about 2^63 to match +} + +test "request journal: image and PDF data stay out, and the journal and its lock are owner-only" { + 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 journalPath(a, tmp, "requests.jsonl"); + const j = try Journal.open(t.allocator, t.io, path); + defer j.close(); + var fake: Fake = .{}; + var text: TestText = .{}; + const srv = try serve(&fake, &text, j); + defer srv.deinit(); + const parts = "[{\"type\":\"image_url\",\"image_url\":{\"url\":\"https://example.test/private.png\"}},{\"type\":\"file\",\"file\":{\"filename\":\"a.pdf\",\"file_data\":\"SECRET-PDF\"}}]"; + _ = try ask(srv, a, "{\"model\":\"m\",\"messages\":[{\"role\":\"user\",\"content\":" ++ parts ++ "}]}", "alice"); + const raw = try std.Io.Dir.cwd().readFileAlloc(t.io, path, a, .limited(1 << 20)); + try t.expect(std.mem.indexOf(u8, raw, "private.png") == null and std.mem.indexOf(u8, raw, "SECRET-PDF") == null); + try t.expect(std.mem.indexOf(u8, raw, "a.pdf") != null and std.mem.indexOf(u8, raw, "") != null); + try t.expect(std.mem.indexOf(u8, raw, "alice") == null); // the key's label is in the fingerprint, not the file + if (builtin.os.tag == .windows) return; // NTFS keeps access in ACLs, not mode bits + for ([_][]const u8{ "requests.jsonl", "requests.jsonl.lock" }) |name| { + const st = try tmp.dir.statFile(t.io, name, .{}); + try t.expectEqual(@as(u32, 0o600), @as(u32, @intCast(st.permissions.toMode())) & 0o777); + } +} + +test "request journal: a request in flight at two crashes is refused after restart, for its own key only" { + 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 journalPath(a, tmp, "requests.jsonl"); + const crashed = hello ++ ",\"seed\":9}"; + var fake: Fake = .{}; + var text: TestText = .{}; + for (0..2) |crash| { + const j = try Journal.open(t.allocator, t.io, path); + defer j.close(); // a close without a stop: the process died + try t.expectEqual(crash, (try kinds(a, path, "quarantine")).len); + const srv = try serve(&fake, &text, j); + defer srv.deinit(); + try t.expectEqual(@as(u16, 200), (try ask(srv, a, crashed, "alice")).status); // one crash only flags it + try inFlight(j, a, crashed, "alice"); + } + { + const j = try Journal.open(t.allocator, t.io, path); + defer j.close(); + try t.expectEqual(@as(usize, 2), (try kinds(a, path, "quarantine")).len); + const srv = try serve(&fake, &text, j); + defer srv.deinit(); + const before = fake.submitted; + const refused = try ask(srv, a, crashed, "alice"); + try t.expectEqual(@as(u16, 400), refused.status); + try t.expectEqualStrings("request_quarantined", refused.last.get("error").?.strField("code").?); + try t.expectEqual(before, fake.submitted); // refused before the engine saw it + try t.expectEqual(@as(u16, 200), (try ask(srv, a, crashed, "bob")).status); + try t.expectEqual(@as(u16, 200), (try ask(srv, a, hello ++ ",\"seed\":10}", "alice")).status); + try t.expectEqual(before + 2, fake.submitted); + const finishes = try kinds(a, path, "finish"); + try t.expectEqualStrings("quarantined", finishes[finishes.len - 3].strField("outcome").?); + j.stopped(); + } + const j = try Journal.open(t.allocator, t.io, path); + defer j.close(); + try t.expectEqual(@as(usize, 2), (try kinds(a, path, "quarantine")).len); // nothing in flight, nothing new + try t.expect(j.quarantined(journal_mod.fingerprint("alice", true, (try json.parse(a, crashed)).ok))); +} + +test "request journal: of several requests in flight at one crash, only one in flight again at a second is refused" { + 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 journalPath(a, tmp, "requests.jsonl"); + const bodies = [_][]const u8{ hello ++ ",\"seed\":1}", hello ++ ",\"seed\":2}", hello ++ ",\"seed\":3}" }; + const fp = struct { + fn of(arena_a: Allocator, body: []const u8) !journal_mod.Fingerprint { + return journal_mod.fingerprint("", true, (try json.parse(arena_a, body)).ok); + } + }.of; + for ([_][2]usize{ .{ 0, 1 }, .{ 0, 2 } }) |pair| { + const j = try Journal.open(t.allocator, t.io, path); + defer j.close(); + for (bodies) |body| try t.expect(!j.quarantined(try fp(a, body))); + for (pair) |k| try inFlight(j, a, bodies[k], ""); + } + const j = try Journal.open(t.allocator, t.io, path); + defer j.close(); + try t.expect(j.quarantined(try fp(a, bodies[0]))); + try t.expect(!j.quarantined(try fp(a, bodies[1])) and !j.quarantined(try fp(a, bodies[2]))); + try t.expectEqual(@as(usize, 4), (try kinds(a, path, "quarantine")).len); +} + +test "request journal: a clean stop quarantines nothing, a clear record lifts one, and an old one lapses" { + 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 journalPath(a, tmp, "requests.jsonl"); + const body = hello ++ "}"; + const fp = journal_mod.fingerprint("", true, (try json.parse(a, body)).ok); + const hex = std.fmt.bytesToHex(fp, .lower); + { + const j = try Journal.open(t.allocator, t.io, path); + defer j.close(); + try inFlight(j, a, body, ""); + j.stopped(); + } + for (0..2) |_| { + const j = try Journal.open(t.allocator, t.io, path); + defer j.close(); + try inFlight(j, a, body, ""); + } + try t.expectEqual(@as(usize, 1), (try kinds(a, path, "quarantine")).len); // the stopped one was not a crash + { + const j = try Journal.open(t.allocator, t.io, path); + defer j.close(); + try t.expect(j.quarantined(fp)); + const line = try std.fmt.allocPrint(a, "{{\"version\":1,\"kind\":\"clear\",\"fingerprint\":\"{s}\"}}\n", .{hex}); + try t.expectEqual(@as(isize, @intCast(line.len)), platform.c.write(j.fd, line.ptr, line.len)); + } + { + const j = try Journal.open(t.allocator, t.io, path); + defer j.close(); + try t.expect(!j.quarantined(fp)); + const old = std.Io.Clock.real.now(t.io).toSeconds() - journal_mod.quarantine_s - 1; + for (0..2) |_| { + const line = try std.fmt.allocPrint(a, "{{\"version\":1,\"kind\":\"quarantine\",\"id\":\"x\",\"fingerprint\":\"{s}\",\"at\":{d}}}\n", .{ hex, old }); + try t.expectEqual(@as(isize, @intCast(line.len)), platform.c.write(j.fd, line.ptr, line.len)); + } + } + const j = try Journal.open(t.allocator, t.io, path); + defer j.close(); + try t.expect(!j.quarantined(fp)); +} + +test "request journal: a torn last line is cut, an unreadable one passed over, and a second server refused" { + 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 journalPath(a, tmp, "requests.jsonl"); + { + const j = try Journal.open(t.allocator, t.io, path); + defer j.close(); + try t.expectError(error.JournalBusy, Journal.open(t.allocator, t.io, path)); + try t.expectEqual(@as(isize, 4), platform.c.write(j.fd, "bad\n", 4)); + try t.expectEqual(@as(isize, 8), platform.c.write(j.fd, "{\"kind\":", 8)); + } + const j = try Journal.open(t.allocator, t.io, path); + j.stopped(); + j.close(); + const raw = try std.Io.Dir.cwd().readFileAlloc(t.io, path, a, .limited(1 << 20)); + try t.expect(std.mem.startsWith(u8, raw, "bad\n{\"version\":1,\"kind\":\"stop\"")); + if (builtin.os.tag == .windows) return; // refusal by mode bits and links; NTFS keeps access in ACLs + try tmp.dir.writeFile(t.io, .{ .sub_path = "shared.jsonl", .data = "" }); + try tmp.dir.setFilePermissions(t.io, "shared.jsonl", .fromMode(0o644), .{}); + try t.expectError(error.JournalPermissions, Journal.open(t.allocator, t.io, try journalPath(a, tmp, "shared.jsonl"))); + try tmp.dir.symLink(t.io, "requests.jsonl", "link.jsonl", .{}); + try t.expectError(error.JournalOpen, Journal.open(t.allocator, t.io, try journalPath(a, tmp, "link.jsonl"))); +} + +test "request journal: files rotate at their cap, four are kept, and a start in a rotated file is still flagged" { + 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 journalPath(a, tmp, "requests.jsonl"); + const body = hello ++ "}"; + { + const j = try Journal.open(t.allocator, t.io, path); + defer j.close(); + j.limit = 2048; + try inFlight(j, a, body, ""); + for (0..40) |_| j.append(a, .{ .object = try j.record(a, "note", "filler") }); // records recovery ignores + } + try t.expectEqual(@as(usize, 1), (try kinds(a, try journalPath(a, tmp, "requests.jsonl.1"), "start")).len); + { + const j = try Journal.open(t.allocator, t.io, path); + defer j.close(); + try t.expectEqual(@as(usize, 1), (try kinds(a, path, "quarantine")).len); + j.limit = 2048; + for (0..400) |_| j.append(a, .{ .object = try j.record(a, "note", "filler") }); + try t.expectEqual(@as(u64, 0), j.lost.load(.monotonic)); + } + for ([_][]const u8{ "requests.jsonl", "requests.jsonl.1", "requests.jsonl.2", "requests.jsonl.3" }) |name| { + try t.expect((try tmp.dir.statFile(t.io, name, .{})).size <= 2048); + } + try t.expectError(error.FileNotFound, tmp.dir.statFile(t.io, "requests.jsonl.4", .{})); +} + +test "request journal: a write that fails loses its record and the request still completes the same" { + 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 journalPath(a, tmp, "requests.jsonl"); + const j = try Journal.open(t.allocator, t.io, path); + defer j.close(); + const writable = j.fd; + j.fd = platform.c.open(try a.dupeSentinel(u8, path, 0), .{ .ACCMODE = .RDONLY }); // writes fail, as on a full disk + defer { + _ = platform.c.close(j.fd); + j.fd = writable; + } + var fake: Fake = .{}; + var text: TestText = .{}; + const srv = try serve(&fake, &text, j); + defer srv.deinit(); + const wire = try ask(srv, a, hello ++ ",\"seed\":5}", null); + try t.expectEqual(@as(u16, 200), wire.status); + try t.expectEqualStrings("5", wire.last.get("choices").?.array[0].get("message").?.strField("content").?); + try t.expect(j.lost.load(.monotonic) >= 3); +} + +test "request journal: off, a request's output path is the caller's and its tokens are a journaled one's" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = t.tmpDir(.{}); + defer tmp.cleanup(); + var wire: Wire = .{ .a = a }; + const parent = wire.out(); + var off: Trace = .{ .journal = null, .a = a, .id = "x", .parent = parent }; + try t.expect(off.out().vt == parent.vt and off.out().ctx == parent.ctx); + try t.expect(!off.begin((try json.parse(a, hello ++ "}")).ok, true, "")); + var fake: Fake = .{}; + var text: TestText = .{}; + const j = try Journal.open(t.allocator, t.io, try journalPath(a, tmp, "requests.jsonl")); + defer j.close(); + var replies: [2]Wire = undefined; + for ([_]?*Journal{ null, j }, &replies) |journal, *reply| { + const srv = try serve(&fake, &text, journal); + defer srv.deinit(); + reply.* = try ask(srv, a, hello ++ ",\"seed\":77,\"stream\":true}", null); + } + try t.expectEqualStrings(replies[0].tokens(), replies[1].tokens()); + try t.expect(json.equal(replies[0].last.get("choices").?, replies[1].last.get("choices").?)); +} diff --git a/zig/src/server/request_log.zig b/zig/src/server/request_log.zig index 9ce6ed35895..394dc63e83c 100644 --- a/zig/src/server/request_log.zig +++ b/zig/src/server/request_log.zig @@ -8,7 +8,7 @@ const Value = json.Value; const Allocator = std.mem.Allocator; /// The body with every image part's URL replaced, the rest kept. -fn redact(a: Allocator, v: Value) Allocator.Error!Value { +pub fn redact(a: Allocator, v: Value) Allocator.Error!Value { switch (v) { .array => |items| { const out = try a.alloc(Value, items.len); @@ -53,7 +53,7 @@ pub fn append(a: Allocator, path: []const u8, body: Value) void { } /// A regular file no one but its owner can read or write: a name in a shared directory can be someone else's file. -fn private(fd: platform.c.fd_t) bool { +pub fn private(fd: platform.c.fd_t) bool { if (builtin.os.tag == .windows) return true; // NTFS keeps access in ACLs, not mode bits const m = meta(fd, null) orelse return false; return m.mode & 0o170000 == 0o100000 and m.mode & 0o077 == 0; diff --git a/zig/src/server/request_trace.zig b/zig/src/server/request_trace.zig new file mode 100644 index 00000000000..92cc7e36857 --- /dev/null +++ b/zig/src/server/request_trace.zig @@ -0,0 +1,182 @@ +//! One request's journal records: its start before any work, its resolved settings, then its reply in one finish. +const std = @import("std"); +const api = @import("engine_api"); +const json = @import("json"); +const openai = @import("openai.zig"); +const journal_mod = @import("request_journal.zig"); +const Journal = journal_mod.Journal; +const Allocator = std.mem.Allocator; +const Value = json.Value; +const Sha256 = std.crypto.hash.sha2.Sha256; + +/// The reply bytes a finish keeps for replay; a longer reply keeps its size, SHA-256 and token hash. +pub const reply_limit: usize = 4 << 20; +pub const quarantine_message = "this request was in flight when the server crashed and is quarantined; its operator can clear it"; + +pub const Trace = struct { + journal: ?*Journal, + a: Allocator, + id: []const u8, + parent: openai.Out, + status: u16 = 0, + stream: bool = false, + done: bool = false, + failed: bool = false, + started: bool = false, + quarantined: bool = false, + whole: bool = true, // every reply byte is kept + size: usize = 0, + sha: Sha256 = .init(.{}), + kept: std.ArrayList(u8) = .empty, + token_sha256: ?[]const u8 = null, + + /// Writes the start before any work; true when this key's same request is quarantined, which the caller refuses. + pub fn begin(t: *Trace, body: Value, chat: bool, key: []const u8) bool { + const j = t.journal orelse return false; + const fp = journal_mod.fingerprint(key, chat, body); + t.started = true; + t.quarantined = j.quarantined(fp); + t.start(j, body, chat, fp) catch {}; + return t.quarantined; + } + + fn start(t: *Trace, j: *Journal, body: Value, chat: bool, fp: journal_mod.Fingerprint) Allocator.Error!void { + const a = t.a; + const o = try j.record(a, "start", t.id); + try o.put(a, "path", .{ .string = if (chat) "/v1/chat/completions" else "/v1/completions" }); + const hex = std.fmt.bytesToHex(fp, .lower); + try o.put(a, "fingerprint", .{ .string = try a.dupe(u8, &hex) }); + try o.put(a, "seed", body.get("seed") orelse .null); + const redacted = try @import("request_log.zig").redact(a, body); + var buf: [1024]u8 = undefined; + var counted: std.Io.Writer.Discarding = .init(&buf); + json.write(&counted.writer, redacted, .{ .compact = true }) catch {}; + // a body too large for one record keeps its size; replay then needs --body + if (counted.fullCount() + 4096 <= journal_mod.record_limit) try o.put(a, "body", redacted) else try o.put(a, "body_bytes", try json.intValue(a, counted.fullCount())); + j.append(a, .{ .object = o }); + } + + /// The settings the server resolved before the engine saw the request; its seed is what a replay needs. + pub fn prepared(t: *Trace, request: *const api.Request, thinking: bool, effort: ?[]const u8) void { + const j = t.journal orelse return; + t.settings(j, request, thinking, effort) catch {}; + } + + fn settings(t: *Trace, j: *Journal, request: *const api.Request, thinking: bool, effort: ?[]const u8) Allocator.Error!void { + const a = t.a; + const o = try j.record(a, "prepared", t.id); + if (request.sampling) |s| { + try o.put(a, "seed", try json.intValue(a, s.seed)); + try o.put(a, "temperature", .{ .float = s.temperature }); + try o.put(a, "top_k", try json.intValue(a, s.top_k)); + try o.put(a, "top_p", .{ .float = s.top_p }); + try o.put(a, "min_p", .{ .float = s.min_p }); + } else try o.put(a, "seed", .null); + try o.put(a, "max_tokens", try json.intValue(a, request.max_tokens)); + try o.put(a, "drafts", .{ .bool = request.drafts }); + try o.put(a, "thinking", .{ .bool = thinking }); + try o.put(a, "reasoning_effort", if (effort) |s| .{ .string = s } else .null); + try o.put(a, "prompt_tokens", try json.intValue(a, request.prompt.len)); + const sha = @import("tokens.zig").tokenSha256(request.prompt); + try o.put(a, "prompt_sha256", .{ .string = try a.dupe(u8, &sha) }); + j.append(a, .{ .object = o }); + } + + /// The finish: status, outcome and the reply as the chat route produced it, written once the reply has gone. + pub fn finish(t: *Trace) void { + const j = t.journal orelse return; + if (!t.started) return; + t.end(j) catch {}; + } + + fn end(t: *Trace, j: *Journal) Allocator.Error!void { + const a = t.a; + const o = try j.record(a, "finish", t.id); + try o.put(a, "status", try json.intValue(a, t.status)); + try o.put(a, "stream", .{ .bool = t.stream }); + const outcome = if (t.quarantined) "quarantined" else if (t.failed) "failed" else if (!t.done) "cancelled" else if (t.status >= 400) "refused" else "completed"; + try o.put(a, "outcome", .{ .string = outcome }); + try o.put(a, "reply_bytes", try json.intValue(a, t.size)); + const hex = std.fmt.bytesToHex(t.sha.finalResult(), .lower); + try o.put(a, "reply_sha256", .{ .string = try a.dupe(u8, &hex) }); + try o.put(a, "token_sha256", if (t.token_sha256) |s| .{ .string = s } else .null); + if (t.whole) { + const codec = std.base64.standard.Encoder; + const encoded = try a.alloc(u8, codec.calcSize(t.kept.items.len)); + try o.put(a, "reply_base64", .{ .string = codec.encode(encoded, t.kept.items) }); + } + j.append(a, .{ .object = o }); + } + + /// The quarantine refusal, a 400 a client should not retry, sent and journaled like any other reply. + pub fn refuse(t: *Trace, id: []const u8) void { + const cx: @import("errors.zig").Cx = .{ .a = t.a, .message = quarantine_message, .code = "request_quarantined" }; + var buf: [256]u8 = undefined; + @import("log.zig").line("{s}", .{@import("log.zig").refused(&buf, id, cx.message)}); + const body = openai.errorBody(t.a, &cx, null) catch return; + reply(t, cx.status(), openai.wrapError(t.a, body) catch return); + } + + /// The parent itself when the journal is off, so a request runs exactly as it would without one. + pub fn out(t: *Trace) openai.Out { + if (t.journal == null) return t.parent; + return .{ .ctx = t, .vt = &.{ .open = open, .event = event, .reply = reply, .keepalive = keepalive } }; + } + + fn keep(t: *Trace, bytes: []const u8) void { + t.sha.update(bytes); + t.size += bytes.len; + if (!t.whole) return; + if (t.kept.items.len + bytes.len > reply_limit) return t.drop(); + t.kept.appendSlice(t.a, bytes) catch t.drop(); + } + + fn keepJson(t: *Trace, value: Value) void { + var scratch: std.heap.ArenaAllocator = .init(t.journal.?.gpa); + defer scratch.deinit(); + t.keep(json.stringify(scratch.allocator(), value, .{}) catch return t.drop()); + if (value.get("tensorfold")) |runtime| if (runtime.strField("token_sha256")) |s| { + t.token_sha256 = t.a.dupe(u8, s) catch null; + }; + } + + fn drop(t: *Trace) void { + t.whole = false; + t.kept.clearAndFree(t.a); + } + + fn open(ctx: *anyopaque, n: usize) error{Closed}!void { + const t: *Trace = @ptrCast(@alignCast(ctx)); + t.stream = true; + t.status = 200; + return t.parent.vt.open(t.parent.ctx, n); + } + + fn event(ctx: *anyopaque, payload: ?Value) error{Closed}!void { + const t: *Trace = @ptrCast(@alignCast(ctx)); + if (payload) |p| { + if (p.has("error")) t.failed = true; + t.keep("data: "); + t.keepJson(p); + t.keep("\n\n"); + } else t.keep("data: [DONE]\n\n"); + try t.parent.vt.event(t.parent.ctx, payload); + if (payload == null) t.done = true; + } + + fn reply(ctx: *anyopaque, status: u16, value: Value) void { + const t: *Trace = @ptrCast(@alignCast(ctx)); + t.status = status; + if (status >= 500) t.failed = true; + t.keepJson(value); + t.parent.vt.reply(t.parent.ctx, status, value); + t.done = true; + } + + fn keepalive(ctx: *anyopaque) error{Closed}!void { + const t: *Trace = @ptrCast(@alignCast(ctx)); + const send = t.parent.vt.keepalive orelse return; + t.keep(": keepalive\n\n"); + return send(t.parent.ctx); + } +}; diff --git a/zig/src/server/root.zig b/zig/src/server/root.zig index 46934088b14..0ce694f5a5d 100644 --- a/zig/src/server/root.zig +++ b/zig/src/server/root.zig @@ -60,6 +60,8 @@ test { _ = @import("reply_code.zig"); _ = @import("reply_text.zig"); _ = @import("reply_incremental_test.zig"); + _ = @import("recipient_reply_test.zig"); + _ = @import("recipient_cut_test.zig"); _ = @import("tool_parse.zig"); _ = @import("tool_lfm2.zig"); _ = @import("tool_lfm2_stream_test.zig"); @@ -92,6 +94,7 @@ test { _ = @import("chunk_plan.zig"); _ = @import("status_routes.zig"); _ = @import("models_input_types_test.zig"); + _ = @import("models_id_test.zig"); _ = @import("speech.zig"); _ = @import("images_generations.zig"); if (comptime @import("builtin").os.tag != .windows) _ = @import("images_batch_test.zig"); // uses a socketpair test @@ -120,6 +123,7 @@ test { _ = @import("process_resident.zig"); _ = @import("log.zig"); _ = @import("request_log.zig"); + _ = @import("request_journal_test.zig"); _ = @import("messages.zig"); _ = @import("pdf.zig"); _ = @import("pdf_flags_test.zig"); @@ -316,6 +320,9 @@ test { test { _ = @import("request_starts_turns_test.zig"); _ = @import("thinking_request_test.zig"); + _ = @import("voice_cli.zig"); + _ = @import("drama_voice_store.zig"); + if (comptime @import("builtin").os.tag != .windows) _ = @import("speech_voice_http_test.zig"); // over a Unix socket pair _ = @import("grafana_dashboard_test.zig"); _ = @import("ocr/types_test.zig"); _ = @import("ocr/geometry_test.zig"); diff --git a/zig/src/server/routes.zig b/zig/src/server/routes.zig index 37dd3f8e58b..6748b0bd098 100644 --- a/zig/src/server/routes.zig +++ b/zig/src/server/routes.zig @@ -23,6 +23,7 @@ const slide = @import("slide.zig"); const recall = @import("recall_routes.zig"); const imprint = @import("imprint_routes.zig"); const slide_forget = @import("slide_forget.zig"); +const voice_routes = @import("drama_voice_routes.zig"); const Server = @import("server.zig").Server; const request_gate = @import("request_gate.zig"); const admission = @import("request_admission.zig"); @@ -33,6 +34,8 @@ const Allocator = std.mem.Allocator; /// DELETE's per-fact route: the fact's id follows it. const fact_path = "/v1/slide/fact/"; +/// DELETE's per-voice route under --manage-voices: the voice's name follows it. +const voice_path = "/v1/voices/"; pub fn dispatch(srv: *Server, conn: *Conn, a: Allocator) void { const m = conn.method; @@ -51,6 +54,7 @@ pub fn dispatch(srv: *Server, conn: *Conn, a: Allocator) void { if (std.mem.startsWith(u8, route, fact_path)) return slide_forget.route(srv, conn, a, route[fact_path.len..]); if (std.mem.eql(u8, route, recall.path)) return recall.empty(srv, conn, a); if (std.mem.eql(u8, route, "/v1/imprint")) return imprint.forget(srv, conn, a); + if (srv.config.voice.manage and std.mem.startsWith(u8, route, voice_path)) return voice_routes.delete(srv, conn, a, route[voice_path.len..]); return responses.delete(srv, conn, a, responses.route(route)); } const message = std.fmt.allocPrint(a, "Unsupported method ({s})", .{http_conn.pyRepr(a, m) catch m}) catch return; @@ -88,7 +92,7 @@ fn get(srv: *Server, conn: *Conn, a: Allocator) void { const route = auth.routePath(conn.path); if (std.mem.eql(u8, route, "/v1/voices")) { if (srv.info.speech == null) return unknown(conn, a); - const value = @import("drama_voice.zig").listing(a, srv.voices) catch return; + const value = srv.voices.listing(a) catch return; return sendValue(conn, a, 200, value); } if (std.mem.eql(u8, route, "/memory") or std.mem.eql(u8, route, "/v1/memory")) @@ -111,6 +115,7 @@ fn get(srv: *Server, conn: *Conn, a: Allocator) void { 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 (auth_scope.modelId(route)) |id| return status.model(srv, conn, a, id) catch {}; if (std.mem.endsWith(u8, route, "/models")) return status.models(srv, conn, a) catch {}; unknown(conn, a); } @@ -132,6 +137,7 @@ fn post(srv: *Server, conn: *Conn, a: Allocator) void { } for (tokens.paths) |r| if (std.mem.eql(u8, route, r)) return tokens.post(srv, conn, a, route); const is_speech = std.mem.eql(u8, route, "/v1/audio/speech"); + const is_voices = srv.config.voice.manage and std.mem.eql(u8, route, "/v1/voices"); const is_images = std.mem.eql(u8, route, "/v1/images/generations"); const is_embedding = std.mem.eql(u8, route, "/v1/embeddings"); const is_anthropic = anthropic.route(conn.path); @@ -147,7 +153,7 @@ fn post(srv: *Server, conn: *Conn, a: Allocator) void { 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")) { + if (!is_voices and !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); } @@ -158,6 +164,7 @@ fn post(srv: *Server, conn: *Conn, a: Allocator) void { 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_voices) return voice_routes.post(srv, conn, a); 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); diff --git a/zig/src/server/serve.zig b/zig/src/server/serve.zig index 994206ed8bf..d06e5753a86 100644 --- a/zig/src/server/serve.zig +++ b/zig/src/server/serve.zig @@ -179,14 +179,18 @@ pub fn run(gpa: Allocator, io: std.Io, args: cli.Args, s: Setup) u8 { std.debug.print("tensorfold: TENSORFOLD_WIRE: expected spark or native\n", .{}); return 1; }; + const journal = if (env(s, "TENSORFOLD_REQUEST_JOURNAL")) |path| @import("request_journal.zig").Journal.open(gpa, io, path) catch |e| { + std.debug.print("tensorfold: TENSORFOLD_REQUEST_JOURNAL {s}: {s}\n", .{ path, @import("request_journal.zig").why(e) }); + return 1; + } else null; + defer if (journal) |j| j.close(); // after the server's own deinit, which runs first const config: server_mod.Config = .{ .browser = .{ .allowed_hosts = args.allowed_host, .allowed_origins = args.allowed_origin, .cors_origins = args.cors_origin }, .allowed_controls = args.allowed_controls, .redraw = args.redraw, .served_name = s.served, .model_dir = s.model_dir, - .voices_dir = args.voices, - .default_voice = args.default_voice, + .voice = .{ .dir = args.voices, .default = args.default_voice, .inline_voices = args.voice.inline_voices, .manage = args.voice.manage }, .model_ids = ids.items, .background_ids = backgrounds, .default_max_tokens = args.max_tokens, @@ -213,6 +217,7 @@ pub fn run(gpa: Allocator, io: std.Io, args: cli.Args, s: Setup) u8 { .prompt_seed = args.prompt_seed, .sse_keepalive_s = keepalive_s, .request_log = env(s, "TENSORFOLD_REQUEST_LOG"), + .journal = journal, .phase_metrics = if (env(s, "TENSORFOLD_PHASE_METRICS")) |v| std.mem.eql(u8, v, "1") else false, .spark_stats = spark_stats, .dashboard = args.dashboard, @@ -296,6 +301,7 @@ pub fn run(gpa: Allocator, io: std.Io, args: cli.Args, s: Setup) u8 { @import("startup_receipt.zig").ready(port); while (!stop_requested.load(.acquire)) std.Io.sleep(io, .fromMilliseconds(50), .awake) catch {}; drain(srv, io, s.stop, drain_s); + if (journal) |j| j.stopped(); // a stop, not a crash: requests still open are not quarantined accept_stop.store(true, .release); accept.join(); lis.close(); diff --git a/zig/src/server/server.zig b/zig/src/server/server.zig index 6077d40ce56..2a3009396f0 100644 --- a/zig/src/server/server.zig +++ b/zig/src/server/server.zig @@ -11,6 +11,7 @@ const request_guard = @import("request_guard.zig"); const metrics = @import("metrics.zig"); const model_text = @import("model_text.zig"); const reply_text = @import("reply_text.zig"); +const recipient_reply = @import("recipient_reply.zig"); const http_conn = @import("http_conn.zig"); const admission = @import("http_admission.zig"); const listener_mod = @import("listener.zig"); @@ -31,7 +32,6 @@ const Cx = errors.Cx; const Allocator = std.mem.Allocator; /// auto compacts near the window. fraction compacts past that share of it. pub const CompactAt = union(enum) { auto, fraction: f64 }; - pub const Identity = @import("identity.zig").Identity; /// The most a kept-alive connection's arena keeps between requests; a longer request's memory goes back. pub const connection_arena_limit: usize = 1 << 20; @@ -43,8 +43,8 @@ pub const Config = struct { sse_keepalive_s: f64 = 15, served_name: []const u8, model_dir: []const u8 = "", - voices_dir: ?[]const u8 = null, - default_voice: []const u8 = "default", + /// --voices, --default-voice, --request-voices and --manage-voices; the last two off keep the startup catalog. + voice: @import("voice_cli.zig").Config = .{}, /// The served name first, then aliases, without repeats. model_ids: []const []const u8, /// Ids a request may name for background priority by default (--name-priority); each is in model_ids. @@ -79,6 +79,7 @@ pub const Config = struct { prompt_seed: bool = false, // --prompt-seed: historical prompt-keyed sampling when a request omits its seed /// TENSORFOLD_REQUEST_LOG: where chat and completion bodies are appended; null: nowhere. request_log: ?[]const u8 = null, + journal: ?*@import("request_journal.zig").Journal = null, // serve owns TENSORFOLD_REQUEST_JOURNAL /// TENSORFOLD_PHASE_METRICS=1: /metrics adds the queue phase's histogram; unset, its families are as before. phase_metrics: bool = false, /// The Spark server's keys in each reply's ``tensorfold`` block (spark_wire.zig): DeepSeek-V4, or TENSORFOLD_WIRE. @@ -137,14 +138,18 @@ pub const Server = struct { info: api.Info, text: model_text.Text, config: Config, - voices: []const @import("drama_voice.zig").Voice = &.{}, + voices: @import("drama_voice_store.zig").Store = .{}, keys: ?*auth.Store, late_system: []const u8 = "system", needs_user_after_tool: bool = false, markers: reply_text.Markers = reply_text.think_markers, + /// Replies are messages to recipients (`to=self` reasoning, `to=user` answer, a tool's name a call). + recipients: bool = false, close_id: ?u32 = null, // the close marker's own token, when the marker is one token chunks: chunk_plan.Plan = .{}, effort_levels: []const []const u8 = &.{}, + /// The effort a recipient template hears with thinking off: it has no switch, so its lowest level, not its default. + off_effort: ?[]const u8 = null, thinking_switch: bool = false, video_decoder: bool = false, // libtfvideo loaded in `init`: with the video offer it decides video input (#3004) eos: []const u32 = &.{}, @@ -206,11 +211,10 @@ pub const Server = struct { return error.InvalidVisionMarkers; }; srv.video_decoder = @import("input_types.zig").decodes(srv.info.vision); // no decoder: video parts are a 400, never a 500 - if (config.voices_dir) |dir| { - if (srv.info.speech == null) return error.VoicesRequireSpeech; - srv.voices = try @import("drama_voice.zig").load(srv.arena.allocator(), io, dir); - } - _ = try @import("drama_voice.zig").select(srv.voices, config.default_voice, "default"); + srv.voices = .{ .gpa = gpa, .io = io, .dir = config.voice.dir }; + if (srv.info.speech == null and (config.voice.dir != null or config.voice.inline_voices or config.voice.manage)) return error.VoicesRequireSpeech; + if (config.voice.dir) |dir| try srv.voices.load(dir); + _ = try srv.voices.select(srv.arena.allocator(), config.voice.default, "default"); if (!srv.info.capability(.text_generation)) { if (config.cortheon) return error.CortheonRequiresTextGeneration; return srv; @@ -228,8 +232,10 @@ pub const Server = struct { const minimax = text.tokenId(reply_text.mm_markers.close) != null; if (minimax) srv.markers = reply_text.mm_markers; srv.close_id = text.tokenId(srv.markers.close); + srv.recipients = recipient_reply.detect(text); const source = text.templateSource(); srv.effort_levels = try fields.effortLevels(a, source); + if (srv.recipients and srv.effort_levels.len > 0) srv.off_effort = fields.coerceEffort("minimal", srv.effort_levels); // MiniMax-M3's template decides on its own; thinking off closes the block in the prompt (prompt.zig) srv.thinking_switch = minimax or std.mem.indexOf(u8, source, "enable_thinking") != null or std.mem.indexOf(u8, source, "thinking_mode") != null; @@ -267,6 +273,7 @@ pub const Server = struct { srv.stopKeepalive(); if (srv.grammars) |g| g.close(); srv.metrics.deinit(); + srv.voices.deinit(); srv.arena.deinit(); srv.store.deinit(); srv.slide.deinit(); @@ -556,14 +563,7 @@ fn seedBits(v: Value) u64 { if (std.fmt.parseInt(i128, v.int, 10)) |n| return @truncate(@as(u128, @bitCast(n))) else |_| return 0; } -/// ``template_late_system``: "system" when the template keeps a later system message in place, else "user". -fn lateSystem(a: Allocator, text: model_text.Text) ![]const u8 { - const probe_text = "tensorfold-late-system-probe"; - const probe = (try json.parse(a, "[{\"role\": \"system\", \"content\": \"s\"}, {\"role\": \"user\", \"content\": \"u\"}, {\"role\": \"assistant\", \"content\": \"a\"}, {\"role\": \"system\", \"content\": \"tensorfold-late-system-probe\"}, {\"role\": \"user\", \"content\": \"v\"}]")).ok; - var problem: []const u8 = ""; - const rendered = text.render(a, probe, .{ .add_generation_prompt = false }, &problem) catch return "user"; - return if (std.mem.indexOf(u8, rendered.text, probe_text) != null) "system" else "user"; -} +const lateSystem = @import("late_system.zig").lateSystem; /// With image input: whether a user turn holding an image part renders an image placeholder (else a startup warning). fn templateImages(srv: *Server) bool { diff --git a/zig/src/server/speech.zig b/zig/src/server/speech.zig index e78662efbcd..e7412ddb939 100644 --- a/zig/src/server/speech.zig +++ b/zig/src/server/speech.zig @@ -81,9 +81,10 @@ fn listed(names: []const []const u8, key: []const u8) bool { } /// Refuses what this route would drop: unknown fields, set modifiers, non-strings, a bad ``stream``/``stream_format``. -fn checkFields(cx: *Cx, body: Value) errors.Refused!void { +fn checkFields(cx: *Cx, body: Value, inline_voices: bool) errors.Refused!void { for (body.object.keys(), body.object.values()) |key, value| { if (listed(&served_fields, key)) { + if (value == .object and inline_voices and std.mem.eql(u8, key, "voice")) continue; // an attested voice object if (value != .string) return cx.fail(.request, "{s} must be a string", .{key}); } else if (std.mem.eql(u8, key, "stream")) { if (value != .bool and value != .null) return cx.refuse("stream must be a boolean"); @@ -110,7 +111,7 @@ fn responseFormat(cx: *Cx, value: []const u8) errors.Refused!Format { /// Every check that can refuse the request, then its prompt ids, before anything reaches the engine. fn prepare(srv: *Server, cx: *Cx, sp: api.SpeechInfo, raw: Value) errors.Refused!Plan { if (raw != .object) return cx.refuse("speech request body must be a JSON object"); - try checkFields(cx, raw); + try checkFields(cx, raw, srv.config.voice.inline_voices); const sampling = try speech_sampling.parse(cx, raw); const model = raw.strField("model") orelse return cx.fail(.request, "model is required: send {s}", .{srv.config.served_name}); if (!listed(srv.config.model_ids, model)) @@ -123,16 +124,30 @@ fn prepare(srv: *Server, cx: *Cx, sp: api.SpeechInfo, raw: Value) errors.Refused const format = try responseFormat(cx, raw.strField("response_format") orelse "wav"); const stream = if (raw.get("stream")) |s| s == .bool and s.bool else false; if (stream and format != .pcm) return cx.refuse("stream=true requires response_format='pcm'"); + const refs = try voiceRefs(srv, cx, raw); + if (try @import("drama_voice.zig").requestPrompt(cx, srv.text, sp, input, refs)) |made| return .{ .input = input, .prompt = made.prompt, .frames = made.frames, .refs = refs, .reference_rows = made.reference_rows, .sampling = sampling, .format = format, .stream = stream }; + const prompt = try promptOf(srv, cx, sp, input); + return .{ .input = input, .prompt = prompt, .sampling = sampling, .format = format, .stream = stream }; +} + +/// The request's references: an attested inline voice under --request-voices, else the named catalog voice's, copied. +fn voiceRefs(srv: *Server, cx: *Cx, raw: Value) errors.Refused![]const @import("drama_prompt").Reference { + if (raw.get("voice")) |value| if (value == .object) { + if (raw.get("speaker") != null) return cx.refuse("an inline voice object takes no speaker"); + return @import("drama_voice.zig").parseDoc(cx.a, value) catch |e| switch (e) { + error.OutOfMemory => error.OutOfMemory, + error.MissingAttestation => cx.refuse("an inline voice needs source.kind synthetic, self or consented and a source.note"), + else => cx.refuse("an inline voice is a drama3-http-voice/1 object with 1 to 4 references"), + }; + }; const voice = raw.strField("voice") orelse raw.strField("speaker") orelse "default"; - const refs = @import("drama_voice.zig").select(srv.voices, srv.config.default_voice, voice) catch { + return srv.voices.select(cx.a, srv.config.voice.default, voice) catch |e| { + if (e == error.OutOfMemory) return error.OutOfMemory; const name = try pyrepr.repr(cx.a, .{ .string = voice }); - if (srv.config.voices_dir != null) + if (srv.config.voice.dir != null or srv.config.voice.manage) return cx.fail(.request, drama_prompt.error_prefix ++ " unknown voice {s}; see /v1/voices", .{name}); return cx.fail(.request, drama_prompt.error_prefix ++ " unknown voice {s}; only the default voice is supported", .{name}); }; - if (try @import("drama_voice.zig").requestPrompt(cx, srv.text, sp, input, refs)) |made| return .{ .input = input, .prompt = made.prompt, .frames = made.frames, .refs = refs, .reference_rows = made.reference_rows, .sampling = sampling, .format = format, .stream = stream }; - const prompt = try promptOf(srv, cx, sp, input); - return .{ .input = input, .prompt = prompt, .sampling = sampling, .format = format, .stream = stream }; } /// The prompt ids of a valid UTF-8 input, refused when it cannot be spoken or is too long. @@ -456,9 +471,9 @@ test "fields: unknown ones are refused even when null, modifiers when set" { var cx: Cx = .{ .a = a }; const body = (try json.parse(a, case[0])).ok; if (case[1].len == 0) { - try checkFields(&cx, body); + try checkFields(&cx, body, false); } else { - try std.testing.expectError(error.Refused, checkFields(&cx, body)); + try std.testing.expectError(error.Refused, checkFields(&cx, body, false)); try std.testing.expectEqualStrings(case[1], cx.message); } } diff --git a/zig/src/server/speech_stream_test.zig b/zig/src/server/speech_stream_test.zig index 40cb36d39eb..ccb41708198 100644 --- a/zig/src/server/speech_stream_test.zig +++ b/zig/src/server/speech_stream_test.zig @@ -186,7 +186,7 @@ pub const Served = struct { s.* = .{ .srv = undefined, .client = pair[0], .route_fd = pair[1], .route = undefined, .write_ms = write_ms, .probe = probe }; s.srv = try server.Server.init(gpa, std.testing.io, script.engine(), s.text.text(), config, null); if (probe) |p| p.srv = s.srv; - s.srv.voices = script.voices; + try s.srv.voices.swap(script.voices); if (script.output_full) s.srv.speech_inflight.store(s.srv.info.lanes, .release); var head: [256]u8 = undefined; const method_path = if (script.get_voices) "GET /v1/voices" else "POST /v1/audio/speech"; diff --git a/zig/src/server/speech_voice_http_test.zig b/zig/src/server/speech_voice_http_test.zig new file mode 100644 index 00000000000..1b4b23135bc --- /dev/null +++ b/zig/src/server/speech_voice_http_test.zig @@ -0,0 +1,238 @@ +//! Real sockets: --manage-voices adds and deletes catalog voices for admin keys, --request-voices takes inline voices. +const std = @import("std"); +const api = @import("engine_api"); +const server = @import("server.zig"); +const auth = @import("auth.zig"); +const listener = @import("listener.zig"); +const voice = @import("drama_voice.zig"); +const wire = @import("speech_stream_test.zig"); +const KeyFile = @import("auth_scope_test.zig").KeyFile; +const posix = @import("sys").posix; +const t = std.testing; +const Allocator = std.mem.Allocator; + +const tone = + \\{"format":"drama3-http-voice/1","source":{"kind":"synthetic","note":"Generated fixture tone."}, + \\"description":"Warm fixture.","references":[{"text":"A small cloud passes.","codes":[[7,1,2,3,4,5,6,7,8,9]]}]} +; + +const Fake = struct { + hold: std.atomic.Value(bool) = .init(false), + held: std.atomic.Value(bool) = .init(false), + encodes: std.atomic.Value(u32) = .init(0), + frames: std.ArrayList([11]i32) = .empty, + + fn engine(e: *Fake) api.Engine { + return .{ .ctx = e, .vtable = &.{ .info = info, .submit = submit, .submit_speech = speech, .cancel = cancel, .status = status, .memory = memory, .encode_voice = encode } }; + } + fn info(_: *anyopaque) api.Info { + return .{ .text_generation = false, .speech = .{ .sample_rate = 44100, .frame_length = 2048, .max_frames = 4, .max_prompt_tokens = 4096 } }; + } + fn speech(ctx: *anyopaque, id: api.Id, request: *const api.SpeechRequest, sink: api.Sink) api.SpeechSubmitError!void { + const e: *Fake = @ptrCast(@alignCast(ctx)); + e.frames.clearRetainingCapacity(); + e.frames.appendSlice(t.allocator, request.frames) catch return error.Busy; + e.held.store(true, .release); + while (e.hold.load(.acquire)) std.Thread.yield() catch {}; + @memset(request.pcm[0..256], 0.125); + request.result.* = .{ .samples = 256, .reason = .stop }; + sink.event(sink.ctx, id, &.{ .finished = .{ .reason = .stop } }); + } + /// Codes from the file's bytes: one row a byte past the 44-byte header, so a test can predict them. + fn encode(ctx: *anyopaque, gpa: Allocator, wav: []const u8) api.EncodeVoiceError![][10]i32 { + const e: *Fake = @ptrCast(@alignCast(ctx)); + _ = e.encodes.fetchAdd(1, .monotonic); + if (wav.len <= 44 or !std.mem.eql(u8, wav[0..4], "RIFF")) return error.BadWav; + const codes = try gpa.alloc([10]i32, wav.len - 44); + for (codes, wav[44..]) |*row, byte| row.* = @splat(byte); + return codes; + } + fn submit(_: *anyopaque, _: api.Id, _: *const api.Request, _: api.Sink) api.SubmitError!void { + return error.Closed; + } + 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, + text: wire.Bytes = .{}, + listener: listener.Listener = undefined, + accept: std.Thread = undefined, + stop: std.atomic.Value(bool) = .init(false), + + fn start(h: *Harness, fake: *Fake, config: server.Config, keys: ?*auth.Store) !void { + h.srv = try server.Server.init(t.allocator, t.io, fake.engine(), h.text.text(), config, 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 == 5000) @panic("voice fixture did not quiesce"); + std.Io.sleep(t.io, .fromMilliseconds(1), .awake) catch {}; + } + h.listener.close(); + h.srv.deinit(); + } + /// The whole reply to one request on its own connection. + fn ask(h: *Harness, a: Allocator, method: []const u8, path: []const u8, key: []const u8, body: []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; + const auth_line = if (key.len > 0) try std.fmt.allocPrint(a, "Authorization: Bearer {s}\r\n", .{key}) else ""; + const raw = try std.fmt.allocPrint(a, "{s} {s} HTTP/1.1\r\nHost: localhost\r\n{s}Content-Length: {d}\r\nConnection: close\r\n\r\n{s}", .{ method, path, auth_line, body.len, body }); + 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, 5000) == 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 expectReply(reply: []const u8, status: []const u8, text: []const u8) !void { + if (!std.mem.startsWith(u8, reply, status) or std.mem.indexOf(u8, reply, text) == null) { + std.debug.print("expected {s} with {s}, got:\n{s}\n", .{ status, text, reply }); + return error.TestUnexpectedResult; + } +} + +fn wavBase64(a: Allocator, samples: []const u8) ![]const u8 { + const wav = try std.mem.concat(a, u8, &.{ "RIFF\x00\x00\x00\x00WAVE", "fmt and data headers stand here.", samples }); + const out = try a.alloc(u8, std.base64.standard.Encoder.calcSize(wav.len)); + return std.base64.standard.Encoder.encode(out, wav); +} + +test "voices HTTP: without --manage-voices and --request-voices every refusal stays as it was" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var fake: Fake = .{}; + defer fake.frames.deinit(t.allocator); + var h: Harness = .{}; + try h.start(&fake, .{ .served_name = "m", .model_ids = &.{"m"}, .keep_warm_s = 0 }, null); + defer h.deinit(); + try expectReply(try h.ask(a, "POST", "/v1/voices", "", "{\"name\":\"tone\"," ++ tone[1..]), "HTTP/1.1 404", "unknown path /v1/voices"); + try expectReply(try h.ask(a, "DELETE", "/v1/voices/tone", "", ""), "HTTP/1.1 404", "no stored response has id None"); + const as_null = try h.ask(a, "POST", "/v1/audio/speech", "", "{\"model\":\"m\",\"input\":\"hi\",\"voice\":null}"); + const as_object = try h.ask(a, "POST", "/v1/audio/speech", "", "{\"model\":\"m\",\"input\":\"hi\",\"voice\":" ++ tone ++ "}"); + try expectReply(as_object, "HTTP/1.1 400", "voice must be a string"); + try t.expectEqualStrings(as_null[std.mem.indexOf(u8, as_null, "\r\n\r\n").?..], as_object[std.mem.indexOf(u8, as_object, "\r\n\r\n").?..]); + try t.expectEqual(@as(u32, 0), fake.encodes.load(.monotonic)); +} + +test "voices HTTP: admin keys add and delete voices; a request already running keeps its voice" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var keys_file = try KeyFile.init("app[inference]: infer-secret\nmonitor[read]: read-secret\nops[admin]: admin-secret\n"); + defer keys_file.deinit(); + var problem: []const u8 = ""; + var keys = try auth.Store.init(t.allocator, &.{}, "", keys_file.path, false, &problem); + defer keys.deinit(); + var tmp = t.tmpDir(.{}); + defer tmp.cleanup(); + const dir = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}", .{tmp.sub_path}); + var fake: Fake = .{}; + defer fake.frames.deinit(t.allocator); + var h: Harness = .{}; + try h.start(&fake, .{ .served_name = "m", .model_ids = &.{"m"}, .keep_warm_s = 0, .voice = .{ .dir = dir, .manage = true } }, &keys); + defer h.deinit(); + const add_tone = "{\"name\":\"tone\"," ++ tone[1..]; + for ([_][]const u8{ "infer-secret", "read-secret" }) |key| { + try expectReply(try h.ask(a, "POST", "/v1/voices", key, add_tone), "HTTP/1.1 403", ""); + try expectReply(try h.ask(a, "DELETE", "/v1/voices/tone", key, ""), "HTTP/1.1 403", ""); + } + const admin = "admin-secret"; + try expectReply(try h.ask(a, "POST", "/v1/voices", admin, "{\"name\":\"default\"," ++ tone[1..]), "HTTP/1.1 400", "not default"); + try expectReply(try h.ask(a, "POST", "/v1/voices", admin, "{\"name\":\"x\",\"format\":\"drama3-http-voice/1\",\"references\":[{\"text\":\"A.\",\"codes\":[[1,2,3,4,5,6,7,8,9,10]]}]}"), "HTTP/1.1 400", "source.kind"); + const unattested_wav = try std.fmt.allocPrint(a, "{{\"name\":\"clone\",\"text\":\"A small cloud passes.\",\"audio\":\"{s}\"}}", .{try wavBase64(a, "\x05\x06")}); + try expectReply(try h.ask(a, "POST", "/v1/voices", admin, unattested_wav), "HTTP/1.1 400", "source.kind"); + try t.expectEqual(@as(u32, 0), fake.encodes.load(.monotonic)); // refused before the codec ran + try expectReply(try h.ask(a, "POST", "/v1/voices", admin, add_tone), "HTTP/1.1 201", "\"added\": true"); + try expectReply(try h.ask(a, "POST", "/v1/voices", admin, add_tone), "HTTP/1.1 200", "\"added\": false"); + const written = try voice.parse(a, try tmp.dir.readFileAlloc(t.io, "tone.json", a, .limited(voice.max_file_bytes))); + try t.expectEqualStrings("A small cloud passes.", written[0].transcript); + try t.expectEqualSlices([10]i32, (try voice.parse(a, tone))[0].codes, written[0].codes); + const wav_body = try std.fmt.allocPrint(a, "{{\"name\":\"clone\",\"text\":\"A small cloud passes.\",\"source\":{{\"kind\":\"self\",\"note\":\"My own voice.\"}},\"audio\":\"{s}\"}}", .{try wavBase64(a, "\x05\x06")}); + try expectReply(try h.ask(a, "POST", "/v1/voices", admin, wav_body), "HTTP/1.1 201", "\"id\": \"clone\""); + const clone = try voice.parse(a, try tmp.dir.readFileAlloc(t.io, "clone.json", a, .limited(voice.max_file_bytes))); + try t.expectEqualSlices([10]i32, &.{ @splat(5), @splat(6) }, clone[0].codes); + try expectReply(try h.ask(a, "GET", "/v1/voices", "read-secret", ""), "HTTP/1.1 200", "\"voices\": [\"default\", \"clone\", \"tone\"]"); + // a request reading "tone" keeps its frames while an admin deletes it + fake.hold.store(true, .release); + const Speaker = struct { + h: *Harness, + reply: []const u8 = "", + fn run(s: *@This(), out: Allocator) void { + s.reply = s.h.ask(out, "POST", "/v1/audio/speech", "infer-secret", "{\"model\":\"m\",\"input\":\"hello\",\"voice\":\"tone\"}") catch "failed"; + } + }; + var speaker: Speaker = .{ .h = &h }; + var speaker_arena: std.heap.ArenaAllocator = .init(t.allocator); + defer speaker_arena.deinit(); + const thread = try std.Thread.spawn(.{}, Speaker.run, .{ &speaker, speaker_arena.allocator() }); + var joined = false; + defer if (!joined) { + fake.hold.store(false, .release); + thread.join(); + }; + while (!fake.held.load(.acquire)) std.Thread.yield() catch {}; + try expectReply(try h.ask(a, "DELETE", "/v1/voices/tone", admin, ""), "HTTP/1.1 200", "\"deleted\": true"); + try t.expectError(error.FileNotFound, tmp.dir.access(t.io, "tone.json", .{})); + fake.hold.store(false, .release); + thread.join(); + joined = true; + try expectReply(speaker.reply, "HTTP/1.1 200", "RIFF"); + const want = try voice.promptFor(a, h.text.text(), "hello", try voice.parse(a, tone)); + try t.expectEqualSlices([11]i32, want.frames, fake.frames.items); + try expectReply(try h.ask(a, "POST", "/v1/audio/speech", "infer-secret", "{\"model\":\"m\",\"input\":\"hello\",\"voice\":\"tone\"}"), "HTTP/1.1 400", "unknown voice 'tone'; see /v1/voices"); + try expectReply(try h.ask(a, "DELETE", "/v1/voices/tone", admin, ""), "HTTP/1.1 404", "no such voice"); +} + +test "voices HTTP: --request-voices takes an attested inline voice as the catalog's own" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = t.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(t.io, .{ .sub_path = "tone.json", .data = tone }); + var fake: Fake = .{}; + defer fake.frames.deinit(t.allocator); + var h: Harness = .{}; + try h.start(&fake, .{ .served_name = "m", .model_ids = &.{"m"}, .keep_warm_s = 0, .voice = .{ .dir = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}", .{tmp.sub_path}), .inline_voices = true } }, null); + defer h.deinit(); + try expectReply(try h.ask(a, "POST", "/v1/audio/speech", "", "{\"model\":\"m\",\"input\":\"A cloud.\",\"voice\":\"tone\"}"), "HTTP/1.1 200", "RIFF"); + const from_catalog = try a.dupe([11]i32, fake.frames.items); + try expectReply(try h.ask(a, "POST", "/v1/audio/speech", "", "{\"model\":\"m\",\"input\":\"A cloud.\",\"voice\":" ++ tone ++ "}"), "HTTP/1.1 200", "RIFF"); + try t.expectEqualSlices([11]i32, from_catalog, fake.frames.items); + try expectReply(try h.ask(a, "POST", "/v1/audio/speech", "", "{\"model\":\"m\",\"input\":\"hi\",\"voice\":{\"format\":\"drama3-http-voice/1\",\"references\":[{\"text\":\"A.\",\"codes\":[[1,2,3,4,5,6,7,8,9,10]]}]}}"), "HTTP/1.1 400", "source.kind"); + try expectReply(try h.ask(a, "POST", "/v1/audio/speech", "", "{\"model\":\"m\",\"input\":\"hi\",\"speaker\":\"tone\",\"voice\":" ++ tone ++ "}"), "HTTP/1.1 400", "takes no speaker"); + try expectReply(try h.ask(a, "POST", "/v1/audio/speech", "", "{\"model\":\"m\",\"input\":\"hi\",\"ref_audio\":\"x.wav\"}"), "HTTP/1.1 400", "ref_audio is not supported by this model"); + try expectReply(try h.ask(a, "POST", "/v1/voices", "", "{\"name\":\"x\"," ++ tone[1..]), "HTTP/1.1 404", "unknown path"); +} diff --git a/zig/src/server/status_routes.zig b/zig/src/server/status_routes.zig index 140b6ada6e7..58b3aeb0707 100644 --- a/zig/src/server/status_routes.zig +++ b/zig/src/server/status_routes.zig @@ -1,9 +1,11 @@ -//! GET /health, /v1/models, /metrics, and the opt-in dashboard. +//! GET /health, /v1/models and one model's /v1/models/{id}, /metrics, and the opt-in dashboard. const std = @import("std"); const api = @import("engine_api"); const json = @import("json"); const live = @import("live.zig"); const routes = @import("routes.zig"); +const pyrepr = @import("pyrepr.zig"); +const percentDecode = @import("tool_kinds.zig").percentDecode; const manifest = @import("benchmark_manifest.zig"); const Server = @import("server.zig").Server; const Conn = @import("http_conn.zig").Conn; @@ -78,17 +80,38 @@ pub fn manifestRoute(srv: *Server, conn: *Conn, a: Allocator) !void { } pub fn models(srv: *Server, conn: *Conn, a: Allocator) !void { + const o = try json.newObject(a); + try o.put(a, "object", .{ .string = "list" }); + try o.put(a, "data", .{ .array = try entries(srv, a, srv.config.model_ids) }); + routes.sendValue(conn, a, 200, .{ .object = o }); +} + +/// GET /v1/models/{id}: the listing's entry for a served id or alias, `raw` percent-decoded; else 404 model_not_found. +pub fn model(srv: *Server, conn: *Conn, a: Allocator, raw: []const u8) !void { + const id = (try percentDecode(a, raw)) orelse raw; // a % that escapes no hex pair is read as written + for (srv.config.model_ids) |known| { + if (std.mem.eql(u8, known, id)) return routes.sendValue(conn, a, 200, (try entries(srv, a, &.{known}))[0]); + } + const err = try json.newObject(a); + try err.put(a, "message", .{ .string = try std.fmt.allocPrint(a, "model {s} is not served here", .{try pyrepr.repr(a, .{ .string = id })}) }); + try err.put(a, "type", .{ .string = "invalid_request_error" }); + try err.put(a, "param", .{ .string = "model" }); + try err.put(a, "code", .{ .string = "model_not_found" }); + const o = try json.newObject(a); + try o.put(a, "error", .{ .object = err }); + routes.sendValue(conn, a, 404, .{ .object = o }); +} + +/// The discovery entries for `ids`, as the listing and the one-model route both send them. +fn entries(srv: *Server, a: Allocator, ids: []const []const u8) ![]Value { const info = if (srv.idle_manager) |m| m.readInfo(srv) else srv.info; const created = std.Io.Clock.real.now(srv.io).toSeconds(); - const data = try a.alloc(Value, srv.config.model_ids.len); + const data = try a.alloc(Value, ids.len); const reasoning = try modelReasoning(a, srv); - for (srv.config.model_ids, data) |id, *slot| { + for (ids, data) |id, *slot| { 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" }); - try o.put(a, "data", .{ .array = data }); - routes.sendValue(conn, a, 200, .{ .object = o }); + return data; } fn modelReasoning(a: Allocator, srv: *const Server) Allocator.Error!?Value { diff --git a/zig/src/server/tool_kinds.zig b/zig/src/server/tool_kinds.zig index 53a9b4f4401..a5a61c4a112 100644 --- a/zig/src/server/tool_kinds.zig +++ b/zig/src/server/tool_kinds.zig @@ -180,8 +180,8 @@ fn resolvePointer(a: Allocator, root: Value, ref: []const u8) Allocator.Error!?V return current; } -/// The fragment with its percent escapes decoded, or null when one is not a hex pair. -fn percentDecode(a: Allocator, text: []const u8) Allocator.Error!?[]const u8 { +/// The text with its percent escapes decoded, or null when one is not a hex pair. +pub fn percentDecode(a: Allocator, text: []const u8) Allocator.Error!?[]const u8 { if (std.mem.indexOfScalar(u8, text, '%') == null) return text; var out: std.ArrayList(u8) = .empty; var i: usize = 0; diff --git a/zig/src/server/vision_inputs.zig b/zig/src/server/vision_inputs.zig index f1caebcb6df..51e9bc97901 100644 --- a/zig/src/server/vision_inputs.zig +++ b/zig/src/server/vision_inputs.zig @@ -299,7 +299,7 @@ fn videoGlm(srv: *Server, cx: *Cx, bytes: []const u8) errors.Refused!qi.glm.Vide const l = library(srv.io) orelse return cx.refuse(@import("sys").optional_libraries.spec(.video).message); var gs: GlmSize = .{ .budget = 16384 }; gs.budget = @import("sys").environment.read(u64, "TENSORFOLD_VIDEO_TOKENS", gs.budget) catch { - return cx.refuse(try @import("sys").environment.describe(cx.a, "TENSORFOLD_VIDEO_TOKENS", @import("sys").getenv("TENSORFOLD_VIDEO_TOKENS").?)); + return cx.refuse(try @import("sys").environment.describe(cx.a, "TENSORFOLD_VIDEO_TOKENS", (@import("sys").environment.Process{}).get("TENSORFOLD_VIDEO_TOKENS").?)); }; var v: TfVideo = undefined; const rc = l.decode(bytes.ptr, bytes.len, 2.0, 2, 256, 3600.0, 8192, sizeForGlm, @ptrCast(&gs), &v); @@ -328,7 +328,7 @@ fn video(srv: *Server, cx: *Cx, bytes: []const u8) errors.Refused!qi.Video { const l = library(srv.io) orelse return cx.refuse(@import("sys").optional_libraries.spec(.video).message); var budget: u64 = 16384; budget = @import("sys").environment.read(u64, "TENSORFOLD_VIDEO_TOKENS", budget) catch { - return cx.refuse(try @import("sys").environment.describe(cx.a, "TENSORFOLD_VIDEO_TOKENS", @import("sys").getenv("TENSORFOLD_VIDEO_TOKENS").?)); + return cx.refuse(try @import("sys").environment.describe(cx.a, "TENSORFOLD_VIDEO_TOKENS", (@import("sys").environment.Process{}).get("TENSORFOLD_VIDEO_TOKENS").?)); }; var v: TfVideo = undefined; const rc = l.decode(bytes.ptr, bytes.len, 2.0, 4, 256, 3600.0, 8192, sizeFor, @ptrCast(&budget), &v); diff --git a/zig/src/server/voice_cli.zig b/zig/src/server/voice_cli.zig new file mode 100644 index 00000000000..b7b2ad4f885 --- /dev/null +++ b/zig/src/server/voice_cli.zig @@ -0,0 +1,39 @@ +//! The opt-in voice flags of a speech server, parsed beside the serve parser's own flag dispatch. +const std = @import("std"); +const cli = @import("cli.zig"); + +pub const flags = [_]cli.Flag{ + .{ .name = "--request-voices", .kind = .store_true, .native = true }, + .{ .name = "--manage-voices", .kind = .store_true, .native = true }, +}; + +/// The served catalog's settings: --voices DIR, --default-voice NAME and the two flags. +pub const Config = struct { + dir: ?[]const u8 = null, + default: []const u8 = "default", + inline_voices: bool = false, + manage: bool = false, +}; + +pub const Flags = struct { + /// --request-voices: a speech request's `voice` may be an attested voice object instead of a catalog name. + inline_voices: bool = false, + /// --manage-voices: admin keys add (POST /v1/voices) and delete (DELETE /v1/voices/NAME) catalog voices. + manage: bool = false, +}; + +/// True when `name` is a voice flag, now set. +pub fn apply(f: *Flags, name: []const u8) bool { + if (std.mem.eql(u8, name, "--request-voices")) f.inline_voices = true else if (std.mem.eql(u8, name, "--manage-voices")) f.manage = true else return false; + return true; +} + +test "voice CLI: --request-voices and --manage-voices default off and are switches" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var u: cli.Usage = .{}; + try std.testing.expectEqual(Flags{}, (try cli.parse(a, &.{"m"}, &u)).voice); + try std.testing.expectEqual(Flags{ .inline_voices = true }, (try cli.parse(a, &.{ "m", "--request-voices" }, &u)).voice); + try std.testing.expectEqual(Flags{ .inline_voices = true, .manage = true }, (try cli.parse(a, &.{ "m", "--manage-voices", "--request-voices" }, &u)).voice); +} diff --git a/zig/src/server/web_cli.zig b/zig/src/server/web_cli.zig index def31010aed..8170bfdd73c 100644 --- a/zig/src/server/web_cli.zig +++ b/zig/src/server/web_cli.zig @@ -38,9 +38,12 @@ pub fn main(init: std.process.Init, args: []const []const u8, version: Version) pub fn command(ctx: Context, args: []const []const u8, version: Version) !u8 { if (try onPath(ctx, "tensorfold-web")) |app| return launch(ctx, app, args); + const uv = try onPath(ctx, "uv"); + if (uv) |tool| { + if (try inUvToolDir(ctx, tool)) |app| return launch(ctx, app, args); + } try ctx.out.writeAll(description); const spec = try std.fmt.allocPrint(ctx.a, "tensorfold-web @ git+https://github.com/ashhart/TensorFold@v{s}#subdirectory=web", .{version.version}); - const uv = try onPath(ctx, "uv"); if (!version.is_release) { try ctx.out.print("Development build without a release tag; the command below targets the manifest version v{s}.\n", .{version.version}); } else if (uv == null) { @@ -62,19 +65,7 @@ pub fn command(ctx: Context, args: []const []const u8, version: Version) !u8 { return instructions(ctx, spec, false); } if (try onPath(ctx, "tensorfold-web")) |app| return launch(ctx, app, args); - // uv's tool-bin directory need not already be on this process's PATH. - const result = std.process.run(ctx.a, ctx.io, .{ - .argv = &.{ uv.?, "tool", "dir", "--bin" }, - .environ_map = ctx.environ, - .stdout_limit = .limited(4096), - .stderr_limit = .limited(4096), - }) catch return instructions(ctx, spec, false); - defer ctx.a.free(result.stdout); - defer ctx.a.free(result.stderr); - const dir = std.mem.trim(u8, result.stdout, "\r\n"); - if (exitCode(result.term) == 0 and std.fs.path.isAbsolute(dir)) { - if (try inDir(ctx, dir, "tensorfold-web")) |app| return launch(ctx, app, args); - } + if (try inUvToolDir(ctx, uv.?)) |app| return launch(ctx, app, args); try ctx.out.writeAll("uv finished, but its tensorfold-web executable could not be found.\n"); } } @@ -131,6 +122,20 @@ fn onPath(ctx: Context, name: []const u8) !?[]const u8 { return null; } +fn inUvToolDir(ctx: Context, uv: []const u8) !?[]const u8 { + const result = std.process.run(ctx.a, ctx.io, .{ + .argv = &.{ uv, "tool", "dir", "--bin" }, + .environ_map = ctx.environ, + .stdout_limit = .limited(4096), + .stderr_limit = .limited(4096), + }) catch return null; + defer ctx.a.free(result.stdout); + defer ctx.a.free(result.stderr); + const dir = std.mem.trim(u8, result.stdout, "\r\n"); + if (exitCode(result.term) != 0 or !std.fs.path.isAbsolute(dir)) return null; + return inDir(ctx, dir, "tensorfold-web"); +} + fn inDir(ctx: Context, dir: []const u8, name: []const u8) !?[]const u8 { const extensions: []const []const u8 = if (builtin.os.tag == .windows) &.{ ".exe", ".com", ".cmd", ".bat", "" } else &.{""}; for (extensions) |extension| { diff --git a/zig/src/server/web_cli_test.zig b/zig/src/server/web_cli_test.zig index 428d0cdb19b..60fde87a0da 100644 --- a/zig/src/server/web_cli_test.zig +++ b/zig/src/server/web_cli_test.zig @@ -56,7 +56,11 @@ fn check(c: Case) !void { const target_bin = if (c.remote_bin) try std.fs.path.join(a, &.{ root, "other bin" }) else bin; const source = try std.fs.path.join(a, &.{ root, "app-source" }); try tmp.dir.writeFile(io, .{ .sub_path = "app-source", .data = app_script, .flags = .{ .permissions = .fromMode(0o700) } }); - if (c.installed) try tmp.dir.writeFile(io, .{ .sub_path = "bin/tensorfold-web", .data = app_script, .flags = .{ .permissions = .fromMode(0o700) } }); + if (c.installed) try tmp.dir.writeFile(io, .{ + .sub_path = if (c.remote_bin) "other bin/tensorfold-web" else "bin/tensorfold-web", + .data = app_script, + .flags = .{ .permissions = .fromMode(0o700) }, + }); if (c.uv) try tmp.dir.writeFile(io, .{ .sub_path = "bin/uv", .data = uv_script, .flags = .{ .permissions = .fromMode(0o700) } }); var env: std.process.Environ.Map = .init(a); defer env.deinit(); @@ -90,8 +94,15 @@ fn check(c: Case) !void { if (!c.launches) try t.expect(std.mem.indexOf(u8, out.written(), "uv tool install \"" ++ spec ++ "\"") != null); } else try t.expectEqualStrings("", out.written()); const uv_log = tmp.dir.readFileAlloc(io, "uv.log", a, .limited(4096)) catch ""; - const expected_uv = if (!c.installs) "" else if (c.remote_bin or c.missing_after_install) "tool\ninstall\n" ++ spec ++ "\ntool\ndir\n--bin\n" else "tool\ninstall\n" ++ spec ++ "\n"; - try t.expectEqualStrings(expected_uv, uv_log); + const query_tool_dir = "tool\ndir\n--bin\n"; + var expected_uv: std.Io.Writer.Allocating = .init(a); + defer expected_uv.deinit(); + if (c.uv and (!c.installed or c.remote_bin)) try expected_uv.writer.writeAll(query_tool_dir); + if (c.installs) { + try expected_uv.writer.writeAll("tool\ninstall\n" ++ spec ++ "\n"); + if (c.remote_bin or c.missing_after_install) try expected_uv.writer.writeAll(query_tool_dir); + } + try t.expectEqualStrings(expected_uv.written(), uv_log); const launched = tmp.dir.readFileAlloc(io, "launch.log", a, .limited(4096)) catch ""; try t.expectEqualStrings(if (c.launches) "/example path/tensorfold\n--port\n9090\ntwo words\n$(untouched);*\n\n" else "", launched); try t.expectEqualStrings("wrong-binary", env.get("TENSORFOLD_BIN").?); @@ -144,3 +155,8 @@ test "web: failed install never launches" { test "web: missing executable after successful install does not retry" { try check(.{ .missing_after_install = true, .asks = true, .installs = true }); } + +test "web: existing uv tool outside PATH launches without prompting or installing" { + try check(.{ .installed = true, .remote_bin = true, .interactive = false, .no_prompt = true, .expected = 0, .launches = true }); + try check(.{ .installed = true, .remote_bin = true, .answer = "yes\n", .expected = 0, .launches = true }); +} diff --git a/zig/src/tensorfold.zig b/zig/src/tensorfold.zig index f04095143b0..011774b1481 100644 --- a/zig/src/tensorfold.zig +++ b/zig/src/tensorfold.zig @@ -16,6 +16,8 @@ pub const qwen_vl_tower = @import("core/qwen_vl/metal.zig"); pub const qwen_image = @import("families/qwen_image/qwen_image.zig"); /// MOSS-Image's transformer on Metal: a denoiser driven by tf-moss-image, outside the lane engine. pub const moss_image = @import("families/moss_image/moss_image.zig"); +/// Idol's denoiser on Metal: driven by tf-idol, outside the lane engine. +pub const idol = @import("families/idol/idol.zig"); /// Unlimited-OCR-2 on Metal: document pages to text (its image encoder and decoder). pub const uocr = @import("families/uocr/uocr.zig"); pub const checkpoint = @import("core/checkpoint_metal.zig"); diff --git a/zig/src/xpu/tp.zig b/zig/src/xpu/tp.zig new file mode 100644 index 00000000000..d339333e9b6 --- /dev/null +++ b/zig/src/xpu/tp.zig @@ -0,0 +1,279 @@ +//! Multi-GPU Level Zero P2P collectives (TP=1, 2, 4) on Intel Xe2 using cross-device events and a 4-slot P2P ring. +const std = @import("std"); +const ze = @import("ze"); + +pub const MAX_TP = 4; +pub const RING_SLOTS = 4; +pub const MAX_PIPE_STEPS = 256; // 64 layers * 2 collectives = 128 steps per forward; 256 leaves ample headroom +/// Threshold above which 2-shot P2P ReduceScatter + DMA AllGather replaces 1-shot P2P AllReduce. +pub const RS_THRESHOLD_BYTES: usize = 512 * 1024; + +pub const Kernels = struct { + ar2_f16: ze.H, + ar4_f16: ze.H, + rs2_f16: ze.H, + rs4_f16: ze.H, + ar2_bf16: ze.H, + ar4_bf16: ze.H, + ar2_f32: ze.H, + ar4_f32: ze.H, + rs4_f32: ze.H, +}; + +pub const TpComm = struct { + tp: usize, + max_bytes: usize, + send_buf: [MAX_TP][RING_SLOTS]*anyopaque = undefined, + rs_buf: [MAX_TP][RING_SLOTS]*anyopaque = undefined, + k: [MAX_TP]Kernels = undefined, + // [step * 2 * MAX_TP + kind * MAX_TP + rank], kind 0 = send ready, kind 1 = rs ready + events: [MAX_PIPE_STEPS * 2 * MAX_TP]ze.H = @splat(null), + step: usize = 0, + + pub fn init(gpus: []ze.Gpu, tp_bin: []const u8, max_bytes: usize) !TpComm { + if (gpus.len != 1 and gpus.len != 2 and gpus.len != 4) return error.InvalidTpDegree; + var c: TpComm = .{ + .tp = gpus.len, + .max_bytes = (max_bytes + 4095) / 4096 * 4096, + }; + if (c.tp == 1) return c; + + const rs_cap = (c.max_bytes / c.tp + 4095) / 4096 * 4096; + for (gpus, 0..) |*g, r| { + for (0..RING_SLOTS) |s| { + c.send_buf[r][s] = try g.deviceAlloc(c.max_bytes); + c.rs_buf[r][s] = try g.deviceAlloc(rs_cap); + } + const m = try g.module(tp_bin); + c.k[r] = .{ + .ar2_f16 = try loadK(g, m, "tp2_allreduce_f16"), + .ar4_f16 = try loadK(g, m, "tp4_allreduce_f16"), + .rs2_f16 = try loadK(g, m, "tp2_rs_f16"), + .rs4_f16 = try loadK(g, m, "tp4_rs_f16"), + .ar2_bf16 = try loadK(g, m, "tp2_allreduce_bf16"), + .ar4_bf16 = try loadK(g, m, "tp4_allreduce_bf16"), + .ar2_f32 = try loadK(g, m, "tp2_allreduce_f32"), + .ar4_f32 = try loadK(g, m, "tp4_allreduce_f32"), + .rs4_f32 = try loadK(g, m, "tp4_rs_f32"), + }; + } + // Make all ring buffers P2P-resident on every peer device in the shared context. + for (gpus) |*g_dst| { + for (0..c.tp) |r_src| { + for (0..RING_SLOTS) |s| { + try g_dst.makeResident(c.send_buf[r_src][s], c.max_bytes); + try g_dst.makeResident(c.rs_buf[r_src][s], rs_cap); + } + } + } + try ze.Gpu.sharedEvents(gpus, c.events[0 .. MAX_PIPE_STEPS * 2 * c.tp]); + return c; + } + + fn loadK(g: *ze.Gpu, m: ze.H, name: [*:0]const u8) !ze.H { + const k = try g.kernel(m, name); + try ze.check(g.api.zeKernelSetGroupSize(k, 256, 1, 1)); + try g.indirect(k); + return k; + } + + /// Rank `r`'s current P2P send buffer so the preceding GEMM can write directly into it without an extra copy. + pub fn currentSendBuf(c: *const TpComm, r: usize) *anyopaque { + return c.send_buf[r][c.step % RING_SLOTS]; + } + + fn readyEv(c: *TpComm, s: usize, r: usize) ze.H { + return c.events[(s * 2 + 0) * c.tp + r]; + } + + fn rsEv(c: *TpComm, s: usize, r: usize) ze.H { + return c.events[(s * 2 + 1) * c.tp + r]; + } + + /// Synchronizes all `gpus` command lists and resets all consumed pipeline events on the host. + pub fn syncAll(c: *TpComm, gpus: []ze.Gpu, lists: []const ze.H) !void { + for (gpus, lists) |*g, l| { + try ze.check(g.api.zeCommandListHostSynchronize(l, std.math.maxInt(u64))); + } + if (c.tp > 1 and c.step > 0) { + const total_evs = c.step * 2 * c.tp; + for (c.events[0..total_evs]) |ev| { + try ze.check(gpus[0].api.zeEventHostReset(ev)); + } + c.step = 0; + } + } + + /// Queues an async cross-GPU FP16 AllReduce from `src_opt` (or `currentSendBuf(r)` if null) into `dst[r]`. + pub fn allReduceF16(c: *TpComm, gpus: []ze.Gpu, lists: []const ze.H, src_opt: ?[]const *anyopaque, dst: []const *anyopaque, count_f16: usize) !void { + if (c.tp == 1) { + if (src_opt) |src| if (src[0] != dst[0]) { + try ze.check(gpus[0].api.zeCommandListAppendMemoryCopy(lists[0], dst[0], src[0], count_f16 * 2, null, 0, null)); + }; + return; + } + if (c.step >= MAX_PIPE_STEPS) try c.syncAll(gpus, lists); + const bytes = count_f16 * 2; + if (bytes > c.max_bytes or count_f16 % 4 != 0) return error.InvalidAllReduceSize; + + const s = c.step; + const slot = s % RING_SLOTS; + c.step += 1; + + var waits: [MAX_TP]ze.H = undefined; + for (0..c.tp) |r| { + const sb = c.send_buf[r][slot]; + if (src_opt) |src| if (src[r] != sb) { + try ze.check(gpus[r].api.zeCommandListAppendMemoryCopy(lists[r], sb, src[r], bytes, null, 0, null)); + }; + const ev = c.readyEv(s, r); + try ze.check(gpus[r].api.zeCommandListAppendSignalEvent(lists[r], ev)); + waits[r] = ev; + } + + const n4: u32 = @intCast(count_f16 / 4); + const use_rs = bytes > RS_THRESHOLD_BYTES and (n4 % @as(u32, @intCast(c.tp)) == 0); + + if (!use_rs) { + const groups: ze.GroupCount = .{ .x = (n4 + 255) / 256 }; + for (0..c.tp) |r| { + const g = &gpus[r]; + if (c.tp == 2) { + const k = c.k[r].ar2_f16; + try g.arg(k, 0, c.send_buf[0][slot]); + try g.arg(k, 1, c.send_buf[1][slot]); + try g.arg(k, 2, dst[r]); + try g.arg(k, 3, @as(i32, @intCast(n4))); + try ze.check(g.api.zeCommandListAppendLaunchKernel(lists[r], k, &groups, null, 2, &waits)); + } else { + const k = c.k[r].ar4_f16; + try g.arg(k, 0, c.send_buf[0][slot]); + try g.arg(k, 1, c.send_buf[1][slot]); + try g.arg(k, 2, c.send_buf[2][slot]); + try g.arg(k, 3, c.send_buf[3][slot]); + try g.arg(k, 4, dst[r]); + try g.arg(k, 5, @as(i32, @intCast(n4))); + try ze.check(g.api.zeCommandListAppendLaunchKernel(lists[r], k, &groups, null, 4, &waits)); + } + } + } else { + const slice_n4: u32 = n4 / @as(u32, @intCast(c.tp)); + const slice_bytes: usize = @as(usize, slice_n4) * 8; + const groups: ze.GroupCount = .{ .x = (slice_n4 + 255) / 256 }; + var rs_waits: [MAX_TP]ze.H = undefined; + for (0..c.tp) |r| { + const g = &gpus[r]; + const off4: i32 = @intCast(@as(u32, @intCast(r)) * slice_n4); + const rev = c.rsEv(s, r); + rs_waits[r] = rev; + if (c.tp == 2) { + const k = c.k[r].rs2_f16; + try g.arg(k, 0, c.send_buf[0][slot]); + try g.arg(k, 1, c.send_buf[1][slot]); + try g.arg(k, 2, c.rs_buf[r][slot]); + try g.arg(k, 3, off4); + try g.arg(k, 4, @as(i32, @intCast(slice_n4))); + try ze.check(g.api.zeCommandListAppendLaunchKernel(lists[r], k, &groups, rev, 2, &waits)); + } else { + const k = c.k[r].rs4_f16; + try g.arg(k, 0, c.send_buf[0][slot]); + try g.arg(k, 1, c.send_buf[1][slot]); + try g.arg(k, 2, c.send_buf[2][slot]); + try g.arg(k, 3, c.send_buf[3][slot]); + try g.arg(k, 4, c.rs_buf[r][slot]); + try g.arg(k, 5, off4); + try g.arg(k, 6, @as(i32, @intCast(slice_n4))); + try ze.check(g.api.zeCommandListAppendLaunchKernel(lists[r], k, &groups, rev, 4, &waits)); + } + } + for (0..c.tp) |r| { + try ze.check(gpus[r].api.zeCommandListAppendWaitOnEvents(lists[r], @intCast(c.tp), &rs_waits)); + for (0..c.tp) |src_r| { + const dst_slice: *anyopaque = @ptrFromInt(@intFromPtr(dst[r]) + src_r * slice_bytes); + try ze.check(gpus[r].api.zeCommandListAppendMemoryCopy(lists[r], dst_slice, c.rs_buf[src_r][slot], slice_bytes, null, 0, null)); + } + } + } + } + + /// Queues an asynchronous cross-GPU deterministic FP32 AllReduce (used by FlashNext / FP32 partials). + pub fn allReduceF32(c: *TpComm, gpus: []ze.Gpu, lists: []const ze.H, src_opt: ?[]const *anyopaque, dst: []const *anyopaque, count_f32: usize) !void { + if (c.tp == 1) { + if (src_opt) |src| if (src[0] != dst[0]) { + try ze.check(gpus[0].api.zeCommandListAppendMemoryCopy(lists[0], dst[0], src[0], count_f32 * 4, null, 0, null)); + }; + return; + } + if (c.step >= MAX_PIPE_STEPS) try c.syncAll(gpus, lists); + const bytes = count_f32 * 4; + if (bytes > c.max_bytes or count_f32 % 4 != 0) return error.InvalidAllReduceSize; + + const s = c.step; + const slot = s % RING_SLOTS; + c.step += 1; + + var waits: [MAX_TP]ze.H = undefined; + for (0..c.tp) |r| { + const sb = c.send_buf[r][slot]; + if (src_opt) |src| if (src[r] != sb) { + try ze.check(gpus[r].api.zeCommandListAppendMemoryCopy(lists[r], sb, src[r], bytes, null, 0, null)); + }; + const ev = c.readyEv(s, r); + try ze.check(gpus[r].api.zeCommandListAppendSignalEvent(lists[r], ev)); + waits[r] = ev; + } + + const n4: u32 = @intCast(count_f32 / 4); + const use_rs = c.tp == 4 and bytes > RS_THRESHOLD_BYTES and (n4 % 4 == 0); + if (!use_rs) { + const groups: ze.GroupCount = .{ .x = (n4 + 255) / 256 }; + for (0..c.tp) |r| { + const g = &gpus[r]; + if (c.tp == 2) { + const k = c.k[r].ar2_f32; + try g.arg(k, 0, c.send_buf[0][slot]); + try g.arg(k, 1, c.send_buf[1][slot]); + try g.arg(k, 2, dst[r]); + try g.arg(k, 3, @as(i32, @intCast(n4))); + try ze.check(g.api.zeCommandListAppendLaunchKernel(lists[r], k, &groups, null, 2, &waits)); + } else { + const k = c.k[r].ar4_f32; + try g.arg(k, 0, c.send_buf[0][slot]); + try g.arg(k, 1, c.send_buf[1][slot]); + try g.arg(k, 2, c.send_buf[2][slot]); + try g.arg(k, 3, c.send_buf[3][slot]); + try g.arg(k, 4, dst[r]); + try g.arg(k, 5, @as(i32, @intCast(n4))); + try ze.check(g.api.zeCommandListAppendLaunchKernel(lists[r], k, &groups, null, 4, &waits)); + } + } + } else { + const slice_n4: u32 = n4 / 4; + const slice_bytes: usize = @as(usize, slice_n4) * 16; + const groups: ze.GroupCount = .{ .x = (slice_n4 + 255) / 256 }; + var rs_waits: [MAX_TP]ze.H = undefined; + for (0..4) |r| { + const g = &gpus[r]; + const off4: i32 = @intCast(@as(u32, @intCast(r)) * slice_n4); + const rev = c.rsEv(s, r); + rs_waits[r] = rev; + const k = c.k[r].rs4_f32; + try g.arg(k, 0, c.send_buf[0][slot]); + try g.arg(k, 1, c.send_buf[1][slot]); + try g.arg(k, 2, c.send_buf[2][slot]); + try g.arg(k, 3, c.send_buf[3][slot]); + try g.arg(k, 4, c.rs_buf[r][slot]); + try g.arg(k, 5, off4); + try g.arg(k, 6, @as(i32, @intCast(slice_n4))); + try ze.check(g.api.zeCommandListAppendLaunchKernel(lists[r], k, &groups, rev, 4, &waits)); + } + for (0..4) |r| { + try ze.check(gpus[r].api.zeCommandListAppendWaitOnEvents(lists[r], 4, &rs_waits)); + for (0..4) |src_r| { + const dst_slice: *anyopaque = @ptrFromInt(@intFromPtr(dst[r]) + src_r * slice_bytes); + try ze.check(gpus[r].api.zeCommandListAppendMemoryCopy(lists[r], dst_slice, c.rs_buf[src_r][slot], slice_bytes, null, 0, null)); + } + } + } + } +}; diff --git a/zig/src/xpu/tp_bench.zig b/zig/src/xpu/tp_bench.zig new file mode 100644 index 00000000000..2b92d04153d --- /dev/null +++ b/zig/src/xpu/tp_bench.zig @@ -0,0 +1,140 @@ +//! Phase 1 benchmark & bit-exactness verification for Level Zero P2P TP=2 and TP=4 collectives on Arc Pro B70. +const std = @import("std"); +const ze = @import("ze"); +const tp_mod = @import("tp.zig"); +const kb = @import("xpu_tp_kernels"); + +fn nowNs() u64 { + var ts: std.c.timespec = undefined; + _ = std.c.clock_gettime(std.c.CLOCK.MONOTONIC, &ts); + return @as(u64, @intCast(ts.sec)) * 1_000_000_000 + @as(u64, @intCast(ts.nsec)); +} + +fn f32ToF16Rte(v: f32) u16 { + const f16_val: f16 = @floatCast(v); + return @bitCast(f16_val); +} + +fn runSuite(tp_deg: usize) !void { + const alloc = std.heap.c_allocator; + var gpus: [4]ze.Gpu = undefined; + ze.Gpu.openPeers(0xe223, gpus[0..tp_deg]) catch |err| { + std.debug.print("skipped TP={d}: {s}\n", .{ tp_deg, @errorName(err) }); + return; + }; + defer ze.Gpu.closePeers(gpus[0..tp_deg]); + + var lists: [4]ze.H = undefined; + for (0..tp_deg) |r| lists[r] = try gpus[r].immediate(0, 0); + + const max_elems: usize = 4096 * 5120; // up to 4096 rows * 5120 fp16 = 40 MB + const max_bytes: usize = max_elems * 2; + var comm = try tp_mod.TpComm.init(gpus[0..tp_deg], &kb.tp, max_bytes); + + var dsts: [4]*anyopaque = undefined; + for (0..tp_deg) |r| dsts[r] = try gpus[r].deviceAlloc(max_bytes); + + // 1. Strict rank-ordered bit-exactness check (with non-associative float magnitudes!) + { + const test_n: usize = 1024 * 5120; // > 512 KB so we also exercise 2-shot ReduceScatter + AllGather! + var host_in: [4][]u16 = undefined; + for (0..tp_deg) |r| { + host_in[r] = try alloc.alloc(u16, test_n); + var prng = std.Random.DefaultPrng.init(0x12345678 + @as(u64, r) * 99991); + const rnd = prng.random(); + for (host_in[r], 0..) |*x, idx| { + // Inject cancellation/non-associative patterns every 4th element + const f: f16 = switch ((idx + r) % 4) { + 0 => 1024.0, + 1 => -1024.0, + 2 => @floatCast((rnd.float(f32) - 0.5) * 2.0), + else => @floatCast((rnd.float(f32) - 0.5) * 0.01), + }; + x.* = @bitCast(f); + } + } + defer for (0..tp_deg) |r| alloc.free(host_in[r]); + + const ref = try alloc.alloc(u16, test_n); + defer alloc.free(ref); + for (0..test_n) |i| { + var s: f32 = 0.0; + for (0..tp_deg) |r| { + const h: f16 = @bitCast(host_in[r][i]); + s += @as(f32, h); + } + ref[i] = f32ToF16Rte(s); + } + + // Check both small (1-shot, 16384 elems = 32 KB) and large (2-shot RS+AG, test_n = 10 MB) + for ([_]usize{ 16384, test_n }) |cnt| { + for (0..tp_deg) |r| { + const sb = comm.currentSendBuf(r); + try ze.check(gpus[r].api.zeCommandListAppendMemoryCopy(lists[r], sb, host_in[r].ptr, cnt * 2, null, 0, null)); + } + try comm.allReduceF16(gpus[0..tp_deg], lists[0..tp_deg], null, dsts[0..tp_deg], cnt); + try comm.syncAll(gpus[0..tp_deg], lists[0..tp_deg]); + + const got = try alloc.alloc(u16, cnt); + defer alloc.free(got); + for (0..tp_deg) |r| { + try ze.check(gpus[r].api.zeCommandListAppendMemoryCopy(lists[r], got.ptr, dsts[r], cnt * 2, null, 0, null)); + try ze.check(gpus[r].api.zeCommandListHostSynchronize(lists[r], std.math.maxInt(u64))); + for (0..cnt) |i| { + if (got[i] != ref[i]) { + std.debug.print("MISMATCH TP={d} rank={d} cnt={d} idx={d}: got=0x{x} ref=0x{x}\n", .{ tp_deg, r, cnt, i, got[i], ref[i] }); + return error.BitMismatch; + } + } + } + } + std.debug.print("=== TP={d}: bit-exactness PASSED (1-shot 32 KB & 2-shot 10 MB, all {d} ranks == rank-ordered FP32 ref) ===\n", .{ tp_deg, tp_deg }); + } + + // 2. Latency & Bandwidth benchmarks (128 pipelined AllReduces per forward pass = 64 layers * 2) + const cases = [_]struct { label: []const u8, elems: usize, steps: usize, reps: usize }{ + .{ .label = "decode 1 row (10 KB)", .elems = 1 * 5120, .steps = 128, .reps = 20 }, + .{ .label = "verify 8 rows (80 KB)", .elems = 8 * 5120, .steps = 128, .reps = 20 }, + .{ .label = "tree 16 rows (160 KB)", .elems = 16 * 5120, .steps = 128, .reps = 20 }, + .{ .label = "prefill 512r (5.0 MB)", .elems = 512 * 5120, .steps = 16, .reps = 10 }, + .{ .label = "prefill 1024r (10 MB)", .elems = 1024 * 5120, .steps = 16, .reps = 10 }, + .{ .label = "prefill 4096r (40 MB)", .elems = 4096 * 5120, .steps = 8, .reps = 5 }, + }; + + for (cases) |tc| { + // Warmup + for (0..2) |_| { + for (0..tc.steps) |_| { + try comm.allReduceF16(gpus[0..tp_deg], lists[0..tp_deg], null, dsts[0..tp_deg], tc.elems); + } + try comm.syncAll(gpus[0..tp_deg], lists[0..tp_deg]); + } + var best_ns: u64 = std.math.maxInt(u64); + var total_ns: u64 = 0; + for (0..tc.reps) |_| { + const t0 = nowNs(); + for (0..tc.steps) |_| { + try comm.allReduceF16(gpus[0..tp_deg], lists[0..tp_deg], null, dsts[0..tp_deg], tc.elems); + } + try comm.syncAll(gpus[0..tp_deg], lists[0..tp_deg]); + const dt = nowNs() - t0; + if (dt < best_ns) best_ns = dt; + total_ns += dt; + } + const mean_step_us = @as(f64, @floatFromInt(total_ns)) / @as(f64, @floatFromInt(tc.reps * tc.steps)) / 1e3; + const best_step_us = @as(f64, @floatFromInt(best_ns)) / @as(f64, @floatFromInt(tc.steps)) / 1e3; + const bytes = @as(f64, @floatFromInt(tc.elems * 2)); + // Algbw = payload_bytes / time_s; Busbw = algbw * 2 * (tp - 1) / tp + const alg_gbs = bytes / (best_step_us * 1e-6) / 1e9; + const bus_gbs = alg_gbs * 2.0 * @as(f64, @floatFromInt(tp_deg - 1)) / @as(f64, @floatFromInt(tp_deg)); + const per_layer64_ms = best_step_us * 128.0 / 1e3; + std.debug.print(" {s}: best={d:6.2} us/op (mean={d:6.2} us) | 128-op/tok={d:5.2} ms | algbw={d:5.2} GB/s | busbw={d:5.2} GB/s\n", .{ + tc.label, best_step_us, mean_step_us, per_layer64_ms, alg_gbs, bus_gbs, + }); + } +} + +pub fn main() !void { + try runSuite(2); + try runSuite(4); +} diff --git a/zig/src/xpu/ze.zig b/zig/src/xpu/ze.zig index 20698c218f2..c1cb3bbb2dd 100644 --- a/zig/src/xpu/ze.zig +++ b/zig/src/xpu/ze.zig @@ -21,6 +21,11 @@ pub const Api = struct { zeCommandListAppendLaunchKernel: *const fn (H, H, *const GroupCount, H, u32, ?[*]H) callconv(.c) u32, zeCommandListAppendMemoryCopy: *const fn (H, ?*anyopaque, ?*const anyopaque, usize, H, u32, ?[*]H) callconv(.c) u32, zeCommandListAppendBarrier: *const fn (H, H, u32, ?[*]H) callconv(.c) u32, + zeCommandListAppendSignalEvent: *const fn (H, H) callconv(.c) u32, + zeCommandListAppendWaitOnEvents: *const fn (H, u32, [*]H) callconv(.c) u32, + zeCommandListAppendEventReset: *const fn (H, H) callconv(.c) u32, + zeDeviceCanAccessPeer: *const fn (H, H, *u8) callconv(.c) u32, + zeContextMakeMemoryResident: *const fn (H, H, ?*anyopaque, usize) callconv(.c) u32, zeMemAllocDevice: *const fn (H, *const DeviceAllocDesc, usize, usize, H, *?*anyopaque) callconv(.c) u32, zeMemAllocHost: *const fn (H, *const HostAllocDesc, usize, usize, *?*anyopaque) callconv(.c) u32, zeMemFree: *const fn (H, ?*anyopaque) callconv(.c) u32, @@ -204,6 +209,7 @@ pub const Gpu = struct { device: H, context: H, props: DeviceProperties, + shared_ctx: bool = false, // true on non-owning peers opened by openPeers; closePeers releases the group owned: Owned = .{}, // what close() gives back /// Every allocation, kernel, module, list and event made through this Gpu, destroyed by close(). @@ -235,11 +241,34 @@ pub const Gpu = struct { /// Waits for every list this Gpu made, then destroys what it made and the context (startup errors included). pub fn close(g: *Gpu) void { + if (g.shared_ctx) { + _ = releasePeer(&g.api, g.context, &g.owned, false); + return; + } if (release(&g.api, g.context, &g.owned)) g.lib.close(); } + /// Drains all peer command lists first, then frees resources across the group and closes the shared context. + pub fn closePeers(gpus: []Gpu) void { + if (gpus.len == 0) return; + for (gpus) |*g| for (g.owned.lists.items) |l| if (g.api.zeCommandListHostSynchronize(l, std.math.maxInt(u64)) != 0) { + std.log.warn("XPU: a command list did not drain at closePeers; memory and context stay until the process ends", .{}); + return; + }; + var idx = gpus.len; + while (idx > 1) { + idx -= 1; + _ = releasePeer(&gpus[idx].api, gpus[idx].context, &gpus[idx].owned, false); + } + if (releasePeer(&gpus[0].api, gpus[0].context, &gpus[0].owned, true)) gpus[0].lib.close(); + } + /// `close` before the loader: false, with nothing destroyed, when a list does not drain (it may still run). fn release(api: *const Api, context: H, o: *Owned) bool { + return releasePeer(api, context, o, true); + } + + fn releasePeer(api: *const Api, context: H, o: *Owned, destroy_ctx: bool) bool { for (o.lists.items) |l| if (api.zeCommandListHostSynchronize(l, std.math.maxInt(u64)) != 0) { std.log.warn("XPU: a command list did not drain at close; its memory and context stay until the process ends", .{}); return false; @@ -253,11 +282,19 @@ pub const Gpu = struct { while (it.next()) |p| _ = api.zeMemFree(context, @ptrFromInt(p.*)); o.mems.deinit(own_alloc); inline for (.{ &o.kernels, &o.modules, &o.lists, &o.events, &o.pools }) |l| l.deinit(own_alloc); - _ = api.zeContextDestroy(context); + if (destroy_ctx) _ = api.zeContextDestroy(context); return true; } pub fn open(device_id: u32) Error!Gpu { + var out: [1]Gpu = undefined; + try openPeers(device_id, &out); + return out[0]; + } + + /// Opens `out.len` peer-accessible devices of `device_id` on one driver and one shared Level Zero context. + pub fn openPeers(device_id: u32, out: []Gpu) Error!void { + if (out.len == 0 or out.len > 8) return error.NoDevice; var lib = std.DynLib.open("libze_loader.so.1") catch return error.LoaderUnavailable; errdefer lib.close(); const api = try resolve(Api, &lib); @@ -271,22 +308,66 @@ pub const Gpu = struct { if (drv == null) continue; var nv: u32 = 0; // the count first, as context.enumerate (a padded list holds nulls) try check(api.zeDeviceGet(drv, &nv, null)); - var devs: [8]H = @splat(null); + var devs: [16]H = @splat(null); nv = @min(nv, devs.len); try check(api.zeDeviceGet(drv, &nv, &devs)); + var picked: [8]H = @splat(null); + var props: [8]DeviceProperties = @splat(.{}); + var found: usize = 0; for (devs[0..nv]) |dev| { if (dev == null) continue; var p: DeviceProperties = .{}; try check(api.zeDeviceGetProperties(dev, &p)); if (p.deviceId != device_id) continue; - var ctx: H = null; - try check(api.zeContextCreate(drv, &.{}, &ctx)); - return .{ .lib = lib, .api = api, .driver = drv, .device = dev, .context = ctx, .props = p }; + picked[found] = dev; + props[found] = p; + found += 1; + if (found == out.len) break; + } + if (found < out.len) continue; + if (out.len > 1) { + for (0..out.len) |i| for (0..out.len) |j| if (i != j) { + var can: u8 = 0; + try check(api.zeDeviceCanAccessPeer(picked[i], picked[j], &can)); + if (can == 0) return error.ZeFailed; + }; + } + var ctx: H = null; + try check(api.zeContextCreate(drv, &.{}, &ctx)); + for (out, 0..) |*g, i| { + g.* = .{ + .lib = if (i == 0) lib else undefined, + .api = api, + .driver = drv, + .device = picked[i], + .context = ctx, + .props = props[i], + .shared_ctx = i > 0, + }; } + return; } return error.NoDevice; } + pub fn makeResident(g: *Gpu, ptr: *anyopaque, size: usize) Error!void { + try check(g.api.zeContextMakeMemoryResident(g.context, g.device, ptr, size)); + } + + /// Allocates a pool of `count` device-scoped events visible across `gpus` (owned by `gpus[0]`). + pub fn sharedEvents(gpus: []Gpu, out_events: []H) Error!void { + var devs: [8]H = @splat(null); + for (gpus, 0..) |*g, i| devs[i] = g.device; + var pool: H = null; + try check(gpus[0].api.zeEventPoolCreate(gpus[0].context, &.{ .flags = pool_host_visible, .count = @intCast(out_events.len) }, @intCast(gpus.len), &devs, &pool)); + _ = try keep(&gpus[0].owned.pools, pool, gpus[0].api.zeEventPoolDestroy); + for (out_events, 0..) |*e, i| { + // signal=1 (DEVICE), wait=1 (DEVICE): cross-GPU synchronization without host round-trips + try check(gpus[0].api.zeEventCreate(pool, &.{ .index = @intCast(i), .signal = 1, .wait = 1 }, e)); + _ = try keep(&gpus[0].owned.events, e.*, gpus[0].api.zeEventDestroy); + } + } + /// On-board bytes free and in all by Sysman (by UUID); without Sysman (WSL2) both are the core total, less nothing. pub fn memory(g: *Gpu) Error!struct { free: u64, size: u64 } { if (!sysmanUsable()) { diff --git a/zig/tests/contract/metal_affine.zig b/zig/tests/contract/metal_affine.zig index b2dbe966ef3..e2a32a5d90e 100644 --- a/zig/tests/contract/metal_affine.zig +++ b/zig/tests/contract/metal_affine.zig @@ -14,10 +14,10 @@ const sqb = row.simd_bits; const mm = tf.affine_mm; const lane = tf.lane_projection; -pub const Kind = enum { row, affine_mm, simd, simd_half, simd_sums, simd_bits, lane, lane_reg }; +pub const Kind = enum { row, affine_mm, simd, simd_half, simd_sums, simd_bits, lane, lane_reg, qk }; /// One variant: kernel, code width and group, output, lane K slices; control: simd_half's or simd_sums' planted fault. -pub const Variant = struct { kind: Kind, bits: u8 = 4, group: usize = 64, f32_out: bool = false, sk: usize = 1, coop: bool = false, control: bool = false, served: ?[]const c.Shape = null }; +pub const Variant = struct { kind: Kind, bits: u8 = 4, group: usize = 64, f32_out: bool = false, sk: usize = 1, coop: bool = false, glm_m3_fast: bool = false, control: bool = false, served: ?[]const c.Shape = null }; pub const Reg = struct { v: Variant, name: []const u8 }; /// The half-operand tiles, the chunk pairs on the prepass's sums, and their planted controls, beside simd_qmm's entry. pub const half = [_]Reg{ @@ -58,12 +58,13 @@ pub fn spec(v: Variant, name: []const u8) c.Spec { const step: usize = @max(16, v.group); return switch (v.kind) { .row => .{ .name = name, .accum = .f32, .depth = rowDepth, .out = out, .tiles = .{ .{ .size = 2 }, .{ .size = 8, .step = 8, .min = 8 }, .{ .size = 512, .step = step, .min = step } }, .served = &.{ .{ .rows = 16, .n = 2688, .k = 4096 }, .{ .rows = 3, .n = 4608, .k = 2688 } } }, - .affine_mm => .{ .name = name, .accum = .f32, .depth = groupDepth64, .out = out, .known = if (v.bits == 4) offset_inf else null, .tiles = .{ .{ .size = 64 }, .{ .size = 64, .step = 64, .min = 64 }, .{ .size = 128, .step = 64, .min = 64 } }, .served = if (v.bits == 8 and v.group == 64) &router_rows else &.{ .{ .rows = 128, .n = 2048, .k = 4096 }, .{ .rows = 65, .n = 1024, .k = 1024 } } }, + .affine_mm => .{ .name = name, .accum = .f32, .depth = groupDepth64, .out = out, .known = if (v.bits == 4) offset_inf else null, .tiles = .{ .{ .size = 64 }, .{ .size = 64, .step = 64, .min = 64 }, .{ .size = 128, .step = @max(64, v.group), .min = @max(64, v.group) } }, .served = if (v.bits == 8 and v.group == 64) &router_rows else &.{ .{ .rows = 128, .n = 2048, .k = 4096 }, .{ .rows = 65, .n = 1024, .k = 1024 } } }, .simd, .simd_bits => .{ .name = name, .accum = .f32, .depth = simdDepth, .out = out, .tiles = .{ .{ .size = 8 }, .{ .size = 32, .step = 8, .min = 8 }, .{ .size = 512, .step = 64, .min = 64 } }, .served = &.{ .{ .rows = 16, .n = 2688, .k = 4096 }, .{ .rows = 9, .n = 6400, .k = 256 } } }, // the 27B's norm-fed widths past 6,144 (8 chunks), as the prompt chunk's tiles and its 9-row tail take them .simd_half => .{ .name = name, .accum = .f32, .depth = simdDepth, .out = out, .replaces = "simd_qmm's fp32 tiles", .tiles = .{ .{ .size = 8 }, .{ .size = 32, .step = 8, .min = 8 }, .{ .size = 512, .step = 64, .min = 64 } }, .served = &.{ .{ .rows = 32, .n = 6240, .k = 512 }, .{ .rows = 9, .n = 12288, .k = 256 } } }, // the 27B's down and o (16 chunks, four column tiles), as a prompt chunk and an odd tail take them .simd_sums => .{ .name = name, .accum = .f32, .depth = simdDepth, .out = out, .replaces = "simd_qmm's fp32 tiles", .tiles = .{ .{ .size = 16, .min = 9 }, .{ .size = 128, .step = 32, .min = 96 }, .{ .size = 512, .step = 64, .min = 64 } }, .served = &.{ .{ .rows = 64, .n = 5120, .k = 1024 }, .{ .rows = 9, .n = 512, .k = 512 } } }, + .qk => .{ .name = name, .accum = .f32, .depth = laneDepth, .out = .bf16, .replaces = "tf_lane_reg on the same K split", .tiles = .{ .{ .size = 48 }, .{ .size = 32, .step = 32, .min = 32 }, .{ .size = 256, .step = 64, .min = 64 } }, .served = v.served orelse &.{} }, .lane, .lane_reg => .{ .name = name, .accum = .f32, .depth = laneDepth, .out = out, .replaces = if (v.kind == .lane_reg) "the cooperative lane kernel" else null, .tiles = .{ .{ .size = 16 }, .{ .size = 32, .step = 16, .min = 32 }, .{ .size = 4 * v.group, .step = v.group, .min = v.group } }, .served = v.served orelse &.{ .{ .rows = 16, .n = 2048, .k = 2048 }, .{ .rows = 5, .n = 512, .k = 896 } } }, }; } @@ -87,6 +88,7 @@ pub const Proj = struct { lane_p: ?lane.Projection = null, coop_p: ?lane.Projection = null, order: ?lane.RegOrder = null, + qk_p: ?lane.qk.Pipelines = null, f: ?Affine = null, x: rig_.Ref = undefined, w: rig_.Ref = undefined, @@ -105,7 +107,7 @@ pub const Proj = struct { .simd, .simd_half, .simd_sums => p.sq_p = try sq.Pipelines.load(device), .simd_bits => p.sqb_p = try sqb.Pipelines.load(device), .affine_mm => { - const src = try mm.source(device, a, .{ .bits = v.bits, .group = @intCast(v.group), .out_f32 = v.f32_out }); + const src = try mm.source(device, a, .{ .bits = v.bits, .group = @intCast(v.group), .out_f32 = v.f32_out, .glm_m3_fast = v.glm_m3_fast }); defer a.free(src); const lib = try mtl.Library.fromSource(device, src, mtl.CompileOptions.mlx()); defer lib.deinit(); @@ -115,6 +117,10 @@ pub const Proj = struct { }, .lane => {}, .lane_reg => p.order = try lane.RegOrder.init(device), + .qk => { + p.order = try lane.RegOrder.init(device); + p.qk_p = lane.qk.Pipelines.init(a, device); + }, } return p; } @@ -126,6 +132,7 @@ pub const Proj = struct { if (p.sqb_p) |*x| x.deinit(); if (p.mm_p) |pipes| for (pipes) |x| x.deinit(); if (p.order) |o| o.deinit(); + if (p.qk_p) |*q| q.deinit(); p.rig.deinit(); } @@ -146,8 +153,8 @@ pub const Proj = struct { const vt = g.hooks(Proj); fn layout(p: *const Proj, shape: c.Shape, coop: bool) lane.Layout { - const reg = p.v.kind == .lane_reg and !coop; - return .{ .n = shape.n, .k = shape.k, .format = .{ .bits = p.v.bits, .group = p.v.group }, .sk = p.v.sk, .output = if (p.v.f32_out) .f32 else .bf16, .precompute_sums = p.v.kind == .lane_reg or p.v.coop, .cooperative = coop or (p.v.coop and !reg), .reg = reg }; + const reg = (p.v.kind == .lane_reg or p.v.kind == .qk) and !coop; + return .{ .n = shape.n, .k = shape.k, .format = .{ .bits = p.v.bits, .group = p.v.group }, .sk = p.v.sk, .output = if (p.v.f32_out) .f32 else .bf16, .precompute_sums = p.v.kind == .lane_reg or p.v.kind == .qk or p.v.coop, .cooperative = coop or (p.v.coop and !reg), .reg = reg }; } /// Whether the kernel takes this shape, as the engine's own validation says. @@ -159,6 +166,7 @@ pub const Proj = struct { .simd_half => shape.n % 8 == 0 and shape.k % 64 == 0 and sq.chunks(shape.n, 0) == sq.half_chunks, .simd_sums => shape.n % 8 == 0 and shape.k % 64 == 0 and (try sq.callSumsAt(&p.sq_p.?, shape.n, shape.k, shape.rows)) != null, .affine_mm => shape.n % 64 == 0 and shape.k % 64 == 0, + .qk => shape.rows <= 2048 and shape.n % 32 == 0 and shape.k % 64 == 0, .lane, .lane_reg => shape.rows <= 16 and if (p.layout(shape, false).validate()) |_| true else |_| false, }; } @@ -188,9 +196,14 @@ pub const Proj = struct { p.base = try p.rig.scratch(out_bytes); } }, - .lane, .lane_reg => { + .lane, .lane_reg, .qk => { const l = p.layout(shape, false); - p.lane_p = try lane.Projection.init(p.a, p.rig.device, l); + p.lane_p = try lane.Projection.init(p.a, p.rig.device, if (p.v.kind == .qk) blk: { + var wide = l; + wide.rows = @max(lane.reg_rows, (shape.rows + 15) / 16 * 16); + wide.row_blocks = true; + break :blk wide; + } else l); const pw = try p.a.alloc(u32, l.weightWords()); defer p.a.free(pw); const psb = try p.a.alloc(u16, l.metadataElements()); @@ -198,7 +211,11 @@ pub const Proj = struct { try lane.pack(l, words, f.scales, f.biases, pw, psb); p.w = try p.rig.input(std.mem.sliceAsBytes(pw)); p.s = try p.rig.input(std.mem.sliceAsBytes(psb)); - if (p.v.kind == .lane_reg) { + if (p.v.kind == .qk) { + p.tiled = try p.rig.input(std.mem.sliceAsBytes(pw)); + try p.order.?.run(&.{.{ .w = ref(p.tiled), .n = shape.n, .k = shape.k }}); + p.base = try p.rig.scratch(out_bytes); + } else if (p.v.kind == .lane_reg) { p.tiled = try p.rig.input(std.mem.sliceAsBytes(pw)); try p.order.?.run(&.{.{ .w = .{ .buf = p.w.buf, .off = p.w.off }, .n = shape.n, .k = shape.k }}); p.coop_p = try lane.Projection.init(p.a, p.rig.device, p.layout(shape, true)); @@ -256,7 +273,13 @@ pub const Proj = struct { const xs = .{ .buf = p.sums.buf, .off = p.sums.off }; const q = .{ .w = .{ .buf = p.w.buf, .off = p.w.off }, .s = .{ .buf = p.s.buf, .off = p.s.off }, .b = .{ .buf = p.b.buf, .off = p.b.off }, .n = @as(u32, @intCast(shape.n)), .k = @as(u32, @intCast(shape.k)) }; mm.rowSums(e, p.mm_p.?, @intCast(p.v.group), x, xs, @intCast(shape.rows), @intCast(shape.k)); - mm.dense(e, p.mm_p.?, x, xs, q, .{ .buf = p.out.buf, .off = p.out.off }, @intCast(shape.rows)); + const bm: u32 = if (p.v.glm_m3_fast and p.v.control) 128 else if (p.v.glm_m3_fast and !p.rig.device.tensorUnits()) 32 else 64; + mm.denseBm(e, p.mm_p.?, x, xs, q, .{ .buf = p.out.buf, .off = p.out.off }, @intCast(shape.rows), bm); + }, + .qk => { + const rows: u32 = @intCast(shape.rows); + const sums = try p.lane_p.?.encodeOwnSums(e, ref(p.x), rows); + try p.qk_p.?.encode(e, shape.n, shape.k, @intCast(p.v.sk), ref(p.x), ref(p.w), ref(p.s), sums, ref(p.out), if (p.v.control and rows > 1) rows - 1 else rows); }, .lane, .lane_reg => try p.lane_p.?.encode(e, ref(p.x), ref(p.w), ref(p.s), ref(p.out), @intCast(shape.rows)), } @@ -269,12 +292,14 @@ pub const Proj = struct { /// The replaced kernel's bytes on the same inputs: the cooperative lane kernel's, or simd_qmm's fp32 tiles'. pub fn replaced(p: *Proj) ![]const u8 { - if (p.v.kind != .lane_reg and p.v.kind != .simd_half and p.v.kind != .simd_sums) return error.NotAReplacement; + if (p.v.kind != .lane_reg and p.v.kind != .simd_half and p.v.kind != .simd_sums and p.v.kind != .qk) return error.NotAReplacement; const f = p.f.?; const len = f.outputs() * c.size(spec(p.v, p.name).out); @memset(p.rig.bytes(p.base, len), 0xff); const pass = p.rig.begin(); - if (p.v.kind == .simd_half or p.v.kind == .simd_sums) { + if (p.v.kind == .qk) { + try p.lane_p.?.encode(pass.e, ref(p.x), ref(p.tiled), ref(p.s), ref(p.base), @intCast(f.shape.rows)); + } else if (p.v.kind == .simd_half or p.v.kind == .simd_sums) { sq.encode(pass.e, try sq.call(&p.sq_p.?, f.shape.n, f.shape.k, f.shape.rows, false, false, 0), p.matrix(f.shape), p.x.buf, p.x.off, p.base.buf, p.base.off); } else try p.coop_p.?.encode(pass.e, ref(p.x), ref(p.tiled), ref(p.s), ref(p.base), @intCast(f.shape.rows)); try p.rig.finish(pass); diff --git a/zig/tests/contract/metal_affine_gather.zig b/zig/tests/contract/metal_affine_gather.zig index f977d501910..d3c52abe424 100644 --- a/zig/tests/contract/metal_affine_gather.zig +++ b/zig/tests/contract/metal_affine_gather.zig @@ -34,15 +34,18 @@ pub const Mutation = enum { }; /// One registered gather: the weights' bits (groups of 64), whether each output goes back to its row's own place. -pub const Variant = struct { bits: u8, scatter: bool, mutation: Mutation = .none }; +pub const Variant = struct { bits: u8, scatter: bool, glm_m3_fast: bool = false, mutation: Mutation = .none }; -/// The widths qwen27 admits for its routed experts on tensor units, each plain and scattering, and three controls. +/// The widths qwen27 admits for its routed experts on tensor units, each plain and scattering, and controls. pub const registered = [_]Variant{ .{ .bits = 4, .scatter = false }, .{ .bits = 4, .scatter = true }, .{ .bits = 8, .scatter = false }, .{ .bits = 8, .scatter = true }, + .{ .bits = 4, .scatter = false, .glm_m3_fast = true }, + .{ .bits = 8, .scatter = true, .glm_m3_fast = true }, .{ .bits = 4, .scatter = false, .mutation = .tail }, + .{ .bits = 4, .scatter = false, .glm_m3_fast = true, .mutation = .tail }, .{ .bits = 8, .scatter = false, .mutation = .expert }, .{ .bits = 4, .scatter = true, .mutation = .scatter }, }; @@ -50,10 +53,10 @@ pub const registered = [_]Variant{ pub fn name(v: Variant) []const u8 { return switch (v.mutation) { .none => switch (v.bits) { - 4 => if (v.scatter) "metal affine_mm q4 g64 gather scatter" else "metal affine_mm q4 g64 gather", - else => if (v.scatter) "metal affine_mm q8 g64 gather scatter" else "metal affine_mm q8 g64 gather", + 4 => if (v.glm_m3_fast) (if (v.scatter) "metal affine_mm glm m3 q4 g64 gather scatter" else "metal affine_mm glm m3 q4 g64 gather") else if (v.scatter) "metal affine_mm q4 g64 gather scatter" else "metal affine_mm q4 g64 gather", + else => if (v.glm_m3_fast) (if (v.scatter) "metal affine_mm glm m3 q8 g64 gather scatter" else "metal affine_mm glm m3 q8 g64 gather") else if (v.scatter) "metal affine_mm q8 g64 gather scatter" else "metal affine_mm q8 g64 gather", }, - .tail => "control: metal affine_mm gather q4 g64, each expert's last row dropped", + .tail => if (v.glm_m3_fast) "control: metal affine_mm glm m3 gather q4 g64, each expert's last row dropped" else "control: metal affine_mm gather q4 g64, each expert's last row dropped", .expert => "control: metal affine_mm gather q8 g64, a tile reads its neighbour expert's weights", .scatter => "control: metal affine_mm gather scatter q4 g64, outputs left in sorted order", }; @@ -93,7 +96,7 @@ pub const Gather = struct { out: rig_.Ref = undefined, pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, v: Variant) !Gather { - const plain = try mm.source(device, a, .{ .bits = v.bits, .group = 64 }); + const plain = try mm.source(device, a, .{ .bits = v.bits, .group = 64, .glm_m3_fast = v.glm_m3_fast }); defer a.free(plain); const src = if (v.mutation == .none) try a.dupe(u8, plain) else blk: { const e = v.mutation.edit(); diff --git a/zig/tests/contract/metal_delta_slots.zig b/zig/tests/contract/metal_delta_slots.zig index 150fe13f175..cdfc6193985 100644 --- a/zig/tests/contract/metal_delta_slots.zig +++ b/zig/tests/contract/metal_delta_slots.zig @@ -91,3 +91,6 @@ fn one(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, pipeline: mtl try expect(try rig.intact() and !rig.overlap() and std.mem.eql(u8, original_inputs, try rig.inputBytes())); } } + +/// Column tests reuse this FP64 fixture and original slot pipeline through the normal gates. +pub const Columns = @import("metal_q27_columns.zig"); diff --git a/zig/tests/contract/metal_dsv41_limits.zig b/zig/tests/contract/metal_dsv41_limits.zig index c07ab959a3d..6dbb66e8f55 100644 --- a/zig/tests/contract/metal_dsv41_limits.zig +++ b/zig/tests/contract/metal_dsv41_limits.zig @@ -6,6 +6,11 @@ const sources = @import("kernel_sources"); const limits = @import("contract").limits; const Launch = @import("metal_limits.zig").Launch; +/// The tensor-unit prompt expert kernels: built only with tensor units, and the loader has no M1/M2 library. +pub fn tensorOnly(name: []const u8) bool { + return std.mem.startsWith(u8, name, "dsv41 xmma units "); +} + /// The dsv41 launch's sources, or null when the name belongs to another family. pub fn launchOf(a: std.mem.Allocator, device: mtl.Device, d: limits.MetalLaunch, fun: []const u8, comptime assemble: bool) !?Launch { _ = device; diff --git a/zig/tests/contract/metal_glm_prompt.zig b/zig/tests/contract/metal_glm_prompt.zig new file mode 100644 index 00000000000..3577db06182 --- /dev/null +++ b/zig/tests/contract/metal_glm_prompt.zig @@ -0,0 +1,565 @@ +//! GLM-5.3-Flash M3 prompt index and KDA contracts: byte-exact against unvectorized baseline, plus planted controls. +const std = @import("std"); +const mtl = @import("metal"); +const tf = @import("tensorfold"); +const sources = @import("kernel_sources"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); + +const c = contract.spec; +const g = contract.gates; +const hi: usize = 32; +const di: usize = 128; +const d_kda: usize = 128; +const taps: usize = 4; + +const ScoreArgs = extern struct { p0: u32, q_stride: u32, w_stride: u32, s_stride: u32, rows: u32 }; + +fn bfVal(x: f32) u16 { + return c.toBf16(x); +} + +fn fillBf(dst: []u16, rng: std.Random, scale: f32) void { + for (dst) |*v| v.* = bfVal((rng.float(f32) * 2 - 1) * scale); +} + +fn fillF32(dst: []f32, rng: std.Random, lo: f32, hi_v: f32) void { + for (dst) |*v| v.* = lo + rng.float(f32) * (hi_v - lo); +} + +fn packRefs(a: std.mem.Allocator, rig: *const rig_.Rig, refs: []const rig_.Ref, lens: []const usize, out: *std.ArrayList(u8)) ![]const u8 { + out.clearRetainingCapacity(); + for (refs, lens) |r, len| try out.appendSlice(a, rig.bytes(r, len)); + return out.items; +} + +fn allocOutputSet(rig: *rig_.Rig, lens: []const usize, refs: []rig_.Ref, bases: []rig_.Ref) !void { + for (lens, 0..) |len, i| { + refs[i] = try rig.output(len); + bases[i] = try rig.scratch(len); + @memset(rig.bytes(bases[i], len), 0xff); + } +} + +pub const IndexKind = enum { scores, decode }; + +pub const Index = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + kind: IndexKind, + control: bool, + name: []const u8, + pipe: mtl.Pipeline, + base_pipe: mtl.Pipeline, + rows: usize = 0, + p0: usize = 0, + most: usize = 0, + s_stride: usize = 0, + refs: [3]rig_.Ref = undefined, + out: rig_.Ref = undefined, + base: rig_.Ref = undefined, + bytes: std.ArrayList(u8) = .empty, + base_bytes: std.ArrayList(u8) = .empty, + + fn depth(s: c.Shape) usize { + _ = s; + return 0; + } + + pub fn spec(kind: IndexKind, control: bool, name: []const u8) c.Spec { + const served: []const c.Shape = switch (kind) { + .scores => &.{ .{ .rows = 1, .n = di, .k = 16 }, .{ .rows = 33, .n = di, .k = 128 }, .{ .rows = 65, .n = di, .k = 260 } }, + .decode => &.{ .{ .rows = 1, .n = di, .k = 16 }, .{ .rows = 4, .n = di, .k = 516 }, .{ .rows = 16, .n = di, .k = 1028 } }, + }; + const tiles: [3]c.Tile = switch (kind) { + .scores => .{ .{ .size = 32, .step = 1, .min = 1 }, .{ .size = di, .step = di, .min = di }, .{ .size = 256, .step = 4, .min = 16 } }, + .decode => .{ .{ .size = 4, .step = 1, .min = 1 }, .{ .size = di, .step = di, .min = di }, .{ .size = 256, .step = 4, .min = 16 } }, + }; + return .{ + .name = name, + .accum = .none, + .depth = depth, + .out = .f32, + .replaces = if (control) null else "unvectorized M3 glm_index_nax kernel", + .nan = .{ .stated = "every output bit matches the unvectorized baseline, non-finite inputs included" }, + .tiles = tiles, + .served = served, + .sums = .{ .why = "bit-preserving layout optimization; arithmetic and accumulation order match the baseline" }, + }; + } + + const vt = blk: { + var v = g.hooks(Index); + v.output = output; + v.intact = intact; + v.check = checkNonfinite; + break :blk v; + }; + + pub fn kernel(self: *Index) g.Kernel { + return .{ .spec = spec(self.kind, self.control, self.name), .ctx = self, .vt = &vt, .control = if (self.control) .shapes else null }; + } + + pub fn deinit(self: *Index) void { + self.rig.deinit(); + self.bytes.deinit(self.a); + self.base_bytes.deinit(self.a); + } + + pub fn prepare(self: *Index, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + self.rig.reset(); + if (shape.rows == 0 or shape.n != di or shape.k + shape.rows < 4) return false; + self.rows = shape.rows; + self.p0 = shape.k; + self.most = (self.p0 + self.rows) / 4; + const q_stride = hi * di + 64; + const w_stride = hi + 16; + self.s_stride = self.most + 5; + const iq = try self.a.alloc(u16, self.rows * q_stride); + defer self.a.free(iq); + const iw = try self.a.alloc(u16, self.rows * w_stride); + defer self.a.free(iw); + const pool = try self.a.alloc(u16, self.most * di); + defer self.a.free(pool); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + fillBf(iq, rng, 1.5); + fillBf(iw, rng, 1.5); + fillBf(pool, rng, 1.5); + if (fill == .nonfinite) { + iq[0] = bfVal(std.math.nan(f32)); + iq[di + 3] = bfVal(std.math.inf(f32)); + iq[2 * di + 7] = bfVal(-std.math.inf(f32)); + iw[1] = bfVal(std.math.inf(f32)); + pool[0] = bfVal(std.math.nan(f32)); + pool[(self.most - 1) * di + 5] = bfVal(-std.math.inf(f32)); + } + self.refs[0] = try self.rig.input(std.mem.sliceAsBytes(iq)); + self.refs[1] = try self.rig.input(std.mem.sliceAsBytes(iw)); + self.refs[2] = try self.rig.input(std.mem.sliceAsBytes(pool)); + self.out = try self.rig.output(self.rows * self.s_stride * 4); + self.base = try self.rig.scratch(self.rows * self.s_stride * 4); + @memset(self.rig.bytes(self.base, self.rows * self.s_stride * 4), 0xff); + return true; + } + + fn encode(self: *const Index, e: mtl.ComputeEncoder, pipe: mtl.Pipeline, out_ref: rig_.Ref, rm: u32, bs: u32) void { + const q_stride: u32 = hi * di + 64; + const w_stride: u32 = hi + 16; + const n: u32 = @intCast(self.rows); + const most: u32 = @intCast(self.most); + e.setPipeline(pipe); + e.setBuffer(self.refs[0].buf, self.refs[0].off, 0); + e.setBuffer(self.refs[1].buf, self.refs[1].off, 1); + e.setBuffer(self.refs[2].buf, self.refs[2].off, 2); + e.setBuffer(out_ref.buf, out_ref.off, 3); + const args = ScoreArgs{ .p0 = @intCast(self.p0), .q_stride = q_stride, .w_stride = w_stride, .s_stride = @intCast(self.s_stride), .rows = n }; + e.setBytes(std.mem.asBytes(&args), 4); + const gx = if (self.kind == .scores) (most + 63) / 64 else (most + bs - 1) / bs; + const gy = if (self.kind == .scores) (n + rm - 1) / rm else n; + e.dispatchGroups(mtl.Size.of(gx, gy, 1), mtl.Size.of(128, 1, 1)); + } + + pub fn run(self: *Index) !void { + const p = self.rig.begin(); + const m3 = !self.rig.device.tensorUnits(); + const rm: u32 = if (self.control) (if (m3) 64 else 128) else if (m3) 32 else 64; + const bs: u32 = if (self.control) (if (m3) 128 else 256) else if (m3) 64 else 128; + self.encode(p.e, self.pipe, self.out, rm, bs); + try self.rig.finish(p); + } + + fn writtenCount(self: *const Index) usize { + var total: usize = 0; + for (0..self.rows) |r| total += (self.p0 + r + 1) / 4; + return total; + } + + pub fn count(self: *Index) usize { + return self.writtenCount(); + } + + fn pack(self: *const Index, from: rig_.Ref, dst: *std.ArrayList(u8)) ![]const u8 { + dst.clearRetainingCapacity(); + const raw = self.rig.bytes(from, self.rows * self.s_stride * 4); + for (0..self.rows) |r| { + const b = (self.p0 + r + 1) / 4; + try dst.appendSlice(self.a, raw[r * self.s_stride * 4 ..][0 .. b * 4]); + } + return dst.items; + } + + fn intact(ctx: *anyopaque) !bool { + const self: *Index = @ptrCast(@alignCast(ctx)); + if (!try self.rig.intact()) return false; + const raw = self.rig.bytes(self.out, self.rows * self.s_stride * 4); + for (0..self.rows) |r| { + const b = (self.p0 + r + 1) / 4; + for (raw[(r * self.s_stride + b) * 4 .. (r + 1) * self.s_stride * 4]) |byte| if (byte != 0xff) return false; + } + return true; + } + + fn output(ctx: *anyopaque) ![]const u8 { + const self: *Index = @ptrCast(@alignCast(ctx)); + if (!try intact(self)) return error.WroteOutsideOutputs; + return self.pack(self.out, &self.bytes); + } + + pub fn replaced(self: *Index) ![]const u8 { + const p = self.rig.begin(); + self.encode(p.e, self.base_pipe, self.base, 64, 128); + try self.rig.finish(p); + return self.pack(self.base, &self.base_bytes); + } + + fn checkNonfinite(ctx: *anyopaque, gate: g.Gate) !?[]const u8 { + const self: *Index = @ptrCast(@alignCast(ctx)); + const want = try self.replaced(); + const got = try output(self); + if (!std.mem.eql(u8, got, want)) { + return if (gate == .nonfinite) "index outputs differ from baseline on nonfinite inputs" else "index outputs differ from baseline"; + } + return null; + } + + pub fn reference(_: *Index, want: []f64, mag: []f64) !void { + @memset(want, 0); + @memset(mag, 0); + } +}; + +pub const KdaKind = enum { prep, scan, post }; + +pub const Kda = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + kind: KdaKind, + heads: u32, + control: bool, + name: []const u8, + pipe: mtl.Pipeline, + base_pipe: mtl.Pipeline, + rows: usize = 0, + r0: usize = 0, + in_refs: [8]rig_.Ref = undefined, + out_refs: [5]rig_.Ref = undefined, + base_refs: [5]rig_.Ref = undefined, + out_lens: [5]usize = undefined, + n_outs: usize = 0, + bytes: std.ArrayList(u8) = .empty, + base_bytes: std.ArrayList(u8) = .empty, + + fn depth(s: c.Shape) usize { + _ = s; + return 0; + } + + fn kdaServed(comptime w: usize, kind: KdaKind) []const c.Shape { + return switch (kind) { + .prep => &.{ .{ .rows = 1, .n = w, .k = 0 }, .{ .rows = 5, .n = w, .k = 4 }, .{ .rows = 16, .n = w, .k = 0 } }, + .scan => &.{ .{ .rows = 1, .n = w, .k = d_kda }, .{ .rows = 24, .n = w, .k = d_kda }, .{ .rows = 25, .n = w, .k = d_kda } }, + .post => &.{ .{ .rows = 1, .n = w, .k = 0 }, .{ .rows = 2, .n = w, .k = 0 }, .{ .rows = 5, .n = w, .k = 0 } }, + }; + } + + pub fn spec(kind: KdaKind, heads: u32, control: bool, name: []const u8) c.Spec { + const w: usize = @as(usize, heads) * d_kda; + const served = if (heads == 32) kdaServed(32 * d_kda, kind) else kdaServed(64 * d_kda, kind); + const tiles: [3]c.Tile = switch (kind) { + .prep => .{ .{ .size = 8, .step = 1, .min = 1 }, .{ .size = w, .step = w, .min = w }, .{ .size = 4, .step = 4, .min = 0 } }, + .scan => .{ .{ .size = 24, .step = 1, .min = 1 }, .{ .size = w, .step = w, .min = w }, .{ .size = d_kda, .step = d_kda, .min = d_kda } }, + .post => .{ .{ .size = 4, .step = 1, .min = 1 }, .{ .size = w, .step = w, .min = w }, .{} }, + }; + return .{ + .name = name, + .accum = .none, + .depth = depth, + .out = .raw, + .replaces = if (control) null else "unvectorized M3 glm_kda_prompt kernel", + .nan = .{ .stated = "every output bit matches the unvectorized baseline, non-finite inputs included" }, + .tiles = tiles, + .served = served, + .sums = .{ .why = "bit-preserving layout optimization; arithmetic and recurrence order match the baseline" }, + }; + } + + const vt = blk: { + var v = g.hooks(Kda); + v.output = output; + v.check = checkNonfinite; + break :blk v; + }; + + pub fn kernel(self: *Kda) g.Kernel { + return .{ .spec = spec(self.kind, self.heads, self.control, self.name), .ctx = self, .vt = &vt, .control = if (self.control) .shapes else null }; + } + + pub fn deinit(self: *Kda) void { + self.rig.deinit(); + self.bytes.deinit(self.a); + self.base_bytes.deinit(self.a); + } + + fn allocBfIn(self: *Kda, len: usize, rng: std.Random, scale: f32, idx: usize, nf: bool) !void { + const buf = try self.a.alloc(u16, len); + defer self.a.free(buf); + fillBf(buf, rng, scale); + if (nf and len > 0) buf[0] = bfVal(std.math.nan(f32)); + if (nf and len > 4) buf[4] = bfVal(std.math.inf(f32)); + if (nf and len > 9) buf[9] = bfVal(-std.math.inf(f32)); + self.in_refs[idx] = try self.rig.input(std.mem.sliceAsBytes(buf)); + } + + fn allocF32In(self: *Kda, len: usize, rng: std.Random, lo: f32, hi_v: f32, idx: usize, nf: bool) !void { + const buf = try self.a.alloc(f32, len); + defer self.a.free(buf); + fillF32(buf, rng, lo, hi_v); + if (nf and len > 0) buf[0] = std.math.inf(f32); + if (nf and len > 3) buf[3] = std.math.nan(f32); + self.in_refs[idx] = try self.rig.input(std.mem.sliceAsBytes(buf)); + } + + pub fn prepare(self: *Kda, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + self.rig.reset(); + const w: usize = @as(usize, self.heads) * d_kda; + if (shape.rows == 0 or shape.n != w) return false; + self.rows = shape.rows; + self.r0 = if (self.kind == .prep) shape.k else 0; + const c3 = 3 * w; + const ps = c3 + 2 * d_kda + self.heads; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const nf = fill == .nonfinite; + switch (self.kind) { + .prep => { + try self.allocBfIn((self.r0 + self.rows) * ps, rng, 0.5, 0, nf); + try self.allocBfIn((taps - 1) * c3, rng, 0.5, 1, nf); + try self.allocF32In(taps * c3, rng, -0.5, 0.5, 2, false); + try self.allocBfIn(self.rows * w, rng, 0.5, 3, nf); + try self.allocF32In(self.heads, rng, -1.5, -0.2, 4, nf); + try self.allocF32In(w, rng, -0.5, 0.5, 5, false); + self.out_lens[0..5].* = .{ self.rows * w * 2, self.rows * w * 2, self.rows * w * 2, self.rows * w * 4, self.rows * self.heads * 4 }; + self.n_outs = 5; + }, + .scan => { + for (0..3) |i| try self.allocBfIn(self.rows * w, rng, 0.4, i, nf); + try self.allocF32In(self.rows * w, rng, 0.5, 1.0, 3, nf); + try self.allocF32In(self.rows * self.heads, rng, 0.1, 0.9, 4, nf); + try self.allocF32In(@as(usize, self.heads) * d_kda * d_kda, rng, -0.5, 0.5, 5, nf); + self.out_lens[0..2].* = .{ @as(usize, self.heads) * d_kda * d_kda * 4, self.rows * w * 2 }; + self.n_outs = 2; + }, + .post => { + try self.allocBfIn(self.rows * w, rng, 0.8, 0, nf); + try self.allocBfIn(self.rows * w, rng, 0.8, 1, nf); + try self.allocF32In(d_kda, rng, 0.5, 1.5, 2, nf); + try self.allocBfIn(self.rows * ps, rng, 0.5, 3, nf); + try self.allocBfIn((taps - 1) * c3, rng, 0.5, 4, nf); + self.out_lens[0..2].* = .{ self.rows * w * 2, (taps - 1) * c3 * 2 }; + self.n_outs = 2; + }, + } + try allocOutputSet(&self.rig, self.out_lens[0..self.n_outs], self.out_refs[0..self.n_outs], self.base_refs[0..self.n_outs]); + return true; + } + + fn encode(self: *const Kda, e: mtl.ComputeEncoder, pipe: mtl.Pipeline, outs: []const rig_.Ref, m3: bool, ctrl: bool) void { + const w: usize = @as(usize, self.heads) * d_kda; + const ps: i32 = @intCast(3 * w + 2 * d_kda + self.heads); + e.setPipeline(pipe); + switch (self.kind) { + .prep => { + const shape = [3]i32{ @intCast(self.rows), ps, @intCast(self.r0) }; + const lb: f32 = -1.0; + e.setBuffer(self.in_refs[0].buf, self.in_refs[0].off, 0); + e.setBytes(std.mem.asBytes(&shape), 1); + for (self.in_refs[1..6], 2..) |r, idx| e.setBuffer(r.buf, r.off, idx); + e.setBytes(std.mem.asBytes(&lb), 7); + for (outs[0..5], 8..) |r, idx| e.setBuffer(r.buf, r.off, idx); + const gy: usize = if (ctrl) self.heads / 8 else self.heads / 4; + e.dispatchGroups(mtl.Size.of(self.rows, gy, 1), mtl.Size.of(128, 1, 1)); + }, + .scan => { + const r_val: i32 = @intCast(self.rows); + for (self.in_refs[0..6], 0..) |r, idx| e.setBuffer(r.buf, r.off, idx); + e.setBuffer(outs[0].buf, outs[0].off, 6); + e.setBuffer(outs[1].buf, outs[1].off, 7); + e.setBytes(std.mem.asBytes(&r_val), 8); + const sg_cols: usize = if (m3) 16 else 64; + const th: usize = if (m3) 128 else 512; + const gx = if (ctrl) (d_kda / sg_cols) / 2 else d_kda / sg_cols; + e.dispatchGroups(mtl.Size.of(gx, self.heads, 1), mtl.Size.of(th, 1, 1)); + }, + .post => { + const shape = [2]i32{ @intCast(self.rows), ps }; + const eps: f32 = 1e-5; + for (self.in_refs[0..3], 0..) |r, idx| e.setBuffer(r.buf, r.off, idx); + e.setBytes(std.mem.asBytes(&eps), 3); + e.setBuffer(outs[0].buf, outs[0].off, 4); + e.setBuffer(self.in_refs[3].buf, self.in_refs[3].off, 5); + e.setBytes(std.mem.asBytes(&shape), 6); + e.setBuffer(self.in_refs[4].buf, self.in_refs[4].off, 7); + e.setBuffer(outs[1].buf, outs[1].off, 8); + const hb: usize = if (m3) 4 else 1; + const th: usize = if (m3) 128 else 32; + const gy = if (ctrl) (self.heads / hb) / 2 else self.heads / hb; + e.dispatchGroups(mtl.Size.of(self.rows, gy, 1), mtl.Size.of(th, 1, 1)); + }, + } + } + + pub fn run(self: *Kda) !void { + const p = self.rig.begin(); + const m3 = !self.rig.device.tensorUnits(); + self.encode(p.e, self.pipe, self.out_refs[0..self.n_outs], m3, self.control); + try self.rig.finish(p); + } + + pub fn count(self: *Kda) usize { + var total: usize = 0; + for (self.out_lens[0..self.n_outs]) |len| total += len; + return total; + } + + fn output(ctx: *anyopaque) ![]const u8 { + const self: *Kda = @ptrCast(@alignCast(ctx)); + return packRefs(self.a, &self.rig, self.out_refs[0..self.n_outs], self.out_lens[0..self.n_outs], &self.bytes); + } + + pub fn replaced(self: *Kda) ![]const u8 { + const p = self.rig.begin(); + self.encode(p.e, self.base_pipe, self.base_refs[0..self.n_outs], false, false); + try self.rig.finish(p); + return packRefs(self.a, &self.rig, self.base_refs[0..self.n_outs], self.out_lens[0..self.n_outs], &self.base_bytes); + } + + fn checkNonfinite(ctx: *anyopaque, gate: g.Gate) !?[]const u8 { + const self: *Kda = @ptrCast(@alignCast(ctx)); + const want = try self.replaced(); + const got = try output(self); + if (!std.mem.eql(u8, got, want)) { + return if (gate == .nonfinite) "kda outputs differ from baseline on nonfinite inputs" else "kda outputs differ from baseline"; + } + return null; + } + + pub fn reference(_: *Kda, want: []f64, mag: []f64) !void { + @memset(want, 0); + @memset(mag, 0); + } +}; + +fn wanted(only: ?[]const u8, name: []const u8) bool { + const text = only orelse return true; + return std.mem.indexOf(u8, name, text) != null; +} + +const kda_specs = [_]struct { kind: KdaKind, heads: u32, fn_name: []const u8, control: bool, name: []const u8 }{ + .{ .kind = .prep, .heads = 64, .fn_name = "glm_kda_prep", .control = false, .name = "metal glm m3 kda_prep" }, + .{ .kind = .prep, .heads = 64, .fn_name = "glm_kda_prep", .control = true, .name = "control: metal glm m3 kda_prep, wrong head tile grid" }, + .{ .kind = .scan, .heads = 64, .fn_name = "glm_kda_scan", .control = false, .name = "metal glm m3 kda_scan" }, + .{ .kind = .scan, .heads = 64, .fn_name = "glm_kda_scan", .control = true, .name = "control: metal glm m3 kda_scan, half value-column grid" }, + .{ .kind = .scan, .heads = 32, .fn_name = "glm_kda_scan_tp", .control = false, .name = "metal glm m3 kda_scan_tp" }, + .{ .kind = .post, .heads = 64, .fn_name = "glm_kda_post", .control = false, .name = "metal glm m3 kda_post" }, + .{ .kind = .post, .heads = 64, .fn_name = "glm_kda_post", .control = true, .name = "control: metal glm m3 kda_post, wrong head tile grid" }, +}; + +const index_specs = [_]struct { kind: IndexKind, fn_name: []const u8, control: bool, name: []const u8 }{ + .{ .kind = .scores, .fn_name = "glm_index_scores_nax", .control = false, .name = "metal glm m3 index_scores_nax" }, + .{ .kind = .scores, .fn_name = "glm_index_scores_nax", .control = true, .name = "control: metal glm m3 index_scores_nax, wrong row tile height" }, + .{ .kind = .decode, .fn_name = "glm_index_decode", .control = false, .name = "metal glm m3 index_decode" }, + .{ .kind = .decode, .fn_name = "glm_index_decode", .control = true, .name = "control: metal glm m3 index_decode, wrong block tile width" }, +}; + +pub const Suite = struct { + a: std.mem.Allocator, + pipes: std.ArrayList(mtl.Pipeline) = .empty, + indices: [index_specs.len]Index = undefined, + index_made: usize = 0, + kdas: [kda_specs.len]Kda = undefined, + kda_made: usize = 0, + + pub fn create(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, out: *std.ArrayList(g.Kernel), only: ?[]const u8) !*Suite { + const s = try a.create(Suite); + s.* = .{ .a = a }; + errdefer s.destroy(); + var need_idx = false; + for (index_specs) |e| if (wanted(only, e.name)) { + need_idx = true; + }; + var need_kda = false; + for (kda_specs) |e| if (wanted(only, e.name)) { + need_kda = true; + }; + const m3_def = if (!device.tensorUnits()) "#define TF_GLM_M3_FAST 1\n" else ""; + if (need_idx) { + const idx_raw = try std.mem.concat(a, u8, &.{ m3_def, sources.glm_index_nax }); + defer a.free(idx_raw); + const idx_src = try tf.frags.source(device, a, idx_raw); + defer a.free(idx_src); + const idx_base_src = try tf.frags.source(device, a, sources.glm_index_nax); + defer a.free(idx_base_src); + const idx_lib = try mtl.Library.fromSource(device, idx_src, mtl.CompileOptions.mlx()); + defer idx_lib.deinit(); + const base_lib = try mtl.Library.fromSource(device, idx_base_src, mtl.CompileOptions.mlx()); + defer base_lib.deinit(); + for (index_specs) |e| { + if (!wanted(only, e.name)) continue; + const pipe = try mtl.Pipeline.init(device, idx_lib, e.fn_name, false); + try s.pipes.append(a, pipe); + const base_pipe = try mtl.Pipeline.init(device, base_lib, e.fn_name, false); + try s.pipes.append(a, base_pipe); + s.indices[s.index_made] = .{ + .a = a, + .rig = .{ .a = a, .device = device, .queue = queue }, + .kind = e.kind, + .control = e.control, + .name = e.name, + .pipe = pipe, + .base_pipe = base_pipe, + }; + try out.append(a, s.indices[s.index_made].kernel()); + s.index_made += 1; + } + } + if (need_kda) { + const kda_prefix = comptime tf.glm.kernels.generatedSource("kda_rows"); + const kda_src = try std.mem.concat(a, u8, &.{ kda_prefix, m3_def, sources.glm_kda_prompt }); + defer a.free(kda_src); + const kda_base_src = kda_prefix ++ sources.glm_kda_prompt; + const kda_lib = try mtl.Library.fromSource(device, kda_src, mtl.CompileOptions.mlx()); + defer kda_lib.deinit(); + const base_lib = try mtl.Library.fromSource(device, kda_base_src, mtl.CompileOptions.mlx()); + defer base_lib.deinit(); + for (kda_specs) |e| { + if (!wanted(only, e.name)) continue; + const pipe = try mtl.Pipeline.init(device, kda_lib, e.fn_name, false); + try s.pipes.append(a, pipe); + const base_pipe = try mtl.Pipeline.init(device, base_lib, e.fn_name, false); + try s.pipes.append(a, base_pipe); + s.kdas[s.kda_made] = .{ + .a = a, + .rig = .{ .a = a, .device = device, .queue = queue }, + .kind = e.kind, + .heads = e.heads, + .control = e.control, + .name = e.name, + .pipe = pipe, + .base_pipe = base_pipe, + }; + try out.append(a, s.kdas[s.kda_made].kernel()); + s.kda_made += 1; + } + } + return s; + } + + pub fn destroy(s: *Suite) void { + for (s.indices[0..s.index_made]) |*it| it.deinit(); + for (s.kdas[0..s.kda_made]) |*it| it.deinit(); + for (s.pipes.items) |p| p.deinit(); + s.pipes.deinit(s.a); + s.a.destroy(s); + } +}; diff --git a/zig/tests/contract/metal_idol.zig b/zig/tests/contract/metal_idol.zig new file mode 100644 index 00000000000..50d1284ae4c --- /dev/null +++ b/zig/tests/contract/metal_idol.zig @@ -0,0 +1,190 @@ +//! Idol's Metal kernels under the contract, each at idol-sdk's fp16 points; controls drop or add one rounding point. +const std = @import("std"); +const mtl = @import("metal"); +const rig_ = @import("rig.zig"); +const id = @import("metal_idol_common.zig"); +const gemm = @import("metal_idol_gemm.zig"); +const norms = @import("metal_idol_norms.zig"); +const steps = @import("metal_idol_steps.zig"); +const elems = @import("metal_idol_rows.zig"); +const attn = @import("metal_idol_attention.zig"); + +const g = id.g; +const ks = id.ks; +const Control = id.Control; +const Lib = id.Lib; + +/// The NAX fp32 GEMM (the tensor unit's fp32 path, not fp32-accurate on M5) in id_gemm32's place. +const nax_gemm32 = + \\[[max_total_threads_per_threadgroup(128)]] [[kernel]] void id_gemm32( + \\ const device float* x [[buffer(0)]], const device float* w [[buffer(1)]], device float* y [[buffer(2)]], + \\ constant IdGemm32& p [[buffer(3)]], uint2 tg [[threadgroup_position_in_grid]], + \\ uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]]) { + \\ const int row = int(tg.y) * 64 + 32 * int(sg / 2), col = int(tg.x) * 64 + 32 * int(sg % 2); + \\ const int rows = min(32, int(p.M) - row), cols = min(32, int(p.N) - col); + \\ const short2 home = tfp::frag_home(ushort(lane)); + \\ tfp::frag acc[2][2]; + \\ tfp::gemm_block(acc, x + long(row) * p.K, w + long(col) * p.K, int(p.K), int(p.K), + \\ int(p.K), int(p.K) / 32, rows, cols, home); + \\ if (rows > 0 && cols > 0) tfp::gemm_store(acc, y + long(row) * p.ldy + col, int(p.ldy), rows, cols, home); + \\} +; + +const mma_line = "for (uint j = 0; j < 4; j++) simdgroup_multiply_accumulate(acc[i][j], a[i], b[j], acc[i][j]);"; +const mma_half = "for (uint j = 0; j < 4; j++) { simdgroup_multiply_accumulate(acc[i][j], a[i], b[j], acc[i][j]); " ++ + "acc[i][j].thread_elements()[0] = id_h(acc[i][j].thread_elements()[0]); " ++ + "acc[i][j].thread_elements()[1] = id_h(acc[i][j].thread_elements()[1]); }"; + +const controls = [_]Control{ + .{ .kernel = "id_linear_gelu_01", .what = "drops fp16(x w + b) before the GELU", .edits = &.{.{ .from = "const float v = id_h(acc[i][j][e] + b);", .to = "const float v = (acc[i][j][e] + b);" }} }, + .{ .kernel = "id_linear_01", .what = "adds fp16(x w) before the bias", .edits = &.{.{ .from = "const float v = id_h(acc[i][j][e] + b);", .to = "const float v = id_h(id_h(acc[i][j][e]) + b);" }} }, + .{ .kernel = "id_norm modulated", .what = "drops fp16(y s1)", .edits = &.{.{ .from = "v = id_h(id_h(v * float(s1[i])) + float(sh[i]));", .to = "v = id_h((v * float(s1[i])) + float(sh[i]));" }} }, + .{ .kernel = "id_norm affine", .what = "adds fp16(y) before the affine", .edits = &.{.{ .from = "if (p.mode == 1) v = v * w[i] + b[i];", .to = "if (p.mode == 1) v = id_h(v) * w[i] + b[i];" }} }, + .{ .kernel = "id_norm32 modulated", .what = "adds fp16(y) before the modulation", .edits = &.{.{ .from = "yr[i] = p.mode == 2 ? v * (1.0f + w[i])", .to = "yr[i] = p.mode == 2 ? id_h(v) * (1.0f + w[i])" }} }, + .{ .kernel = "id_norm32 modulated", .what = "sums the simdgroups in fp16", .gate = .sums, .edits = &.{.{ .from = " v = simd_sum(v);\n if (lane == 0) part[sg] = v;", .to = " v = float(simd_sum(half(v)));\n if (lane == 0) part[sg] = v;" }} }, + .{ .kernel = "id_norm_split", .what = "rounds the row to fp16 before its split", .edits = &.{.{ .from = "const float v = (float(xr[i]) - mean) * inv * w[i] + b[i];", .to = "const float v = id_h((float(xr[i]) - mean) * inv * w[i] + b[i]);" }} }, + .{ .kernel = "id_repo", .what = "adds fp16(u)", .edits = &.{.{ .from = "u[i] = (a / (1.0f + metal::precise::exp(-a))) * (g[128 + i] * p.inv);", .to = "u[i] = id_h((a / (1.0f + metal::precise::exp(-a))) * (g[128 + i] * p.inv));" }} }, + .{ .kernel = "id_repo", .what = "sums d in fp16", .gate = .sums, .edits = &.{.{ .from = "s = fma(u[k], wf[t * 128 + k], s);", .to = "s = id_h(fma(u[k], wf[t * 128 + k], s));" }} }, + .{ .kernel = "id_qk", .what = "drops fp16(q0 c - q1 s)", .edits = &.{.{ .from = "const float rq0 = id_h(q0 * c - q1 * s), rq1", .to = "const float rq0 = (q0 * c - q1 * s), rq1" }} }, + .{ .kernel = "id_qk", .what = "sums q's squares in fp16", .gate = .sums, .edits = &.{.{ .from = "simd_sum(rq0 * rq0 + rq1 * rq1)", .to = "float(simd_sum(half(rq0 * rq0 + rq1 * rq1)))" }} }, + .{ .kernel = "id_gate_add", .what = "drops fp16(g y)", .edits = &.{.{ .from = "half(float(x[i]) + id_h(float(g[at.x]) * float(y[i])));", .to = "half(float(x[i]) + (float(g[at.x]) * float(y[i])));" }} }, + .{ .kernel = "id_embed", .what = "drops fp16(z w + b)", .edits = &.{.{ .from = "x[i] = half(float(half(s + b[c])) + float(pe[i]));", .to = "x[i] = half((s + b[c]) + float(pe[i]));" }} }, + .{ .kernel = "id_embed", .what = "sums z w in fp16", .gate = .sums, .edits = &.{.{ .from = "s = fma(z[r * 16 + k], w[c * 16 + k], s);", .to = "s = id_h(fma(z[r * 16 + k], w[c * 16 + k], s));" }} }, + .{ .kernel = "id_cond", .what = "adds fp16(a + ba)", .edits = &.{.{ .from = "y[i] = half((a[i] + ba[at.x]) + (c[i] + bc[at.x]));", .to = "y[i] = half(id_h(a[i] + ba[at.x]) + (c[i] + bc[at.x]));" }} }, + .{ .kernel = "id_bias32", .what = "adds fp16(b)", .edits = &.{.{ .from = "y[ulong(at.y) * width + at.x] += b[at.x];", .to = "y[ulong(at.y) * width + at.x] += id_h(b[at.x]);" }} }, + .{ .kernel = "id_gemm32", .what = "sums in fp16", .gate = .sums, .edits = &.{.{ .from = mma_line, .to = mma_half }} }, + .{ .kernel = "id_gemm32", .what = "takes the NAX fp32 path", .gate = .sums, .edits = &.{.{ .from = "void id_gemm32(", .to = "void id_gemm32_simd(" }}, .append = nax_gemm32 }, + .{ .kernel = "id_attention_00", .what = "keys past Lk unmasked", .edits = &.{.{ .from = "s[f][e] = (16 * f + home.x + TF_COL(e)) < k_rows ? s[f][e] : kIdMasked;", .to = "s[f][e] = s[f][e];" }} }, +}; + +/// A test the suite made, and how it goes. +const Made = struct { ptr: *anyopaque, free: *const fn (std.mem.Allocator, *anyopaque) void }; + +pub const Suite = struct { + a: std.mem.Allocator, + libs: std.ArrayList(*Lib) = .empty, + names: std.ArrayList([]u8) = .empty, + made: std.ArrayList(Made) = .empty, + + fn label(s: *Suite, comptime fmt: []const u8, args: anytype) ![]const u8 { + const name = try std.fmt.allocPrint(s.a, fmt, args); + errdefer s.a.free(name); + try s.names.append(s.a, name); + return name; + } + + fn make(s: *Suite, comptime T: type, value: T) !*T { + const t = try s.a.create(T); + errdefer s.a.destroy(t); + t.* = value; + const f = struct { + fn free(a: std.mem.Allocator, p: *anyopaque) void { + const x: *T = @ptrCast(@alignCast(p)); + x.deinit(); + a.destroy(x); + } + }; + try s.made.append(s.a, .{ .ptr = t, .free = f.free }); + return t; + } + + /// Each kernel (or, with `ctl`, the one it breaks) on `lib`'s pipelines. + fn add(s: *Suite, device: mtl.Device, queue: mtl.Queue, lib: *Lib, ctl: ?Control, out: *std.ArrayList(g.Kernel), only: ?[]const u8) !void { + const suffix = if (ctl) |x| try s.label(" control: {s}", .{x.what}) else ""; + const gate: ?g.Gate = if (ctl) |x| x.gate else null; + const rig: rig_.Rig = .{ .a = s.a, .device = device, .queue = queue }; + const ends: id.Ends = .{ .a = s.a }; + const W = struct { + s: *Suite, + ctl: ?Control, + suffix: []const u8, + only: ?[]const u8, + /// The test's name when this pass registers `kernel`, else null. + fn name(w: @This(), kernel: []const u8) !?[]const u8 { + if (w.ctl) |x| if (!std.mem.eql(u8, x.kernel, kernel)) return null; + const full = try w.s.label("metal idol {s}{s}", .{ kernel, w.suffix }); + if (w.only) |needle| if (std.mem.indexOf(u8, full, needle) == null) return null; + return full; + } + }; + const w = W{ .s = s, .ctl = ctl, .suffix = suffix, .only = only }; + for ([_]gemm.Kind{ .linear, .gelu, .split }) |kind| for (0..4) |f| { + const form: u2 = @intCast(f); + if (kind == .split and form & 1 == 0) continue; + const fun = gemm.pipeline(kind, form); + const name = (try w.name(fun)) orelse continue; + const t = try s.make(gemm.Gemm16, .{ .a = s.a, .rig = rig, .lib = lib, .kind = kind, .form = form, .name = name, .ends = ends }); + try out.append(s.a, t.kernel(gate)); + }; + if (try w.name("id_gemm32")) |name| { + const t = try s.make(gemm.Gemm32, .{ .a = s.a, .rig = rig, .lib = lib, .name = name }); + try out.append(s.a, t.kernel(gate)); + } + const norm_kinds = [_]struct { kind: norms.Kind, mode: ks.Norm, fun: []const u8 }{ + .{ .kind = .norm, .mode = .plain, .fun = "id_norm plain" }, + .{ .kind = .norm, .mode = .affine, .fun = "id_norm affine" }, + .{ .kind = .norm, .mode = .modulated, .fun = "id_norm modulated" }, + .{ .kind = .norm32, .mode = .affine, .fun = "id_norm32 affine" }, + .{ .kind = .norm32, .mode = .modulated, .fun = "id_norm32 modulated" }, + .{ .kind = .split, .mode = .affine, .fun = "id_norm_split" }, + }; + for (norm_kinds) |nk| { + const name = (try w.name(nk.fun)) orelse continue; + const t = try s.make(norms.Norm, .{ .a = s.a, .rig = rig, .lib = lib, .kind = nk.kind, .mode = nk.mode, .name = name, .ends = ends }); + try out.append(s.a, t.kernel(gate)); + } + if (try w.name("id_repo")) |name| { + const t = try s.make(steps.Repo, .{ .a = s.a, .rig = rig, .lib = lib, .name = name, .ends = ends }); + try out.append(s.a, t.kernel(gate)); + } + if (try w.name("id_qk")) |name| { + const t = try s.make(steps.Qk, .{ .a = s.a, .rig = rig, .lib = lib, .name = name, .ends = ends }); + try out.append(s.a, t.kernel(gate)); + } + inline for (.{ .{ elems.GateAdd, "id_gate_add" }, .{ elems.Embed, "id_embed" }, .{ elems.Cond, "id_cond" }, .{ elems.Bias32, "id_bias32" } }) |e| { + if (try w.name(e[1])) |name| { + const t = try s.make(e[0], .{ .a = s.a, .rig = rig, .lib = lib, .name = name, .ends = ends }); + try out.append(s.a, t.kernel(gate)); + } + } + for (attn.forms, 0..) |f, i| { + const name = (try w.name(f.name)) orelse continue; + const t = try s.make(attn.Attention, .{ .a = s.a, .rig = rig, .lib = lib, .form = i, .name = name }); + try out.append(s.a, t.kernel(gate)); + } + } + + pub fn create(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, out: *std.ArrayList(g.Kernel), only: ?[]const u8) !*Suite { + const s = try a.create(Suite); + s.* = .{ .a = a }; + errdefer s.destroy(); + if (!device.tensorUnits()) { + std.debug.print("UNSUPPORTED metal idol: the family runs on tensor units (M5) alone; its kernels unchecked here\n", .{}); + return s; + } + for ([_]?Control{null} ++ controls) |x| { + const lib = try a.create(Lib); + lib.* = .{ .a = a, .device = device, .ctl = x }; + s.libs.append(a, lib) catch |err| { + a.destroy(lib); + return err; + }; + try s.add(device, queue, lib, x, out, only); + } + return s; + } + + pub fn destroy(s: *Suite) void { + const a = s.a; + for (s.made.items) |m| m.free(a, m.ptr); + s.made.deinit(a); + for (s.libs.items) |l| { + l.deinit(); + a.destroy(l); + } + s.libs.deinit(a); + for (s.names.items) |n| a.free(n); + s.names.deinit(a); + a.destroy(s); + } +}; diff --git a/zig/tests/contract/metal_idol_attention.zig b/zig/tests/contract/metal_idol_attention.zig new file mode 100644 index 00000000000..fc75fac7471 --- /dev/null +++ b/zig/tests/contract/metal_idol_attention.zig @@ -0,0 +1,233 @@ +//! id_attention under the contract: softmax(q k^T / 8) v at head width 64, against attention_ref's float64 formula. +const std = @import("std"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); +const id = @import("metal_idol_common.zig"); + +const c = id.c; +const g = id.g; +const D = id.D; +const kref = id.kref; + +const heads = id.cfg.heads; + +/// Query rows repeat at this period (prime to the 64-row blocks): float64 costs 89 queries a head over every key. +const query_period = 89; + +/// Each form's name, served lengths and edges by (Lq % 64 == 0)(Lk % 32 == 0); Lq is n, Lk is k. +pub const forms = [4]struct { name: []const u8, served: []const c.Shape, tiles: [3]c.Tile }{ + .{ + .name = "id_attention_00", + .served = &.{ .{ .rows = heads, .n = 12294, .k = 12294 }, .{ .rows = heads, .n = 4101, .k = 4101 } }, + .tiles = .{ .{}, .{ .size = 64 }, .{ .size = 32 } }, + }, + // no served call has Lq != Lk: the cross-length forms are checked at their tails + .{ + .name = "id_attention_01", + .served = &.{ .{ .rows = heads, .n = 4101, .k = 4128 }, .{ .rows = heads, .n = 100, .k = 64 } }, + .tiles = .{ .{}, .{ .size = 64 }, .{ .size = 64, .step = 32, .min = 32 } }, + }, + .{ + .name = "id_attention_10", + .served = &.{ .{ .rows = heads, .n = 4096, .k = 4101 }, .{ .rows = heads, .n = 128, .k = 70 } }, + .tiles = .{ .{}, .{ .size = 128, .step = 64, .min = 64 }, .{ .size = 32 } }, + }, + .{ + .name = "id_attention_11", + .served = &.{.{ .rows = heads, .n = 8192, .k = 8192 }}, + .tiles = .{ .{}, .{ .size = 128, .step = 64, .min = 64 }, .{ .size = 64, .step = 32, .min = 32 } }, + }, +}; + +pub fn form(lq: usize, lk: usize) usize { + return @as(usize, @intFromBool(lq % 64 == 0)) * 2 + @intFromBool(lk % 32 == 0); +} + +/// The scores' 64-deep sums, then the keys' sums. +fn attentionDepth(s: c.Shape) usize { + return D + s.k; +} + +pub const Attention = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + lib: *id.Lib, + form: usize, + name: []const u8, + lq: usize = 0, + lk: usize = 0, + stress: bool = false, + q: []f16 = &.{}, + k: []f16 = &.{}, + v: []f16 = &.{}, + ins: [3]rig_.Ref = undefined, + out: rig_.Ref = undefined, + + /// Rows: the launch's 16 heads (fixed; a gate's fewer rows run all 16); n: query rows Lq; k: key rows Lk. + pub fn spec(name: []const u8, f: usize) c.Spec { + return .{ .name = name, .accum = .f32, .depth = attentionDepth, .ops = 8, .out = .f16, .tiles = forms[f].tiles, .served = forms[f].served }; + } + + pub fn deinit(t: *Attention) void { + t.free(); + t.rig.deinit(); + } + fn free(t: *Attention) void { + t.a.free(t.q); + t.a.free(t.k); + t.a.free(t.v); + t.q = &.{}; + t.k = &.{}; + t.v = &.{}; + } + pub fn kernel(t: *Attention, control: ?g.Gate) g.Kernel { + return .{ .spec = spec(t.name, t.form), .ctx = t, .vt = &vt, .control = control }; + } + const vt = g.hooks(Attention); + + pub fn prepare(t: *Attention, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.n == 0 or shape.k == 0 or form(shape.n, shape.k) != t.form) return false; + t.rig.reset(); + t.free(); + t.lq = shape.n; + t.lk = shape.k; + t.stress = fill == .stress; + const L = t.lk; + t.q = try t.a.alloc(f16, heads * t.lq * D); + t.k = try t.a.alloc(f16, heads * L * D); + t.v = try t.a.alloc(f16, heads * L * D); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + if (t.stress) { + // equal scores (q = k = 0), each column's values integers whose partial sums reach ~2^23 and cancel to 4 + @memset(t.q, 0); + @memset(t.k, 0); + const half = L / 2; + for (0..heads) |h| for (0..L) |j| { + const at = if (j < half) j else j - half; + const positive: f32 = if (at % 2 == 0) 127 else 4064; + const residual: f32 = if (at < 8 and at % 2 == 0) 1 else 0; + const v: f32 = if (j < half) positive else if (j < 2 * half) residual - positive else 0; + @memset(t.v[(h * L + j) * D ..][0..D], @floatCast(v)); + }; + } else { + id.randomF16(rng, t.q, -2, 2); + id.randomF16(rng, t.k, -2, 2); + id.randomF16(rng, t.v, -1, 1); + } + if (fill == .nonfinite) { + // head 0: values NaN, +Inf, -Inf, and both infinities in one column; head 1: a NaN query, an infinite key + for ([_][2]usize{ .{ 0, 0 }, .{ 1, 1 }, .{ 2, 2 }, .{ 3, 3 }, .{ 4, 3 } }, [_]f16{ id.nan16, id.inf16, -id.inf16, id.inf16, -id.inf16 }) |p, v| if (p[0] < L) { + t.v[p[0] * D + p[1]] = v; + }; + t.q[(t.lq + 0) * D + 5] = id.nan16; + if (L > 7) t.k[(L + 7) * D + 3] = id.inf16; + } + // every head's queries repeat at the period, so float64 computes each distinct one once + const p = @min(t.lq, query_period); + for (0..heads) |h| for (p..t.lq) |i| { + @memcpy(t.q[(h * t.lq + i) * D ..][0..D], t.q[(h * t.lq + i % p) * D ..][0..D]); + }; + t.ins[0] = try t.rig.input(std.mem.sliceAsBytes(t.q)); + t.ins[1] = try t.rig.input(std.mem.sliceAsBytes(t.k)); + t.ins[2] = try t.rig.input(std.mem.sliceAsBytes(t.v)); + t.out = try t.rig.output(heads * t.lq * D * 2); + return true; + } + + pub fn run(t: *Attention) !void { + try t.lib.need(forms[t.form].name); + const p = t.rig.begin(); + t.lib.k.attention(p.e, kref(t.ins[0]), kref(t.ins[1]), kref(t.ins[2]), kref(t.out), t.lq, t.lk); + try t.rig.finish(p); + } + + pub fn count(t: *Attention) usize { + return heads * t.lq * D; + } + + /// attention_ref.head's formula, one pass over the keys a distinct query; O rows [Lq, heads * 64]. + pub fn reference(t: *Attention, want: []f64, mag: []f64) !void { + const L = t.lk; + const scale: f64 = @as(f32, 1.0 / @sqrt(@as(f32, D))); + const kf = try t.a.alloc(f64, L * D); + defer t.a.free(kf); + const vf = try t.a.alloc(f64, L * D); + defer t.a.free(vf); + const s = try t.a.alloc(f64, L); + defer t.a.free(s); + var qf: [D]f64 = undefined; + var out: [D]f64 = undefined; + var tol: [D]f64 = undefined; + const p = @min(t.lq, query_period); + for (0..heads) |h| { + for (kf, vf, t.k[h * L * D ..][0 .. L * D], t.v[h * L * D ..][0 .. L * D]) |*kd, *vd, kb, vb| { + kd.* = kb; + vd.* = vb; + } + for (0..p) |i| { + var zero = true; + for (&qf, t.q[(h * t.lq + i) * D ..][0..D]) |*x, b| { + x.* = b; + zero = zero and x.* == 0; + } + var m: f64 = -std.math.inf(f64); + var nan = false; + for (s, 0..) |*sj, j| { + var dot: f64 = 0; + if (!zero) { + const Vec = @Vector(8, f64); + var acc: Vec = @splat(0); + var e: usize = 0; + while (e < D) : (e += 8) acc += @as(Vec, qf[e..][0..8].*) * @as(Vec, kf[j * D + e ..][0..8].*); + dot = @reduce(.Add, acc); + } + sj.* = dot * scale; + nan = nan or std.math.isNan(sj.*); + m = @max(m, sj.*); + } + if (nan) m = std.math.nan(f64); + var l: f64 = 0; + @memset(&out, 0); + @memset(&tol, 0); + for (s, 0..) |sj, j| { + const pj = @exp(sj - m); + l += pj; + for (&out, &tol, vf[j * D ..][0..D]) |*o, *tl, vv| { + o.* += pj * vv; + tl.* += pj * @abs(vv); + } + } + var r = i; + while (r < t.lq) : (r += p) { + const at = (r * heads + h) * D; + for (out, tol, 0..) |o, tl, e| { + want[at + e] = o / l; + // P enters P x V at the tensor unit's fp32 (~2^-10 relative); O rounds to fp16 + mag[at + e] = tl / l * 0x1p-9 + @abs(o / l) * 0x1p-10 + 1e-6; + } + } + } + } + } + + pub fn bounds(t: *Attention, want: []const f64, tolerance: []const f64, allow: []f64) !void { + for (want, tolerance, allow) |w, tl, *l| l.* = if (t.stress) c.boundExact(spec(t.name, t.form), w) else if (std.math.isFinite(w)) tl else 0; + } + + pub fn simulate(t: *Attention, acc: c.Accum, order: g.Order, out: []f64) !void { + if (!t.stress) return error.AttentionStressNeedsEqualScores; + const L = t.lk; + const terms = try t.a.alloc(f64, L); + defer t.a.free(terms); + const ones = try t.a.alloc(f64, L); + defer t.a.free(ones); + @memset(ones, 1); + const l = contract.rows.sumIn(acc, order, ones); + for (0..heads) |h| for (0..D) |e| { + for (terms, 0..) |*v, j| v.* = t.v[(h * L + j) * D + e]; + const o = contract.rows.sumIn(acc, order, terms) / l; + for (0..t.lq) |i| out[(i * heads + h) * D + e] = o; + }; + } +}; diff --git a/zig/tests/contract/metal_idol_common.zig b/zig/tests/contract/metal_idol_common.zig new file mode 100644 index 00000000000..222b6b22b48 --- /dev/null +++ b/zig/tests/contract/metal_idol_common.zig @@ -0,0 +1,245 @@ +//! Idol's kernel tests' shared parts: float64 values at fp16 points, their ranges, inputs and the family's library. +const std = @import("std"); +const mtl = @import("metal"); +pub const tf = @import("tensorfold"); +const contract = @import("contract"); +const sources = @import("kernel_sources"); +const rig_ = @import("rig.zig"); + +pub const c = contract.spec; +pub const g = contract.gates; +pub const rows = contract.rows; +pub const ks = tf.idol.kernels; +pub const cfg = tf.idol.config; +pub const H = cfg.hidden; +pub const D = cfg.head_dim; + +pub fn noSums(_: c.Shape) usize { + return 0; +} + +/// A value rounded once to fp16 (the kernels' half(fp32) of a value float64 holds exactly, or float64's own). +pub fn hf(v: f64) f64 { + return @as(f16, @floatCast(v)); +} + +pub fn kref(r: rig_.Ref) ks.Ref { + return .{ .buf = r.buf, .off = r.off }; +} + +/// Every value the kernel may hold at a step: its fp32 steps widen both ends, its fp16 points round them. +pub const Range = struct { + lo: f64, + hi: f64, + pub fn of(v: f64) Range { + return .{ .lo = v, .hi = v }; + } + /// An fp32 step good to `ulps` units in the last place (a correctly rounded one: 0.5). + pub fn fp32(a: Range, ulps: f64) Range { + const u = ulps * 0x1p-23; + return .{ .lo = a.lo - u * @abs(a.lo) - 0x1p-149, .hi = a.hi + u * @abs(a.hi) + 0x1p-149 }; + } + pub fn fp16(a: Range) Range { + return .{ .lo = hf(a.lo), .hi = hf(a.hi) }; + } + pub fn add(a: Range, b: Range) Range { + return .{ .lo = a.lo + b.lo, .hi = a.hi + b.hi }; + } + pub fn neg(a: Range) Range { + return .{ .lo = -a.hi, .hi = -a.lo }; + } + pub fn sub(a: Range, b: Range) Range { + return a.add(b.neg()); + } + pub fn widen(a: Range, e: f64) Range { + return .{ .lo = a.lo - e, .hi = a.hi + e }; + } + pub fn mul(a: Range, b: Range) Range { + const p = [4]f64{ a.lo * b.lo, a.lo * b.hi, a.hi * b.lo, a.hi * b.hi }; + return .{ .lo = @min(@min(p[0], p[1]), @min(p[2], p[3])), .hi = @max(@max(p[0], p[1]), @max(p[2], p[3])) }; + } + /// An increasing function at both ends. + pub fn up(a: Range, comptime f: fn (f64) f64) Range { + return .{ .lo = f(a.lo), .hi = f(a.hi) }; + } + /// 1 / sqrt(a), a positive. + pub fn rsqrt(a: Range) Range { + return .{ .lo = 1 / @sqrt(a.hi), .hi = 1 / @sqrt(a.lo) }; + } + /// 1 / a, a positive. + pub fn recip(a: Range) Range { + return .{ .lo = 1 / a.hi, .hi = 1 / a.lo }; + } + /// a^2 over the range. + pub fn square(a: Range) Range { + const m = @max(a.lo * a.lo, a.hi * a.hi); + return .{ .lo = if (a.lo <= 0 and a.hi >= 0) 0 else @min(a.lo * a.lo, a.hi * a.hi), .hi = m }; + } +}; + +pub fn tanh(x: f64) f64 { + return std.math.tanh(x); +} + +pub fn sqrt(x: f64) f64 { + return @sqrt(x); +} + +// Metal's error bounds with the engine's options (fast math on, the kernels' own `precise::` calls). +pub const div_ulps = 2.5; +pub const rsqrt_ulps = 2; +pub const sqrt_ulps = 3; +pub const exp_ulps = 4; +pub const tanh_ulps = 5; +pub const trig_ulps = 4; + +/// f over [lo, hi] (cos or sin): its ends, and 1 or -1 where an extreme (a multiple of pi past `at`) falls inside. +fn trigOver(lo: f64, hi: f64, comptime f: fn (f64) f64, at: f64) Range { + const pi = std.math.pi; + if (!(hi - lo < 2 * pi)) return .{ .lo = -1, .hi = 1 }; + var out = Range{ .lo = @min(f(lo), f(hi)), .hi = @max(f(lo), f(hi)) }; + var k = @ceil((lo - at) / pi); + while (k * pi + at <= hi) : (k += 1) { + if (@mod(k, 2) == 0) out.hi = 1 else out.lo = -1; + } + return out; +} + +fn cos(x: f64) f64 { + return @cos(x); +} + +fn sin(x: f64) f64 { + return @sin(x); +} + +pub fn cosOver(lo: f64, hi: f64) Range { + return trigOver(lo, hi, cos, 0); +} + +pub fn sinOver(lo: f64, hi: f64) Range { + return trigOver(lo, hi, sin, std.math.pi / 2.0); +} + +/// Each output's float64 value at the kernel's rounding points, and its range, kept for the bounds and intervals. +pub const Ends = struct { + a: std.mem.Allocator, + lo: []f64 = &.{}, + hi: []f64 = &.{}, + + pub fn deinit(e: *Ends) void { + e.a.free(e.lo); + e.a.free(e.hi); + e.lo = &.{}; + e.hi = &.{}; + } + + pub fn size(e: *Ends, n: usize) !void { + e.deinit(); + e.lo = try e.a.alloc(f64, n); + e.hi = try e.a.alloc(f64, n); + } + + pub fn put(e: *Ends, want: []f64, mag: []f64, i: usize, w: f64, r: Range) void { + want[i] = w; + mag[i] = if (std.math.isFinite(w)) @abs(w) else 0; + e.lo[i] = r.lo; + e.hi[i] = r.hi; + } + + /// The allowance about the float64 value: its range's farther end (a non-finite value is checked by class). + pub fn bounds(e: *const Ends, want: []const f64, allow: []f64) void { + for (allow, want, e.lo, e.hi) |*l, w, lo, hi| l.* = if (std.math.isFinite(w)) @max(@abs(w - lo), @abs(hi - w)) else 0; + } + + pub fn intervals(e: *const Ends, low: []f64, high: []f64) void { + @memcpy(low, e.lo); + @memcpy(high, e.hi); + } +}; + +pub fn randomF16(rng: std.Random, out: []f16, lo: f32, hi: f32) void { + for (out) |*v| v.* = @floatCast(lo + rng.float(f32) * (hi - lo)); +} + +pub fn randomF32(rng: std.Random, out: []f32, lo: f32, hi: f32) void { + for (out) |*v| v.* = lo + rng.float(f32) * (hi - lo); +} + +/// An integer in [lo, hi]. +pub fn int(rng: std.Random, lo: i32, hi: i32) f32 { + return @floatFromInt(lo + @as(i32, @intCast(rng.uintLessThan(u32, @intCast(hi - lo + 1))))); +} + +/// +1 or -1. +pub fn sign(rng: std.Random) f32 { + return if (rng.boolean()) 1 else -1; +} + +pub const nan16: f16 = std.math.nan(f16); +pub const inf16: f16 = std.math.inf(f16); +pub const nan32: f32 = std.math.nan(f32); +pub const inf32: f32 = std.math.inf(f32); + +/// [count, width] rows of which row r is `distinct`'s row r % (its rows): a period prime to every tile. +pub fn periodic(comptime T: type, a: std.mem.Allocator, distinct: []const T, width: usize, count: usize) ![]T { + const p = distinct.len / width; + const out = try a.alloc(T, count * width); + for (0..count) |r| @memcpy(out[r * width ..][0..width], distinct[(r % p) * width ..][0..width]); + return out; +} + +/// One text change a control makes to the family's source. +pub const Edit = struct { from: []const u8, to: []const u8 }; + +/// A control: the kernel it breaks, the gate that must go red, its source edits and any text it appends. +pub const Control = struct { kernel: []const u8, what: []const u8, gate: g.Gate = .shapes, edits: []const Edit = &.{}, append: []const u8 = "" }; + +/// The family's source as the engine compiles it (or a control's copy), its pipelines made as tests ask for them. +pub const Lib = struct { + a: std.mem.Allocator, + device: mtl.Device, + ctl: ?Control, + k: ks.Kernels = undefined, + built: bool = false, + made: [ks.names.len]bool = @splat(false), + + fn text(l: *Lib) ![]u8 { + var out = try tf.frags.source(l.device, l.a, sources.idol); + const x = l.ctl orelse return out; + for (x.edits) |e| { + errdefer l.a.free(out); + if (std.mem.count(u8, out, e.from) != 1) { + std.debug.print("control {s}: text not found once: {s}\n", .{ x.what, e.from }); + return error.ControlTextNotFoundOnce; + } + const next = try std.mem.replaceOwned(u8, l.a, out, e.from, e.to); + l.a.free(out); + out = next; + } + if (x.append.len == 0) return out; + defer l.a.free(out); + return std.mem.concat(l.a, u8, &.{ out, "\n", x.append }); + } + + /// The pipeline `name` made on this library (compiled on first use). + pub fn need(l: *Lib, name: []const u8) !void { + if (!l.built) { + const src = try l.text(); + defer l.a.free(src); + l.k.own = try mtl.Library.fromSource(l.device, src, mtl.CompileOptions.mlx()); + l.built = true; + } + for (ks.names, 0..) |n, i| if (std.mem.eql(u8, n, name)) { + if (!l.made[i]) l.k.p[i] = try mtl.Pipeline.init(l.device, l.k.own, n, false); + l.made[i] = true; + return; + }; + return error.NoSuchPipeline; + } + + pub fn deinit(l: *Lib) void { + for (l.k.p, l.made) |p, m| if (m) p.deinit(); + if (l.built) l.k.own.deinit(); + } +}; diff --git a/zig/tests/contract/metal_idol_gemm.zig b/zig/tests/contract/metal_idol_gemm.zig new file mode 100644 index 00000000000..7cb64720f49 --- /dev/null +++ b/zig/tests/contract/metal_idol_gemm.zig @@ -0,0 +1,430 @@ +//! id_linear (plain and GELU), id_split and id_gemm32 under the contract: products against float64, sums proven fp32. +const std = @import("std"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); +const id = @import("metal_idol_common.zig"); + +const c = id.c; +const g = id.g; +const H = id.H; +const Range = id.Range; +const Ends = id.Ends; +const hf = id.hf; +const kref = id.kref; + +/// Rows of x and of w (with the bias) repeat at these periods, prime to every tile: 97 x 131 dots a shape. +const row_period = 97; +const col_period = 131; + +pub const Kind = enum { linear, gelu, split }; + +/// An output's float64 value and its range. +const Out = struct { w: f64, r: Range }; + +/// The M5 tensor unit's fp32 sums: 36 roundings of 2^-24 of |acc| + sum |a b| a 16-deep step (attention_range's). +fn naxDepth(s: c.Shape) usize { + return s.k / 16 * contract.attention_range.mma_step + 8; +} + +/// float64's dot of an fp16 row pair and the tensor unit's allowance on its fp32 sums, step by 16-deep step. +fn naxDot(x: []const f16, w: []const f16) [3]f64 { + var s: f64 = 0; + var spread: f64 = 0; + var mag: f64 = 0; + var i: usize = 0; + while (i < x.len) : (i += 16) { + var t: f64 = 0; + var abs: f64 = 0; + for (x[i..@min(i + 16, x.len)], w[i..@min(i + 16, x.len)]) |a, b| { + const p = @as(f64, a) * @as(f64, b); + t += p; + abs += @abs(p); + } + spread += @abs(s) + abs; + s += t; + mag += abs; + } + return .{ s, spread * contract.attention_range.mma_step * 0x1p-24, mag }; +} + +const gelu_c: f64 = @as(f32, 0.7978845608028654); +const gelu_k: f64 = @as(f32, 0.044715); + +fn inner(x: f64) f64 { + return gelu_c * (x + gelu_k * x * x * x); +} + +/// torch's tanh GELU in float64 at the kernel's fp32 constants. +fn gelu(x: f64) f64 { + return 0.5 * x * (1 + std.math.tanh(inner(x))); +} + +/// The GELU's fp32 steps over a range of fp16 inputs: its inner polynomial rises, tanh rises, the rest as products. +fn geluRange(v: Range) Range { + const t = (Range{ .lo = inner(v.lo), .hi = inner(v.hi) }).fp32(3).up(id.tanh).fp32(id.tanh_ulps); + return (Range{ .lo = 0.5 * v.lo, .hi = 0.5 * v.hi }).mul(t.add(Range.of(1)).fp32(0.5)).fp32(0.5); +} + +const Served = struct { served: []const c.Shape, tiles: [3]c.Tile }; + +/// Forms by (M % 64 == 0)(N % 128 == 0); rows: 64-row tiles in whole-row forms, a last tile's rows first in the rest. +fn envelope(kind: Kind, form: u2) Served { + const row_tail: c.Tile = .{ .size = 64 }; + const row_whole: c.Tile = .{ .size = 2, .step = 1, .min = 1 }; + const col_tail: c.Tile = .{ .size = 128 }; + const col_whole: c.Tile = .{ .size = 256, .step = 128, .min = 128 }; + const k_tile: c.Tile = .{ .size = 256, .step = 32, .min = 32 }; + const rt = if (form & 2 != 0) row_whole else row_tail; + if (kind == .split) return .{ + .served = if (form & 2 != 0) &.{.{ .rows = 8192 / 64, .n = 256, .k = 3 * H }} else &.{ .{ .rows = 6, .n = 256, .k = 3 * H }, .{ .rows = 12294, .n = 256, .k = 3 * H }, .{ .rows = 4101, .n = 256, .k = 3 * H } }, + .tiles = .{ rt, .{}, .{} }, + }; + const ct = if (form & 1 != 0) col_whole else col_tail; + const tiles: [3]c.Tile = .{ rt, ct, k_tile }; + if (kind == .gelu) return .{ + .tiles = tiles, + .served = switch (form) { + 3 => &.{.{ .rows = 8192 / 64, .n = 4 * H, .k = H }}, + 1 => &.{ .{ .rows = 6, .n = 4 * H, .k = H }, .{ .rows = 12294, .n = 4 * H, .k = H }, .{ .rows = 4101, .n = 4 * H, .k = H } }, + // no served call takes a width short of 128 columns: these forms are checked at one + 2 => &.{.{ .rows = 4096 / 64, .n = 1000, .k = H }}, + 0 => &.{ .{ .rows = 5, .n = 1000, .k = H }, .{ .rows = 4101, .n = 1000, .k = H } }, + }, + }; + return .{ .tiles = tiles, .served = switch (form) { + 3 => &.{ .{ .rows = 8192 / 64, .n = 3 * H, .k = H }, .{ .rows = 8192 / 64, .n = H, .k = H }, .{ .rows = 8192 / 64, .n = H, .k = 4 * H } }, + 1 => &.{ .{ .rows = 6, .n = 3 * H, .k = H }, .{ .rows = 12294, .n = 3 * H, .k = H }, .{ .rows = 12294, .n = H, .k = H }, .{ .rows = 12294, .n = H, .k = 4 * H }, .{ .rows = 4101, .n = 3 * H, .k = H }, .{ .rows = 4101, .n = H, .k = H }, .{ .rows = 4101, .n = H, .k = 4 * H } }, + 2 => &.{.{ .rows = 4096 / 64, .n = 1000, .k = H }}, + 0 => &.{ .{ .rows = 5, .n = 1000, .k = H }, .{ .rows = 4101, .n = 1000, .k = H } }, + } }; +} + +/// The pipeline a kind and form run. +pub fn pipeline(kind: Kind, form: u2) []const u8 { + const names = [3][4][]const u8{ + .{ "id_linear_00", "id_linear_01", "id_linear_10", "id_linear_11" }, + .{ "id_linear_gelu_00", "id_linear_gelu_01", "id_linear_gelu_10", "id_linear_gelu_11" }, + .{ "id_split_0", "id_split_0", "id_split_1", "id_split_1" }, + }; + return names[@backingInt(kind)][form]; +} + +pub const Gemm16 = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + lib: *id.Lib, + kind: Kind, + /// split's forms are 1 and 3: its N, 256, is whole 128-column tiles. + form: u2, + name: []const u8, + m: usize = 0, + n: usize = 0, + k: usize = 0, + stress: bool = false, + x: []f16 = &.{}, + w: []f16 = &.{}, + b: []f16 = &.{}, + out: rig_.Ref = undefined, + ins: [3]rig_.Ref = undefined, + ends: Ends, + + pub fn spec(name: []const u8, kind: Kind, form: u2) c.Spec { + const e = envelope(kind, form); + return .{ + .name = name, + .accum = .f32, + .depth = naxDepth, + .ops = 1, + .out = if (kind == .split) .f32 else .f16, + .tiles = e.tiles, + .served = e.served, + }; + } + + pub fn deinit(t: *Gemm16) void { + t.free(); + t.ends.deinit(); + t.rig.deinit(); + } + fn free(t: *Gemm16) void { + t.a.free(t.x); + t.a.free(t.w); + t.a.free(t.b); + t.x = &.{}; + t.w = &.{}; + t.b = &.{}; + } + pub fn kernel(t: *Gemm16, control: ?g.Gate) g.Kernel { + return .{ .spec = spec(t.name, t.kind, t.form), .ctx = t, .vt = &vt, .control = control }; + } + const vt = g.hooks(Gemm16); + + pub fn prepare(t: *Gemm16, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + const m = if (t.form & 2 != 0) shape.rows * 64 else shape.rows; + if (m == 0 or shape.n == 0 or shape.k == 0 or shape.k % 2 != 0) return false; + if (t.kind == .split and (shape.n != 256 or shape.k != 3 * H)) return false; + const form = @as(u2, @intFromBool(m % 64 == 0)) * 2 + @intFromBool(shape.n % 128 == 0); + if (form != t.form) return false; + t.rig.reset(); + t.free(); + t.m = m; + t.n = shape.n; + t.k = shape.k; + t.stress = fill == .stress; + const K = shape.k; + const px = @min(m, row_period); + const pw = @min(shape.n, col_period); + t.x = try t.a.alloc(f16, px * K); + t.w = try t.a.alloc(f16, pw * K); + t.b = try t.a.alloc(f16, pw); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + if (t.stress) { + // integers in [hi / 2, hi), hi^2 K <= 2^24: fp32 sums exact in any order, a 32nd of a half past fp16's + const hi: i32 = @intFromFloat(@sqrt(@as(f64, 0x1p24) / @as(f64, @floatFromInt(K)))); + for (0..px) |r| for (0..K / 2) |i| { + const v = id.int(rng, @divTrunc(hi, 2), hi - 1); + t.x[r * K + i] = @floatCast(v); + // x's halves differ by 1 in their first 8: the sums cancel to a few hundred + t.x[r * K + K / 2 + i] = @floatCast(v - @as(f32, if (i < 8) 1 else 0)); + }; + for (0..pw) |j| for (0..K / 2) |i| { + const v = id.int(rng, @divTrunc(hi, 2), hi - 1); + t.w[j * K + i] = @floatCast(v); + t.w[j * K + K / 2 + i] = @floatCast(-v); + }; + for (t.b) |*v| v.* = @floatCast(id.int(rng, -4, 4)); + } else { + id.randomF16(rng, t.x, -2, 2); + id.randomF16(rng, t.w, -0.25, 0.25); + id.randomF16(rng, t.b, -1, 1); + } + if (fill == .nonfinite) { + const at = [_][2]usize{ .{ 0, K / 3 }, .{ 1, K / 2 }, .{ 2, K - 1 }, .{ 3, 0 }, .{ 3, K - 1 } }; + for (at, [_]f16{ id.nan16, id.inf16, -id.inf16, id.inf16, -id.inf16 }) |p, v| if (p[0] < px) { + t.x[p[0] * K + p[1]] = v; + }; + if (pw > 2) t.b[2] = id.inf16; + } + const xs = try id.periodic(f16, t.a, t.x, K, m); + defer t.a.free(xs); + const ws = try id.periodic(f16, t.a, t.w, K, shape.n); + defer t.a.free(ws); + const bs = try id.periodic(f16, t.a, t.b, 1, shape.n); + defer t.a.free(bs); + t.ins[0] = try t.rig.input(std.mem.sliceAsBytes(xs)); + t.ins[1] = try t.rig.input(std.mem.sliceAsBytes(ws)); + t.ins[2] = try t.rig.input(std.mem.sliceAsBytes(bs)); + t.out = try t.rig.output(m * shape.n * @as(usize, if (t.kind == .split) 4 else 2)); + return true; + } + + pub fn run(t: *Gemm16) !void { + try t.lib.need(pipeline(t.kind, t.form)); + const p = t.rig.begin(); + const k = &t.lib.k; + switch (t.kind) { + .split => k.split(p.e, kref(t.ins[0]), kref(t.ins[1]), kref(t.out), t.m), + else => k.linear(p.e, kref(t.ins[0]), kref(t.ins[1]), kref(t.ins[2]), kref(t.out), t.m, t.n, t.k, t.kind == .gelu), + } + try t.rig.finish(p); + } + + pub fn count(t: *Gemm16) usize { + return t.m * t.n; + } + + /// The output of a sum `s` (range `sr`) of column j: its bias, fp16 rounding and GELU; split's fp32 sum as is. + fn finish(t: *const Gemm16, s: f64, sr: Range, j: usize) Out { + if (t.kind == .split) return .{ .w = s, .r = sr.fp32(0.5) }; + const b: f64 = t.b[j]; + const v = hf(s + b); + const vr = sr.add(Range.of(b)).fp32(0.5).fp16(); + if (t.kind == .linear) return .{ .w = v, .r = vr }; + return .{ .w = hf(gelu(v)), .r = geluRange(vr).fp16() }; + } + + /// The distinct outputs' values and ranges by `value(r, j)`, then every output from its row's and column's. + fn table(t: *Gemm16, ends: *Ends, want: []f64, mag: []f64, ctx: anytype, comptime value: anytype) !void { + const px = t.x.len / t.k; + const pw = t.w.len / t.k; + const tw = try t.a.alloc(f64, 3 * px * pw); + defer t.a.free(tw); + for (0..px) |r| for (0..pw) |j| { + const o = value(ctx, t, r, j); + tw[3 * (r * pw + j) ..][0..3].* = .{ o.w, o.r.lo, o.r.hi }; + }; + for (0..t.m) |r| for (0..t.n) |j| { + const e = tw[3 * ((r % px) * pw + j % pw) ..][0..3]; + ends.put(want, mag, r * t.n + j, e[0], .{ .lo = e[1], .hi = e[2] }); + }; + } + + pub fn reference(t: *Gemm16, want: []f64, mag: []f64) !void { + try t.ends.size(t.count()); + const f = struct { + fn value(_: void, s: *const Gemm16, r: usize, j: usize) Out { + const d = naxDot(s.x[r * s.k ..][0..s.k], s.w[j * s.k ..][0..s.k]); + return s.finish(d[0], if (s.stress) Range.of(d[0]) else Range.of(d[0]).widen(d[1]), j); + } + }; + try t.table(&t.ends, want, mag, {}, f.value); + } + pub fn bounds(t: *Gemm16, want: []const f64, _: []const f64, allow: []f64) !void { + t.ends.bounds(want, allow); + } + pub fn intervals(t: *Gemm16, low: []f64, high: []f64) !void { + t.ends.intervals(low, high); + } + + pub fn simulate(t: *Gemm16, acc: c.Accum, order: g.Order, out: []f64) !void { + const mag = try t.a.alloc(f64, out.len); + defer t.a.free(mag); + var scratch: Ends = .{ .a = t.a }; + defer scratch.deinit(); + try scratch.size(t.count()); + const terms = try t.a.alloc(f64, t.k); + defer t.a.free(terms); + const Ctx = struct { acc: c.Accum, order: g.Order, terms: []f64 }; + const f = struct { + fn value(x: Ctx, s: *const Gemm16, r: usize, j: usize) Out { + for (x.terms, s.x[r * s.k ..][0..s.k], s.w[j * s.k ..][0..s.k]) |*v, a, b| v.* = @as(f64, a) * @as(f64, b); + const sum = id.rows.sumIn(x.acc, x.order, x.terms); + return s.finish(sum, Range.of(sum), j); + } + }; + try t.table(&scratch, out, mag, Ctx{ .acc = acc, .order = order, .terms = terms }, f.value); + } +}; + +// --- id_gemm32: fp32 x [M, K] times w [N, K]^T, sums that must be fp32's (the NAX fp32 path's are not) ----------- + +/// Each 8x8 step's eight FMAs in one chain over K. +fn gemm32Depth(s: c.Shape) usize { + return s.k + 8; +} + +pub const Gemm32 = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + lib: *id.Lib, + name: []const u8, + shape: c.Shape = undefined, + x: []f32 = &.{}, + w: []f32 = &.{}, + ins: [2]rig_.Ref = undefined, + out: rig_.Ref = undefined, + + pub fn spec(name: []const u8) c.Spec { + return .{ + .name = name, + .accum = .f32, + .depth = gemm32Depth, + .out = .f32, + .tiles = .{ .{ .size = 64 }, .{ .size = 64, .step = 8, .min = 8 }, .{ .size = 32, .step = 32, .min = 32 } }, + .served = &.{ .{ .rows = 4101, .n = H, .k = 1280 }, .{ .rows = 4101, .n = H, .k = 128 }, .{ .rows = 8192, .n = 16, .k = H } }, + }; + } + + pub fn deinit(t: *Gemm32) void { + t.free(); + t.rig.deinit(); + } + fn free(t: *Gemm32) void { + t.a.free(t.x); + t.a.free(t.w); + t.x = &.{}; + t.w = &.{}; + } + pub fn kernel(t: *Gemm32, control: ?g.Gate) g.Kernel { + return .{ .spec = spec(t.name), .ctx = t, .vt = &vt, .control = control }; + } + const vt = g.hooks(Gemm32); + + pub fn prepare(t: *Gemm32, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + const n_ok = shape.n % 64 == 0 or (shape.n < 64 and shape.n % 8 == 0); + if (shape.rows == 0 or shape.n == 0 or shape.k == 0 or shape.k % 32 != 0 or !n_ok) return false; + t.rig.reset(); + t.free(); + t.shape = shape; + const K = shape.k; + const px = @min(shape.rows, row_period); + const pw = @min(shape.n, col_period); + t.x = try t.a.alloc(f32, px * K); + t.w = try t.a.alloc(f32, pw * K); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + if (fill == .stress) { + // 13-bit integers against +-1, in turn on either side: exact fp32 products and sums below 2^24 + for (0..px) |r| for (0..K) |i| { + t.x[r * K + i] = id.sign(rng) * if (i % 2 == 0) id.int(rng, 4097, 8191) else 1; + }; + for (0..pw) |j| for (0..K) |i| { + t.w[j * K + i] = id.sign(rng) * if (i % 2 == 1) id.int(rng, 4097, 8191) else 1; + }; + } else { + id.randomF32(rng, t.x, -2, 2); + id.randomF32(rng, t.w, -0.25, 0.25); + } + if (fill == .nonfinite) { + const at = [_][2]usize{ .{ 0, K / 3 }, .{ 1, K / 2 }, .{ 2, K - 1 }, .{ 3, 0 }, .{ 3, K - 1 } }; + for (at, [_]f32{ id.nan32, id.inf32, -id.inf32, id.inf32, -id.inf32 }) |p, v| if (p[0] < px) { + t.x[p[0] * K + p[1]] = v; + }; + } + const xs = try id.periodic(f32, t.a, t.x, K, shape.rows); + defer t.a.free(xs); + const ws = try id.periodic(f32, t.a, t.w, K, shape.n); + defer t.a.free(ws); + t.ins[0] = try t.rig.input(std.mem.sliceAsBytes(xs)); + t.ins[1] = try t.rig.input(std.mem.sliceAsBytes(ws)); + t.out = try t.rig.output(shape.rows * shape.n * 4); + return true; + } + + pub fn run(t: *Gemm32) !void { + try t.lib.need("id_gemm32"); + const p = t.rig.begin(); + t.lib.k.linear32(p.e, kref(t.ins[0]), kref(t.ins[1]), kref(t.out), t.shape.rows, t.shape.n, t.shape.k, t.shape.n); + try t.rig.finish(p); + } + + pub fn count(t: *Gemm32) usize { + return t.shape.rows * t.shape.n; + } + + fn each(t: *Gemm32, want: []f64, mag: []f64, acc: ?c.Accum, order: g.Order) !void { + const K = t.shape.k; + const px = t.x.len / K; + const pw = t.w.len / K; + const tw = try t.a.alloc(f64, 2 * px * pw); + defer t.a.free(tw); + const terms = try t.a.alloc(f64, K); + defer t.a.free(terms); + for (0..px) |r| for (0..pw) |j| { + var s: f64 = 0; + var m: f64 = 0; + for (terms, t.x[r * K ..][0..K], t.w[j * K ..][0..K]) |*v, a, b| { + v.* = @as(f64, a) * @as(f64, b); + s += v.*; + m += @abs(v.*); + } + tw[2 * (r * pw + j) ..][0..2].* = .{ if (acc) |x| id.rows.sumIn(x, order, terms) else s, m }; + }; + for (0..t.shape.rows) |r| for (0..t.shape.n) |j| { + const e = tw[2 * ((r % px) * pw + j % pw) ..][0..2]; + want[r * t.shape.n + j] = e[0]; + mag[r * t.shape.n + j] = e[1]; + }; + } + + pub fn reference(t: *Gemm32, want: []f64, mag: []f64) !void { + try t.each(want, mag, null, .sequential); + } + + pub fn simulate(t: *Gemm32, acc: c.Accum, order: g.Order, out: []f64) !void { + const mag = try t.a.alloc(f64, out.len); + defer t.a.free(mag); + try t.each(out, mag, acc, order); + } +}; diff --git a/zig/tests/contract/metal_idol_norms.zig b/zig/tests/contract/metal_idol_norms.zig new file mode 100644 index 00000000000..c9ea5236595 --- /dev/null +++ b/zig/tests/contract/metal_idol_norms.zig @@ -0,0 +1,251 @@ +//! id_norm, id_norm32 and id_norm_split under the contract: LayerNorm32 in fp32, at idol-sdk's fp16 points. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); +const id = @import("metal_idol_common.zig"); + +const c = id.c; +const g = id.g; +const ks = id.ks; +const cfg = id.cfg; +const H = id.H; +const Range = id.Range; +const Ends = id.Ends; +const hf = id.hf; +const kref = id.kref; + +pub const Kind = enum { norm, norm32, split }; + +const norm_why = "an fp16 output follows the sums as var^-1/2: a bf16 sum's error is a few output ulps"; + +/// A thread's 4 values of the 1,024 in turn, the simdgroup tree, then the tree over the threadgroup's 8 simdgroups. +const sum_depth = 1024 / 256 + 5 + 5; + +fn normDepth(_: c.Shape) usize { + return sum_depth + 3; +} + +pub const Norm = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + lib: *id.Lib, + kind: Kind, + mode: ks.Norm, + name: []const u8, + shape: c.Shape = undefined, + stress: bool = false, + x: []f16 = &.{}, + /// w then b, fp32 + wb: []f32 = &.{}, + /// the modulation's 1 + scale, then its shift, fp16 + mod: []f16 = &.{}, + ins: [5]rig_.Ref = undefined, + out: rig_.Ref = undefined, + ends: Ends, + + /// Rows: positions; n and k: the width, 1,024 (the launcher's). + pub fn spec(name: []const u8, kind: Kind, mode: ks.Norm) c.Spec { + const all: []const c.Shape = &.{ .{ .rows = 12294, .n = H, .k = H }, .{ .rows = 8192, .n = H, .k = H }, .{ .rows = 4101, .n = H, .k = H } }; + return .{ + .name = name, + .accum = .f32, + .depth = normDepth, + .ops = 2 * (id.div_ulps + id.rsqrt_ulps) + 3, + .out = if (kind == .norm32) .f32 else .f16, + .served = switch (kind) { + .norm => switch (mode) { + .modulated => all[0..2], + .affine => all[2..], + // no block calls the plain form: checked at every stream's length + .plain => all, + }, + // the output head's modulated LayerNorm; the affine form at the same rows + .norm32 => all[1..2], + .split => all, + }, + .sums = if (kind == .norm) .{ .bf16 = 0, .why = norm_why } else .{}, + }; + } + + pub fn deinit(t: *Norm) void { + t.free(); + t.ends.deinit(); + t.rig.deinit(); + } + fn free(t: *Norm) void { + t.a.free(t.x); + t.a.free(t.wb); + t.a.free(t.mod); + t.x = &.{}; + t.wb = &.{}; + t.mod = &.{}; + } + pub fn kernel(t: *Norm, control: ?g.Gate) g.Kernel { + return .{ .spec = spec(t.name, t.kind, t.mode), .ctx = t, .vt = &vt, .control = control }; + } + const vt = g.hooks(Norm); + + fn eps(t: *const Norm) f32 { + return if (t.kind == .norm) cfg.block_eps else cfg.default_eps; + } + + pub fn prepare(t: *Norm, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n != H or shape.k != H) return false; + t.rig.reset(); + t.free(); + t.shape = shape; + t.stress = fill == .stress; + t.x = try t.a.alloc(f16, shape.rows * H); + t.wb = try t.a.alloc(f32, 2 * H); + t.mod = try t.a.alloc(f16, 2 * H); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + if (t.stress) { + // integers mirrored in each row's halves: a mean of exactly 0 and squares summing to ~2^22, exact in fp32 + for (0..shape.rows) |r| for (0..H / 2) |i| { + const v = id.int(rng, -64, 64); + t.x[r * H + i] = @floatCast(v); + t.x[r * H + H / 2 + i] = @floatCast(-v); + }; + } else id.randomF16(rng, t.x, -3, 3); + id.randomF32(rng, t.wb[0..H], 0.25, 2); + id.randomF32(rng, t.wb[H..], -1, 1); + id.randomF16(rng, t.mod[0..H], 0.5, 1.5); + id.randomF16(rng, t.mod[H..], -1, 1); + if (fill == .nonfinite) { + const at = [_][2]usize{ .{ 0, H / 3 }, .{ 1, H / 2 }, .{ 2, H - 1 }, .{ 3, 0 }, .{ 3, H - 1 } }; + for (at, [_]f16{ id.nan16, id.inf16, -id.inf16, id.inf16, -id.inf16 }) |p, v| if (p[0] < shape.rows) { + t.x[p[0] * H + p[1]] = v; + }; + t.wb[5] = id.nan32; + t.wb[H + 6] = id.inf32; + t.mod[7] = -id.inf16; + t.mod[H + 8] = id.nan16; + } + t.ins[0] = try t.rig.input(std.mem.sliceAsBytes(t.x)); + t.ins[1] = try t.rig.input(std.mem.sliceAsBytes(t.wb[0..H])); + t.ins[2] = try t.rig.input(std.mem.sliceAsBytes(t.wb[H..])); + t.ins[3] = try t.rig.input(std.mem.sliceAsBytes(t.mod[0..H])); + t.ins[4] = try t.rig.input(std.mem.sliceAsBytes(t.mod[H..])); + t.out = try t.rig.output(t.count() * @as(usize, if (t.kind == .norm32) 4 else 2)); + return true; + } + + pub fn run(t: *Norm) !void { + const k = &t.lib.k; + try t.lib.need(switch (t.kind) { + .norm => "id_norm", + .norm32 => "id_norm32", + .split => "id_norm_split", + }); + const p = t.rig.begin(); + const in = t.ins; + switch (t.kind) { + .norm => k.norm(p.e, kref(in[0]), kref(in[1]), kref(in[2]), kref(in[3]), kref(in[4]), kref(t.out), t.shape.rows, t.eps(), t.mode), + .norm32 => k.norm32(p.e, kref(in[0]), kref(in[1]), kref(in[2]), kref(t.out), t.shape.rows, t.eps(), t.mode), + .split => k.normSplit(p.e, kref(in[0]), kref(in[1]), kref(in[2]), kref(t.out), t.shape.rows, t.eps()), + } + try t.rig.finish(p); + } + + pub fn count(t: *Norm) usize { + return t.shape.rows * H * @as(usize, if (t.kind == .split) 3 else 1); + } + + /// Row r's outputs from the kernel's mean (range `mr`) and sum of squared deviations (range `qr`). + fn row(t: *Norm, ends: *Ends, r: usize, mean: f64, mr: Range, q: f64, qr: Range, want: []f64, mag: []f64) void { + const n: f64 = H; + const e: f64 = t.eps(); + const inv = 1 / @sqrt(q / n + e); + const ir = (Range{ .lo = qr.lo / n, .hi = qr.hi / n }).add(Range.of(e)).fp32(0.5).rsqrt().fp32(id.rsqrt_ulps); + for (0..H) |i| { + const x: f64 = t.x[r * H + i]; + const v = (x - mean) * inv; + const vr = Range.of(x).sub(mr).fp32(0.5).mul(ir).fp32(0.5); + const w: f64 = t.wb[i]; + const b: f64 = t.wb[H + i]; + const s1: f64 = t.mod[i]; + const sh: f64 = t.mod[H + i]; + const at = r * H + i; + switch (t.kind) { + .norm => switch (t.mode) { + .plain => ends.put(want, mag, at, hf(v), vr.fp16()), + .affine => ends.put(want, mag, at, hf(v * w + b), vr.mul(Range.of(w)).fp32(0.5).add(Range.of(b)).fp32(0.5).fp16()), + .modulated => { + const y = vr.fp16().mul(Range.of(s1)).fp32(0.5).fp16().add(Range.of(sh)).fp32(0.5).fp16(); + ends.put(want, mag, at, hf(hf(hf(v) * s1) + sh), y); + }, + }, + .norm32 => switch (t.mode) { + .modulated => ends.put(want, mag, at, v * (1 + w) + b, vr.mul(Range.of(1 + w).fp32(0.5)).fp32(0.5).add(Range.of(b)).fp32(0.5)), + else => ends.put(want, mag, at, v * w + b, vr.mul(Range.of(w)).fp32(0.5).add(Range.of(b)).fp32(0.5)), + }, + .split => { + const y = v * w + b; + const yr = vr.mul(Range.of(w)).fp32(0.5).add(Range.of(b)).fp32(0.5); + const hi = hf(y); + const hr = yr.fp16(); + // hi + lo: lo = fp16(y - hi), y - hi exact in fp32 for whichever fp16 hi the range rounds to + const lr = (Range{ .lo = yr.lo - hr.hi, .hi = yr.hi - hr.lo }).fp16(); + const base = r * 3 * H + i; + ends.put(want, mag, base, hi, hr); + ends.put(want, mag, base + H, hi, hr); + ends.put(want, mag, base + 2 * H, hf(y - hi), lr); + }, + } + } + } + + pub fn reference(t: *Norm, want: []f64, mag: []f64) !void { + try t.ends.size(t.count()); + const n: f64 = H; + const gs = c.gamma(sum_depth, c.unit(.f32)); + const gq = c.gamma(sum_depth + 3, c.unit(.f32)); + for (0..t.shape.rows) |r| { + const xs = t.x[r * H ..][0..H]; + var s: f64 = 0; + var abs: f64 = 0; + for (xs) |v| { + s += v; + abs += @abs(@as(f64, v)); + } + const mean = s / n; + var q: f64 = 0; + for (xs) |v| q += (v - mean) * (v - mean); + if (t.stress) { + // a mean of 0 exactly, the deviations the integers and their squares' sums exact in fp32 + t.row(&t.ends, r, mean, Range.of(mean), q, Range.of(q), want, mag); + continue; + } + const mr = Range{ .lo = (s - gs * abs) / n, .hi = (s + gs * abs) / n }; + // the squares about the kernel's mean exceed float64's by n (m' - mean)^2, then fp32 rounds them + const dm = @max(@abs(mr.lo - mean), @abs(mr.hi - mean)); + const qr = Range{ .lo = q * (1 - gq), .hi = (q + n * dm * dm) * (1 + gq) }; + t.row(&t.ends, r, mean, mr, q, qr, want, mag); + } + } + pub fn bounds(t: *Norm, want: []const f64, _: []const f64, allow: []f64) !void { + t.ends.bounds(want, allow); + } + pub fn intervals(t: *Norm, low: []f64, high: []f64) !void { + t.ends.intervals(low, high); + } + + pub fn simulate(t: *Norm, acc: c.Accum, order: g.Order, out: []f64) !void { + const mag = try t.a.alloc(f64, out.len); + defer t.a.free(mag); + var scratch: Ends = .{ .a = t.a }; + defer scratch.deinit(); + try scratch.size(t.count()); + var terms: [H]f64 = undefined; + for (0..t.shape.rows) |r| { + const xs = t.x[r * H ..][0..H]; + for (&terms, xs) |*v, x| v.* = x; + const mean = contract.rows.sumIn(acc, order, &terms) / H; + for (&terms, xs) |*v, x| v.* = (x - mean) * (x - mean); + const q = contract.rows.sumIn(acc, order, &terms); + t.row(&scratch, r, mean, Range.of(mean), q, Range.of(q), out, mag); + } + } +}; diff --git a/zig/tests/contract/metal_idol_rows.zig b/zig/tests/contract/metal_idol_rows.zig new file mode 100644 index 00000000000..63fa5b1043e --- /dev/null +++ b/zig/tests/contract/metal_idol_rows.zig @@ -0,0 +1,442 @@ +//! id_gate_add, id_embed, id_cond and id_bias32 under the contract: elementwise steps at idol-sdk's fp16 points. +const std = @import("std"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); +const id = @import("metal_idol_common.zig"); + +const c = id.c; +const g = id.g; +const cfg = id.cfg; +const H = id.H; +const Range = id.Range; +const Ends = id.Ends; +const hf = id.hf; +const kref = id.kref; + +/// The steps' common parts: the outputs' ends, and its bounds and intervals from them. +fn Common(comptime T: type) type { + return struct { + pub fn bounds(t: *T, want: []const f64, _: []const f64, allow: []f64) !void { + t.ends.bounds(want, allow); + } + pub fn intervals(t: *T, low: []f64, high: []f64) !void { + t.ends.intervals(low, high); + } + }; +} + +// --- id_gate_add: x = fp16(x + fp16(g y)), in place ------------------------------------------------------------ + +pub const GateAdd = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + lib: *id.Lib, + name: []const u8, + rows: usize = 0, + old: []f16 = &.{}, + y: []f16 = &.{}, + gv: []f16 = &.{}, + ins: [2]rig_.Ref = undefined, + out: rig_.Ref = undefined, + ends: Ends, + + /// Rows: positions; n: the stream's width, 1,024 (the launcher's). + pub fn spec(name: []const u8) c.Spec { + return .{ + .name = name, + .accum = .none, + .depth = id.noSums, + .ops = 1, + .mids = 1, + .out = .f16, + .in_place = true, + .served = &.{ .{ .rows = 12294, .n = H, .k = 1 }, .{ .rows = 8192, .n = H, .k = 1 }, .{ .rows = 4101, .n = H, .k = 1 } }, + }; + } + + pub fn deinit(t: *GateAdd) void { + t.free(); + t.ends.deinit(); + t.rig.deinit(); + } + fn free(t: *GateAdd) void { + t.a.free(t.old); + t.a.free(t.y); + t.a.free(t.gv); + t.old = &.{}; + t.y = &.{}; + t.gv = &.{}; + } + pub fn kernel(t: *GateAdd, control: ?g.Gate) g.Kernel { + return .{ .spec = spec(t.name), .ctx = t, .vt = &vt, .control = control }; + } + const vt = blk: { + var hooks = g.hooks(GateAdd); + hooks.overlap = overlap; + break :blk hooks; + }; + /// The stream is its own output. + fn overlap(_: *anyopaque) bool { + return true; + } + pub const bounds = Common(GateAdd).bounds; + pub const intervals = Common(GateAdd).intervals; + + pub fn prepare(t: *GateAdd, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n != H) return false; + t.rig.reset(); + t.free(); + t.rows = shape.rows; + const n = shape.rows * H; + t.old = try t.a.alloc(f16, n); + t.y = try t.a.alloc(f16, n); + t.gv = try t.a.alloc(f16, H); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + id.randomF16(rng, t.old, -8, 8); + id.randomF16(rng, t.y, -4, 4); + id.randomF16(rng, t.gv, -2, 2); + if (fill == .nonfinite) { + for ([_]f16{ id.nan16, id.inf16, -id.inf16 }, 0..) |v, i| { + t.old[(i * 13) % n] = v; + t.y[(i * 17 + 1) % n] = v; + } + t.gv[5] = id.nan16; + } + t.ins[0] = try t.rig.input(std.mem.sliceAsBytes(t.y)); + t.ins[1] = try t.rig.input(std.mem.sliceAsBytes(t.gv)); + t.out = try t.rig.output(n * 2); + return true; + } + + pub fn run(t: *GateAdd) !void { + try t.lib.need("id_gate_add"); + // in place: the stream's rows go back before each independent run + @memcpy(t.rig.bytes(t.out, t.count() * 2), std.mem.sliceAsBytes(t.old)); + const p = t.rig.begin(); + t.lib.k.gateAdd(p.e, kref(t.out), kref(t.ins[0]), kref(t.ins[1]), t.rows); + try t.rig.finish(p); + } + + pub fn count(t: *GateAdd) usize { + return t.rows * H; + } + + pub fn reference(t: *GateAdd, want: []f64, mag: []f64) !void { + try t.ends.size(t.count()); + for (t.old, t.y, 0..) |xb, yb, i| { + const x: f64 = xb; + const y: f64 = yb; + const gv: f64 = t.gv[i % H]; + const r = Range.of(gv * y).fp32(0.5).fp16().add(Range.of(x)).fp32(0.5).fp16(); + t.ends.put(want, mag, i, hf(x + hf(gv * y)), r); + } + } +}; + +// --- id_embed: x = fp16(fp16(z w^T + b) + pe), z [8192, 16] fp32 -------------------------------------------------- + +/// The 16 inputs' FMA chain. +fn embedDepth(_: c.Shape) usize { + return cfg.latent_channels + 1; +} + +pub const Embed = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + lib: *id.Lib, + name: []const u8, + stress: bool = false, + z: []f32 = &.{}, + /// w [1024, 16] then b [1024] + wb: []f32 = &.{}, + pe: []f16 = &.{}, + ins: [4]rig_.Ref = undefined, + out: rig_.Ref = undefined, + ends: Ends, + + const R = cfg.latent_rows; + const K = cfg.latent_channels; + + /// Rows: the latent's 8,192, which the launcher fixes (a gate's fewer rows run all of them); k: its 16 channels. + pub fn spec(name: []const u8) c.Spec { + return .{ .name = name, .accum = .f32, .depth = embedDepth, .ops = 2, .mids = 1, .out = .f16, .served = &.{.{ .rows = R, .n = H, .k = K }} }; + } + + pub fn deinit(t: *Embed) void { + t.free(); + t.ends.deinit(); + t.rig.deinit(); + } + fn free(t: *Embed) void { + t.a.free(t.z); + t.a.free(t.wb); + t.a.free(t.pe); + t.z = &.{}; + t.wb = &.{}; + t.pe = &.{}; + } + pub fn kernel(t: *Embed, control: ?g.Gate) g.Kernel { + return .{ .spec = spec(t.name), .ctx = t, .vt = &vt, .control = control }; + } + const vt = g.hooks(Embed); + pub const bounds = Common(Embed).bounds; + pub const intervals = Common(Embed).intervals; + + pub fn prepare(t: *Embed, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n != H or shape.k != K) return false; + t.rig.reset(); + t.free(); + t.stress = fill == .stress; + t.z = try t.a.alloc(f32, R * K); + t.wb = try t.a.alloc(f32, H * K + H); + t.pe = try t.a.alloc(f16, R * H); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + if (t.stress) { + // products to 2^16 whose halves cancel but for the first: partial sums near 2^19, exact in fp32 + for (0..R) |r| for (0..K / 2) |k| { + t.z[r * K + k] = id.int(rng, 1, 255); + t.z[r * K + K / 2 + k] = t.z[r * K + k] + @as(f32, if (k == 0) 1 else 0); + }; + for (0..H) |o| for (0..K / 2) |k| { + t.wb[o * K + k] = id.sign(rng) * id.int(rng, 1, 255); + t.wb[o * K + K / 2 + k] = -t.wb[o * K + k]; + }; + for (t.wb[H * K ..]) |*v| v.* = id.int(rng, -8, 8); + for (t.pe) |*v| v.* = @floatCast(id.int(rng, -8, 8)); + } else { + id.randomF32(rng, t.z, -3, 3); + id.randomF32(rng, t.wb, -0.5, 0.5); + id.randomF16(rng, t.pe, -1, 1); + } + if (fill == .nonfinite) { + for ([_]f32{ id.nan32, id.inf32, -id.inf32 }, 0..) |v, i| t.z[i * K + 3 * i] = v; + t.wb[H * K + 9] = id.nan32; + t.pe[5 * H + 11] = id.inf16; + } + t.ins[0] = try t.rig.input(std.mem.sliceAsBytes(t.z)); + t.ins[1] = try t.rig.input(std.mem.sliceAsBytes(t.wb[0 .. H * K])); + t.ins[2] = try t.rig.input(std.mem.sliceAsBytes(t.wb[H * K ..])); + t.ins[3] = try t.rig.input(std.mem.sliceAsBytes(t.pe)); + t.out = try t.rig.output(R * H * 2); + return true; + } + + pub fn run(t: *Embed) !void { + try t.lib.need("id_embed"); + const p = t.rig.begin(); + t.lib.k.embed(p.e, kref(t.ins[0]), kref(t.ins[1]), kref(t.ins[2]), kref(t.ins[3]), kref(t.out)); + try t.rig.finish(p); + } + + pub fn count(_: *Embed) usize { + return R * H; + } + + fn each(t: *Embed, ends: *Ends, want: []f64, mag: []f64, acc: ?c.Accum, order: g.Order) void { + const gd = c.gamma(@floatFromInt(embedDepth(.{ .rows = 1, .n = 1, .k = 1 })), c.unit(.f32)); + var terms: [K]f64 = undefined; + for (0..R) |r| for (0..H) |o| { + var s: f64 = 0; + var abs: f64 = 0; + for (&terms, t.z[r * K ..][0..K], t.wb[o * K ..][0..K]) |*v, z, w| { + v.* = @as(f64, z) * @as(f64, w); + s += v.*; + abs += @abs(v.*); + } + var sr = Range.of(s).widen(gd * abs); + if (acc) |x| { + s = contract.rows.sumIn(x, order, &terms); + sr = Range.of(s); + } else if (t.stress) sr = Range.of(s); + const b: f64 = t.wb[H * K + o]; + const pe: f64 = t.pe[r * H + o]; + const y = sr.add(Range.of(b)).fp32(0.5).fp16().add(Range.of(pe)).fp32(0.5).fp16(); + ends.put(want, mag, r * H + o, hf(hf(s + b) + pe), y); + }; + } + + pub fn reference(t: *Embed, want: []f64, mag: []f64) !void { + try t.ends.size(t.count()); + t.each(&t.ends, want, mag, null, .sequential); + } + + pub fn simulate(t: *Embed, acc: c.Accum, order: g.Order, out: []f64) !void { + const mag = try t.a.alloc(f64, out.len); + defer t.a.free(mag); + var scratch: Ends = .{ .a = t.a }; + defer scratch.deinit(); + try scratch.size(t.count()); + t.each(&scratch, out, mag, acc, order); + } +}; + +// --- id_cond: y = fp16((a + ba) + (c + bc)), the two condition projections' fp32 sums and biases ----------------- + +pub const Cond = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + lib: *id.Lib, + name: []const u8, + rows: usize = 0, + /// a, c [rows, 1024], then ba, bc [1024] + v: []f32 = &.{}, + ins: [4]rig_.Ref = undefined, + out: rig_.Ref = undefined, + ends: Ends, + + /// Rows: the condition's 4,101; n: its width, 1,024 (the launcher's). + pub fn spec(name: []const u8) c.Spec { + return .{ .name = name, .accum = .none, .depth = id.noSums, .ops = 3, .out = .f16, .served = &.{.{ .rows = cfg.cond_rows, .n = H, .k = 1 }} }; + } + + pub fn deinit(t: *Cond) void { + t.a.free(t.v); + t.v = &.{}; + t.ends.deinit(); + t.rig.deinit(); + } + pub fn kernel(t: *Cond, control: ?g.Gate) g.Kernel { + return .{ .spec = spec(t.name), .ctx = t, .vt = &vt, .control = control }; + } + const vt = g.hooks(Cond); + pub const bounds = Common(Cond).bounds; + pub const intervals = Common(Cond).intervals; + + pub fn prepare(t: *Cond, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n != H) return false; + t.rig.reset(); + t.a.free(t.v); + t.rows = shape.rows; + const n = shape.rows * H; + t.v = try t.a.alloc(f32, 2 * n + 2 * H); + var prng = std.Random.DefaultPrng.init(seed); + id.randomF32(prng.random(), t.v, -8, 8); + if (fill == .nonfinite) { + for ([_]f32{ id.nan32, id.inf32, -id.inf32 }, 0..) |v, i| { + t.v[(i * 13) % n] = v; + t.v[n + (i * 17 + 1) % n] = v; + } + t.v[2 * n + 5] = id.inf32; + t.v[2 * n + H + 6] = id.nan32; + } + for (0..4) |i| { + const part = if (i < 2) t.v[i * n ..][0..n] else t.v[2 * n + (i - 2) * H ..][0..H]; + t.ins[i] = try t.rig.input(std.mem.sliceAsBytes(part)); + } + t.out = try t.rig.output(n * 2); + return true; + } + + pub fn run(t: *Cond) !void { + try t.lib.need("id_cond"); + const p = t.rig.begin(); + t.lib.k.cond(p.e, kref(t.ins[0]), kref(t.ins[2]), kref(t.ins[1]), kref(t.ins[3]), kref(t.out), t.rows); + try t.rig.finish(p); + } + + pub fn count(t: *Cond) usize { + return t.rows * H; + } + + pub fn reference(t: *Cond, want: []f64, mag: []f64) !void { + try t.ends.size(t.count()); + const n = t.count(); + for (0..n) |i| { + const av: f64 = t.v[i]; + const cv: f64 = t.v[n + i]; + const ba: f64 = t.v[2 * n + i % H]; + const bc: f64 = t.v[2 * n + H + i % H]; + const r = Range.of(av + ba).fp32(0.5).add(Range.of(cv + bc).fp32(0.5)).fp32(0.5).fp16(); + t.ends.put(want, mag, i, hf((av + ba) + (cv + bc)), r); + } + } +}; + +// --- id_bias32: y += b by column, fp32, in place -------------------------------------------------------------- + +pub const Bias32 = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + lib: *id.Lib, + name: []const u8, + shape: c.Shape = undefined, + old: []f32 = &.{}, + b: []f32 = &.{}, + ins: [1]rig_.Ref = undefined, + out: rig_.Ref = undefined, + ends: Ends, + + /// Rows: the latent's; n: the velocity's 16 channels. + pub fn spec(name: []const u8) c.Spec { + return .{ .name = name, .accum = .none, .depth = id.noSums, .ops = 1, .out = .f32, .in_place = true, .served = &.{.{ .rows = cfg.latent_rows, .n = cfg.latent_channels, .k = 1 }} }; + } + + pub fn deinit(t: *Bias32) void { + t.free(); + t.ends.deinit(); + t.rig.deinit(); + } + fn free(t: *Bias32) void { + t.a.free(t.old); + t.a.free(t.b); + t.old = &.{}; + t.b = &.{}; + } + pub fn kernel(t: *Bias32, control: ?g.Gate) g.Kernel { + return .{ .spec = spec(t.name), .ctx = t, .vt = &vt, .control = control }; + } + const vt = blk: { + var hooks = g.hooks(Bias32); + hooks.overlap = overlap; + break :blk hooks; + }; + /// The sums are their own output. + fn overlap(_: *anyopaque) bool { + return true; + } + pub const bounds = Common(Bias32).bounds; + pub const intervals = Common(Bias32).intervals; + + pub fn prepare(t: *Bias32, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n == 0) return false; + t.rig.reset(); + t.free(); + t.shape = shape; + const n = shape.rows * shape.n; + t.old = try t.a.alloc(f32, n); + t.b = try t.a.alloc(f32, shape.n); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + id.randomF32(rng, t.old, -16, 16); + id.randomF32(rng, t.b, -2, 2); + if (fill == .nonfinite) { + for ([_]f32{ id.nan32, id.inf32, -id.inf32 }, 0..) |v, i| t.old[(i * 13) % n] = v; + if (shape.n > 6) t.b[5] = id.inf32; + } + t.ins[0] = try t.rig.input(std.mem.sliceAsBytes(t.b)); + t.out = try t.rig.output(n * 4); + return true; + } + + pub fn run(t: *Bias32) !void { + try t.lib.need("id_bias32"); + @memcpy(t.rig.bytes(t.out, t.count() * 4), std.mem.sliceAsBytes(t.old)); + const p = t.rig.begin(); + t.lib.k.bias32(p.e, kref(t.out), kref(t.ins[0]), t.shape.rows, t.shape.n); + try t.rig.finish(p); + } + + pub fn count(t: *Bias32) usize { + return t.shape.rows * t.shape.n; + } + + pub fn reference(t: *Bias32, want: []f64, mag: []f64) !void { + try t.ends.size(t.count()); + for (t.old, 0..) |y, i| { + const b: f64 = t.b[i % t.shape.n]; + t.ends.put(want, mag, i, y + b, Range.of(y + b).fp32(0.5)); + } + } +}; diff --git a/zig/tests/contract/metal_idol_steps.zig b/zig/tests/contract/metal_idol_steps.zig new file mode 100644 index 00000000000..0202b284b20 --- /dev/null +++ b/zig/tests/contract/metal_idol_steps.zig @@ -0,0 +1,423 @@ +//! id_repo and id_qk under the contract: RePo's angles in fp32, and the heads rotated, normed and rounded to fp16. +const std = @import("std"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); +const id = @import("metal_idol_common.zig"); + +const c = id.c; +const g = id.g; +const H = id.H; +const D = id.D; +const Range = id.Range; +const Ends = id.Ends; +const hf = id.hf; +const kref = id.kref; + +const streams: []const c.Shape = &.{ .{ .rows = 12294, .n = 512, .k = 128 }, .{ .rows = 8192, .n = 512, .k = 128 }, .{ .rows = 4101, .n = 512, .k = 128 } }; + +// --- id_repo: u = silu(g) c, d = u final^T (48), angles x f pi as cos and sin [rows, 16, 32] -------------------- + +const pi32: f64 = @as(f32, std.math.pi); + +/// d's FMA chain over 128. +fn repoDepth(_: c.Shape) usize { + return 128 + 1; +} + +/// A pair's axis: 10 x, 10 y, then 12 z. +fn axis(j: usize) usize { + return if (j < 10) 0 else if (j < 20) 1 else 2; +} + +pub const Repo = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + lib: *id.Lib, + name: []const u8, + rows: usize = 0, + stress: bool = false, + /// gate sums then content sums, 128 each a row + gc: []f32 = &.{}, + /// the final map [48, 128] + wf: []f32 = &.{}, + freqs: []f32 = &.{}, + inv: f32 = 0.5, + ins: [3]rig_.Ref = undefined, + outs: [2]rig_.Ref = undefined, + ends: Ends, + + /// Rows: positions; n: 16 heads x 32 pairs; k: RePo's hidden width. + pub fn spec(name: []const u8) c.Spec { + return .{ .name = name, .accum = .f32, .depth = repoDepth, .ops = id.exp_ulps + id.div_ulps + 2, .out = .f32, .served = streams }; + } + + pub fn deinit(t: *Repo) void { + t.free(); + t.ends.deinit(); + t.rig.deinit(); + } + fn free(t: *Repo) void { + t.a.free(t.gc); + t.a.free(t.wf); + t.a.free(t.freqs); + t.gc = &.{}; + t.wf = &.{}; + t.freqs = &.{}; + } + pub fn kernel(t: *Repo, control: ?g.Gate) g.Kernel { + return .{ .spec = spec(t.name), .ctx = t, .vt = &vt, .control = control }; + } + const vt = g.hooks(Repo); + + pub fn prepare(t: *Repo, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n != 512 or shape.k != 128) return false; + t.rig.reset(); + t.free(); + t.rows = shape.rows; + t.stress = fill == .stress; + t.gc = try t.a.alloc(f32, shape.rows * 256); + t.wf = try t.a.alloc(f32, 48 * 128); + t.freqs = try t.a.alloc(f32, 32); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + if (t.stress) { + // gates of 20 to 40 (sigmoid 1 in fp32), integer contents: u's halves differ by a gate twice, d small + for (0..shape.rows) |r| for (0..64) |i| { + const gr = t.gc[r * 256 ..][0..256]; + gr[i] = id.int(rng, 20, 40) / t.inv; + gr[i + 64] = gr[i]; + gr[128 + i] = id.sign(rng) * id.int(rng, 1, 8) / t.inv; + gr[128 + i + 64] = gr[128 + i] + @as(f32, if (i < 2) 1 / t.inv else 0); + }; + for (0..48) |o| for (0..64) |i| { + t.wf[o * 128 + i] = id.sign(rng) * id.int(rng, 1, 32); + t.wf[o * 128 + 64 + i] = -t.wf[o * 128 + i]; + }; + id.randomF32(rng, t.freqs, 0.001, 0.01); + } else { + id.randomF32(rng, t.gc, -4, 4); + id.randomF32(rng, t.wf, -0.2, 0.2); + id.randomF32(rng, t.freqs, 0.05, 1.5); + } + if (fill == .nonfinite) { + const at = [_]usize{ 0 * 256 + 5, 1 * 256 + 7, 2 * 256 + 128 + 3 }; + for (at, [_]f32{ id.nan32, id.inf32, -id.inf32 }) |p, v| if (p < t.gc.len) { + t.gc[p] = v; + }; + t.freqs[4] = id.nan32; + } + t.ins[0] = try t.rig.input(std.mem.sliceAsBytes(t.gc)); + t.ins[1] = try t.rig.input(std.mem.sliceAsBytes(t.wf)); + t.ins[2] = try t.rig.input(std.mem.sliceAsBytes(t.freqs)); + for (&t.outs) |*o| o.* = try t.rig.output(shape.rows * 512 * 4); + return true; + } + + pub fn run(t: *Repo) !void { + try t.lib.need("id_repo"); + const p = t.rig.begin(); + t.lib.k.repo(p.e, kref(t.ins[0]), t.inv, kref(t.ins[1]), kref(t.ins[2]), kref(t.outs[0]), kref(t.outs[1]), t.rows); + try t.rig.finish(p); + } + + pub fn count(t: *Repo) usize { + return 2 * t.rows * 512; + } + + /// Row r's u values in float64 and their ranges through the kernel's exp, add, division and product. + fn us(t: *const Repo, r: usize, u: *[128]f64, ur: *[128]Range) void { + const inv: f64 = t.inv; + for (u, ur, 0..) |*v, *vr, i| { + const a = @as(f64, t.gc[r * 256 + i]) * inv; + const cc = @as(f64, t.gc[r * 256 + 128 + i]) * inv; + v.* = a / (1 + @exp(-a)) * cc; + // a >= 20: 1 + exp(-a) is 1 in fp32 and a / 1 is a, so u = a c exactly + if (t.stress) { + v.* = a * cc; + vr.* = Range.of(v.*); + continue; + } + const den = Range.of(@exp(-a)).fp32(id.exp_ulps).add(Range.of(1)).fp32(0.5); + vr.* = Range.of(a).mul(den.recip()).fp32(id.div_ulps).mul(Range.of(cc)).fp32(0.5); + } + } + + /// Row r's outputs from its 48 offsets d (ranges dr). + fn row(t: *Repo, ends: *Ends, r: usize, d: *const [48]f64, dr: *const [48]Range, want: []f64, mag: []f64) void { + for (0..512) |i| { + const h = i / 32; + const j = i % 32; + const x = d[h * 3 + axis(j)]; + const xr = dr[h * 3 + axis(j)]; + const f: f64 = t.freqs[j]; + const th = std.math.tanh(f); + const ang = (x * th + x * (f - th)) * pi32; + // tanh's error cancels between the two products: fp32 rounds each product, the sum and the scale + const xm = @max(@abs(xr.lo), @abs(xr.hi)); + const e = 2 * 0x1p-24 * pi32 * xm * (@abs(th) + 2 * @abs(f - th) + 2 * @abs(f)) + 0x1p-140; + const lo = @min(xr.lo * f, xr.hi * f) * pi32 - e; + const hi = @max(xr.lo * f, xr.hi * f) * pi32 + e; + ends.put(want, mag, r * 512 + i, @cos(ang), id.cosOver(lo, hi).fp32(id.trig_ulps)); + ends.put(want, mag, (t.rows + r) * 512 + i, @sin(ang), id.sinOver(lo, hi).fp32(id.trig_ulps)); + } + } + + pub fn reference(t: *Repo, want: []f64, mag: []f64) !void { + try t.ends.size(t.count()); + const gd = c.gamma(@floatFromInt(repoDepth(.{ .rows = 1, .n = 1, .k = 1 })), c.unit(.f32)); + var u: [128]f64 = undefined; + var ur: [128]Range = undefined; + var d: [48]f64 = undefined; + var dr: [48]Range = undefined; + for (0..t.rows) |r| { + t.us(r, &u, &ur); + for (&d, &dr, 0..) |*dv, *dv_r, o| { + var s: f64 = 0; + var rr = Range.of(0); + var abs: f64 = 0; + for (u, ur, t.wf[o * 128 ..][0..128]) |uv, uvr, wv| { + s += uv * wv; + rr = rr.add(uvr.mul(Range.of(wv))); + abs += @max(@abs(uvr.lo), @abs(uvr.hi)) * @abs(@as(f64, wv)); + } + dv.* = s; + dv_r.* = if (t.stress) rr else rr.widen(gd * abs); + } + t.row(&t.ends, r, &d, &dr, want, mag); + } + } + pub fn bounds(t: *Repo, want: []const f64, _: []const f64, allow: []f64) !void { + t.ends.bounds(want, allow); + } + pub fn intervals(t: *Repo, low: []f64, high: []f64) !void { + t.ends.intervals(low, high); + } + + pub fn simulate(t: *Repo, acc: c.Accum, order: g.Order, out: []f64) !void { + const mag = try t.a.alloc(f64, out.len); + defer t.a.free(mag); + var scratch: Ends = .{ .a = t.a }; + defer scratch.deinit(); + try scratch.size(t.count()); + var u: [128]f64 = undefined; + var ur: [128]Range = undefined; + var d: [48]f64 = undefined; + var dr: [48]Range = undefined; + var terms: [128]f64 = undefined; + for (0..t.rows) |r| { + t.us(r, &u, &ur); + for (&d, &dr, 0..) |*dv, *dv_r, o| { + for (&terms, u, t.wf[o * 128 ..][0..128]) |*v, uv, wv| v.* = uv * wv; + dv.* = contract.rows.sumIn(acc, order, &terms); + dv_r.* = Range.of(dv.*); + } + t.row(&scratch, r, &d, &dr, out, mag); + } + } +}; + +// --- id_qk: (q, k) pairs turned by cos and sin and rounded, F.normalize, times gamma and 8, rounded; v copied ----- + +const qk_why = "an fp16 output follows the head's sum of squares as its square root: a bf16 sum is off a few ulps"; + +/// A lane's two squares, then the simdgroup tree. +fn qkDepth(_: c.Shape) usize { + return 1 + 5; +} + +pub const Qk = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + lib: *id.Lib, + name: []const u8, + rows: usize = 0, + stress: bool = false, + qkv: []f16 = &.{}, + /// gq then gk [1024] each + gam: []f32 = &.{}, + /// cos then sin [rows, 512] each + rot: []f32 = &.{}, + ins: [5]rig_.Ref = undefined, + outs: [3]rig_.Ref = undefined, + ends: Ends, + + /// Rows: positions; n: heads; k: the head width. + pub fn spec(name: []const u8) c.Spec { + return .{ + .name = name, + .accum = .f32, + .depth = qkDepth, + .ops = id.sqrt_ulps + id.div_ulps + 2, + .out = .f16, + .served = &.{ .{ .rows = 12294, .n = 16, .k = D }, .{ .rows = 8192, .n = 16, .k = D }, .{ .rows = 4101, .n = 16, .k = D } }, + .sums = .{ .bf16 = 0, .why = qk_why }, + }; + } + + pub fn deinit(t: *Qk) void { + t.free(); + t.ends.deinit(); + t.rig.deinit(); + } + fn free(t: *Qk) void { + t.a.free(t.qkv); + t.a.free(t.gam); + t.a.free(t.rot); + t.qkv = &.{}; + t.gam = &.{}; + t.rot = &.{}; + } + pub fn kernel(t: *Qk, control: ?g.Gate) g.Kernel { + return .{ .spec = spec(t.name), .ctx = t, .vt = &vt, .control = control }; + } + const vt = g.hooks(Qk); + + pub fn prepare(t: *Qk, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n != 16 or shape.k != D) return false; + t.rig.reset(); + t.free(); + t.rows = shape.rows; + t.stress = fill == .stress; + const n = shape.rows; + t.qkv = try t.a.alloc(f16, n * 3 * H); + t.gam = try t.a.alloc(f32, 2 * H); + t.rot = try t.a.alloc(f32, 2 * n * 512); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + id.randomF16(rng, t.qkv, -4, 4); + id.randomF32(rng, t.gam, 0.25, 2); + for (0..n * 512) |i| { + if (t.stress) { + // quarter turns: exact rotations of integer heads, whose squares sum to ~2^20 exactly + const turns = [4][2]f32{ .{ 1, 0 }, .{ 0, 1 }, .{ -1, 0 }, .{ 0, -1 } }; + const turn = turns[rng.uintLessThan(usize, 4)]; + t.rot[i] = turn[0]; + t.rot[n * 512 + i] = turn[1]; + continue; + } + const angle = rng.float(f32) * 2 * std.math.pi; + t.rot[i] = @cos(angle); + t.rot[n * 512 + i] = @sin(angle); + } + if (t.stress) for (0..n) |r| for (0..2 * H) |i| { + t.qkv[r * 3 * H + i] = @floatCast(id.int(rng, -128, 128)); + }; + if (fill == .nonfinite) { + // q NaN, k +inf, v -inf, in turn; then a NaN cos + const at = [_]usize{ 0 * 3 * H + 0 * D + 5, 1 * 3 * H + H + 2 * D + 9, 2 * 3 * H + 2 * H + 3 * D + 1 }; + for (at, [_]f16{ id.nan16, id.inf16, -id.inf16 }) |p, v| if (p < t.qkv.len) { + t.qkv[p] = v; + }; + if (n > 3) t.rot[3 * 512 + 4 * 32 + 6] = id.nan32; + } + t.ins[0] = try t.rig.input(std.mem.sliceAsBytes(t.qkv)); + t.ins[1] = try t.rig.input(std.mem.sliceAsBytes(t.gam[0..H])); + t.ins[2] = try t.rig.input(std.mem.sliceAsBytes(t.gam[H..])); + t.ins[3] = try t.rig.input(std.mem.sliceAsBytes(t.rot[0 .. n * 512])); + t.ins[4] = try t.rig.input(std.mem.sliceAsBytes(t.rot[n * 512 ..])); + for (&t.outs) |*o| o.* = try t.rig.output(n * H * 2); + return true; + } + + pub fn run(t: *Qk) !void { + try t.lib.need("id_qk"); + const p = t.rig.begin(); + const in = t.ins; + t.lib.k.heads(p.e, kref(in[0]), kref(in[1]), kref(in[2]), kref(in[3]), kref(in[4]), kref(t.outs[0]), kref(t.outs[1]), kref(t.outs[2]), t.rows); + try t.rig.finish(p); + } + + pub fn count(t: *Qk) usize { + return 3 * t.rows * H; + } + + /// Head h of row r of q (0) or k (1): its pairs turned and rounded, as float64 values and ranges. + fn turned(t: *const Qk, which: usize, r: usize, h: usize, v: *[D]f64, vr: *[D]Range) void { + const x = t.qkv[r * 3 * H + which * H + h * D ..][0..D]; + for (0..D / 2) |p| { + const cs: f64 = t.rot[r * 512 + h * 32 + p]; + const sn: f64 = t.rot[(t.rows + r) * 512 + h * 32 + p]; + const a: f64 = x[2 * p]; + const b: f64 = x[2 * p + 1]; + v[2 * p] = hf(a * cs - b * sn); + v[2 * p + 1] = hf(a * sn + b * cs); + const ac = Range.of(a * cs).fp32(0.5); + const bs = Range.of(b * sn).fp32(0.5); + const as_ = Range.of(a * sn).fp32(0.5); + const bc = Range.of(b * cs).fp32(0.5); + vr[2 * p] = ac.sub(bs).fp32(0.5).fp16(); + vr[2 * p + 1] = as_.add(bc).fp32(0.5).fp16(); + } + } + + /// The head's outputs from its sum of squares `ss` (range `ssr`). + fn head(t: *Qk, ends: *Ends, which: usize, r: usize, h: usize, v: *const [D]f64, vr: *const [D]Range, ss: f64, ssr: Range, want: []f64, mag: []f64) void { + const e12: f64 = @as(f32, 1e-12); + // torch's clamp_min keeps a NaN norm (@max would drop it) + const norm = if (std.math.isNan(ss)) ss else @max(@sqrt(ss), e12); + const nr0 = ssr.up(id.sqrt).fp32(id.sqrt_ulps); + const nr = Range{ .lo = @max(nr0.lo, e12), .hi = @max(nr0.hi, e12) }; + const gam = t.gam[which * H + h * D ..][0..D]; + const base = which * t.rows * H + (h * t.rows + r) * D; + for (0..D) |i| { + const gv: f64 = gam[i]; + const w = hf(v[i] / norm * gv * 8); + const rr = vr[i].mul(nr.recip()).fp32(id.div_ulps).mul(Range.of(gv)).fp32(0.5).mul(Range.of(8)).fp32(0.5).fp16(); + ends.put(want, mag, base + i, w, rr); + } + } + + /// v's heads, copied bit for bit. + fn values(t: *Qk, ends: *Ends, want: []f64, mag: []f64) void { + for (0..t.rows) |r| for (0..16) |h| for (0..D) |i| { + const f: f64 = t.qkv[r * 3 * H + 2 * H + h * D + i]; + ends.put(want, mag, 2 * t.rows * H + (h * t.rows + r) * D + i, f, Range.of(f)); + }; + } + + pub fn reference(t: *Qk, want: []f64, mag: []f64) !void { + try t.ends.size(t.count()); + const gd = c.gamma(@floatFromInt(qkDepth(.{ .rows = 1, .n = 1, .k = 1 })), c.unit(.f32)); + var v: [D]f64 = undefined; + var vr: [D]Range = undefined; + for (0..2) |which| for (0..t.rows) |r| for (0..16) |h| { + t.turned(which, r, h, &v, &vr); + var ss: f64 = 0; + var lo: f64 = 0; + var hi: f64 = 0; + for (v, vr) |x, xr| { + ss += x * x; + const q = xr.square(); + lo += q.lo; + hi += q.hi; + } + const ssr = if (t.stress) Range.of(ss) else Range{ .lo = lo * (1 - gd), .hi = hi * (1 + gd) }; + t.head(&t.ends, which, r, h, &v, &vr, ss, ssr, want, mag); + }; + t.values(&t.ends, want, mag); + } + pub fn bounds(t: *Qk, want: []const f64, _: []const f64, allow: []f64) !void { + t.ends.bounds(want, allow); + } + pub fn intervals(t: *Qk, low: []f64, high: []f64) !void { + t.ends.intervals(low, high); + } + + pub fn simulate(t: *Qk, acc: c.Accum, order: g.Order, out: []f64) !void { + const mag = try t.a.alloc(f64, out.len); + defer t.a.free(mag); + var scratch: Ends = .{ .a = t.a }; + defer scratch.deinit(); + try scratch.size(t.count()); + var v: [D]f64 = undefined; + var vr: [D]Range = undefined; + var terms: [D]f64 = undefined; + for (0..2) |which| for (0..t.rows) |r| for (0..16) |h| { + t.turned(which, r, h, &v, &vr); + for (&terms, v) |*s, x| s.* = x * x; + const ss = contract.rows.sumIn(acc, order, &terms); + t.head(&scratch, which, r, h, &v, &vr, ss, Range.of(ss), out, mag); + }; + t.values(&scratch, out, mag); + } +}; diff --git a/zig/tests/contract/metal_limits.zig b/zig/tests/contract/metal_limits.zig index dd38d01f48d..dbdcc8ca8a9 100644 --- a/zig/tests/contract/metal_limits.zig +++ b/zig/tests/contract/metal_limits.zig @@ -32,13 +32,21 @@ pub fn requireMapped(d: limits.MetalLaunch) !void { /// Only launches the loader can build on this device enter the limits compiler; declarations are checked first. pub fn supported(device: mtl.Device, d: limits.MetalLaunch) bool { + if (std.mem.startsWith(u8, d.name, "q27 stack qk ")) return @import("metal_support.zig").tensor(device.tensorUnits(), d.name); if (std.mem.startsWith(u8, d.name, "lfm2 masked prompt ")) return @import("metal_support.zig").tensor(tf.lfm2_moe.source.optionalAvailable(device), d.name); + if (@import("metal_dsv41_limits.zig").tensorOnly(d.name)) + return @import("metal_support.zig").tensor(device.tensorUnits(), d.name); return !std.mem.startsWith(u8, d.name, "qwen27 q8 ") or @import("metal_support.zig").tensor(device.tensorUnits(), d.name); } fn resolve(a: std.mem.Allocator, device: mtl.Device, d: limits.MetalLaunch, comptime assemble: bool) !Launch { const fun = d.name[std.mem.lastIndexOfScalar(u8, d.name, ' ').? + 1 ..]; + if (std.mem.startsWith(u8, d.name, "q27 stack ")) { + if (!assemble) return undefined; + const body = try @import("metal_q27_limits.zig").source(a, d.name); + return .{ .decl = d, .function = fun, .here = body, .pre_m5 = if (d.offline) body else "" }; + } var text: []const u8 = undefined; var head: []const u8 = ""; var frags = false; @@ -180,6 +188,10 @@ fn resolve(a: std.mem.Allocator, device: mtl.Device, d: limits.MetalLaunch, comp const body = try tf.lfm2_moe.source.prompt(device, a, true); return .{ .decl = d, .function = fun, .here = body, .pre_m5 = "" }; } + if (std.mem.startsWith(u8, d.name, "tree round picks ")) { + if (!assemble) return undefined; + return .{ .decl = d, .function = fun, .here = sources.core_tree_round, .pre_m5 = sources.core_tree_round }; + } if (std.mem.startsWith(u8, d.name, "metal lfm2 ")) { if (!assemble) return undefined; return .{ .decl = d, .function = fun, .here = sources.lfm2, .pre_m5 = sources.lfm2 }; @@ -189,6 +201,11 @@ fn resolve(a: std.mem.Allocator, device: mtl.Device, d: limits.MetalLaunch, comp const body = @import("ling_metal").route; return .{ .decl = d, .function = fun, .here = body, .pre_m5 = body }; } + if (std.mem.startsWith(u8, d.name, "metal ling mla ")) { + if (!assemble) return undefined; + const body = @import("ling_metal").mla; + return .{ .decl = d, .function = fun, .here = body, .pre_m5 = body }; + } if (std.mem.startsWith(u8, d.name, "nemotron paged ")) { if (!assemble) return undefined; return pagedLaunch(a, device, d, fun); @@ -273,6 +290,10 @@ fn resolve(a: std.mem.Allocator, device: mtl.Device, d: limits.MetalLaunch, comp if (!assemble) return undefined; text = sources.moss_image; frags = true; + } else if (std.mem.startsWith(u8, d.name, "idol ")) { + if (!assemble) return undefined; + text = sources.idol; + frags = true; } else if (std.mem.startsWith(u8, d.name, "core deltanet ")) { if (!assemble) return undefined; text = sources.core_deltanet; @@ -305,11 +326,18 @@ fn resolve(a: std.mem.Allocator, device: mtl.Device, d: limits.MetalLaunch, comp text = sources.core_simd_qmm; } else if (has(d.name, "affine_mm")) { if (!assemble) return undefined; - const bits: u8 = if (has(d.name, "q8")) 8 else 4; - const group: u16 = if (has(d.name, "g32")) 32 else 64; - head = try std.fmt.allocPrint(a, "#define TF_BITS {d}\n#define TF_GROUP {d}\n#define TF_OUT_T bfloat\n", .{ bits, group }); - text = sources.core_affine_mm; - frags = true; + const bits: u8 = if (has(d.name, "q8")) 8 else if (has(d.name, "q6")) 6 else if (has(d.name, "q5")) 5 else if (has(d.name, "q2")) 2 else 4; + const group: u16 = if (has(d.name, "g128")) 128 else if (has(d.name, "g32")) 32 else 64; + const out_t: []const u8 = if (has(d.name, "fp32")) "float" else "bfloat"; + const m3_head: []const u8 = if (has(d.name, "glm m3")) "#define TF_GLM_M3_FAST 1\n" else ""; + head = try std.fmt.allocPrint(a, "#define TF_BITS {d}\n#define TF_GROUP {d}\n#define TF_OUT_T {s}\n", .{ bits, group, out_t }); + const pre_head = if (m3_head.len == 0) head else try std.mem.concat(a, u8, &.{ head, m3_head }); + const pre = try preM5(a, pre_head, sources.core_affine_mm); + const here = if (device.tensorUnits()) blk: { + const body = try tf.frags.source(device, a, sources.core_affine_mm); + break :blk try std.mem.concat(a, u8, &.{ head, body }); + } else pre; + return .{ .decl = d, .function = fun, .here = here, .pre_m5 = pre }; } else if (has(d.name, "lane projection")) { if (!assemble) return undefined; const sk: usize = if (has(d.name, "sk4")) 4 else 1; diff --git a/zig/tests/contract/metal_ling_mla.zig b/zig/tests/contract/metal_ling_mla.zig new file mode 100644 index 00000000000..46a0dd42040 --- /dev/null +++ b/zig/tests/contract/metal_ling_mla.zig @@ -0,0 +1,327 @@ +//! Ling MLA extras under the contract: GPT-J RoPE on cache and q, and per-head gate expand. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); +const controls = @import("metal_ling_mla_controls.zig"); + +const c = contract.spec; +const g = contract.gates; +const Which = controls.Which; +const Mutation = controls.Mutation; + +const LAT: u32 = 512; +const ROPE: u32 = 64; +const KEY: u32 = LAT + ROPE; +const NOPE: u32 = 128; +const VD: u32 = 128; +const QD: u32 = NOPE + ROPE; +const NFREQ: u32 = ROPE / 2; +const HEADS: u32 = 16; +const THETA: f64 = 6_000_000; +const no_sums: c.Sums = .{ .f16 = 0, .bf16 = 0, .why = "no sums: elementwise rotate or a broadcast" }; + +const MlaRow = extern struct { slot: u32, pos: u32 }; +const MlaArgs = extern struct { + cache: u64, + slot_keys: u32, + heads: u32, + head0: u32, + rows: u32, + q_stride: u32, + kv_stride: u32, + gate_stride: u32, + out_stride: u32, + eps: f32, + scale: f32, +}; +comptime { + if (@sizeOf(MlaArgs) != 48) @compileError("MlaArgs must stay 48 bytes, matching k3"); +} + +fn none(_: c.Shape) usize { + return 0; +} + +fn invFreq(i: usize) f64 { + return 1.0 / std.math.pow(f64, THETA, @as(f64, @floatFromInt(2 * i)) / @as(f64, @floatFromInt(ROPE))); +} + +pub fn spec(w: Which) c.Spec { + const rope = [_]c.Shape{ .{ .rows = 8, .n = HEADS, .k = ROPE }, .{ .rows = 1, .n = HEADS, .k = ROPE } }; + const cache = [_]c.Shape{ .{ .rows = 8, .n = 1, .k = ROPE }, .{ .rows = 1, .n = 1, .k = ROPE } }; + const gate = [_]c.Shape{ .{ .rows = 8, .n = HEADS * VD, .k = HEADS }, .{ .rows = 1, .n = HEADS * VD, .k = HEADS } }; + return switch (w) { + .rope_cache => .{ .name = "metal ling mla tf_ling_mla_rope_cache", .accum = .none, .depth = none, .ops = 2, .mids = 1, .out = .bf16, .in_place = true, .served = &cache, .sums = no_sums }, + .rope_q => .{ .name = "metal ling mla tf_ling_mla_rope_q", .accum = .none, .depth = none, .ops = 2, .mids = 1, .out = .bf16, .in_place = true, .served = &rope, .sums = no_sums }, + .gate_expand => .{ .name = "metal ling mla tf_ling_mla_gate_expand", .accum = .none, .depth = none, .out = .bf16, .served = &gate, .sums = no_sums }, + }; +} + +fn random16(rng: std.Random, out: []u16, lo: f32, hi: f32) void { + for (out) |*v| v.* = c.toBf16(lo + rng.float(f32) * (hi - lo)); +} + +fn plant(v: []u16, stride: usize, rows: usize, col: usize) void { + const put = [_]f32{ std.math.nan(f32), std.math.inf(f32), -std.math.inf(f32) }; + for (put, 0..) |f, r| if (r < rows) { + v[r * stride + col] = c.toBf16(f); + }; +} + +pub const Probe = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + which: Which, + mutation: Mutation, + lib: mtl.Library, + pipe: mtl.Pipeline, + shape: c.Shape = .{ .rows = 0, .n = 0, .k = 0 }, + q: []u16 = &.{}, + cache: []u16 = &.{}, + gate: []u16 = &.{}, + cs: []f32 = &.{}, + rows: []MlaRow = &.{}, + in_cs: rig_.Ref = undefined, + in_rows: rig_.Ref = undefined, + in_g: rig_.Ref = undefined, + out: rig_.Ref = undefined, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, which: Which, mutation: Mutation) !Probe { + const plain = @import("ling_metal").mla; + const src = try controls.apply(a, plain, mutation); + defer a.free(src); + const lib = try mtl.Library.fromSource(device, src, mtl.CompileOptions.mlx()); + errdefer lib.deinit(); + return .{ + .a = a, + .rig = .{ .a = a, .device = device, .queue = queue }, + .which = which, + .mutation = mutation, + .lib = lib, + .pipe = try mtl.Pipeline.init(device, lib, controls.function(which), false), + }; + } + + fn drop(p: *Probe) void { + for ([_]*[]u16{ &p.q, &p.cache, &p.gate }) |s| { + p.a.free(s.*); + s.* = &.{}; + } + p.a.free(p.cs); + p.cs = &.{}; + p.a.free(p.rows); + p.rows = &.{}; + p.rig.reset(); + } + + pub fn deinit(p: *Probe) void { + p.drop(); + p.rig.deinit(); + p.pipe.deinit(); + p.lib.deinit(); + } + + const vt = g.hooks(Probe); + + pub fn kernel(p: *Probe) g.Kernel { + var k: g.Kernel = .{ .spec = spec(p.which), .ctx = p, .vt = &vt }; + if (p.mutation != .none) { + k.spec.name = p.mutation.name(); + k.control = p.mutation.gate(); + } + return k; + } + + pub fn prepare(p: *Probe, s: c.Shape, fill: g.Fill, seed: u64) !bool { + switch (p.which) { + .rope_cache => if (s.k != ROPE or s.n != 1) return false, + .rope_q => if (s.k != ROPE or s.n != HEADS) return false, + .gate_expand => if (s.n != HEADS * VD or s.k != HEADS) return false, + } + if (s.rows == 0) return false; + p.drop(); + p.shape = s; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const rows: u32 = @intCast(s.rows); + p.rows = try p.a.alloc(MlaRow, rows); + for (p.rows, 0..) |*r, t| r.* = .{ .slot = 0, .pos = @intCast(t) }; + p.cs = try p.a.alloc(f32, rows * NFREQ * 2); + for (p.rows, 0..) |r, t| for (0..NFREQ) |i| { + const ang = @as(f64, @floatFromInt(r.pos)) * invFreq(i); + const at = (t * NFREQ + i) * 2; + p.cs[at] = @floatCast(@cos(ang)); + p.cs[at + 1] = @floatCast(@sin(ang)); + }; + p.in_cs = try p.rig.input(std.mem.sliceAsBytes(p.cs)); + switch (p.which) { + .rope_cache => { + p.cache = try p.a.alloc(u16, rows * KEY); + random16(rng, p.cache, -3, 3); + if (fill == .nonfinite) plant(p.cache, KEY, s.rows, LAT); + p.out = try p.rig.output(p.cache.len * 2); + }, + .rope_q => { + p.q = try p.a.alloc(u16, rows * HEADS * QD); + random16(rng, p.q, -3, 3); + if (fill == .nonfinite) plant(p.q, HEADS * QD, s.rows, NOPE); + p.out = try p.rig.output(p.q.len * 2); + }, + .gate_expand => { + p.gate = try p.a.alloc(u16, rows * HEADS); + random16(rng, p.gate, -2, 2); + if (fill == .nonfinite) plant(p.gate, HEADS, s.rows, 0); + p.in_g = try p.rig.input(std.mem.sliceAsBytes(p.gate)); + p.out = try p.rig.output(rows * HEADS * VD * 2); + }, + } + if (p.which == .rope_cache) p.in_rows = try p.rig.input(std.mem.sliceAsBytes(p.rows)); + return true; + } + + pub fn count(p: *Probe) usize { + const rows = p.shape.rows; + return switch (p.which) { + .rope_cache => rows * KEY, + .rope_q => rows * HEADS * QD, + .gate_expand => rows * HEADS * VD, + }; + } + + fn args(p: *Probe) MlaArgs { + const rows: u32 = @intCast(p.shape.rows); + return .{ + .cache = if (p.which == .rope_cache) p.out.buf.gpuAddress() + p.out.off else 0, + .slot_keys = rows, + .heads = HEADS, + .head0 = 0, + .rows = rows, + .q_stride = HEADS * QD, + .kv_stride = KEY, + .gate_stride = HEADS * VD, + .out_stride = HEADS * VD, + .eps = 1e-6, + .scale = 1, + }; + } + + pub fn run(p: *Probe) !void { + const rows = p.shape.rows; + switch (p.which) { + .rope_cache => @memcpy(p.rig.bytes(p.out, p.cache.len * 2), std.mem.sliceAsBytes(p.cache)), + .rope_q => @memcpy(p.rig.bytes(p.out, p.q.len * 2), std.mem.sliceAsBytes(p.q)), + .gate_expand => {}, + } + const pass = p.rig.begin(); + const e = pass.e; + e.setPipeline(p.pipe); + const aa = p.args(); + switch (p.which) { + .rope_cache => { + e.setBuffer(p.in_rows.buf, p.in_rows.off, 0); + e.setValue(aa, 1); + e.setBuffer(p.in_cs.buf, p.in_cs.off, 2); + e.useResource(p.out.buf, mtl.ResourceUsage.read | mtl.ResourceUsage.write); + e.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(32, 1, 1)); + }, + .rope_q => { + e.setBuffer(p.out.buf, p.out.off, 0); + e.setValue(aa, 1); + e.setBuffer(p.in_cs.buf, p.in_cs.off, 2); + e.dispatchGroups(mtl.Size.of(HEADS, rows, 1), mtl.Size.of(32, 1, 1)); + }, + .gate_expand => { + e.setBuffer(p.in_g.buf, p.in_g.off, 0); + e.setBuffer(p.out.buf, p.out.off, 1); + e.setValue(aa, 2); + e.dispatchThreads(mtl.Size.of(HEADS * VD, rows, 1), mtl.Size.of(128, 1, 1)); + }, + } + try p.rig.finish(pass); + } + + pub fn reference(p: *Probe, want: []f64, mag: []f64) !void { + const rows = p.shape.rows; + switch (p.which) { + .rope_cache => for (0..rows) |t| { + const z = p.cache[t * KEY ..][0..KEY]; + for (0..LAT) |i| { + want[t * KEY + i] = c.fromBf16(z[i]); + mag[t * KEY + i] = @abs(want[t * KEY + i]); + } + rotateRef(want[t * KEY + LAT ..][0..ROPE], mag[t * KEY + LAT ..][0..ROPE], z[LAT..][0..ROPE], p.cs[t * NFREQ * 2 ..][0 .. NFREQ * 2]); + }, + .rope_q => for (0..rows) |t| for (0..HEADS) |h| { + const base = (t * HEADS + h) * QD; + const z = p.q[base..][0..QD]; + for (0..NOPE) |i| { + want[base + i] = c.fromBf16(z[i]); + mag[base + i] = @abs(want[base + i]); + } + rotateRef(want[base + NOPE ..][0..ROPE], mag[base + NOPE ..][0..ROPE], z[NOPE..][0..ROPE], p.cs[t * NFREQ * 2 ..][0 .. NFREQ * 2]); + }, + .gate_expand => for (0..rows) |t| for (0..HEADS) |h| { + const v = c.fromBf16(p.gate[t * HEADS + h]); + const lo = (t * HEADS + h) * VD; + for (0..VD) |d| { + want[lo + d] = v; + mag[lo + d] = @abs(v); + } + }, + } + } +}; + +fn rotateRef(want: []f64, mag: []f64, z: []const u16, cs: []const f32) void { + for (0..NFREQ) |i| { + const x0: f64 = c.fromBf16(z[2 * i]); + const x1: f64 = c.fromBf16(z[2 * i + 1]); + const cv: f64 = cs[i * 2]; + const sv: f64 = cs[i * 2 + 1]; + want[i] = x0 * cv - x1 * sv; + want[NFREQ + i] = x1 * cv + x0 * sv; + mag[i] = @abs(x0) * @abs(cv) + @abs(x1) * @abs(sv); + mag[NFREQ + i] = mag[i]; + } +} + +fn wanted(only: ?[]const u8, name: []const u8) bool { + const needle = only orelse return true; + return std.mem.indexOf(u8, name, needle) != null; +} + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + probes: std.ArrayList(*Probe) = .empty, + + pub fn collect(s: *Suite, kernels: *std.ArrayList(g.Kernel), only: ?[]const u8) !void { + for (std.enums.values(Which)) |w| { + const name = spec(w).name; + if (!wanted(only, name)) continue; + const p = try s.a.create(Probe); + errdefer s.a.destroy(p); + p.* = try Probe.init(s.a, s.device, s.queue, w, .none); + try s.probes.append(s.a, p); + try kernels.append(s.a, p.kernel()); + } + for (std.enums.values(Mutation)) |m| { + if (m == .none or !wanted(only, m.name())) continue; + const p = try s.a.create(Probe); + errdefer s.a.destroy(p); + p.* = try Probe.init(s.a, s.device, s.queue, m.which(), m); + try s.probes.append(s.a, p); + try kernels.append(s.a, p.kernel()); + } + } + + pub fn deinit(s: *Suite) void { + for (s.probes.items) |p| { + p.deinit(); + s.a.destroy(p); + } + s.probes.deinit(s.a); + } +}; diff --git a/zig/tests/contract/metal_ling_mla_controls.zig b/zig/tests/contract/metal_ling_mla_controls.zig new file mode 100644 index 00000000000..31e96a46462 --- /dev/null +++ b/zig/tests/contract/metal_ling_mla_controls.zig @@ -0,0 +1,88 @@ +//! Planted controls for Ling MLA extras: one source edit a kernel, which gate 3 must report. +const std = @import("std"); +const contract = @import("contract"); + +pub const Which = enum { rope_cache, rope_q, gate_expand }; + +pub fn function(w: Which) []const u8 { + return switch (w) { + .rope_cache => "tf_ling_mla_rope_cache", + .rope_q => "tf_ling_mla_rope_q", + .gate_expand => "tf_ling_mla_gate_expand", + }; +} + +pub const Mutation = enum { + none, + rope_cache_cs0, + rope_q_cs0, + gate_head0, + + pub fn name(m: Mutation) []const u8 { + return switch (m) { + .none => "", + .rope_cache_cs0 => "control: metal ling mla rope_cache, every row rotates at cs[0]", + .rope_q_cs0 => "control: metal ling mla rope_q, every row rotates at cs[0]", + .gate_head0 => "control: metal ling mla gate_expand, every head takes gate 0", + }; + } + + pub fn gate(m: Mutation) ?contract.gates.Gate { + return switch (m) { + .none => null, + else => .shapes, + }; + } + + pub fn which(m: Mutation) Which { + return switch (m) { + .none => unreachable, + .rope_cache_cs0 => .rope_cache, + .rope_q_cs0 => .rope_q, + .gate_head0 => .gate_expand, + }; + } + + const Edit = struct { from: []const u8, to: []const u8 }; + + fn edit(m: Mutation) Edit { + return switch (m) { + .none => unreachable, + .rope_cache_cs0 => .{ + .from = "const float2 o = ling_apply(float(dst[2 * t]), float(dst[2 * t + 1]), cs, row, t);", + .to = "const float2 o = ling_apply(float(dst[2 * t]), float(dst[2 * t + 1]), cs, 0, t);", + }, + .rope_q_cs0 => .{ + .from = "const float2 o = ling_apply(float(z[2 * t]), float(z[2 * t + 1]), cs, row, t);", + .to = "const float2 o = ling_apply(float(z[2 * t]), float(z[2 * t + 1]), cs, 0, t);", + }, + .gate_head0 => .{ + .from = "g2[row * a.gate_stride + col] = g[row * a.heads + col / VD];", + .to = "g2[row * a.gate_stride + col] = g[row * a.heads];", + }, + }; + } +}; + +pub fn apply(a: std.mem.Allocator, text: []const u8, m: Mutation) ![]u8 { + if (m == .none) return a.dupe(u8, text); + const e = m.edit(); + if (std.mem.count(u8, text, e.from) != 1) return error.ControlEditMissing; + return std.mem.replaceOwned(u8, a, text, e.from, e.to); +} + +test "ling mla source control: each edit hits once" { + const a = std.testing.allocator; + const plain = @import("ling_metal").mla; + for (std.enums.values(Mutation)) |m| { + if (m == .none) continue; + const edited = try apply(a, plain, m); + defer a.free(edited); + try std.testing.expect(std.mem.indexOf(u8, edited, m.edit().to) != null); + try std.testing.expectError(error.ControlEditMissing, apply(a, edited, m)); + try std.testing.expectEqual(contract.gates.Gate.shapes, m.gate().?); + } + const unchanged = try apply(a, plain, .none); + defer a.free(unchanged); + try std.testing.expectEqualStrings(plain, unchanged); +} diff --git a/zig/tests/contract/metal_main.zig b/zig/tests/contract/metal_main.zig index c72b53086c5..65daae0ddeb 100644 --- a/zig/tests/contract/metal_main.zig +++ b/zig/tests/contract/metal_main.zig @@ -8,6 +8,7 @@ const affine_k = @import("metal_affine.zig"); const gather_k = @import("metal_affine_gather.zig"); const topk_k = @import("metal_topk.zig"); const ling_route = @import("metal_ling_route.zig"); +const ling_mla = @import("metal_ling_mla.zig"); const tile_k = @import("metal_tile.zig"); const h3_k = @import("metal_h3.zig"); const h3_topk = @import("metal_h3_topk.zig"); @@ -68,6 +69,15 @@ const common = [_]Reg{ .{ .v = .{ .kind = .affine_mm, .bits = 4, .group = 64, .f32_out = true }, .name = "metal affine_mm q4 g64 fp32 out" }, .{ .v = .{ .kind = .affine_mm, .bits = 8, .group = 32 }, .name = "metal affine_mm q8 g32" }, .{ .v = .{ .kind = .affine_mm, .bits = 8, .group = 64 }, .name = "metal affine_mm q8 g64" }, + .{ .v = .{ .kind = .affine_mm, .bits = 4, .group = 64, .glm_m3_fast = true }, .name = "metal affine_mm glm m3 q4 g64" }, + .{ .v = .{ .kind = .affine_mm, .bits = 4, .group = 64, .f32_out = true, .glm_m3_fast = true }, .name = "metal affine_mm glm m3 q4 g64 fp32 out" }, + .{ .v = .{ .kind = .affine_mm, .bits = 2, .group = 64, .glm_m3_fast = true }, .name = "metal affine_mm glm m3 q2 g64" }, + .{ .v = .{ .kind = .affine_mm, .bits = 5, .group = 64, .glm_m3_fast = true }, .name = "metal affine_mm glm m3 q5 g64" }, + .{ .v = .{ .kind = .affine_mm, .bits = 6, .group = 64, .glm_m3_fast = true }, .name = "metal affine_mm glm m3 q6 g64" }, + .{ .v = .{ .kind = .affine_mm, .bits = 8, .group = 64, .glm_m3_fast = true }, .name = "metal affine_mm glm m3 q8 g64" }, + .{ .v = .{ .kind = .affine_mm, .bits = 4, .group = 32, .glm_m3_fast = true }, .name = "metal affine_mm glm m3 q4 g32" }, + .{ .v = .{ .kind = .affine_mm, .bits = 4, .group = 128, .glm_m3_fast = true }, .name = "metal affine_mm glm m3 q4 g128" }, + .{ .v = .{ .kind = .affine_mm, .bits = 4, .group = 64, .glm_m3_fast = true, .control = true }, .name = "control: metal affine_mm glm m3 q4 g64, wrong row tile height" }, .{ .v = .{ .kind = .simd, .bits = 4, .group = 64 }, .name = "metal simd_qmm q4 g64" }, .{ .v = .{ .kind = .simd_bits, .bits = 3, .group = 64 }, .name = "metal simd_qmm_bits q3 g64" }, .{ .v = .{ .kind = .simd_bits, .bits = 6, .group = 64 }, .name = "metal simd_qmm_bits q6 g64" }, @@ -209,6 +219,12 @@ pub fn main(init: std.process.Init) !u8 { if (wanted(o, mixed.kernel().spec.name)) { if (@import("metal_support.zig").tensor(tensor, mixed.kernel().spec.name)) try kernels.append(a, mixed.kernel()); } + var picks: @import("metal_tree_round_picks.zig").Suite = .{}; + defer picks.deinit(a); + try picks.collect(a, device, queue, o.only, &kernels); + var q27_stack: @import("metal_q27_stack.zig").Suite = .{}; + defer q27_stack.deinit(a); + try q27_stack.collect(a, device, queue, o.only, &kernels); var lfm2: @import("metal_lfm2_suite.zig").Suite = .{ .a = a, .device = device, .queue = queue, .kernels = &kernels }; defer lfm2.deinit(); try lfm2.collect(o.only); @@ -353,6 +369,9 @@ pub fn main(init: std.process.Init) !u8 { ling = try ling_route.Route.init(a, device, queue); try kernels.append(a, ling.?.kernel()); } + var ling_mla_set = ling_mla.Suite{ .a = a, .device = device, .queue = queue }; + defer ling_mla_set.deinit(); + try ling_mla_set.collect(&kernels, o.only); for ([_][]const Reg{ &common, if (tensor) &m5_only else &.{} }) |list| for (list) |v| { if (!wanted(o, v.name)) continue; const p = try a.create(affine_k.Proj); @@ -371,14 +390,15 @@ pub fn main(init: std.process.Init) !u8 { } gathers.deinit(a); } - if (tensor) for (gather_k.registered) |v| { + for (gather_k.registered) |v| { + if (!tensor and !v.glm_m3_fast) continue; if (!wanted(o, gather_k.name(v))) continue; const p = try a.create(gather_k.Gather); errdefer a.destroy(p); p.* = try gather_k.Gather.init(a, device, queue, v); try gathers.append(a, p); try kernels.append(a, p.kernel()); - }; + } var h3_list: std.ArrayList(*h3_k.H3) = .empty; defer for (h3_list.items) |x| x.deinit(); var qwen3_heads: @import("metal_qwen3_heads.zig").Suite = .{}; @@ -536,6 +556,10 @@ pub fn main(init: std.process.Init) !u8 { defer moss_image_decoder.destroy(); var dsv41_suites = try @import("metal_dsv41_main.zig").Suites.create(a, device, queue, &kernels, o.only); defer dsv41_suites.destroy(); + const idol = try @import("metal_idol.zig").Suite.create(a, device, queue, &kernels, o.only); + defer idol.destroy(); + const glm_prompt = try @import("metal_glm_prompt.zig").Suite.create(a, device, queue, &kernels, o.only); + defer glm_prompt.destroy(); var t: g.Tally = .{}; const t0 = std.Io.Clock.awake.now(init.io); if (o.gates) { diff --git a/zig/tests/contract/metal_mapping_test.zig b/zig/tests/contract/metal_mapping_test.zig index 741a7a86218..abf540ea8f8 100644 --- a/zig/tests/contract/metal_mapping_test.zig +++ b/zig/tests/contract/metal_mapping_test.zig @@ -37,3 +37,22 @@ test "Metal launch map: LFM2 masked prompt follows its loader on each device cla try launches.requireMapped(base); try std.testing.expect(launches.supported(.{ .units = false }, base)); } + +test "Metal launch map: DeepSeek-V4.1 tensor-unit expert launches follow their loader" { + var units: usize = 0; + var simd: usize = 0; + for (registry.all_metal) |d| { + if (std.mem.startsWith(u8, d.name, "dsv41 xmma units ")) { + units += 1; + try launches.requireMapped(d); + try std.testing.expect(!launches.supported(.{ .units = false }, d)); + try std.testing.expect(launches.supported(.{ .units = true }, d)); + } else if (std.mem.startsWith(u8, d.name, "dsv41 xmma ")) { + simd += 1; + try launches.requireMapped(d); + try std.testing.expect(launches.supported(.{ .units = false }, d)); + } + } + try std.testing.expectEqual(@as(usize, 4), units); + try std.testing.expectEqual(@as(usize, 4), simd); +} diff --git a/zig/tests/contract/metal_q27_columns.zig b/zig/tests/contract/metal_q27_columns.zig new file mode 100644 index 00000000000..c3df8bd1254 --- /dev/null +++ b/zig/tests/contract/metal_q27_columns.zig @@ -0,0 +1,143 @@ +//! Column scans retain the slot kernel's bytes and the independent parent-indexed FP64 recurrence. +const std = @import("std"); +const mtl = @import("metal"); +const tf = @import("tensorfold"); +const contract = @import("contract"); +const sources = @import("kernel_sources"); +const rig_ = @import("rig.zig"); +const c = contract.spec; +const g = contract.gates; +const ref = contract.delta_slots_ref; +const sums = contract.q27_stack_sums; +fn none(_: c.Shape) usize { + return 0; +} +pub const Probe = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + arena: std.heap.ArenaAllocator, + pipe: mtl.Pipeline, + old: mtl.Pipeline, + slots: usize, + bad: bool, + precision_bad: bool, + name: []const u8, + f: ref.Fixture = undefined, + nonfinite: bool = false, + ins: [8]rig_.Ref = undefined, + steps: rig_.Ref = undefined, + parents: rig_.Ref = undefined, + out: rig_.Ref = undefined, + base: rig_.Ref = undefined, + scratch: rig_.Ref = undefined, + before: rig_.Ref = undefined, + + pub fn init(a: std.mem.Allocator, d: mtl.Device, q: mtl.Queue, slots: usize, bad: bool, precision_bad: bool, name: []const u8) !Probe { + const text = if (precision_bad) try std.mem.replaceOwned(u8, a, sources.core_deltanet, "result += t[part] * qi[part];", "result = float(half(result + t[part] * qi[part]));") else if (bad) try std.mem.replaceOwned(u8, a, sources.core_deltanet, "row = flow & 0xffffu;", "row = 0u;") else try a.dupe(u8, sources.core_deltanet); + defer a.free(text); + var buf: [80]u8 = undefined; + const pipe = try rig_.pipeline(d, text, try std.fmt.bufPrint(&buf, "tf_delta_gdn_columns_{d}", .{slots})); + errdefer pipe.deinit(); + const old = try rig_.pipeline(d, sources.core_deltanet, try std.fmt.bufPrint(&buf, "tf_delta_gdn_tree_slots_{d}", .{slots})); + return .{ .a = a, .rig = .{ .a = a, .device = d, .queue = q }, .arena = .init(a), .pipe = pipe, .old = old, .slots = slots, .bad = bad, .precision_bad = precision_bad, .name = name }; + } + + pub fn kernel(p: *Probe) g.Kernel { + return .{ .ctx = p, .vt = &g.hooks(Probe), .control = if (p.precision_bad) .sums else if (p.bad) .shapes else null, .spec = .{ + .name = p.name, + .accum = .f32, + .out = .bf16, + .depth = none, + .served = &.{ .{ .rows = 1, .n = 128, .k = 128 }, .{ .rows = 3, .n = 128, .k = 128 }, .{ .rows = 15, .n = 128, .k = 128 } }, + .replaces = "tf_delta_gdn_tree_slots on the same flow schedule", + .nan = .{ .stated = "planted NaN and infinity classes and all finite bytes equal the slot recurrence" }, + .sums = .{ .exact = true, .f16 = 100, .bf16 = 0, .why = "exact read sums plus replacement bytes and independent FP64 recurrence; cancellation can hide BF16 sums" }, + } }; + } + pub fn prepare(p: *Probe, s: c.Shape, fill: g.Fill, seed: u64) !bool { + if (s.n != 128 or s.k != 128 or s.rows == 0 or s.rows > 15) return false; + p.nonfinite = fill == .nonfinite; + p.rig.reset(); + _ = p.arena.reset(.retain_capacity); + const a = p.arena.allocator(); + p.f = try ref.make(tf.tree_slots, a, p.slots, s.rows, false, seed); + if (fill == .nonfinite) { + p.f.query[0] = c.toBf16(std.math.nan(f32)); + p.f.value[128] = c.toBf16(std.math.inf(f32)); + } + if (fill == .stress) ref.exactRead(&p.f); + const f = p.f; + const flows = try a.alloc(u32, f.steps.len); + for (f.segments) |seg| { + const at = seg.first; + const steps: []const tf.tree_slots.Step = @ptrCast(f.steps[at..][0..seg.rows]); + if (!tf.tree_slots.flows(steps, flows[at..][0..seg.rows])) return error.InvalidFlowFixture; + } + p.ins = .{ + try p.rig.input(std.mem.sliceAsBytes(f.query)), try p.rig.input(std.mem.sliceAsBytes(f.key)), + try p.rig.input(std.mem.sliceAsBytes(f.value)), try p.rig.input(std.mem.sliceAsBytes(f.decay)), + try p.rig.input(std.mem.sliceAsBytes(f.mixing)), try p.rig.input(std.mem.sliceAsBytes(f.state)), + try p.rig.input(std.mem.asBytes(&f.segments)), try p.rig.input(std.mem.sliceAsBytes(flows)), + }; + p.parents = try p.rig.input(std.mem.sliceAsBytes(f.parents)); + p.steps = try p.rig.input(std.mem.sliceAsBytes(f.steps)); + p.out = try p.rig.output(f.output.len * 2); + p.base = try p.rig.scratch(f.output.len * 2); + p.scratch = try p.rig.scratch(256); + p.before = try p.rig.scratch(f.state.len * 4); + return true; + } + pub fn run(p: *Probe) !void { + const pass = p.rig.begin(); + const e = pass.e; + e.setPipeline(p.pipe); + for (p.ins[0..7], 0..) |b, i| e.setBuffer(b.buf, b.off, i); + e.setValue(p.f.p, 7); + e.setBuffer(p.out.buf, p.out.off, 8); + e.setBuffer(p.ins[7].buf, p.ins[7].off, 9); + e.dispatchGroups(mtl.Size.of(1, 32, 96), mtl.Size.of(32, 1, 1)); + try p.rig.finish(pass); + } + pub fn replaced(p: *Probe) ![]const u8 { + const pass = p.rig.begin(); + const e = pass.e; + e.setPipeline(p.old); + for (p.ins[0..6], 0..) |b, i| e.setBuffer(b.buf, b.off, i); + e.setBuffer(p.parents.buf, p.parents.off, 6); + e.setBuffer(p.ins[6].buf, p.ins[6].off, 7); + e.setValue(p.f.p, 8); + e.setBuffer(p.base.buf, p.base.off, 9); + e.setBuffer(p.scratch.buf, p.scratch.off, 10); + e.setBuffer(p.steps.buf, p.steps.off, 11); + e.setBuffer(p.ins[5].buf, p.ins[5].off, 12); + e.setBuffer(p.before.buf, p.before.off, 13); + e.dispatchThreads(mtl.Size.of(32, 128, 96), mtl.Size.of(32, 4, 1)); + try p.rig.finish(pass); + const bytes = p.rig.bytes(p.base, p.count() * 2); + if (!p.nonfinite and !p.f.accepts(bytes)) return error.SlotBaselineOutsideFp64Bound; + return bytes; + } + pub fn check(p: *Probe, gate: g.Gate) !?[]const u8 { + const out = p.rig.bytes(p.out, p.count() * 2); + const baseline = try p.replaced(); + if (!std.mem.eql(u8, out, baseline)) return "column bytes differ from register-slot bytes"; + if (gate != .nonfinite and !p.f.accepts(out)) return "column output leaves independent FP64 recurrence bound"; + return null; + } + pub fn deinit(p: *Probe) void { + p.pipe.deinit(); + p.old.deinit(); + p.rig.deinit(); + p.arena.deinit(); + } + pub fn count(p: *Probe) usize { + return p.f.output.len; + } + pub fn simulate(_: *Probe, acc: c.Accum, order: g.Order, out: []f64) !void { + @memset(out, sums.output(.columns, 0, acc, order)); + } + pub fn reference(p: *Probe, want: []f64, mag: []f64) !void { + @memcpy(want, p.f.output); + @memset(mag, 0); + } +}; diff --git a/zig/tests/contract/metal_q27_glue.zig b/zig/tests/contract/metal_q27_glue.zig new file mode 100644 index 00000000000..3691db5864f --- /dev/null +++ b/zig/tests/contract/metal_q27_glue.zig @@ -0,0 +1,193 @@ +//! Flat GDN preparation and MLP rows compare every output byte with their original production kernels. +const std = @import("std"); +const mtl = @import("metal"); +const tf = @import("tensorfold"); +const contract = @import("contract"); +const sources = @import("kernel_sources"); +const rig_ = @import("rig.zig"); +const c = contract.spec; +const g = contract.gates; +const Params = contract.delta_slots_ref.Params; +pub const Kind = enum { pre, mlp, mlp_xs }; +fn none(_: c.Shape) usize { + return 0; +} +const pre_shapes = [_]c.Shape{ .{ .rows = 1, .n = 128, .k = 0 }, .{ .rows = 3, .n = 128, .k = 96 }, .{ .rows = 16, .n = 128, .k = 0 }, .{ .rows = 2048, .n = 128, .k = 96 } }; +const mlp_shapes = [_]c.Shape{ .{ .rows = 1, .n = 17408, .k = 1 }, .{ .rows = 15, .n = 17408, .k = 1 }, .{ .rows = 17, .n = 64, .k = 1 }, .{ .rows = 128, .n = 64, .k = 1 }, .{ .rows = 2048, .n = 64, .k = 1 } }; +pub const Probe = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + kind: Kind, + bad: bool, + name: []const u8, + pipe: ?mtl.Pipeline = null, + old: ?mtl.Pipeline = null, + shape: c.Shape = undefined, + p: Params = undefined, + ins: std.ArrayList(rig_.Ref) = .empty, + lens: std.ArrayList(usize) = .empty, + outs: std.ArrayList(rig_.Ref) = .empty, + bases: std.ArrayList(rig_.Ref) = .empty, + joined: std.ArrayList(u8) = .empty, + baseline: std.ArrayList(u8) = .empty, + + pub fn init(a: std.mem.Allocator, d: mtl.Device, q: mtl.Queue, kind: Kind, bad: bool, name: []const u8) Probe { + return .{ .a = a, .rig = .{ .a = a, .device = d, .queue = q }, .kind = kind, .bad = bad, .name = name }; + } + fn reset(p: *Probe) void { + p.rig.reset(); + p.ins.clearRetainingCapacity(); + p.outs.clearRetainingCapacity(); + p.bases.clearRetainingCapacity(); + p.lens.clearRetainingCapacity(); + if (p.pipe) |v| v.deinit(); + if (p.old) |v| v.deinit(); + p.pipe = null; + p.old = null; + } + pub fn deinit(p: *Probe) void { + p.reset(); + p.ins.deinit(p.a); + p.outs.deinit(p.a); + p.bases.deinit(p.a); + p.lens.deinit(p.a); + p.joined.deinit(p.a); + p.baseline.deinit(p.a); + p.rig.deinit(); + } + pub fn kernel(p: *Probe) g.Kernel { + return .{ .spec = .{ + .name = p.name, + .accum = .none, + .out = .raw, + .depth = none, + .served = if (p.kind == .pre) &pre_shapes else &mlp_shapes, + .tiles = if (p.kind == .pre) .{ .{ .size = 16, .min = 1 }, .{}, .{} } else .{ .{ .size = 16, .min = 1 }, .{ .size = 64, .step = 64, .min = 64 }, .{} }, + .replaces = if (p.kind == .pre) "tf_delta_gdn_pre" else "custom_kernel_q27_mlp_xs with identical Q27_XS", + .nan = .{ .stated = "all bytes, including planted non-finite outputs and untouched XS when off, equal the original" }, + .sums = .{ .f16 = 0, .bf16 = 0, .why = "replacement bytes preserve the original rounding and sums; no independent stress claim" }, + }, .ctx = p, .vt = &vtable, .control = if (p.bad) .shapes else null }; + } + const vtable = blk: { + var vt = g.hooks(Probe); + vt.output = output; + break :blk vt; + }; + fn input(p: *Probe, bytes: []const u8) !void { + try p.ins.append(p.a, try p.rig.input(bytes)); + } + fn bf(p: *Probe, n: usize, fill: g.Fill, seed: u64, plant: bool) !void { + const data = try p.a.alloc(u16, n); + defer p.a.free(data); + var rng = std.Random.DefaultPrng.init(seed); + for (data) |*x| x.* = c.toBf16(rng.random().float(f32) * 2 - 1); + if (fill == .nonfinite and plant and n > 128) { + data[0] = c.toBf16(std.math.nan(f32)); + data[128] = c.toBf16(std.math.inf(f32)); + } + try p.input(std.mem.sliceAsBytes(data)); + } + fn out(p: *Probe, bytes: usize) !void { + try p.lens.append(p.a, bytes); + try p.outs.append(p.a, try p.rig.output(bytes)); + try p.bases.append(p.a, try p.rig.scratch(bytes)); + } + pub fn prepare(p: *Probe, s: c.Shape, fill: g.Fill, seed: u64) !bool { + if (s.rows == 0 or s.rows > 2048) return false; + if (p.kind == .pre and (s.n != 128 or (s.k != 0 and s.k != 96))) return false; + if (p.kind != .pre and (s.n == 0 or s.n % 64 != 0)) return false; + p.reset(); + p.shape = s; + if (p.kind == .pre) { + p.p = .{ .rows = @intCast(s.rows), .zba_stride = @intCast(s.k) }; + const channels = 80 * 128; + try p.bf(s.rows * channels, fill, seed, true); + const gates = s.rows * @max(s.k, 48); + try p.bf(gates, fill, seed +% 1, true); + try p.bf(gates, fill, seed +% 2, true); + try p.bf(3 * 3 * channels, fill, seed +% 3, false); + try p.bf(channels * 4, fill, seed +% 4, false); + try p.bf(48, fill, seed +% 5, false); + try p.bf(48, fill, seed +% 6, false); + const windows = try p.a.alloc(u32, s.rows * 4); + defer p.a.free(windows); + for (windows, 0..) |*v, i| v.* = @intCast(i / 4 + i % 4); + try p.input(std.mem.sliceAsBytes(windows)); + const slots = try p.a.alloc(u32, s.rows); + defer p.a.free(slots); + for (slots, 0..) |*v, i| v.* = @intCast(i % 3); + try p.input(std.mem.sliceAsBytes(slots)); + for ([_]usize{ s.rows * 16 * 128 * 2, s.rows * 16 * 128 * 2, s.rows * 48 * 128 * 2, s.rows * 48 * 4, s.rows * 48 * 2 }) |bytes| try p.out(bytes); + const text = if (p.bad) try std.mem.replaceOwned(u8, p.a, sources.core_deltanet, "value[(row * p.nv + output_head) * 32 + lane] =", "value[(row * p.nv + output_head) * 32 + lane] = vec(0) *") else try p.a.dupe(u8, sources.core_deltanet); + defer p.a.free(text); + p.pipe = try rig_.pipeline(p.rig.device, text, "tf_delta_gdn_pre_vectors"); + p.old = try rig_.pipeline(p.rig.device, sources.core_deltanet, "tf_delta_gdn_pre"); + } else { + try p.bf(s.rows * 2 * s.n, fill, seed, true); + const dims = [2]i32{ @intCast(s.rows), @intCast((s.rows + 15) / 16 * 16) }; + try p.input(std.mem.asBytes(&dims)); + try p.out(s.rows * s.n * 2); + try p.out(s.n / 64 * @as(usize, @intCast(dims[1])) * 4); + const text = try tf.qwen27.quant_gpu.specializedSource(p.a, .{ .kind = .mlp_rows, .k = @intCast(s.n), .n = @intCast(s.n), .xs = p.kind == .mlp_xs }); + defer p.a.free(text); + const edit = if (p.bad) try std.mem.replaceOwned(u8, p.a, text, "HOUT[m * (width / 4) + four] = rounded;", "HOUT[m * (width / 4) + four] = vec(0);") else try p.a.dupe(u8, text); + defer p.a.free(edit); + p.pipe = try rig_.pipeline(p.rig.device, edit, "q27_mlp_rows"); + p.old = try rig_.pipeline(p.rig.device, text, "custom_kernel_q27_mlp_xs_bfloat16_t_bfloat16_t_int32_t_bfloat16_t_float"); + } + return true; + } + fn launch(p: *Probe, old: bool) !void { + const targets = if (old) p.bases.items else p.outs.items; + for (targets, p.lens.items) |b, n| @memset(p.rig.bytes(b, n), 0xff); + const pass = p.rig.begin(); + const e = pass.e; + e.setPipeline(if (old) p.old.? else p.pipe.?); + if (p.kind == .pre) { + for (p.ins.items, 0..) |b, i| e.setBuffer(b.buf, b.off, i); + e.setValue(p.p, 9); + for (targets, 10..) |b, i| e.setBuffer(b.buf, b.off, i); + e.dispatchGroups(mtl.Size.of(1, 80, p.shape.rows), mtl.Size.of(32, 1, 1)); + } else { + const fused = p.ins.items[0]; + e.setBuffer(fused.buf, fused.off, 0); + e.setBuffer(fused.buf, fused.off + p.shape.n * 2, 1); + const dims = p.ins.items[1]; + e.setBuffer(dims.buf, dims.off, 2); + for (targets, 3..) |b, i| e.setBuffer(b.buf, b.off, i); + const padded = (p.shape.rows + 15) / 16 * 16; + if (!old) e.setValue(@as(u32, @intCast(p.shape.n)), 5); + e.dispatchGroups(mtl.Size.of(p.shape.n / 64, if (!old) padded / 16 else if (p.kind == .mlp_xs) padded else p.shape.rows, 1), mtl.Size.of(if (old) 64 else 256, 1, 1)); + } + try p.rig.finish(pass); + } + pub fn run(p: *Probe) !void { + try p.launch(false); + } + fn gather(p: *Probe, refs: []const rig_.Ref, list: *std.ArrayList(u8)) ![]const u8 { + list.clearRetainingCapacity(); + for (refs, p.lens.items) |b, n| try list.appendSlice(p.a, p.rig.bytes(b, n)); + return list.items; + } + fn output(ctx: *anyopaque) ![]const u8 { + const p: *Probe = @ptrCast(@alignCast(ctx)); + return p.gather(p.outs.items, &p.joined); + } + pub fn replaced(p: *Probe) ![]const u8 { + try p.launch(true); + return p.gather(p.bases.items, &p.baseline); + } + pub fn check(p: *Probe, _: g.Gate) !?[]const u8 { + if (!std.mem.eql(u8, try output(p), try p.replaced())) return "flat glue differs from original output bytes"; + return null; + } + pub fn count(p: *Probe) usize { + var n: usize = 0; + for (p.lens.items) |bytes| n += bytes; + return n; + } + pub fn reference(_: *Probe, want: []f64, mag: []f64) !void { + @memset(want, 0); + @memset(mag, 0); + } +}; diff --git a/zig/tests/contract/metal_q27_limits.zig b/zig/tests/contract/metal_q27_limits.zig new file mode 100644 index 00000000000..9014d3e40a8 --- /dev/null +++ b/zig/tests/contract/metal_q27_limits.zig @@ -0,0 +1,15 @@ +//! Resolve each specialized Qwen27 stack record to the source its production loader compiles. +const std = @import("std"); +const sources = @import("kernel_sources"); +pub fn source(a: std.mem.Allocator, name: []const u8) ![]u8 { + if (std.mem.startsWith(u8, name, "q27 stack qk ")) { + var words = std.mem.tokenizeScalar(u8, name[13..], ' '); + const sk = try std.fmt.parseInt(u32, words.next().?[2..], 10); + const rows = try std.fmt.parseInt(u32, words.next().?[4..], 10); + return std.fmt.allocPrint(a, "#define TF_SK {d}\n#define TF_ROWS {d}\n{s}", .{ sk, rows, sources.core_qk }); + } + const xs = std.mem.indexOf(u8, name, "xs1") != null; + const body = try std.mem.replaceOwned(u8, a, sources.q27_mlp_xs, "Q27_SPECIALIZE", "constexpr int N=17408;"); + defer a.free(body); + return std.fmt.allocPrint(a, "#define Q27_XS {d}\n{s}", .{ @intFromBool(xs), body }); +} diff --git a/zig/tests/contract/metal_q27_stack.zig b/zig/tests/contract/metal_q27_stack.zig new file mode 100644 index 00000000000..e3b84db7046 --- /dev/null +++ b/zig/tests/contract/metal_q27_stack.zig @@ -0,0 +1,108 @@ +//! The Qwen27 replacements join the normal Metal SUMMARY, with a red control for each variant. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const affine = @import("metal_affine.zig"); +const columns = @import("metal_delta_slots.zig").Columns; +const sums = @import("metal_q27_sums.zig"); +const glue = @import("metal_q27_glue.zig"); +const g = contract.gates; +const shapes = [_]contract.spec.Shape{ + .{ .rows = 16, .n = 64, .k = 6144 }, .{ .rows = 1, .n = 248320, .k = 64 }, + .{ .rows = 16, .n = 64, .k = 6144 }, .{ .rows = 1, .n = 248320, .k = 64 }, + .{ .rows = 16, .n = 64, .k = 5120 }, .{ .rows = 49, .n = 32, .k = 17408 }, + .{ .rows = 16, .n = 64, .k = 6144 }, .{ .rows = 1, .n = 248320, .k = 64 }, + .{ .rows = 128, .n = 32, .k = 64 }, .{ .rows = 2048, .n = 32, .k = 64 }, +}; +pub const Suite = struct { + projections: std.ArrayList(*affine.Proj) = .empty, + scans: std.ArrayList(*columns.Probe) = .empty, + glues: std.ArrayList(*glue.Probe) = .empty, + precision: std.ArrayList(*sums.Probe) = .empty, + names: std.ArrayList([]u8) = .empty, + fn label(s: *Suite, a: std.mem.Allocator, comptime fmt: []const u8, args: anytype) ![]const u8 { + const name = try std.fmt.allocPrint(a, fmt, args); + try s.names.append(a, name); + return name; + } + fn wanted(only: ?[]const u8, name: []const u8) bool { + return if (only) |filter| std.mem.indexOf(u8, name, filter) != null else true; + } + pub fn collect(s: *Suite, a: std.mem.Allocator, d: mtl.Device, q: mtl.Queue, only: ?[]const u8, kernels: *std.ArrayList(g.Kernel)) !void { + try s.scans.ensureUnusedCapacity(a, 9); + try s.glues.ensureUnusedCapacity(a, 6); + try s.projections.ensureUnusedCapacity(a, 16); + for ([_]usize{ 1, 2, 4 }) |slots| for (0..3) |fault| { + const bad = fault == 1; + const precision_bad = fault == 2; + const name = try s.label(a, "{s}core deltanet columns{d}{s}", .{ if (bad or precision_bad) "control: " else "", slots, if (precision_bad) " half sums" else "" }); + if (!wanted(only, name)) continue; + const p = try a.create(columns.Probe); + errdefer a.destroy(p); + p.* = try columns.Probe.init(a, d, q, slots, bad, precision_bad, name); + errdefer p.deinit(); + try kernels.append(a, p.kernel()); + s.scans.appendAssumeCapacity(p); + }; + for (std.enums.values(glue.Kind)) |kind| for ([_]bool{ false, true }) |bad| { + const name = try s.label(a, "{s}qwen27 flat {t}", .{ if (bad) "control: " else "", kind }); + if (!wanted(only, name)) continue; + const p = try a.create(glue.Probe); + errdefer a.destroy(p); + p.* = glue.Probe.init(a, d, q, kind, bad, name); + errdefer p.deinit(); + try kernels.append(a, p.kernel()); + s.glues.appendAssumeCapacity(p); + }; + try s.precision.ensureUnusedCapacity(a, 6); + for ([_]contract.q27_stack_sums.Kind{ .conv, .norm, .xs }) |kind| for ([_]bool{ false, true }) |bad| { + const name = try s.label(a, "{s}qwen27 flat sums {t}", .{ if (bad) "control: " else "", kind }); + if (!wanted(only, name)) continue; + const p = try a.create(sums.Probe); + errdefer a.destroy(p); + p.* = sums.Probe.init(a, d, q, kind, bad, name); + errdefer p.deinit(); + try kernels.append(a, p.kernel()); + s.precision.appendAssumeCapacity(p); + }; + if (d.tensorUnits()) for (1..9) |sk| for ([_]bool{ false, true }) |bad| { + const name = try s.label(a, "{s}metal qk q4 g64 sk{d}", .{ if (bad) "control: " else "", sk }); + if (!wanted(only, name)) continue; + const p = try a.create(affine.Proj); + errdefer a.destroy(p); + p.* = try affine.Proj.init(a, d, q, .{ .kind = .qk, .sk = sk, .control = bad, .served = &shapes }, name); + errdefer p.deinit(); + try kernels.append(a, p.kernel()); + s.projections.appendAssumeCapacity(p); + }; + } + pub fn deinit(s: *Suite, a: std.mem.Allocator) void { + for (s.precision.items) |p| { + p.deinit(); + a.destroy(p); + } + s.precision.deinit(a); + for (s.precision.items) |p| { + p.deinit(); + a.destroy(p); + } + s.precision.deinit(a); + for (s.projections.items) |p| { + p.deinit(); + a.destroy(p); + } + s.projections.deinit(a); + for (s.scans.items) |p| { + p.deinit(); + a.destroy(p); + } + s.scans.deinit(a); + for (s.glues.items) |p| { + p.deinit(); + a.destroy(p); + } + s.glues.deinit(a); + for (s.names.items) |name| a.free(name); + s.names.deinit(a); + } +}; diff --git a/zig/tests/contract/metal_q27_sums.zig b/zig/tests/contract/metal_q27_sums.zig new file mode 100644 index 00000000000..84bbd00a7fe --- /dev/null +++ b/zig/tests/contract/metal_q27_sums.zig @@ -0,0 +1,137 @@ +//! Numeric FP32 gates supplement the mixed-output replacement checks with independent sum panels. +const std = @import("std"); +const mtl = @import("metal"); +const tf = @import("tensorfold"); +const contract = @import("contract"); +const sources = @import("kernel_sources"); +const rig_ = @import("rig.zig"); +const glue = @import("metal_q27_glue.zig"); +const ref = contract.q27_stack_sums; +const c = contract.spec; +const g = contract.gates; +fn none(_: c.Shape) usize { + return 0; +} +pub const Probe = struct { + raw: glue.Probe, + rig: *rig_.Rig = undefined, + kind: ref.Kind, + bad: bool, + name: []const u8, + pub fn init(a: std.mem.Allocator, d: mtl.Device, q: mtl.Queue, kind: ref.Kind, bad: bool, name: []const u8) Probe { + return .{ .raw = glue.Probe.init(a, d, q, if (kind == .xs) .mlp_xs else .pre, false, name), .kind = kind, .bad = bad, .name = name }; + } + pub fn deinit(p: *Probe) void { + p.raw.deinit(); + } + fn index(p: *const Probe) usize { + return switch (p.kind) { + .norm => 0, + .xs => 1, + .conv => 2, + .columns => unreachable, + }; + } + fn outType(p: *const Probe) c.Elem { + return if (p.kind == .xs) .f32 else .bf16; + } + pub fn kernel(p: *Probe) g.Kernel { + p.rig = &p.raw.rig; + return .{ .spec = .{ + .name = p.name, + .accum = .f32, + .out = p.outType(), + .depth = none, + .served = if (p.kind == .xs) &.{.{ .rows = 4, .n = 64, .k = 64 }} else &.{.{ .rows = 4, .n = 128, .k = 0 }}, + .replaces = "the original GDN pre or MLP output on identical inputs", + .nan = .{ .stated = "non-finite output bytes equal the original mixed-output kernel" }, + .sums = .{ .exact = true, .f16 = 100, .bf16 = if (p.kind == .conv) 100 else 0, .why = "BF16 output or cancellation can hide a BF16 sum; half accumulation must still fail" }, + }, .ctx = p, .vt = &vt, .control = if (p.bad) .sums else null }; + } + const vt = blk: { + var v = g.hooks(Probe); + v.output = output; + break :blk v; + }; + fn words(p: *Probe, at: usize, n: usize) []u16 { + return @alignCast(std.mem.bytesAsSlice(u16, p.raw.rig.bytes(p.raw.ins.items[at], n * 2))); + } + fn panel(p: *Probe) void { + const rows = p.raw.shape.rows; + if (p.kind == .xs) { + const n = p.raw.shape.n; + const fused = p.words(0, rows * 2 * n); + for (0..rows) |r| for (0..n) |i| { + fused[r * 2 * n + i] = c.toBf16(256); + fused[r * 2 * n + n + i] = c.toBf16(@floatCast(ref.term(.xs, i % 64) / 256)); + }; + } else { + const channels = 80 * 128; + const projection = p.words(0, rows * channels); + for (projection, 0..) |*v, i| v.* = c.toBf16(if (p.kind == .conv) -0x1p20 else if (i % 128 == 0) 40 else 32); + const history = p.words(3, 3 * 3 * channels); + for (history, 0..) |*v, i| v.* = c.toBf16(if (p.kind == .conv) (if ((i / channels) % 3 == 0) @as(f32, 0x1p20) else 64) else 0); + const weights = p.words(4, channels * 4); + for (weights, 0..) |*v, i| v.* = c.toBf16(if (p.kind == .conv or i % 4 == 0) 1 else 0); + const windows = std.mem.bytesAsSlice(u32, p.raw.rig.bytes(p.raw.ins.items[7], rows * 4 * 4)); + for (windows, 0..) |*v, i| v.* = if (p.kind == .conv) @intCast(i % 4) else if (i % 4 == 0) 3 else 0; + } + } + fn control(p: *Probe) !void { + const a = p.raw.a; + const source = if (p.kind == .xs) try tf.qwen27.quant_gpu.specializedSource(a, .{ .kind = .mlp_rows, .k = 64, .n = 64, .xs = true }) else try a.dupe(u8, sources.core_deltanet); + defer a.free(source); + const symbol = if (p.kind == .xs) "q27_mlp_rows" else "tf_delta_gdn_pre_vectors"; + const from, const to = switch (p.kind) { + .conv => .{ "result += w[tap] * taps[tap][part];", "result = float(half(result + w[tap] * taps[tap][part]));" }, + .norm => .{ "square = simd_sum(square);", "square = float(simd_sum(half(square)));" }, + .xs => .{ "acc += x[part];", "acc = float(half(acc + x[part]));" }, + .columns => unreachable, + }; + const at = std.mem.indexOf(u8, source, symbol).?; + if (std.mem.count(u8, source[at..], from) != 1) return error.MissingPrecisionControl; + const tail = try std.mem.replaceOwned(u8, a, source[at..], from, to); + defer a.free(tail); + const text = try std.mem.concat(a, u8, &.{ source[0..at], tail }); + defer a.free(text); + const pipe = try rig_.pipeline(p.raw.rig.device, text, symbol); + p.raw.pipe.?.deinit(); + p.raw.pipe = pipe; + } + pub fn prepare(p: *Probe, s: c.Shape, fill: g.Fill, seed: u64) !bool { + var actual = s; + if (p.kind != .xs) actual.k = 0; + if (!try p.raw.prepare(actual, fill, seed)) return false; + if (fill == .stress) p.panel(); + if (p.bad) try p.control(); + return true; + } + pub fn run(p: *Probe) !void { + try p.raw.run(); + } + fn output(ctx: *anyopaque) ![]const u8 { + const p: *Probe = @ptrCast(@alignCast(ctx)); + return p.raw.rig.bytes(p.raw.outs.items[p.index()], p.raw.lens.items[p.index()]); + } + pub fn replaced(p: *Probe) ![]const u8 { + _ = try p.raw.replaced(); + return p.raw.rig.bytes(p.raw.bases.items[p.index()], p.raw.lens.items[p.index()]); + } + pub fn count(p: *Probe) usize { + return p.raw.lens.items[p.index()] / c.size(p.outType()); + } + pub fn check(p: *Probe, _: g.Gate) !?[]const u8 { + return p.raw.check(.nonfinite); + } + pub fn reference(p: *Probe, want: []f64, mag: []f64) !void { + for (want, 0..) |*v, i| v.* = p.value(i, .none, .sequential); + @memset(mag, 0); + } + pub fn simulate(p: *Probe, acc: c.Accum, order: g.Order, out: []f64) !void { + for (out, 0..) |*v, i| v.* = p.value(i, acc, order); + } + fn value(p: *Probe, i: usize, acc: c.Accum, order: g.Order) f64 { + if (p.kind == .xs and i % ((p.raw.shape.rows + 15) / 16 * 16) >= p.raw.shape.rows) return 0; + return ref.output(p.kind, i, acc, order); + } +}; diff --git a/zig/tests/contract/metal_tree_round_picks.zig b/zig/tests/contract/metal_tree_round_picks.zig new file mode 100644 index 00000000000..733d4cd21f7 --- /dev/null +++ b/zig/tests/contract/metal_tree_round_picks.zig @@ -0,0 +1,207 @@ +//! Chunked BF16 picks: every Pick byte equals the original row reduction, including non-finite masks. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const sources = @import("kernel_sources"); +const c = contract.spec; +const g = contract.gates; +const rig_ = @import("rig.zig"); +pub const name = "tree round picks"; +const shapes = [_]c.Shape{ + .{ .rows = 1, .n = 248320, .k = 1 }, + .{ .rows = 4, .n = 248320, .k = 1 }, + .{ .rows = 16, .n = 248320, .k = 1 }, + .{ .rows = 64, .n = 248320, .k = 1 }, + .{ .rows = 4, .n = 8192, .k = 1 }, + .{ .rows = 4, .n = 8193, .k = 1 }, +}; +fn none(_: c.Shape) usize { + return 0; +} +pub const Mutation = enum { + none, + last_tie, + no_mask, + fn label(m: Mutation) []const u8 { + return switch (m) { + .none => name, + .last_tie => "control: tree round picks, higher id wins a chunk tie", + .no_mask => "control: tree round picks, chunk masks are lost", + }; + } +}; +fn source(a: std.mem.Allocator, mutation: Mutation) ![]u8 { + const text = sources.core_tree_round; + if (mutation == .none) return a.dupe(u8, text); + const at = std.mem.indexOf(u8, text, "kernel void tf_round_pick_rows").?; + const from, const to = if (mutation == .last_tie) + .{ "const uint who = simd_min(best == top && id != 0xffffffffu ? id : 0xffffffffu);", "const uint who = simd_max(best == top && id != 0xffffffffu ? id : 0u);" } + else + .{ "mask |= other.mask;", "mask |= 0;" }; + if (std.mem.count(u8, text[at..], from) != 1) return error.ControlEditMissing; + const tail = try std.mem.replaceOwned(u8, a, text[at..], from, to); + defer a.free(tail); + return std.mem.concat(a, u8, &.{ text[0..at], tail }); +} +pub const Probe = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + chunks_pipe: mtl.Pipeline, + rows_pipe: mtl.Pipeline, + old_pipe: mtl.Pipeline, + mutation: Mutation, + rows: usize = 0, + vocab: u32 = 0, + stride: u32 = 0, + x: []u16 = &.{}, + input: rig_.Ref = undefined, + scratch: rig_.Ref = undefined, + out: rig_.Ref = undefined, + original: rig_.Ref = undefined, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, mutation: Mutation) !Probe { + const text = try source(a, mutation); + defer a.free(text); + const chunks = try rig_.pipeline(device, text, "tf_round_pick_chunks"); + errdefer chunks.deinit(); + const rows = try rig_.pipeline(device, text, "tf_round_pick_rows"); + errdefer rows.deinit(); + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .chunks_pipe = chunks, .rows_pipe = rows, .old_pipe = try rig_.pipeline(device, sources.core_tree_round, "tf_round_bf16_argmax"), .mutation = mutation }; + } + fn drop(p: *Probe) void { + p.a.free(p.x); + p.x = &.{}; + p.rig.reset(); + } + pub fn deinit(p: *Probe) void { + p.drop(); + p.rig.deinit(); + p.chunks_pipe.deinit(); + p.rows_pipe.deinit(); + p.old_pipe.deinit(); + } + const vt = g.hooks(Probe); + pub fn kernel(p: *Probe) g.Kernel { + return .{ .ctx = p, .vt = &vt, .spec = .{ .name = p.mutation.label(), .accum = .none, .depth = none, .out = .raw, .served = &shapes, .replaces = "tf_round_bf16_argmax", .nan = .{ .stated = "any NaN or infinity gives token 0xffffffff and ORed NaN/+Inf/-Inf bits 1/2/4" }, .sums = .{ .f16 = 0, .bf16 = 0, .why = "comparison only, no sums" } }, .control = switch (p.mutation) { + .none => null, + .last_tie => .shapes, + .no_mask => .nonfinite, + } }; + } + pub fn prepare(p: *Probe, s: c.Shape, fill: g.Fill, seed: u64) !bool { + p.drop(); + if (s.rows == 0 or s.rows > 64 or s.n < 8192 or s.k != 1) return false; + p.rows = s.rows; + p.vocab = @intCast(s.n); + p.stride = p.vocab + 37; + p.x = try p.a.alloc(u16, p.rows * p.stride); + @memset(p.x, 0x7fc0); // padding is never a logit + for (0..p.rows) |r| { + const row = p.x[r * p.stride ..][0..p.vocab]; + for (row, 0..) |*v, i| { + const h = (@as(u64, i) *% 0x9e3779b97f4a7c15 +% seed +% r) >> 40; + v.* = c.toBf16(@as(f32, @floatFromInt(h % 61)) / 8 - 4); + } + if (r % 4 == 1) { + row[p.vocab - 1] = c.toBf16(5); // maximum in the partial last chunk + } else if (r % 4 == 2) { + for (row, 0..) |*v, i| v.* = if (i % 2 == 0) 0x8000 else 0; + } else { + for ([_]usize{ 31, 32, 1023, 1024, 32799, 32800 }) |i| if (i < p.vocab) { + row[i] = c.toBf16(5); + }; + } + if (fill == .nonfinite) switch (r % 4) { + 0 => { + row[17] = 0x7fc0; + row[1024] = 0x7f80; + row[p.vocab - 1] = 0xff80; + }, + 1 => row[p.vocab - 1] = 0x7fc0, + 2 => row[p.vocab - 1] = 0x7f80, + 3 => row[p.vocab - 1] = 0xff80, + else => unreachable, + }; + } + p.input = try p.rig.input(std.mem.sliceAsBytes(p.x)); + p.scratch = try p.rig.scratch(p.rows * ((p.vocab + 1023) / 1024) * 12); + p.out = try p.rig.output(p.count()); + p.original = try p.rig.scratch(p.count()); + return true; + } + pub fn count(p: *Probe) usize { + return p.rows * 8; + } + fn args(p: *Probe, e: mtl.ComputeEncoder) void { + e.setValue([3]u32{ @intCast(p.rows), p.vocab, p.stride }, 2); + } + pub fn run(p: *Probe) !void { + const pass = p.rig.begin(); + const e = pass.e; + e.setPipeline(p.chunks_pipe); + e.setBuffer(p.input.buf, p.input.off, 0); + e.setBuffer(p.scratch.buf, p.scratch.off, 1); + p.args(e); + e.dispatchGroups(mtl.Size.of((p.vocab + 1023) / 1024, p.rows, 1), mtl.Size.of(32, 1, 1)); + e.barrier(); + e.setPipeline(p.rows_pipe); + e.setBuffer(p.scratch.buf, p.scratch.off, 0); + e.setBuffer(p.out.buf, p.out.off, 1); + p.args(e); + e.dispatchGroups(mtl.Size.of(p.rows, 1, 1), mtl.Size.of(32, 1, 1)); + try p.rig.finish(pass); + } + pub fn replaced(p: *Probe) ![]const u8 { + const pass = p.rig.begin(); + const e = pass.e; + e.setPipeline(p.old_pipe); + e.setBuffer(p.input.buf, p.input.off, 0); + e.setBuffer(p.original.buf, p.original.off, 1); + p.args(e); + e.dispatchGroups(mtl.Size.of(p.rows, 1, 1), mtl.Size.of(256, 1, 1)); + try p.rig.finish(pass); + return p.rig.bytes(p.original, p.count()); + } + pub fn reference(_: *Probe, want: []f64, mag: []f64) !void { + @memset(want, 0); + @memset(mag, 0); + } + pub fn check(p: *Probe, _: g.Gate) !?[]const u8 { + const out = p.rig.bytes(p.out, p.count()); + for (0..p.rows) |r| { + var mask: u32 = 0; + var best: u32 = std.math.maxInt(u32); + var value: f64 = -std.math.inf(f64); + for (p.x[r * p.stride ..][0..p.vocab], 0..) |v, id| { + const x = c.fromBf16(v); + if (!std.math.isFinite(x)) { + mask |= if (std.math.isNan(x)) @as(u32, 1) else if (x > 0) @as(u32, 2) else 4; + } else if (best == std.math.maxInt(u32) or x > value) { + best = @intCast(id); + value = x; + } + } + const got = std.mem.readInt(u32, out[r * 8 ..][0..4], .little); + const flags = std.mem.readInt(u32, out[r * 8 + 4 ..][0..4], .little); + if (flags != mask) return "non-finite mask differs from the scalar rule"; + if (got != (if (mask != 0) std.math.maxInt(u32) else best)) return "lowest-id pick differs from the scalar rule"; + } + return null; + } +}; + +pub const Suite = struct { + probes: std.ArrayList(Probe) = .empty, + pub fn collect(s: *Suite, a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, only: ?[]const u8, kernels: *std.ArrayList(g.Kernel)) !void { + try s.probes.ensureTotalCapacity(a, 3); + for (std.enums.values(Mutation)) |m| { + if (only) |o| if (std.mem.indexOf(u8, m.label(), o) == null) continue; + s.probes.appendAssumeCapacity(try Probe.init(a, device, queue, m)); + try kernels.append(a, s.probes.items[s.probes.items.len - 1].kernel()); + } + } + pub fn deinit(s: *Suite, a: std.mem.Allocator) void { + for (s.probes.items) |*p| p.deinit(); + s.probes.deinit(a); + } +}; diff --git a/zig/tests/cuda/glm_exl3_items_tests.zig b/zig/tests/cuda/glm_exl3_items_tests.zig new file mode 100644 index 00000000000..b5ed16e903a --- /dev/null +++ b/zig/tests/cuda/glm_exl3_items_tests.zig @@ -0,0 +1,221 @@ +//! GLM's EXL3 decode on the 16-pair item plan gives the plain decode's slot-row bytes, case by case. +const std = @import("std"); +const cuda = @import("cuda"); +const glm = @import("glm_cuda"); +const check = @import("check.zig"); +const qr = @import("quant_ref_tests.zig"); +const Gpu = check.Gpu; +const Rig = qr.RigT; +const ex = cuda.exl3_experts; + +const E = 12; // routed experts (the shared one is id E, skipped) +const D = 512; // dims +const top = glm.exl3.top_k; +const slots = top + 1; +const limit: f32 = 7.0; + +fn signs(r: *Rig, n: usize, scale: f16) ![]f16 { + const out = try r.a.alloc(f16, n); + for (out) |*v| v.* = if (r.rng.boolean()) scale else -scale; + return out; +} + +/// `E` K x N trellises back to back as the loader lays them out: the pointer table, with suh and svh. +fn matrix(r: *Rig, k: usize, n: usize, shared_suh: ?[]const f16, suh: *u64, svh: *u64) !u64 { + const words = k / 16 * (n / 16) * 64; // i16 an expert + const tr = try r.a.alloc(i16, E * words); + for (tr) |*v| v.* = r.rng.int(i16); + const su = try r.a.alloc(f16, E * k); + for (0..E) |e| @memcpy(su[e * k ..][0..k], if (shared_suh) |s| s else try signs(r, k, 1.0)); + suh.* = try r.dev(std.mem.sliceAsBytes(su)); + svh.* = try r.dev(std.mem.sliceAsBytes(try signs(r, E * n, 0.02))); + const base = try r.dev(std.mem.sliceAsBytes(tr)); + const ptrs = try r.a.alloc(u64, E); + for (ptrs, 0..) |*ptr, e| ptr.* = base + e * words * 2; + return r.dev(std.mem.sliceAsBytes(ptrs)); +} + +/// A layer of width `n`; `one`: every gate and up input shares one rotation (the loader's shx). +fn weights(r: *Rig, dims: usize, n: usize, one: bool) !glm.exl3.Experts { + var w: glm.exl3.Experts = .{ .gt = 0, .ut = 0, .dt = 0, .k2 = 0, .suh_g = 0, .suh_u = 0, .svh_g = 0, .svh_u = 0, .suh_d = 0, .svh_d = 0, .shx = one }; + const k2: [E]i32 = @splat(8); + w.k2 = try r.dev(std.mem.sliceAsBytes(&k2)); + const rot = if (one) try signs(r, dims, 1.0) else null; + w.gt = try matrix(r, dims, n, rot, &w.suh_g, &w.svh_g); + w.ut = try matrix(r, dims, n, rot, &w.suh_u, &w.svh_u); + w.dt = try matrix(r, n, dims, null, &w.suh_d, &w.svh_d); + return w; +} + +/// The common module's layer GLM's cuda_exl3.layer builds from `w` (the stage checks call the module directly). +fn commonLayer(w: glm.exl3.Experts, dims: usize, n: usize) ex.Layer { + return .{ .gate = w.gt, .up = w.ut, .down = w.dt, .gate_k2 = w.k2, .up_k2 = w.k2, .down_k2 = w.k2, .suh_g = w.suh_g, .suh_u = w.suh_u, .svh_g = w.svh_g, .svh_u = w.svh_u, .suh_d = w.suh_d, .svh_d = w.svh_d, .experts = E, .dims = dims, .width = n, .codebook = .mcg, .limit = limit, .act_mode = 0, .uniform_k2 = 8, .shared_input = w.shx }; +} + +/// Each row's 8 distinct routed picks (lockstep: every row the same picks), then the shared expert's id. +fn picks(r: *Rig, rows: usize, lockstep: bool) ![]i32 { + const out = try r.a.alloc(i32, rows * slots); + var first: [top]i32 = undefined; // row 0's routed picks, reused every row under lockstep + for (0..rows) |row| { + if (row == 0 or !lockstep) { + var seen: [E]bool = @splat(false); + for (0..top) |j| { + var e = r.rng.uintLessThan(usize, E); + while (seen[e]) e = r.rng.uintLessThan(usize, E); + seen[e] = true; + first[j] = @intCast(e); + } + } + for (0..top) |j| out[row * slots + j] = first[j]; + out[row * slots + slots - 1] = E; + } + return out; +} + +/// The routed slot rows of `ey` [rows][slots][D] packed as [rows][top][D] (the plain path's y layout). +fn packSlots(r: *Rig, ey: u64, rows: usize, dims: usize) ![]u8 { + const raw = try r.back(ey, rows * slots * dims * 4); + const out = try r.a.alloc(u8, rows * top * dims * 4); + for (0..rows) |row| @memcpy(out[row * top * dims * 4 ..][0 .. top * dims * 4], raw[row * slots * dims * 4 ..][0 .. top * dims * 4]); + return out; +} + +/// The plain decode, as the old launch shape: the 8 compacted picks through the common module's runSlots. +fn plain(r: *Rig, k: *const glm.exl3.Kernels, l: ex.Layer, x: []const u16, pk: []const i32, rows: usize, dims: usize) ![]u8 { + const p8 = try r.a.alloc(i32, rows * top); + for (0..rows) |row| @memcpy(p8[row * top ..][0..top], pk[row * slots ..][0..top]); + const sc = try ex.scratch(try r.zeros(try ex.scratchBytes(l, rows, top)), l, rows, top); + try k.runSlots(r.s, l, try r.dev(std.mem.sliceAsBytes(x)), dims, .bf16, try r.dev(std.mem.sliceAsBytes(p8)), rows, sc); + try r.s.synchronize(); + return r.back(sc.y, rows * top * dims * 4); +} + +/// The family's decode dispatch, whose decode windows run on the item plan: ey [rows][slots][D] fp32 bytes. +fn items(r: *Rig, k: *const glm.exl3.Kernels, ek: *const glm.experts.Kernels, w: glm.exl3.Experts, n: usize, x: []const u16, pk: []const i32, rows: usize, dims: usize) ![]u8 { + const P = rows * slots; // the item plan groups all 9 slots + const plan: cuda.grouped.Plan = .{ + .members = try r.zeros(P * 4), + .items = try r.zeros(cuda.grouped.maxItems(P, E + 1, glm.experts.tile) * 12), + .counts = try r.zeros(8), + .rank = try r.zeros(P * 4), + .hist = try r.zeros(4), + }; + const sz = glm.exl3.scratchBytes(rows, dims, n, false, w.shx); + const sc: glm.exl3.Scratch = .{ .picks = try r.zeros(sz[0]), .xg = try r.zeros(sz[1]), .xu = try r.zeros(sz[2]), .z = try r.zeros(sz[3]) }; + const ey = try r.zeros(rows * slots * dims * 4); + const xd = try r.zeros(P * n * 2); + try glm.exl3.run(k, ek, r.s, w, sc, plan, try r.dev(std.mem.sliceAsBytes(x)), dims, try r.dev(std.mem.sliceAsBytes(pk)), slots, rows, E, dims, n, limit, false, ey, xd); + return packSlots(r, ey, rows, dims); +} + +const Tally = struct { cases: usize = 0, failed: usize = 0 }; + +const Case = struct { rows: usize, lock: bool }; + +/// 17 rows is the only distinct window that spans two 16-pair items, so it stays distinct. +const base_cases = [_]Case{ + .{ .rows = 1, .lock = false }, .{ .rows = 2, .lock = false }, .{ .rows = 3, .lock = false }, + .{ .rows = 8, .lock = false }, .{ .rows = 17, .lock = false }, .{ .rows = 16, .lock = true }, + .{ .rows = 32, .lock = true }, .{ .rows = 48, .lock = true }, .{ .rows = 64, .lock = true }, +}; + +const served_cases = [_]Case{ .{ .rows = 8, .lock = false }, .{ .rows = 64, .lock = true } }; + +fn value(b: []const u8) f64 { + if (b.len == 4) return @as(f32, @bitCast(std.mem.readInt(u32, b[0..4], .little))); + return @as(f16, @bitCast(std.mem.readInt(u16, b[0..2], .little))); +} + +fn bitsOf(b: []const u8) u32 { + return if (b.len == 4) std.mem.readInt(u32, b[0..4], .little) else std.mem.readInt(u16, b[0..2], .little); +} + +/// Byte-equal, else one FAIL line: the count, the first (row of `per_row`, column), got/want, canaries, NaNs, most. +fn same(t: *Tally, name: []const u8, got: []const u8, want: []const u8, elem: usize, per_row: usize) void { + t.cases += 1; + if (got.len == want.len and std.mem.eql(u8, got, want)) return; + t.failed += 1; + if (got.len != want.len) { + std.debug.print("FAIL {s}: {d} bytes, expected {d}\n", .{ name, got.len, want.len }); + return; + } + var first: usize = 0; + var differ: usize = 0; + var canary: usize = 0; + var nan: usize = 0; + var most: f64 = 0; + var scale: f64 = 0; + for (0..got.len / elem) |i| { + const g = got[i * elem ..][0..elem]; + const w = want[i * elem ..][0..elem]; + if (std.mem.allEqual(u8, g, 0xff)) canary += 1; + const gv = value(g); + const wv = value(w); + if (std.math.isNan(gv)) nan += 1; + if (std.math.isFinite(wv)) scale = @max(scale, @abs(wv)); + if (std.mem.eql(u8, g, w)) continue; + if (differ == 0) first = i; + differ += 1; + if (std.math.isFinite(gv) and std.math.isFinite(wv)) most = @max(most, @abs(gv - wv)); + } + const g = got[first * elem ..][0..elem]; + const w = want[first * elem ..][0..elem]; + std.debug.print("FAIL {s}: {d} of {d} values differ, first at row {d} column {d}: got {e} (0x{x}), want {e} (0x{x}); {d} canary, {d} NaN; largest finite difference {e} of largest |want| {e}\n", .{ name, differ, got.len / elem, first / per_row, first % per_row, value(g), bitsOf(g), value(w), bitsOf(w), canary, nan, most, scale }); +} + +pub fn run_(gpu: Gpu) !void { + var arena: std.heap.ArenaAllocator = .init(gpu.gpa); + defer arena.deinit(); + var stream = try cuda.Stream.init(gpu.d, false); + defer stream.deinit(); + var prng = std.Random.DefaultPrng.init(29); + var r: Rig = .{ .gpu = gpu, .a = arena.allocator(), .s = stream, .rng = prng.random() }; + defer { + for (r.bufs.items) |*b| b.free(); + r.bufs.deinit(gpu.gpa); + } + + var pm = try cuda.Module.load(gpu.d, cuda.kernels.experts); + defer pm.unload(); + var k = try glm.exl3.Kernels.load(gpu.d); + defer k.unload(); + var ek = try glm.experts.Kernels.load(gpu.d, pm, @intCast(try gpu.ctx.attribute(.multiprocessor_count)), null); + defer ek.unload(); + var t: Tally = .{}; + // dims 4096 is GLM-5.3-Flash's served size, at the 768/1024 widths a rank meets + for ([_]struct { dims: usize, widths: []const usize, cases: []const Case }{ + .{ .dims = D, .widths = &.{ 256, 640 }, .cases = &base_cases }, + .{ .dims = 4096, .widths = &.{ 768, 1024 }, .cases = &served_cases }, + }) |shape| { + for (shape.widths) |n| { // 640: a TP=3 rank's 5 blocks, 10 down steps + for (shape.cases) |cs| { // distinct and lockstep decode windows, each listed rather than derived + const dims = shape.dims; + const rows = cs.rows; + const x = try r.bfs(rows * dims, 1.0); + const pk = try picks(&r, rows, cs.lock); + const case = try std.fmt.allocPrint(r.a, "dims {d}, width {d}, {d} rows {s}", .{ dims, n, rows, if (cs.lock) "lockstep" else "distinct" }); + const w = try weights(&r, dims, n, false); + const l = commonLayer(w, dims, n); + const want = try plain(&r, &k, l, x, pk, rows, dims); + same(&t, try std.fmt.allocPrint(r.a, "glm-exl3-items {s}: plain twice (control)", .{case}), try plain(&r, &k, l, x, pk, rows, dims), want, 4, dims); + var nan: usize = 0; + for (0..rows) |row| for (0..top) |j| for (0..dims) |c| { + nan += @intFromBool(std.math.isNan(value(want[((row * top + j) * dims + c) * 4 ..][0..4]))); + }; + t.cases += 1; + if (nan != 0) { + t.failed += 1; + std.debug.print("FAIL glm-exl3-items {s}: the plain decode left {d} routed values NaN\n", .{ case, nan }); + } + // A wrong plan (a members offset, a bad first/count, the shared item unskipped) misroutes a slot. + same(&t, try std.fmt.allocPrint(r.a, "glm-exl3-items {s}, items: ey", .{case}), try items(&r, &k, &ek, w, n, x, pk, rows, dims), want, 4, dims); + } + } + } + std.debug.print("RESULT glm-exl3-items: {d} of {d} comparisons differ\n", .{ t.failed, t.cases }); + if (t.failed != 0) { + std.debug.print("FAIL glm-exl3-items: {d} of {d} comparisons differ\n", .{ t.failed, t.cases }); + return error.TestFailed; + } + check.pass("glm-exl3-items: {d} comparisons equal the plain decode byte for byte", .{t.cases}); +} diff --git a/zig/tests/cuda/glm_exl3_tests.zig b/zig/tests/cuda/glm_exl3_tests.zig index 8db777a1e3c..690559ecd37 100644 --- a/zig/tests/cuda/glm_exl3_tests.zig +++ b/zig/tests/cuda/glm_exl3_tests.zig @@ -219,6 +219,12 @@ fn expect(r: *Rig, name: []const u8, out: Run, s: Set, x: []const u16, pk: []con try check.expect(most <= 1, "{s} within its float64 tolerance", .{name}); } +/// The glm-exl3 command and its items form: this file's check, or the item plan against the plain decode. +pub fn runCmd(gpu: Gpu, cmd: []const u8) !void { + if (std.mem.eql(u8, cmd, "glm-exl3-items")) return @import("glm_exl3_items_tests.zig").run_(gpu); + return run_(gpu); +} + pub fn run_(gpu: Gpu) !void { var arena: std.heap.ArenaAllocator = .init(gpu.gpa); defer arena.deinit(); diff --git a/zig/tests/cuda/main.zig b/zig/tests/cuda/main.zig index 2fa18ca0de0..002937e03fe 100644 --- a/zig/tests/cuda/main.zig +++ b/zig/tests/cuda/main.zig @@ -268,7 +268,7 @@ const usage = \\ flashnext-modelopt-contract Flash Next NVFP4's BF16 dense and FP8 MTP-expert downs through gates 1-4 \\ minimax-contract MiniMax-M3.1-Flash's indexer and block-sparse attention through gates 1-4, controls red \\ moss-contract MOSS-Image's own kernels and its full attention through gates 1-4, controls red - \\ glm-exl3 GLM's EXL3 routed experts, decode and prompt, against float64 (synthetic) + \\ glm-exl3 | glm-exl3-items GLM's EXL3 routed experts, decode and prompt, against float64, and the item plan's decode against the plain decode, byte for byte (synthetic) \\ glm-kda-pad-split TF_GLM_KDA_PAD's padding of the bf16 and split KDA stacks at TP=3 (synthetic) \\ glm-vision MODEL F32 BF16 IMG GLM's image tower and preparation against vision_ref.py's torch runs \\ glm-mm-fixed Prompt K policies: FP64, every row alone/batched, offsets and guarded tails @@ -437,7 +437,7 @@ fn run(gpu: check.Gpu, cmd: []const u8, rest: []const [:0]const u8) !void { if (std.mem.eql(u8, cmd, "native-fp")) return native_fp_tests.run(gpu); if (std.mem.eql(u8, cmd, "affine4-decode")) return affine4_decode_tests.run(gpu); if (std.mem.eql(u8, cmd, "w4a8")) return w4a8_tests.run(gpu); - if (std.mem.eql(u8, cmd, "glm-exl3")) return glm_exl3_tests.run_(gpu); + if (std.mem.eql(u8, cmd, "glm-exl3") or std.mem.eql(u8, cmd, "glm-exl3-items")) return glm_exl3_tests.runCmd(gpu, cmd); if (std.mem.eql(u8, cmd, "glm-kda-pad-split")) return glm_kda_pad_check.run(gpu); if (std.mem.eql(u8, cmd, "glm-mm-fixed")) return @import("glm_mm_fixed_tests.zig").run(gpu); if (std.mem.eql(u8, cmd, "glm-mm-bench")) return glm_mm_bench.run(gpu); diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index 87228dc7dae..883de89e707 100644 --- a/zig/tests/fixtures/gradient-serving.tsv +++ b/zig/tests/fixtures/gradient-serving.tsv @@ -44,7 +44,7 @@ zig/kernels/cuda/nemotron_mamba.cu dcaba12253d3931ae48c7ebd4e13dfb956f540ae19f4a 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 +zig/kernels/cuda/nvfp4_experts.cu cb54357e2c06252cc594cd1223401170dadefd995b0c67db0cae5edf628719d0 raw #2266 (decode cp.async rings, GB10 SASS unchanged) zig/kernels/cuda/nvfp4q.cuh 5fe4fa58568f2293bb72ccfa58b362ba2783b21a781e56946a5a2c328303d111 raw zig/kernels/cuda/prefill_attention.cu 905fff2c9018d778557a60ed2c81c24ce220adf5b092c8c32f8a1782963f9f28 raw main 82f3dde92 (pattn_kernel<64, 8, 4, 8> over paged caches), 94a9a48d6 (helpers to prefill_attention.cuh, SASS unchanged), 191061381 (#2609: two new pattn_kernel instances at two query heads a block, head dims 128 and 64; existing instances unchanged) zig/kernels/cuda/prefill_attention_rows.cuh 21975248a7ec9efd199a28324bba837e7b78f066a63b426ab26587cba38fda5e raw main 94a9a48d6 (helpers shared with the contract controls, SASS unchanged) @@ -99,7 +99,7 @@ zig/src/cuda/memory.zig 7d2a91bfca8a08ae59df16ddf30d22226aba773cc814dd106930840a zig/src/cuda/modelopt.zig 648c9ba58197af0ce905f8792383502fc44a52c45d1413fe9e21d28d04c22253 raw zig/src/cuda/module.zig 1f0a141cf7149a87ad456e96cb1830f0c137ad98af70071721918989b0720b92 raw zig/src/cuda/mxfp8.zig 2bbe9ea41b462f633b68e7a32c06814a28e34dee284383788c0a8f06e8df2af4 raw -zig/src/cuda/nccl.zig 30abc4b904e675916e9bb8c4701ca3f1e5615472da4a5e09d2476865d81afe65 raw commits 53abe4556, ba1a9a2bb, 05350da4c, 40dccba55, 6bdb12918, b923e554c, 7c9d845c0, 98a5dc657, 143ed758f, 6636e6964; 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/nccl.zig 005a4dd9ed6929b6022c4daff8d8d82c0ee43ea3e468221fd4a8de9ae6dde640 raw commits 53abe4556, ba1a9a2bb, 05350da4c, 40dccba55, 6bdb12918, b923e554c, 7c9d845c0, 98a5dc657, 143ed758f, 6636e6964; series patches 14-runtime-foundation.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate; #3106 (Library.open reads TF_NCCL_LIB through pathFrom, shared with the TP session's settings; unset, empty and blank keep libnccl.so.2) zig/src/cuda/norms.zig c6ac613ff91b31257b5bce55311d8cf38a785862bfad9eb0c7bf0b2ba7b0df95 raw zig/src/cuda/nvfp4.zig 0556e93c12e4eb21db45d0d9d9ee7d4c1c4ab6a32a359b67edfc0b4b7fb90928 raw #3252: launcher for the lean SwiGLU pair zig/src/cuda/qlinear.zig 680c653d110b53e52918bb13f7c54c12ffac4097959319281dc7509c085c062f raw commits da01294e0, 7f6f940eb, 4cec0eba1, c360607f0, ba1a9a2bb, b631fe069, 0a2a1c681, aca5a88e2, c12503be2, 7b17d0eb7, d7e44b555, 59be20e24, d40bc9e8b, f1f7f9abd, 3915bceaf, e8eabc82c; series patches 14-runtime-foundation.patch, 25-mimo-02.patch; MiMo-only aliases omitted from this candidate; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate @@ -131,7 +131,7 @@ zig/src/families/flashnext/cuda_images.zig 5bd8a6c06cb69440522f4392794d9ef52b376 zig/src/families/flashnext/cuda_images_test.zig df984d54d9de1bb732544785cddf82a124de2a7019041ed1f7483b2a4a2d7c99 raw zig/src/families/flashnext/cuda_lanes.zig 8578e64c69611c219709f48a4ba646bfd01fa02d793d788ea7e577ae03d07808 raw main 4f6017ced (marks inside the pass), fbca90714 (shared solo-chunk rule, #2391), 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), #1953: the ladder's values through snap_intermediate, #3308 (loader host test updates the named startup-refusal expectations; no runtime edit to this pinned file); #3135 (kept_disk renamed kept_view for the shared kept image; no served change) zig/src/families/flashnext/cuda_lanes_admission_test.zig 4b8052db793ba81f0e73e1b9bd77b1780bbc4fd550d90976d017da47e76faaa2 raw -zig/src/families/flashnext/cuda_lanes_load.zig 241d091d4b5199325665d25ea5d4def81fd15660351a199773c596ca2025fa18 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_lanes_load.zig 26596c5f9bb0fb01b96cb96b50d51a70cf8ef1ef4f2af91e33e6f4a0c74a6f10 raw main dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning), #3467: after load a shard drops its page cache except the n-gram ranges, and the sweep reaches nested shards; tensors and replies are unchanged zig/src/families/flashnext/cuda_lanes_restore_test.zig f9947521a6d9c7d7380ca1b784a93a43b364c6fa5861cad15efd3538d2b8ceff raw zig/src/families/flashnext/cuda_launch.zig f8bebb5ed074e6c8ab8cef667cb01fa2bb1a2b2d6a4d3874a92291390278d9f7 raw exports cuda_moe_exchange.zig for its device test; no served change; #2837 (Flash Next TP=2 graph replay) zig/src/families/flashnext/cuda_media.zig 394601e8a807f5516f501efcaefa6fb3308f392ee322db7296b11c90814f8eea raw @@ -157,7 +157,7 @@ zig/src/families/flashnext/cuda_prompt.zig 64dfa63d6c9608d04b524689047f3f2bcf193 zig/src/families/flashnext/cuda_prompt_load.zig 334d68cfca85c15c9d986d0c6b4f8f2a38569309b21bdac6d365935d73c115cd raw zig/src/families/flashnext/cuda_prompt_main.zig 2543cd166dc80cd97b1ca1ce930a6150f9d36b52ee231744606f83bf54f0669d raw main dfd9ac5ef4 (#2585: the TF_FLASHNEXT_* startup check), c274b45cc1 (the check through the flashnext module) zig/src/families/flashnext/cuda_prompt_step.zig e04030fb4a4fdb8780704a1bc0b5ba4b786159ab08a927fe32a636a893129d0c raw -zig/src/families/flashnext/cuda_prompt_wt.zig 9f0b8f853cc33e23c3ae3785c7031721615fc043e240161c84fb945e499e809f raw +zig/src/families/flashnext/cuda_prompt_wt.zig 4885be0ea938cfba80b34fbe9c160d200226761a73f8bd9d785172cbc7cef9bb raw #3467: after load a shard drops its page cache except the n-gram ranges, and the sweep reaches nested shards; tensors and replies are unchanged zig/src/families/flashnext/cuda_qmm.zig 6d035feb053691cc9750a369c86a5463d41ed942764ad85b861bb628c106dccf raw zig/src/families/flashnext/cuda_rank_engine.zig df6a83bcf80edfd94ac4474dbbc2e73818d40b7532430399af73f2eb95ccfa33 raw zig/src/families/flashnext/cuda_rank_media.zig e5c268c8cf257934bb49fe401ba6213ea8b108258bbfd4d06edb990d568c3c2b raw diff --git a/zig/tests/glm_rows_batch.zig b/zig/tests/glm_rows_batch.zig index d7e0de77358..eb63df441c1 100644 --- a/zig/tests/glm_rows_batch.zig +++ b/zig/tests/glm_rows_batch.zig @@ -64,7 +64,7 @@ pub fn headsCheck(g: *const Gpu, mm: affine_mm.Pipes, bits: u8, n: usize, k: usi bs[3].slice(u16, m * k)[i * k ..][0..k], bs[0].slice(u16, m * ldx)[i * ldx + h * k ..][0..k], ); - try g.run(mmDense, .{ mm, w.part(h, nh), ref(bs[3]), ref(bs[1]), ref(bs[4]), @as(u32, m) }); + try g.run(mmDense, .{ mm, g.p.mm_bm, w.part(h, nh), ref(bs[3]), ref(bs[1]), ref(bs[4]), @as(u32, m) }); for (0..m) |i| try eql(all[(i * nh + h) * n ..][0..n], bs[4].slice(u16, m * n)[i * n ..][0..n]); t.pairs += m * n; } @@ -117,7 +117,7 @@ pub fn splitMmCheck(g: *const Gpu, k: usize, ns: []const usize, bits: []const u8 for (ms[0..ns.len], 0..) |x, i| { const run = q.run(i); if (wide.mm(&g.p, x.q) != null and run.n % 64 == 0) { - try g.run(mmDense, .{ wide.mm(&g.p, x.q).?, x.q, ref(bs[0]), ref(bs[1]), ref(bs[3]), @as(u32, m) }); + try g.run(mmDense, .{ wide.mm(&g.p, x.q).?, g.p.mm_bm, x.q, ref(bs[0]), ref(bs[1]), ref(bs[3]), @as(u32, m) }); on_mm += 1; } else try g.run( dense, diff --git a/zig/tests/glm_rows_check.zig b/zig/tests/glm_rows_check.zig index fefe0d2c2cd..1cc09572bd3 100644 --- a/zig/tests/glm_rows_check.zig +++ b/zig/tests/glm_rows_check.zig @@ -310,6 +310,7 @@ fn partsCheck(g: *const Gpu, m: Mat, up: Mat, t: *Tally) !void { pub fn mmDense( e: mtl.ComputeEncoder, mm: affine_mm.Pipes, + bm: u32, q: affine.Affine, x: Ref, sums: Ref, @@ -317,7 +318,7 @@ pub fn mmDense( n_rows: u32, ) void { affine_mm.rowSums(e, mm, 64, x, sums, n_rows, q.k); - affine_mm.dense(e, mm, x, sums, q, y, n_rows); + affine_mm.denseBm(e, mm, x, sums, q, y, n_rows, bm); } /// dims: x rows, sorted pairs, experts, picks a row. @@ -365,7 +366,8 @@ fn gatherCheck(g: *const Gpu, m: Mat, up: Mat, t: *Tally) !void { upq.n = @intCast(r); // every expert's gate and up, dense on every x row: [2][parts][rows, r] for (0..parts) |e| for ([2]Mat{ m, up }, 0..) |w, j| { - try g.run(mmDense, .{ mm, w.part(e, parts), ref(m.x()), sums, ref(bs[1]).at(((j * parts + e) * rows * r) * 2), @as(u32, rows) }); + const y_at = ref(bs[1]).at(((j * parts + e) * rows * r) * 2); + try g.run(mmDense, .{ mm, g.p.mm_bm, w.part(e, parts), ref(m.x()), sums, y_at, @as(u32, rows) }); }; const dg = bs[1].slice(u16, 2 * parts * rows * r); const gu = bs[2].slice(u16, slots * 2 * r); @@ -384,7 +386,10 @@ fn gatherCheck(g: *const Gpu, m: Mat, up: Mat, t: *Tally) !void { for (order, 0..) |o, i| @memcpy(xs[i * k ..][0..k], m.x().slice(u16, rows * k)[@as(usize, @intCast(o)) * k ..][0..k]); const y = bs[5].slice(u16, (parts + 1) * slots * r); try g.run(mmDown, .{ mm, gate, ref(bs[4]), sums, sorted, ref(bs[5]), @as(u32, slots), @as(u32, parts) }); - for (0..parts) |e| try g.run(mmDense, .{ mm, m.part(e, parts), ref(bs[4]), sums, ref(bs[5]).at((1 + e) * slots * r * 2), @as(u32, slots) }); + for (0..parts) |e| { + const y_at = ref(bs[5]).at((1 + e) * slots * r * 2); + try g.run(mmDense, .{ mm, g.p.mm_bm, m.part(e, parts), ref(bs[4]), sums, y_at, @as(u32, slots) }); + } for (order, 0..) |o, i| { const e: usize = @intCast(picks[@intCast(o)]); try eql(y[@as(usize, @intCast(o)) * r ..][0..r], y[((1 + e) * slots + i) * r ..][0..r]); diff --git a/zig/tests/glm_rows_classes.zig b/zig/tests/glm_rows_classes.zig index 4b9f99d4f6e..978ea2eed01 100644 --- a/zig/tests/glm_rows_classes.zig +++ b/zig/tests/glm_rows_classes.zig @@ -123,11 +123,11 @@ fn rowsLaunch(e: mtl.ComputeEncoder, p: *const wide.Pipes, q: affine.Affine, x: wide.dense(p, e, q, .{ .in = (affine.Ref{ .buf = x }).at(at), .ldx = q.k, .out = .{ .buf = out }, .ldo = q.n, .rows = m }); } -fn mmLaunch(e: mtl.ComputeEncoder, mm: affine_mm.Pipes, q: affine.Affine, x: mtl.Buffer, sums: mtl.Buffer, out: mtl.Buffer, m: u32) void { +fn mmLaunch(e: mtl.ComputeEncoder, mm: affine_mm.Pipes, bm: u32, q: affine.Affine, x: mtl.Buffer, sums: mtl.Buffer, out: mtl.Buffer, m: u32) void { const xr: affine.Ref = .{ .buf = x }; const sr: affine.Ref = .{ .buf = sums }; affine_mm.rowSums(e, mm, 64, xr, sr, m, q.k); - affine_mm.dense(e, mm, xr, sr, q, affine.Ref{ .buf = out }, m); + affine_mm.denseBm(e, mm, xr, sr, q, affine.Ref{ .buf = out }, m, bm); } /// Each class at its widths (g64): decode rows (alone == windowed) and the prompt's product vs fp64, every column. @@ -167,7 +167,7 @@ pub fn check(p: *const wide.Pipes, device: mtl.Device, queue: mtl.Queue) !Tally // prompt: the chunk's product at rows 0 and 32; on the row kernels every row's bits equal the decode's const mm: ?affine_mm.Pipes = wide.mm(p, q); // prompt.zig's (2: the routed experts' gathers) const on_mm = mm != null; - if (mm) |pipes| try submit(queue, mmLaunch, .{ pipes, q, bufs[3], bufs[6], bufs[5], prompt_rows }) else try submit(queue, rowsLaunch, .{ p, q, bufs[3], 0, bufs[5], prompt_rows }); + if (mm) |pipes| try submit(queue, mmLaunch, .{ pipes, p.mm_bm, q, bufs[3], bufs[6], bufs[5], prompt_rows }) else try submit(queue, rowsLaunch, .{ p, q, bufs[3], 0, bufs[5], prompt_rows }); t.worst = 0; const pitch = if (on_mm) np else n; for ([_]usize{ 0, prompt_rows - 1 }) |i| try against(q, w, s, b, x, bufs[5].slice(u16, prompt_rows * pitch), pitch, i, &t, 1); diff --git a/zig/tests/glm_rows_speed_prompt.zig b/zig/tests/glm_rows_speed_prompt.zig index 0aab170c6ec..55cab5c132f 100644 --- a/zig/tests/glm_rows_speed_prompt.zig +++ b/zig/tests/glm_rows_speed_prompt.zig @@ -25,11 +25,11 @@ fn headsRows(e: mtl.ComputeEncoder, i: usize, p: *const wide.Pipes, pool: Pool, wide.perHead(p, e, q, H, .{ .in = rf(io.x), .ldx = ldx, .out = rf(io.y), .ldo = q.n, .rows = PM }, kx, q.n / H); } /// The same as one affine_mm batch (prompt.zig headsMm). -fn headsMm(e: mtl.ComputeEncoder, i: usize, mm: tf.affine_mm.Pipes, pool: Pool, io: Io, ldx: u32, kx: u32) void { +fn headsMm(e: mtl.ComputeEncoder, i: usize, mm: tf.affine_mm.Pipes, bm: u32, pool: Pool, io: Io, ldx: u32, kx: u32) void { var head = pool.at(i); head.n /= H; tf.affine_mm.rowSumsAt(e, mm, 64, rf(io.x), rf(io.z), PM, H * kx, ldx); - tf.affine_mm.denseBatch(e, mm, rf(io.x), rf(io.z), head, rf(io.y), PM, H, .{ + tf.affine_mm.denseBatchBm(e, mm, rf(io.x), rf(io.z), head, rf(io.y), PM, H, .{ .x_row = @intCast(ldx), .y_row = @intCast(H * head.n), .sums_row = H, @@ -37,7 +37,7 @@ fn headsMm(e: mtl.ComputeEncoder, i: usize, mm: tf.affine_mm.Pipes, pool: Pool, .y_batch = @intCast(head.n), .sums_batch = 1, .w_batch = @intCast(head.n), - }); + }, bm); } fn ehRows(e: mtl.ComputeEncoder, i: usize, p: *const wide.Pipes, eh: mtl.Buffer, io: Io) void { _ = i; @@ -49,10 +49,10 @@ fn chunkRows(e: mtl.ComputeEncoder, i: usize, p: *const wide.Pipes, pool: Pool, const q = pool.at(i); wide.dense(p, e, q, .{ .in = rf(io.x), .ldx = q.k, .out = rf(io.y), .ldo = q.n, .rows = PM }); } -fn chunkMm(e: mtl.ComputeEncoder, i: usize, mm: tf.affine_mm.Pipes, pool: Pool, io: Io) void { +fn chunkMm(e: mtl.ComputeEncoder, i: usize, mm: tf.affine_mm.Pipes, bm: u32, pool: Pool, io: Io) void { const q = pool.at(i); tf.affine_mm.rowSums(e, mm, 64, rf(io.x), rf(io.z), PM, q.k); - tf.affine_mm.dense(e, mm, rf(io.x), rf(io.z), q, rf(io.y), PM); + tf.affine_mm.denseBm(e, mm, rf(io.x), rf(io.z), q, rf(io.y), PM, bm); } /// A prompt chunk's products where oQ's paths differ from uniform's, ms a chunk of 2048 rows. @@ -64,13 +64,13 @@ pub fn prompt(b: *Bench, k: *const kernels.Kernels, p: *const wide.Pipes) !void defer eq.deinit(); std.debug.print(" embed_q q8 per-head rows {d:8.2} affine_mm batch {d:8.2} (x11 a chunk)\n", .{ try b.time(headsRows, .{ p, eq, b.io, @as(u32, QR), @as(u32, 256) }) / 1e3, - try b.time(headsMm, .{ p.mm8, eq, b.io, @as(u32, QR), @as(u32, 256) }) / 1e3, + try b.time(headsMm, .{ p.mm8, p.mm_bm, eq, b.io, @as(u32, QR), @as(u32, 256) }) / 1e3, }); const uo = try Pool.init(b.device, H * 256, 512, 8, 1, 2); defer uo.deinit(); std.debug.print(" unembed_out q8 per-head rows {d:8.2} affine_mm batch {d:8.2} (x11 a chunk)\n", .{ try b.time(headsRows, .{ p, uo, b.io, @as(u32, H * 512), @as(u32, 512) }) / 1e3, - try b.time(headsMm, .{ p.mm8, uo, b.io, @as(u32, H * 512), @as(u32, 512) }) / 1e3, + try b.time(headsMm, .{ p.mm8, p.mm_bm, uo, b.io, @as(u32, H * 512), @as(u32, 512) }) / 1e3, }); { // the MTP head's bf16 eh_proj [4096, 8192] over the chunk (prompt.zig mtp) const eh = try buf(b.device, D * 2 * D * 2); @@ -86,12 +86,13 @@ pub fn prompt(b: *Bench, k: *const kernels.Kernels, p: *const wide.Pipes) !void defer m8.deinit(); const m4 = try Pool.init(b.device, s[0], s[1], 4, 1, 2); defer m4.deinit(); - const t8 = try b.time(chunkMm, .{ p.mm8, m8, b.io }); - const t4 = try b.time(chunkMm, .{ k.mm_bf16, m4, b.io }); + const t8 = try b.time(chunkMm, .{ p.mm8, p.mm_bm, m8, b.io }); + const k_bm: u32 = if (k.m3_fast) 32 else 64; + const t4 = try b.time(chunkMm, .{ k.mm_bf16, k_bm, m4, b.io }); for ([_]u8{ 5, 6 }) |bits| { const m = try Pool.init(b.device, s[0], s[1], bits, 1, 2); defer m.deinit(); - const on_mm = if (wide.mm(p, m.at(0))) |mm| try b.time(chunkMm, .{ mm, m, b.io }) else 0; + const on_mm = if (wide.mm(p, m.at(0))) |mm| try b.time(chunkMm, .{ mm, p.mm_bm, m, b.io }) else 0; std.debug.print( " [{d}, {d}] q{d} rows {d:8.2} affine_mm {d:8.2} (affine_mm q8 {d:.2}, q4 {d:.2})\n", .{ s[0], s[1], bits, try b.time(chunkRows, .{ p, m, b.io }) / 1e3, on_mm / 1e3, t8 / 1e3, t4 / 1e3 }, diff --git a/zig/tests/idol.zig b/zig/tests/idol.zig new file mode 100644 index 00000000000..4359d38e454 --- /dev/null +++ b/zig/tests/idol.zig @@ -0,0 +1,242 @@ +//! tf-idol: Idol's denoiser on a case from tools/zig/idol_case.py, compared with idol-sdk's, gated and timed. +const std = @import("std"); +const mtl = @import("metal"); +const tf = @import("tensorfold"); +const id = tf.idol; +const cfg = id.config; +const ref = id.reference; + +const usage = + \\tf-idol SNAPSHOT_DIR CASE_DIR [blocks STEP] + \\SNAPSHOT_DIR is a speridlabs/idol snapshot (config.json, denoiser.safetensors). CASE_DIR (tools/zig/idol_case.py) + \\holds case.safetensors: both image conditions, the starting noise and the SDK's run (each step's input and both + \\branches' velocities), and optionally exact.safetensors (the same steps in float32). Each step runs both branches on + \\the SDK's input; with exact.safetensors each 1 - cosine against float32 must be within twice the SDK's own, and + \\so must the worst row over the run. Then the whole guided schedule runs from the noise, timed; CASE_DIR gets tf-idol.json and + \\sample.f32 (8192 x 16, then the 5 camera values). Exit 1 on a failed gate or a forward that does not repeat. + \\With `blocks STEP`, runs each joint block alone on the SDK's input rows at that step (blocksSTEP.safetensors) + \\and gates it against the same block in float32 (blocksSTEP_f32.safetensors), worst row and 1 - cosine. +; + +/// The card's sampling defaults. +const guidance: f32 = 3.0; +const rescale: f64 = 3.0; + +fn take(a: std.mem.Allocator, f: *const tf.safetensors.File, name: []const u8, n: usize) ![]f32 { + const t = f.get(name) orelse { + std.debug.print("the case has no {s}\n", .{name}); + return error.MissingTensor; + }; + if (t.dtype != .f32 or t.numel() != n) { + std.debug.print("{s} is not {d} float32 values\n", .{ name, n }); + return error.BadCaseTensor; + } + const out = try a.alloc(f32, n); + @memcpy(std.mem.sliceAsBytes(out), t.bytes); + return out; +} + +fn print(list: *std.ArrayList(u8), a: std.mem.Allocator, comptime fmt: []const u8, args: anytype) !void { + try list.appendSlice(a, try std.fmt.allocPrint(a, fmt, args)); +} + +fn json(list: *std.ArrayList(u8), a: std.mem.Allocator, key: []const u8, m: ref.Match) !void { + try print(list, a, ", \"{s}\": {{\"max_abs\": {d:.6}, \"cosine\": {d:.9}, \"worst_row\": {d:.6}}}", .{ key, m.max_abs, m.cosine, m.worst_row }); +} + +const Case = struct { + steps: usize, + timesteps: []f32, + inputs: []f32, + inputs_camera: []f32, + velocity: [2][]f32, + velocity_camera: [2][]f32, + exact: ?[2][]f32, +}; + +const N = cfg.latent_rows * cfg.latent_channels; +const labels = [2][]const u8{ "conditional", "negative" }; + +/// Each step's two branches on the SDK's input against its velocities; returns false when a gate fails. +fn teacher(a: std.mem.Allocator, c: Case, model: *id.Model, conds: *[2]id.Condition, out: *std.ArrayList(u8)) !bool { + var pass = true; + var worst = [2]f64{ 0, 0 }; + const v = try a.alloc(f32, N); + var vc: [cfg.camera_channels]f32 = undefined; + try print(out, a, ", \"teacher_forced\": [", .{}); + for (0..c.steps) |s| { + try print(out, a, "{s}{{\"step\": {d}, \"time\": {d:.4}", .{ if (s == 0) "" else ", ", s + 1, c.timesteps[s] }); + const cam: *const [cfg.camera_channels]f32 = c.inputs_camera[s * cfg.camera_channels ..][0..cfg.camera_channels]; + for (0..2) |b| { + _ = try model.forward(&conds[b], c.inputs[s * N ..][0..N], cam, c.timesteps[s], v, &vc); + const theirs = c.velocity[b][s * N ..][0..N]; + const m = ref.match(v, theirs, cfg.latent_channels); + const mc = ref.match(&vc, c.velocity_camera[b][s * cfg.camera_channels ..][0..cfg.camera_channels], cfg.camera_channels); + std.debug.print("step {d} {s}: against the SDK max |diff| {d:.5}, cosine {d:.8}, worst row {d:.5}; camera cosine {d:.7}\n", .{ s + 1, labels[b], m.max_abs, m.cosine, m.worst_row, mc.cosine }); + try json(out, a, try std.fmt.allocPrint(a, "{s}_sdk", .{labels[b]}), m); + try json(out, a, try std.fmt.allocPrint(a, "{s}_camera_sdk", .{labels[b]}), mc); + if (c.exact) |ex| if (ex[b].len >= (s + 1) * N) { + const want = ex[b][s * N ..][0..N]; + const ours = ref.match(v, want, cfg.latent_channels); + const sdk = ref.match(theirs, want, cfg.latent_channels); + const ok = ref.withinCosine(ours, sdk); + pass = pass and ok; + worst[0] = @max(worst[0], ours.worst_row); + worst[1] = @max(worst[1], sdk.worst_row); + std.debug.print(" against float32: worst row {d:.5}, cosine {d:.8}; the SDK's own {d:.5}, {d:.8}: {s}\n", .{ ours.worst_row, ours.cosine, sdk.worst_row, sdk.cosine, if (ok) "pass" else "FAIL" }); + try json(out, a, try std.fmt.allocPrint(a, "{s}_fp32", .{labels[b]}), ours); + try json(out, a, try std.fmt.allocPrint(a, "{s}_sdk_vs_fp32", .{labels[b]}), sdk); + }; + } + try out.append(a, '}'); + } + if (c.exact != null) { + const ok = worst[0] <= ref.factor * worst[1]; + std.debug.print("worst row over the run against float32: {d:.5}; the SDK's own {d:.5}: {s}\n", .{ worst[0], worst[1], if (ok) "pass" else "FAIL" }); + pass = pass and ok; + } + try print(out, a, "], \"worst_row_fp32\": {d:.6}, \"sdk_worst_row_fp32\": {d:.6}", .{ worst[0], worst[1] }); + return pass; +} + +/// The same step twice with the other branch between: identical bytes or not. +fn repeats(a: std.mem.Allocator, c: Case, model: *id.Model, conds: *[2]id.Condition) !bool { + const first = try a.alloc(f32, N); + const again = try a.alloc(f32, N); + var vc: [cfg.camera_channels]f32 = undefined; + const cam: *const [cfg.camera_channels]f32 = c.inputs_camera[0..cfg.camera_channels]; + _ = try model.forward(&conds[0], c.inputs[0..N], cam, c.timesteps[0], first, &vc); + _ = try model.forward(&conds[1], c.inputs[0..N], cam, c.timesteps[@min(1, c.steps - 1)], again, &vc); + _ = try model.forward(&conds[0], c.inputs[0..N], cam, c.timesteps[0], again, &vc); + return std.mem.eql(u8, std.mem.sliceAsBytes(first), std.mem.sliceAsBytes(again)); +} + +/// The case tensor `name`, fp16 or fp32 rows, as f32. +fn rows(a: std.mem.Allocator, f: *const tf.safetensors.File, name: []const u8) ![]f32 { + const t = f.get(name) orelse return error.MissingTensor; + const out = try a.alloc(f32, t.numel()); + switch (t.dtype) { + .f16 => for (out, @as([*]align(1) const f16, @ptrCast(t.bytes.ptr))[0..out.len]) |*o, v| { + o.* = v; + }, + .f32 => @memcpy(std.mem.sliceAsBytes(out), t.bytes), + else => return error.BadCaseTensor, + } + return out; +} + +/// Each joint block alone on the SDK's own input rows at step `step`, against that block in float32; false on a fail. +fn blockGates(a: std.mem.Allocator, io: std.Io, dir: []const u8, step: usize, c: Case, model: *id.Model) !bool { + var f = try tf.safetensors.File.open(a, io, try std.fmt.allocPrint(a, "{s}/blocks{d}.safetensors", .{ dir, step })); + defer f.close(io); + var g = try tf.safetensors.File.open(a, io, try std.fmt.allocPrint(a, "{s}/blocks{d}_f32.safetensors", .{ dir, step })); + defer g.close(io); + const H = cfg.hidden; + var pass = true; + var name: [32]u8 = undefined; + for (1..cfg.layers) |i| { + const input = try rows(a, &f, try std.fmt.bufPrint(&name, "block.{d}", .{i - 1})); + const in16 = try a.alloc(f16, input.len); + for (in16, input) |*o, v| o.* = @floatCast(v); + try model.blockAt(cfg.refiners + i, in16, c.timesteps[step]); + const ours = try a.alloc(f32, input.len); + for (ours, model.stream(cfg.joint_rows)) |*o, v| o.* = v; + const label = try std.fmt.bufPrint(&name, "block.{d}", .{i}); + const want = try rows(a, &g, label); + const m = ref.match(ours, want, H); + const r = ref.match(try rows(a, &f, label), want, H); + const ok = ref.within(m, r); + pass = pass and ok; + std.debug.print("step {d} block {d} against float32: worst row {d:.5}, cosine {d:.9}; the SDK's own {d:.5}, {d:.9}: {s}\n", .{ step + 1, i, m.worst_row, m.cosine, r.worst_row, r.cosine, if (ok) "pass" else "FAIL" }); + } + return pass; +} + +pub fn main(init: std.process.Init) !u8 { + const a = init.arena.allocator(); + const io = init.io; + const args = try init.minimal.args.toSlice(a); + if (args.len != 3 and args.len != 5) { + std.debug.print("{s}\n", .{usage}); + return 2; + } + var case = try tf.safetensors.File.open(a, io, try std.fmt.allocPrint(a, "{s}/case.safetensors", .{args[2]})); + defer case.close(io); + const steps = (case.get("timesteps") orelse return error.MissingTensor).numel(); + const S = steps; + const cam_n = cfg.camera_channels; + var c: Case = .{ .steps = S, .timesteps = try take(a, &case, "timesteps", S), .inputs = try take(a, &case, "inputs", S * N), .inputs_camera = try take(a, &case, "inputs_camera", S * cam_n), .velocity = .{ try take(a, &case, "velocity", S * N), try take(a, &case, "velocity_negative", S * N) }, .velocity_camera = .{ try take(a, &case, "velocity_camera", S * cam_n), try take(a, &case, "velocity_negative_camera", S * cam_n) }, .exact = null }; + const exact_path = try std.fmt.allocPrint(a, "{s}/exact.safetensors", .{args[2]}); + var exact_file: ?tf.safetensors.File = tf.safetensors.File.open(a, io, exact_path) catch null; + defer if (exact_file) |*f| f.close(io); + if (exact_file) |*f| { + const n = (f.get("velocity_f32") orelse return error.MissingTensor).numel(); + c.exact = .{ try take(a, f, "velocity_f32", n), try take(a, f, "velocity_negative_f32", n) }; + } + const f1 = try take(a, &case, "feature1", cfg.cond_rows * cfg.cond_channels); + const f2 = try take(a, &case, "feature2", cfg.cond_rows * cfg.cond2_channels); + const noise = try take(a, &case, "latent", N); + const noise_cam = try take(a, &case, "camera", cam_n); + + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const device = try mtl.Device.init(); + const loading = mtl.clock.seconds(); + const model = try id.Model.load(std.heap.page_allocator, io, device, args[1]); + defer model.deinit(); + const load_s = mtl.clock.seconds() - loading; + std.debug.print("{s}: {d} steps; loaded in {d:.1} s\n", .{ device.name(), S, load_s }); + + var out: std.ArrayList(u8) = .empty; + const conditioning = mtl.clock.seconds(); + var conds: [2]id.Condition = undefined; + conds[0] = try model.condition(f1, f2); + defer conds[0].deinit(); + @memset(f1, 0); + @memset(f2, 0); + conds[1] = try model.condition(f1, f2); + defer conds[1].deinit(); + const condition_s = mtl.clock.seconds() - conditioning; + if (args.len == 5) return if (try blockGates(a, io, args[2], try std.fmt.parseInt(usize, args[4], 10), c, model)) 0 else 1; + try print(&out, a, "{{\"device\": \"{s}\", \"steps\": {d}, \"load_s\": {d:.2}, \"condition_s\": {d:.4}", .{ device.name(), S, load_s, condition_s }); + const pass = try teacher(a, c, model, &conds, &out); + const repeat = try repeats(a, c, model, &conds); + std.debug.print("the same step twice, another between: {s}\n", .{if (repeat) "identical bytes" else "DIFFERENT bytes"}); + try print(&out, a, ", \"gates_pass\": {}, \"repeat_identical\": {}, \"run\": [", .{ pass and c.exact != null, repeat }); + + const ts = try a.alloc(f64, S + 1); + id.host.schedule(ts, rescale); + const x = try a.alloc(f32, N + cam_n); + @memcpy(x[0..N], noise); + @memcpy(x[N..], noise_cam); + const vc = try a.alloc(f32, N); + const vu = try a.alloc(f32, N); + var cc: [cam_n]f32 = undefined; + var cu: [cam_n]f32 = undefined; + var total: f64 = 0; + for (0..S) |s| { + const time: f32 = @floatCast(1000 * ts[s]); + const cam: *const [cam_n]f32 = x[N..][0..cam_n]; + const p = try model.forward(&conds[0], x[0..N], cam, time, vc, &cc); + const q = try model.forward(&conds[1], x[0..N], cam, time, vu, &cu); + const by: f32 = @floatCast(ts[s] - ts[s + 1]); + for (x[0..N], vc, vu) |*o, pc, pu| o.* -= ((1 + guidance) * pc - guidance * pu) * by; + for (x[N..], cc, cu) |*o, pc, pu| o.* -= ((1 + guidance) * pc - guidance * pu) * by; + const wall = p.wall + q.wall; + total += wall; + std.debug.print("step {d}/{d}: {d:.3} s ({d:.3} s on the GPU)\n", .{ s + 1, S, wall, p.gpu + q.gpu }); + try print(&out, a, "{s}{{\"wall_s\": {d:.4}, \"gpu_s\": {d:.4}}}", .{ if (s == 0) "" else ", ", wall, p.gpu + q.gpu }); + } + if (case.get("sample") != null) { + const sample = try take(a, &case, "sample", N); + const m = ref.match(x[0..N], sample, cfg.latent_channels); + std.debug.print("final sample against the SDK's: cosine {d:.6}, worst row {d:.4}\n", .{ m.cosine, m.worst_row }); + try print(&out, a, "]", .{}); + try json(&out, a, "sample_sdk", m); + try print(&out, a, ", \"denoise_s\": {d:.3}}}\n", .{total}); + } else try print(&out, a, "], \"denoise_s\": {d:.3}}}\n", .{total}); + std.debug.print("denoise: {d:.2} s for {d} steps ({d} forwards)\n", .{ total, S, 2 * S }); + try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = try std.fmt.allocPrint(a, "{s}/sample.f32", .{args[2]}), .data = std.mem.sliceAsBytes(x) }); + try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = try std.fmt.allocPrint(a, "{s}/tf-idol.json", .{args[2]}), .data = out.items }); + return if (repeat and (c.exact == null or pass)) 0 else 1; +} diff --git a/zig/tests/ling_mla_gpu.zig b/zig/tests/ling_mla_gpu.zig new file mode 100644 index 00000000000..15dc64e79d1 --- /dev/null +++ b/zig/tests/ling_mla_gpu.zig @@ -0,0 +1,6 @@ +//! GPU check of Ling MLA around k3_mla: RoPE, head-gate expand, mixer vs mla.zig. +test { + _ = @import("ling_mla_gpu_kernels.zig"); + _ = @import("ling_mla_gpu_mixer.zig"); + _ = @import("ling_mla_gpu_chunks.zig"); +} diff --git a/zig/tests/ling_mla_gpu_chunks.zig b/zig/tests/ling_mla_gpu_chunks.zig new file mode 100644 index 00000000000..412eaf117d3 --- /dev/null +++ b/zig/tests/ling_mla_gpu_chunks.zig @@ -0,0 +1,238 @@ +//! Ling MLA whole vs chunks, resume vs fresh, large-T and dump gates. +const std = @import("std"); +const mtl = @import("metal"); +const mla = @import("mla"); +const c = @import("ling_mla_gpu_common.zig"); +const dump = @import("ling_mla_gpu_dump.zig"); + +const k3_gpu_rows: u32 = 256; + +fn checkChunks() !void { + const a = std.testing.allocator; + const rows: u32 = 4; + const s = mla.Shape{ .heads = 16, .eps = mla.eps_tiny, .theta = mla.theta_tiny }; + const in = try c.Inputs.make(a, s, rows, 0x6d6c61); + defer in.free(a); + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + var g = try c.Gpu.init(); + defer g.deinit(); + var whole = try c.Launch.open(g, s, rows, in.q, in.kv, in.w, in.kvb, in.g); + defer whole.deinit(); + try whole.dispatchMixer(g, 0, rows); + var chunks = try c.Launch.open(g, s, rows, in.q, in.kv, in.w, in.kvb, in.g); + defer chunks.deinit(); + try chunks.dispatchMixer(g, 0, 2); + try chunks.dispatchMixer(g, 2, 2); + try c.expectBitsEqual("whole vs chunks", whole.y(), chunks.y()); +} + +fn checkResume() !void { + const a = std.testing.allocator; + const rows: u32 = 4; + const s = mla.Shape{ .heads = 16, .eps = mla.eps_tiny, .theta = mla.theta_tiny }; + const in = try c.Inputs.make(a, s, rows, 0x72657375); + defer in.free(a); + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + var g = try c.Gpu.init(); + defer g.deinit(); + var fresh = try c.Launch.open(g, s, rows, in.q, in.kv, in.w, in.kvb, in.g); + defer fresh.deinit(); + try fresh.dispatchMixer(g, 0, rows); + var continued = try c.Launch.open(g, s, rows, in.q, in.kv, in.w, in.kvb, in.g); + defer continued.deinit(); + try continued.dispatchMixer(g, 0, 2); + try continued.dispatchMixer(g, 2, 2); + const W = s.outWidth(); + try c.expectBitsEqual("resume vs fresh (all rows)", fresh.y(), continued.y()); + try c.expectBitsEqual("resume vs fresh (last 2)", fresh.y()[2 * W ..], continued.y()[2 * W ..]); +} + +fn checkRopeLargePos() !void { + const a = std.testing.allocator; + const s = mla.Shape{ .heads = 16, .eps = mla.eps_tiny, .theta = mla.theta_tiny }; + const rows_n: u32 = 2; + const first_pos: u32 = 29998; + const slot_keys: u32 = 30000; + const H = s.heads; + var seed: u64 = 0x72333030; + const q = try c.fill(&seed, rows_n * H * mla.qd, a); + defer a.free(q); + c.roundSlice(q); + const rope_in = try c.fill(&seed, rows_n * mla.rope_dim, a); + defer a.free(rope_in); + c.roundSlice(rope_in); + + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + var gpu = try c.Gpu.init(); + defer gpu.deinit(); + const shared = mtl.ResourceOptions.shared; + const b_q = try gpu.device.buffer(q.len * 2, shared); + defer b_q.deinit(); + c.putBf16(b_q, q); + const b_rows = try gpu.device.buffer(rows_n * @sizeOf(c.MlaRow), shared); + defer b_rows.deinit(); + const rows = b_rows.slice(c.MlaRow, rows_n); + for (rows, 0..) |*r, i| r.* = .{ .slot = 0, .pos = first_pos + @as(u32, @intCast(i)) }; + const b_cs = try gpu.device.buffer(rows_n * mla.nfreq * 2 * 4, shared); + defer b_cs.deinit(); + c.writeCs(b_cs.slice(f32, rows_n * mla.nfreq * 2), rows, s.theta); + const b_cache = try gpu.device.buffer(@as(usize, slot_keys) * mla.key * 2, shared); + defer b_cache.deinit(); + const cache = b_cache.slice(u16, slot_keys * mla.key); + for (0..rows_n) |t| { + const base = (first_pos + t) * mla.key + mla.lat; + for (0..mla.rope_dim) |i| cache[base + i] = c.toBf16(rope_in[t * mla.rope_dim + i]); + } + const aa = c.MlaArgs{ + .cache = b_cache.gpuAddress(), + .slot_keys = slot_keys, + .heads = H, + .head0 = 0, + .rows = rows_n, + .q_stride = H * mla.qd, + .kv_stride = mla.key, + .gate_stride = H * mla.vd, + .out_stride = H * mla.vd, + .eps = s.eps, + .scale = @floatCast(s.scale()), + }; + + { + const cb = gpu.queue.commandBuffer(); + const e = cb.compute(.serial); + e.setPipeline(gpu.rope_q); + e.setBuffer(b_q, 0, 0); + e.setValue(aa, 1); + e.setBuffer(b_cs, 0, 2); + e.dispatchGroups(mtl.Size.of(H, rows_n, 1), mtl.Size.of(32, 1, 1)); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |why| { + std.debug.print("rope_q large pos failed: {s}\n", .{why}); + return error.GpuFailed; + } + } + const got_q = b_q.slice(u16, q.len); + const nq = rows_n * H * mla.rope_dim; + const metal_q = try a.alloc(f64, nq); + defer a.free(metal_q); + const f64_q = try a.alloc(f64, nq); + defer a.free(f64_q); + const bf_q = try a.alloc(f64, nq); + defer a.free(bf_q); + var k: usize = 0; + for (0..rows_n) |t| { + for (0..H) |h| { + var z64: [mla.rope_dim]f64 = undefined; + var out: [mla.rope_dim]f64 = undefined; + const base = (t * H + h) * mla.qd + mla.nope; + for (0..mla.rope_dim) |i| z64[i] = q[base + i]; + mla.rotate(&out, &z64, first_pos + @as(u32, @intCast(t)), s.theta); + for (0..mla.rope_dim) |i| { + f64_q[k] = out[i]; + bf_q[k] = c.fromBf16(c.toBf16(@floatCast(out[i]))); + metal_q[k] = c.fromBf16(got_q[base + i]); + k += 1; + } + } + } + const q_gate = c.gateNamedF64("rope_q pos 29998-29999", metal_q, f64_q, bf_q); + + { + const cb = gpu.queue.commandBuffer(); + const e = cb.compute(.serial); + e.setPipeline(gpu.rope_cache); + e.setBuffer(b_rows, 0, 0); + e.setValue(aa, 1); + e.setBuffer(b_cs, 0, 2); + e.useResource(b_cache, mtl.ResourceUsage.read | mtl.ResourceUsage.write); + e.dispatchGroups(mtl.Size.of(rows_n, 1, 1), mtl.Size.of(32, 1, 1)); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |why| { + std.debug.print("rope_cache large pos failed: {s}\n", .{why}); + return error.GpuFailed; + } + } + const nc = rows_n * mla.rope_dim; + const metal_c = try a.alloc(f64, nc); + defer a.free(metal_c); + const f64_c = try a.alloc(f64, nc); + defer a.free(f64_c); + const bf_c = try a.alloc(f64, nc); + defer a.free(bf_c); + k = 0; + for (0..rows_n) |t| { + var z64: [mla.rope_dim]f64 = undefined; + var out: [mla.rope_dim]f64 = undefined; + for (0..mla.rope_dim) |i| z64[i] = rope_in[t * mla.rope_dim + i]; + mla.rotate(&out, &z64, first_pos + @as(u32, @intCast(t)), s.theta); + const base = (first_pos + t) * mla.key + mla.lat; + for (0..mla.rope_dim) |i| { + f64_c[k] = out[i]; + bf_c[k] = c.fromBf16(c.toBf16(@floatCast(out[i]))); + metal_c[k] = c.fromBf16(cache[base + i]); + k += 1; + } + } + const cache_gate = c.gateNamedF64("rope_cache pos 29998-29999", metal_c, f64_c, bf_c); + q_gate catch |e| return e; + cache_gate catch |e| return e; +} + +fn checkLarge(rows: u32, left: u32, seed: u64, tag: []const u8) !void { + const a = std.testing.allocator; + const s = mla.Shape{ .heads = 16, .eps = mla.eps_tiny, .theta = mla.theta_tiny }; + const in = try c.Inputs.make(a, s, rows, seed); + defer in.free(a); + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + var g = try c.Gpu.init(); + defer g.deinit(); + var whole = try c.Launch.open(g, s, rows, in.q, in.kv, in.w, in.kvb, in.g); + defer whole.deinit(); + try whole.dispatchMixer(g, 0, rows); + var parts = try c.Launch.open(g, s, rows, in.q, in.kv, in.w, in.kvb, in.g); + defer parts.deinit(); + try parts.dispatchMixer(g, 0, left); + try parts.dispatchMixer(g, left, rows - left); + var buf: [96]u8 = undefined; + const t1 = try std.fmt.bufPrint(&buf, "{s} whole vs chunks", .{tag}); + try c.expectBitsEqual(t1, whole.y(), parts.y()); + var buf2: [96]u8 = undefined; + const t2 = try std.fmt.bufPrint(&buf2, "{s} resume vs fresh", .{tag}); + try c.expectBitsEqual(t2, whole.y(), parts.y()); +} + +test "MLA mixer 4 rows equals 2+2 bits-equal" { + try checkChunks(); +} + +test "MLA mixer resume vs fresh bits-equal" { + try checkResume(); +} + +test "TFLINGA1 tiny layer 3 T=4 pos0=0 Metal and mixF64 vs python f64" { + try dump.checkDumpFile(dump.dump_a1_t4_path, 0, "dump T=4 pos0=0", true); +} + +test "TFLINGA1 tiny layer 3 T=2 pos0=30000 mixF64 vs python host-only" { + try dump.checkDumpFile(dump.dump_a1_t2_path, 1, "dump T=2 pos0=30000", false); +} + +test "Ling rope_q and rope_cache at pos 29998-29999 vs f64" { + try checkRopeLargePos(); +} + +test "MLA mixer T=100 as 37+63 bits-equal" { + try checkLarge(100, 37, 0x74313030, "T=100"); +} + +test "MLA mixer T=257 as 256+1 bits-equal (k3 gpu_rows)" { + try checkLarge(257, k3_gpu_rows, 0x74323537, "T=257"); +} diff --git a/zig/tests/ling_mla_gpu_common.zig b/zig/tests/ling_mla_gpu_common.zig new file mode 100644 index 00000000000..39b8b2316f0 --- /dev/null +++ b/zig/tests/ling_mla_gpu_common.zig @@ -0,0 +1,427 @@ +//! Shared Gpu/Launch/helpers for Ling MLA GPU tests around k3_mla. +const std = @import("std"); +const mtl = @import("metal"); +const mla = @import("mla"); +const metallib = @import("kimi_metallib"); + +const source = @import("ling_metal").mla; +const mla_splits: u32 = 16; + +pub const MlaRow = extern struct { slot: u32, pos: u32 }; +pub const MlaArgs = extern struct { + cache: u64, + slot_keys: u32, + heads: u32, + head0: u32, + rows: u32, + q_stride: u32, + kv_stride: u32, + gate_stride: u32, + out_stride: u32, + eps: f32, + scale: f32, +}; + +comptime { + if (@sizeOf(MlaArgs) != 48) @compileError("MlaArgs must stay 48 bytes, matching k3"); +} + +pub fn toBf16(v: f32) u16 { + const bits: u32 = @bitCast(v); + if (std.math.isNan(v)) return @truncate((bits >> 16) | 0x40); + return @truncate((bits +% 0x7fff +% ((bits >> 16) & 1)) >> 16); +} +pub fn fromBf16(h: u16) f32 { + return @bitCast(@as(u32, h) << 16); +} + +pub fn fill(seed: *u64, n: usize, a: std.mem.Allocator) ![]f32 { + const x = try a.alloc(f32, n); + for (x) |*v| { + seed.* = seed.* *% 1103515245 +% 12345; + v.* = @as(f32, @floatFromInt((seed.* >> 16) & 0x7fff)) / 16384.0 - 1.0; + } + return x; +} + +pub fn putBf16(buf: mtl.Buffer, x: []const f32) void { + const d = buf.slice(u16, x.len); + for (x, d) |v, *o| o.* = toBf16(v); +} + +pub fn roundSlice(x: []f32) void { + for (x) |*v| v.* = fromBf16(toBf16(v.*)); +} + +/// Host f64 cos/sin of each row's pos, rounded to f32. Layout [t][i][comp] = t*64 + i*2 + comp. +pub fn writeCs(cs: []f32, rows: []const MlaRow, theta: f64) void { + std.debug.assert(cs.len >= rows.len * mla.nfreq * 2); + for (rows, 0..) |r, t| { + for (0..mla.nfreq) |i| { + const ang = @as(f64, @floatFromInt(r.pos)) * mla.invFreq(theta, i); + const at = (t * mla.nfreq + i) * 2; + cs[at] = @floatCast(@cos(ang)); + cs[at + 1] = @floatCast(@sin(ang)); + } + } +} + +pub const Gpu = struct { + device: mtl.Device, + queue: mtl.Queue, + kimi: mtl.Library, + ling: mtl.Library, + cache: mtl.Pipeline, + qlat: mtl.Pipeline, + attend: mtl.Pipeline, + merge: mtl.Pipeline, + uv: mtl.Pipeline, + rope_cache: mtl.Pipeline, + rope_q: mtl.Pipeline, + gate_expand: mtl.Pipeline, + + pub fn init() !Gpu { + const device = try mtl.Device.init(); + errdefer device.deinit(); + const kimi = try mtl.Library.fromBytes(device, metallib.bytes); + errdefer kimi.deinit(); + const ling = try mtl.Library.fromSource(device, source, mtl.CompileOptions.mlx()); + errdefer ling.deinit(); + const cache = try mtl.Pipeline.init(device, kimi, "k3_mla_cache", false); + errdefer cache.deinit(); + const qlat = try mtl.Pipeline.init(device, kimi, "k3_mla_qlat", false); + errdefer qlat.deinit(); + const attend = try mtl.Pipeline.init(device, kimi, "k3_mla_attend", false); + errdefer attend.deinit(); + const merge = try mtl.Pipeline.init(device, kimi, "k3_mla_merge", false); + errdefer merge.deinit(); + const uv = try mtl.Pipeline.init(device, kimi, "k3_mla_uv", false); + errdefer uv.deinit(); + const rope_cache = try mtl.Pipeline.init(device, ling, "tf_ling_mla_rope_cache", false); + errdefer rope_cache.deinit(); + const rope_q = try mtl.Pipeline.init(device, ling, "tf_ling_mla_rope_q", false); + errdefer rope_q.deinit(); + const gate_expand = try mtl.Pipeline.init(device, ling, "tf_ling_mla_gate_expand", false); + errdefer gate_expand.deinit(); + const queue = try device.queue(); + return .{ + .device = device, + .queue = queue, + .kimi = kimi, + .ling = ling, + .cache = cache, + .qlat = qlat, + .attend = attend, + .merge = merge, + .uv = uv, + .rope_cache = rope_cache, + .rope_q = rope_q, + .gate_expand = gate_expand, + }; + } + + pub fn deinit(g: *Gpu) void { + g.gate_expand.deinit(); + g.rope_q.deinit(); + g.rope_cache.deinit(); + g.uv.deinit(); + g.merge.deinit(); + g.attend.deinit(); + g.qlat.deinit(); + g.cache.deinit(); + g.ling.deinit(); + g.kimi.deinit(); + g.queue.deinit(); + g.device.deinit(); + } +}; + +pub const Launch = struct { + s: mla.Shape, + cap: u32, + b_q: mtl.Buffer, + b_kv: mtl.Buffer, + b_w: mtl.Buffer, + b_kvb: mtl.Buffer, + b_g: mtl.Buffer, + b_g2: mtl.Buffer, + b_y: mtl.Buffer, + b_rows: mtl.Buffer, + b_cache: mtl.Buffer, + b_qlat: mtl.Buffer, + b_partial: mtl.Buffer, + b_olat: mtl.Buffer, + b_cs: mtl.Buffer, + + pub fn open(g: Gpu, s: mla.Shape, cap: u32, q: []const f32, kv: []const f32, w_rms: []const f32, kvb: []const f32, gate: []const f32) !Launch { + const H = s.heads; + const shared = mtl.ResourceOptions.shared; + const b_q = try g.device.buffer(q.len * 2, shared); + const b_kv = try g.device.buffer(kv.len * 2, shared); + const b_w = try g.device.buffer(w_rms.len * 2, shared); + const b_kvb = try g.device.buffer(kvb.len * 2, shared); + const b_g = try g.device.buffer(gate.len * 2, shared); + const b_g2 = try g.device.buffer(cap * H * mla.vd * 2, shared); + const b_y = try g.device.buffer(cap * H * mla.vd * 2, shared); + const b_rows = try g.device.buffer(cap * @sizeOf(MlaRow), shared); + const b_cache = try g.device.buffer(cap * mla.key * 2, shared); + const b_qlat = try g.device.buffer(cap * H * mla.lat * 4, shared); + const b_partial = try g.device.buffer(cap * H * mla_splits * (mla.lat + 2) * 4, shared); + const b_olat = try g.device.buffer(cap * H * mla.lat * 4, shared); + const b_cs = try g.device.buffer(cap * mla.nfreq * 2 * 4, shared); + putBf16(b_q, q); + putBf16(b_kv, kv); + putBf16(b_w, w_rms); + putBf16(b_kvb, kvb); + putBf16(b_g, gate); + @memset(b_g2.slice(u16, cap * H * mla.vd), 0); + @memset(b_y.slice(u16, cap * H * mla.vd), 0); + @memset(b_cache.slice(u16, cap * mla.key), 0); + return .{ + .s = s, + .cap = cap, + .b_q = b_q, + .b_kv = b_kv, + .b_w = b_w, + .b_kvb = b_kvb, + .b_g = b_g, + .b_g2 = b_g2, + .b_y = b_y, + .b_rows = b_rows, + .b_cache = b_cache, + .b_qlat = b_qlat, + .b_partial = b_partial, + .b_olat = b_olat, + .b_cs = b_cs, + }; + } + + pub fn deinit(l: *Launch) void { + l.b_q.deinit(); + l.b_kv.deinit(); + l.b_w.deinit(); + l.b_kvb.deinit(); + l.b_g.deinit(); + l.b_g2.deinit(); + l.b_y.deinit(); + l.b_rows.deinit(); + l.b_cache.deinit(); + l.b_qlat.deinit(); + l.b_partial.deinit(); + l.b_olat.deinit(); + l.b_cs.deinit(); + } + + pub fn args(l: *Launch, n: u32) MlaArgs { + const H = l.s.heads; + const ow = H * mla.vd; + return .{ + .cache = l.b_cache.gpuAddress(), + .slot_keys = l.cap, + .heads = H, + .head0 = 0, + .rows = n, + .q_stride = H * mla.qd, + .kv_stride = mla.key, + .gate_stride = ow, + .out_stride = ow, + .eps = l.s.eps, + .scale = @floatCast(l.s.scale()), + }; + } + + pub fn fillRows(l: *Launch, first: u32, n: u32) void { + const rows = l.b_rows.slice(MlaRow, n); + for (rows, 0..) |*r, i| r.* = .{ .slot = 0, .pos = first + @as(u32, @intCast(i)) }; + } + + pub fn fillCs(l: *Launch, n: u32) void { + writeCs(l.b_cs.slice(f32, n * mla.nfreq * 2), l.b_rows.slice(MlaRow, n), l.s.theta); + } + + pub fn dispatchMixer(l: *Launch, g: Gpu, first: u32, n: u32) !void { + const H = l.s.heads; + const a = l.args(n); + l.fillRows(first, n); + l.fillCs(n); + const q_off = first * a.q_stride * 2; + const kv_off = first * a.kv_stride * 2; + const g_off = first * H * 2; + const y_off = first * a.out_stride * 2; + const g2_off = first * a.gate_stride * 2; + const rw = mtl.ResourceUsage.read | mtl.ResourceUsage.write; + const cb = g.queue.commandBuffer(); + const e = cb.compute(.serial); + + e.setPipeline(g.cache); + e.setBuffer(l.b_kv, kv_off, 0); + e.setBuffer(l.b_w, 0, 1); + e.setBuffer(l.b_rows, 0, 2); + e.setValue(a, 3); + e.useResource(l.b_cache, rw); + e.dispatchGroups(mtl.Size.of(n, 1, 1), mtl.Size.of(256, 1, 1)); + + e.setPipeline(g.rope_cache); + e.setBuffer(l.b_rows, 0, 0); + e.setValue(a, 1); + e.setBuffer(l.b_cs, 0, 2); + e.useResource(l.b_cache, rw); + e.dispatchGroups(mtl.Size.of(n, 1, 1), mtl.Size.of(32, 1, 1)); + + e.setPipeline(g.qlat); + e.setBuffer(l.b_q, q_off, 0); + e.setBuffer(l.b_kvb, 0, 1); + e.setBuffer(l.b_qlat, 0, 2); + e.setValue(a, 3); + e.dispatchGroups(mtl.Size.of(2, H, 1), mtl.Size.of(256, 1, 1)); + + e.setPipeline(g.rope_q); + e.setBuffer(l.b_q, q_off, 0); + e.setValue(a, 1); + e.setBuffer(l.b_cs, 0, 2); + e.dispatchGroups(mtl.Size.of(H, n, 1), mtl.Size.of(32, 1, 1)); + + e.setPipeline(g.attend); + e.setBuffer(l.b_q, q_off, 0); + e.setBuffer(l.b_qlat, 0, 1); + e.setBuffer(l.b_rows, 0, 2); + e.setBuffer(l.b_partial, 0, 3); + e.setValue(a, 4); + e.useResource(l.b_cache, mtl.ResourceUsage.read); + const fit: u32 = @intCast(@min(32, g.attend.maxThreads() / 32)); + const groups = (H + fit - 1) / fit; + const per = (H + groups - 1) / groups; + e.dispatchGroups(mtl.Size.of(groups, mla_splits, n), mtl.Size.of(32 * per, 1, 1)); + + e.setPipeline(g.merge); + e.setBuffer(l.b_partial, 0, 0); + e.setBuffer(l.b_rows, 0, 1); + e.setBuffer(l.b_olat, 0, 2); + e.setValue(a, 3); + e.dispatchGroups(mtl.Size.of(H, n, 1), mtl.Size.of(256, 1, 1)); + + e.setPipeline(g.gate_expand); + e.setBuffer(l.b_g, g_off, 0); + e.setBuffer(l.b_g2, g2_off, 1); + e.setValue(a, 2); + e.dispatchThreads(mtl.Size.of(H * mla.vd, n, 1), mtl.Size.of(128, 1, 1)); + + e.setPipeline(g.uv); + e.setBuffer(l.b_olat, 0, 0); + e.setBuffer(l.b_kvb, 0, 1); + e.setBuffer(l.b_g2, g2_off, 2); + e.setBuffer(l.b_y, y_off, 3); + e.setValue(a, 4); + e.dispatchGroups(mtl.Size.of(mla.vd / 4, H, 1), mtl.Size.of(128, 1, 1)); + + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |why| { + std.debug.print("GPU mixer failed: {s}\n", .{why}); + return error.GpuFailed; + } + } + + pub fn y(l: *Launch) []u16 { + return l.b_y.slice(u16, l.cap * l.s.outWidth()); + } +}; + +pub const Dist = struct { rel_l2: f64, max_abs: f64 }; + +pub fn dist(got: []const f64, ref: []const f64) Dist { + var num: f64 = 0; + var den: f64 = 0; + var max_abs: f64 = 0; + for (got, ref) |a, b| { + const d = a - b; + num += d * d; + den += b * b; + max_abs = @max(max_abs, @abs(d)); + } + const rel = if (den == 0) @sqrt(num) else @sqrt(num) / @sqrt(den); + return .{ .rel_l2 = rel, .max_abs = max_abs }; +} + +pub fn bitsToF64(bits: []const u16, out: []f64) void { + for (bits, out) |h, *o| o.* = fromBf16(h); +} + +pub fn gateNamed(tag: []const u8, metal: []const u16, f64_y: []const f64, bf16_y: []const f64) !void { + const a = std.testing.allocator; + const metal_f = try a.alloc(f64, metal.len); + defer a.free(metal_f); + bitsToF64(metal, metal_f); + try gateNamedF64(tag, metal_f, f64_y, bf16_y); +} + +pub fn gateNamedF64(tag: []const u8, metal: []const f64, f64_y: []const f64, bf16_y: []const f64) !void { + const m = dist(metal, f64_y); + const b = dist(bf16_y, f64_y); + std.debug.print("{s} Metal-to-f64 rel L2 {e} max abs {e}; bf16-ref-to-f64 rel L2 {e} max abs {e}\n", .{ tag, m.rel_l2, m.max_abs, b.rel_l2, b.max_abs }); + if (m.rel_l2 > b.rel_l2 or m.max_abs > b.max_abs) { + std.debug.print("{s} gate miss: Metal further from f64 than bf16-ref\n", .{tag}); + return error.Gate; + } +} + +pub fn oProj(out: []f64, y: []const f64, wo: []const f32, rows: u32, hidden: u32, width: u32) void { + std.debug.assert(out.len == rows * hidden and y.len == rows * width and wo.len == hidden * width); + for (0..rows) |t| { + for (0..hidden) |j| { + var acc: f64 = 0; + const wr = j * width; + const yr = t * width; + for (0..width) |i| acc += y[yr + i] * @as(f64, wo[wr + i]); + out[t * hidden + j] = acc; + } + } +} + +pub fn expectBitsEqual(tag: []const u8, a: []const u16, b: []const u16) !void { + if (std.mem.eql(u16, a, b)) return; + var n: usize = 0; + var first: usize = 0; + for (a, b, 0..) |x, yv, i| { + if (x != yv) { + if (n == 0) first = i; + n += 1; + } + } + std.debug.print("{s} bits-equal miss: {d} of {d} first i={d} a={x} b={x}\n", .{ tag, n, a.len, first, a[first], b[first] }); + return error.BitsEqual; +} + +pub const Inputs = struct { + q: []f32, + kv: []f32, + w: []f32, + kvb: []f32, + g: []f32, + + pub fn make(alloc: std.mem.Allocator, s: mla.Shape, rows: u32, seed0: u64) !Inputs { + var seed = seed0; + const H = s.heads; + const q = try fill(&seed, rows * H * mla.qd, alloc); + const kv = try fill(&seed, rows * mla.key, alloc); + const w = try fill(&seed, mla.lat, alloc); + const kvb = try fill(&seed, H * (mla.nope + mla.vd) * mla.lat, alloc); + const g = try fill(&seed, rows * H, alloc); + for (w) |*v| v.* = 0.5 + 0.5 * v.*; + roundSlice(q); + roundSlice(kv); + roundSlice(w); + roundSlice(kvb); + roundSlice(g); + return .{ .q = q, .kv = kv, .w = w, .kvb = kvb, .g = g }; + } + + pub fn free(in: Inputs, alloc: std.mem.Allocator) void { + alloc.free(in.q); + alloc.free(in.kv); + alloc.free(in.w); + alloc.free(in.kvb); + alloc.free(in.g); + } +}; diff --git a/zig/tests/ling_mla_gpu_dump.zig b/zig/tests/ling_mla_gpu_dump.zig new file mode 100644 index 00000000000..9a94d0efd6f --- /dev/null +++ b/zig/tests/ling_mla_gpu_dump.zig @@ -0,0 +1,251 @@ +//! TFLINGM1/TFLINGA1 dump parsing and Metal-vs-python mixer check. +const std = @import("std"); +const mtl = @import("metal"); +const mla = @import("mla"); +const c = @import("ling_mla_gpu_common.zig"); + +const dump_dir = "/tmp/ling-mla-dumps"; +pub const dump_mixer_path = dump_dir ++ "/mla_tiny_mixer.bin"; +pub const dump_a1_t4_path = dump_dir ++ "/mla_tiny_t4_pos0.bin"; +pub const dump_a1_t2_path = dump_dir ++ "/mla_tiny_t2_pos30000.bin"; +const dump_py = "zig/src/families/ling/oracle/mla_dump.py"; + +fn takeU32(b: []const u8, off: *usize) u32 { + const v = std.mem.readInt(u32, b[off.*..][0..4], .little); + off.* += 4; + return v; +} + +fn takeF32s(alloc: std.mem.Allocator, b: []const u8, off: *usize, n: usize) ![]f32 { + const x = try alloc.alloc(f32, n); + @memcpy(std.mem.sliceAsBytes(x), b[off.* .. off.* + n * 4]); + off.* += n * 4; + return x; +} + +fn takeF64s(alloc: std.mem.Allocator, b: []const u8, off: *usize, n: usize) ![]f64 { + const x = try alloc.alloc(f64, n); + @memcpy(std.mem.sliceAsBytes(x), b[off.* .. off.* + n * 8]); + off.* += n * 8; + return x; +} + +const DumpCase = struct { + T: u32, + pos0: u32, + q: []f32, + kv: []f32, + g: []f32, + y_pre: []f64, + y64: []f64, + ybf: []f64, +}; + +const Dump = struct { + hidden: u32, + layer: u32, + heads: u32, + w: []f32, + kvb: []f32, + Wo: []f32, + cases: []DumpCase, + + fn load(alloc: std.mem.Allocator, bytes: []const u8) !Dump { + try std.testing.expect(std.mem.eql(u8, bytes[0..8], "TFLINGM1")); + var off: usize = 8; + const hidden = takeU32(bytes, &off); + const layer = takeU32(bytes, &off); + const heads = takeU32(bytes, &off); + const n_cases = takeU32(bytes, &off); + const w = try takeF32s(alloc, bytes, &off, mla.lat); + errdefer alloc.free(w); + const kvb = try takeF32s(alloc, bytes, &off, heads * (mla.nope + mla.vd) * mla.lat); + errdefer alloc.free(kvb); + const Wo = try takeF32s(alloc, bytes, &off, hidden * heads * mla.vd); + errdefer alloc.free(Wo); + const cases = try alloc.alloc(DumpCase, n_cases); + errdefer alloc.free(cases); + for (cases) |*case| { + const T = takeU32(bytes, &off); + const pos0 = takeU32(bytes, &off); + const q = try takeF32s(alloc, bytes, &off, T * heads * mla.qd); + const kv = try takeF32s(alloc, bytes, &off, T * mla.key); + const g = try takeF32s(alloc, bytes, &off, T * heads); + const y_pre = try takeF64s(alloc, bytes, &off, T * heads * mla.vd); + const y64 = try takeF64s(alloc, bytes, &off, T * hidden); + const ybf = try takeF64s(alloc, bytes, &off, T * hidden); + case.* = .{ .T = T, .pos0 = pos0, .q = q, .kv = kv, .g = g, .y_pre = y_pre, .y64 = y64, .ybf = ybf }; + } + try std.testing.expectEqual(bytes.len, off); + return .{ .hidden = hidden, .layer = layer, .heads = heads, .w = w, .kvb = kvb, .Wo = Wo, .cases = cases }; + } + + fn deinit(d: Dump, alloc: std.mem.Allocator) void { + for (d.cases) |case| { + alloc.free(case.q); + alloc.free(case.kv); + alloc.free(case.g); + alloc.free(case.y_pre); + alloc.free(case.y64); + alloc.free(case.ybf); + } + alloc.free(d.cases); + alloc.free(d.w); + alloc.free(d.kvb); + alloc.free(d.Wo); + } +}; + +fn parseA1(alloc: std.mem.Allocator, bytes: []const u8) !struct { T: u32, hidden: u32, layer: u32, pos0: u32, y64: []f64, ybf: []f64 } { + try std.testing.expect(std.mem.eql(u8, bytes[0..8], "TFLINGA1")); + var off: usize = 8; + const T = takeU32(bytes, &off); + const hidden = takeU32(bytes, &off); + const layer = takeU32(bytes, &off); + const pos0 = takeU32(bytes, &off); + const n = T * hidden; + const y64 = try takeF64s(alloc, bytes, &off, n); + errdefer alloc.free(y64); + const ybf = try takeF64s(alloc, bytes, &off, n); + errdefer alloc.free(ybf); + try std.testing.expectEqual(bytes.len, off); + return .{ .T = T, .hidden = hidden, .layer = layer, .pos0 = pos0, .y64 = y64, .ybf = ybf }; +} + +fn dupeRound(alloc: std.mem.Allocator, src: []const f32) ![]f32 { + const d = try alloc.dupe(f32, src); + c.roundSlice(d); + return d; +} + +fn fileOk(path: []const u8) bool { + std.Io.Dir.cwd().access(std.testing.io, path, .{}) catch return false; + return true; +} + +fn hasTorch(py: []const u8) bool { + const a = std.testing.allocator; + const r = std.process.run(a, std.testing.io, .{ + .argv = &.{ py, "-c", "import torch" }, + .stdout_limit = .limited(256), + .stderr_limit = .limited(4096), + }) catch return false; + defer a.free(r.stdout); + defer a.free(r.stderr); + return r.term.success(); +} + +fn findPython() ?[]const u8 { + if (std.c.getenv("TF_LING_PYTHON")) |p| { + const s = std.mem.span(p); + if (hasTorch(s)) return s; + } + if (hasTorch("python3")) return "python3"; + return null; +} + +fn ensureDumps() !void { + if (fileOk(dump_mixer_path) and fileOk(dump_a1_t4_path) and fileOk(dump_a1_t2_path)) return; + if (!fileOk(dump_py)) { + std.debug.print("skip: {s} not in cwd; TFLINGA1 dumps need ling_forward.py at test time\n", .{dump_py}); + return error.SkipZigTest; + } + const py = findPython() orelse { + std.debug.print("skip: no torch (set TF_LING_PYTHON or python3 on PATH); TFLINGA1 dumps come from ling_forward.py at test time\n", .{}); + return error.SkipZigTest; + }; + const a = std.testing.allocator; + const r = try std.process.run(a, std.testing.io, .{ + .argv = &.{ py, dump_py, dump_dir }, + .stdout_limit = .limited(4096), + .stderr_limit = .limited(65536), + }); + defer a.free(r.stdout); + defer a.free(r.stderr); + if (!r.term.success()) { + std.debug.print("mla_dump.py failed: {s}{s}\n", .{ r.stdout, r.stderr }); + return error.DumpGen; + } + if (!fileOk(dump_mixer_path) or !fileOk(dump_a1_t4_path) or !fileOk(dump_a1_t2_path)) return error.DumpGen; +} + +fn readDump(path: []const u8) ![]u8 { + return std.Io.Dir.cwd().readFileAlloc(std.testing.io, path, std.testing.allocator, .limited(32 << 20)); +} + +pub fn checkDumpFile(a1_path: []const u8, case_i: usize, tag: []const u8, gpu: bool) !void { + try ensureDumps(); + const a = std.testing.allocator; + const mixer_bytes = try readDump(dump_mixer_path); + defer a.free(mixer_bytes); + const a1_bytes = try readDump(a1_path); + defer a.free(a1_bytes); + try checkDump(mixer_bytes, a1_bytes, case_i, tag, gpu); +} + +fn checkDump(mixer_bytes: []const u8, a1_bytes: []const u8, case_i: usize, tag: []const u8, gpu: bool) !void { + const a = std.testing.allocator; + const dump = try Dump.load(a, mixer_bytes); + defer dump.deinit(a); + const a1 = try parseA1(a, a1_bytes); + defer a.free(a1.y64); + defer a.free(a1.ybf); + const case = dump.cases[case_i]; + try std.testing.expectEqual(a1.T, case.T); + try std.testing.expectEqual(a1.hidden, dump.hidden); + try std.testing.expectEqual(a1.layer, dump.layer); + try std.testing.expectEqual(a1.pos0, case.pos0); + try std.testing.expect(std.mem.eql(f64, a1.y64, case.y64)); + + const s = mla.Shape{ .heads = dump.heads, .eps = mla.eps_tiny, .theta = mla.theta_tiny }; + const width = s.outWidth(); + const n_mix = case.T * width; + const mix64 = try a.alloc(f64, n_mix); + defer a.free(mix64); + try mla.mixF64(a, mix64, case.q, case.kv, dump.w, dump.kvb, case.g, s, case.T, case.pos0); + const d_pre = c.dist(mix64, case.y_pre); + std.debug.print("{s} mixF64-to-python mixer rel L2 {e} max abs {e}\n", .{ tag, d_pre.rel_l2, d_pre.max_abs }); + const layer_mix = try a.alloc(f64, case.T * dump.hidden); + defer a.free(layer_mix); + c.oProj(layer_mix, mix64, dump.Wo, case.T, dump.hidden, width); + const d_layer = c.dist(layer_mix, a1.y64); + std.debug.print("{s} mixF64+o_proj-to-TFLINGA1 rel L2 {e} max abs {e}\n", .{ tag, d_layer.rel_l2, d_layer.max_abs }); + if (!gpu) return; + + const mix_bf = try a.alloc(f64, n_mix); + defer a.free(mix_bf); + const q_m = try dupeRound(a, case.q); + defer a.free(q_m); + const kv_m = try dupeRound(a, case.kv); + defer a.free(kv_m); + const w_m = try dupeRound(a, dump.w); + defer a.free(w_m); + const kvb_m = try dupeRound(a, dump.kvb); + defer a.free(kvb_m); + const g_m = try dupeRound(a, case.g); + defer a.free(g_m); + try mla.mixBf16(a, mix_bf, q_m, kv_m, w_m, kvb_m, g_m, s, case.T, case.pos0); + + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + var gpu_dev = try c.Gpu.init(); + defer gpu_dev.deinit(); + var l = try c.Launch.open(gpu_dev, s, case.T, q_m, kv_m, w_m, kvb_m, g_m); + defer l.deinit(); + try l.dispatchMixer(gpu_dev, 0, case.T); + const metal_mix = try a.alloc(f64, n_mix); + defer a.free(metal_mix); + c.bitsToF64(l.y(), metal_mix); + const d_metal_pre = c.dist(metal_mix, case.y_pre); + std.debug.print("{s} Metal-to-python mixer rel L2 {e} max abs {e}\n", .{ tag, d_metal_pre.rel_l2, d_metal_pre.max_abs }); + + const layer_bf = try a.alloc(f64, case.T * dump.hidden); + defer a.free(layer_bf); + const layer_metal = try a.alloc(f64, case.T * dump.hidden); + defer a.free(layer_metal); + c.oProj(layer_bf, mix_bf, dump.Wo, case.T, dump.hidden, width); + c.oProj(layer_metal, metal_mix, dump.Wo, case.T, dump.hidden, width); + var tbuf: [96]u8 = undefined; + const layer_tag = try std.fmt.bufPrint(&tbuf, "{s} TFLINGA1", .{tag}); + try c.gateNamedF64(layer_tag, layer_metal, a1.y64, layer_bf); +} diff --git a/zig/tests/ling_mla_gpu_kernels.zig b/zig/tests/ling_mla_gpu_kernels.zig new file mode 100644 index 00000000000..c5be824d160 --- /dev/null +++ b/zig/tests/ling_mla_gpu_kernels.zig @@ -0,0 +1,200 @@ +//! Ling MLA kernels-alone: rope_q, rope_cache, gate_expand vs host. +const std = @import("std"); +const mtl = @import("metal"); +const mla = @import("mla"); +const c = @import("ling_mla_gpu_common.zig"); + +fn checkRopeQ() !void { + const a = std.testing.allocator; + const s = mla.Shape{ .heads = 16, .eps = mla.eps_tiny, .theta = mla.theta_tiny }; + const rows: u32 = 4; + const H = s.heads; + var seed: u64 = 0x7271; + const q = try c.fill(&seed, rows * H * mla.qd, a); + defer a.free(q); + c.roundSlice(q); + const kv = try a.alloc(f32, rows * mla.key); + defer a.free(kv); + @memset(kv, 0); + const w_rms: [mla.lat]f32 = @splat(1); + const kvb_w = try a.alloc(f32, H * (mla.nope + mla.vd) * mla.lat); + defer a.free(kvb_w); + @memset(kvb_w, 0); + const g = try a.alloc(f32, rows * H); + defer a.free(g); + @memset(g, 0); + + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + var gpu = try c.Gpu.init(); + defer gpu.deinit(); + var l = try c.Launch.open(gpu, s, rows, q, kv, &w_rms, kvb_w, g); + defer l.deinit(); + l.fillRows(0, rows); + l.fillCs(rows); + const aa = l.args(rows); + const cb = gpu.queue.commandBuffer(); + const e = cb.compute(.serial); + e.setPipeline(gpu.rope_q); + e.setBuffer(l.b_q, 0, 0); + e.setValue(aa, 1); + e.setBuffer(l.b_cs, 0, 2); + e.dispatchGroups(mtl.Size.of(H, rows, 1), mtl.Size.of(32, 1, 1)); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |why| { + std.debug.print("rope_q failed: {s}\n", .{why}); + return error.GpuFailed; + } + const got = l.b_q.slice(u16, q.len); + var worst: f32 = 0; + var bits_miss: usize = 0; + for (0..rows) |t| { + for (0..H) |h| { + var z64: [mla.rope_dim]f64 = undefined; + var out: [mla.rope_dim]f64 = undefined; + const base = (t * H + h) * mla.qd + mla.nope; + for (0..mla.rope_dim) |i| z64[i] = q[base + i]; + mla.rotate(&out, &z64, @intCast(t), s.theta); + for (0..mla.rope_dim) |i| { + const want = c.toBf16(@floatCast(out[i])); + const gbits = got[base + i]; + if (want != gbits) bits_miss += 1; + worst = @max(worst, @abs(c.fromBf16(want) - c.fromBf16(gbits))); + } + } + } + std.debug.print("rope_q vs host rotate: bits miss {d} worst abs {e}\n", .{ bits_miss, worst }); + if (worst > 2e-3) return error.RopeQ; +} + +fn checkRopeCache() !void { + const a = std.testing.allocator; + const s = mla.Shape{ .heads = 16, .eps = mla.eps_tiny, .theta = mla.theta_tiny }; + const rows: u32 = 4; + var seed: u64 = 0x7263; + const rope_in = try c.fill(&seed, rows * mla.rope_dim, a); + defer a.free(rope_in); + c.roundSlice(rope_in); + const H = s.heads; + const q = try a.alloc(f32, rows * H * mla.qd); + defer a.free(q); + @memset(q, 0); + const kv = try a.alloc(f32, rows * mla.key); + defer a.free(kv); + @memset(kv, 0); + const w_rms: [mla.lat]f32 = @splat(1); + const kvb_w = try a.alloc(f32, H * (mla.nope + mla.vd) * mla.lat); + defer a.free(kvb_w); + @memset(kvb_w, 0); + const g = try a.alloc(f32, rows * H); + defer a.free(g); + @memset(g, 0); + + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + var gpu = try c.Gpu.init(); + defer gpu.deinit(); + var l = try c.Launch.open(gpu, s, rows, q, kv, &w_rms, kvb_w, g); + defer l.deinit(); + const cache = l.b_cache.slice(u16, rows * mla.key); + @memset(cache, 0); + for (0..rows) |t| { + for (0..mla.rope_dim) |i| cache[t * mla.key + mla.lat + i] = c.toBf16(rope_in[t * mla.rope_dim + i]); + } + l.fillRows(0, rows); + l.fillCs(rows); + const aa = l.args(rows); + const cb = gpu.queue.commandBuffer(); + const e = cb.compute(.serial); + e.setPipeline(gpu.rope_cache); + e.setBuffer(l.b_rows, 0, 0); + e.setValue(aa, 1); + e.setBuffer(l.b_cs, 0, 2); + e.useResource(l.b_cache, mtl.ResourceUsage.read | mtl.ResourceUsage.write); + e.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(32, 1, 1)); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |why| { + std.debug.print("rope_cache failed: {s}\n", .{why}); + return error.GpuFailed; + } + var worst: f32 = 0; + var bits_miss: usize = 0; + for (0..rows) |t| { + var z64: [mla.rope_dim]f64 = undefined; + var out: [mla.rope_dim]f64 = undefined; + for (0..mla.rope_dim) |i| z64[i] = rope_in[t * mla.rope_dim + i]; + mla.rotate(&out, &z64, @intCast(t), s.theta); + for (0..mla.rope_dim) |i| { + const want = c.toBf16(@floatCast(out[i])); + const gbits = cache[t * mla.key + mla.lat + i]; + if (want != gbits) bits_miss += 1; + worst = @max(worst, @abs(c.fromBf16(want) - c.fromBf16(gbits))); + } + } + std.debug.print("rope_cache vs host rotate: bits miss {d} worst abs {e}\n", .{ bits_miss, worst }); + if (worst > 2e-3) return error.RopeCache; +} + +fn checkExpand() !void { + const a = std.testing.allocator; + const s = mla.Shape{ .heads = 16, .eps = mla.eps_tiny, .theta = mla.theta_tiny }; + const rows: u32 = 4; + const H = s.heads; + var seed: u64 = 0x6765; + const gate = try c.fill(&seed, rows * H, a); + defer a.free(gate); + c.roundSlice(gate); + const q = try a.alloc(f32, rows * H * mla.qd); + defer a.free(q); + @memset(q, 0); + const kv = try a.alloc(f32, rows * mla.key); + defer a.free(kv); + @memset(kv, 0); + const w_rms: [mla.lat]f32 = @splat(1); + const kvb_w = try a.alloc(f32, H * (mla.nope + mla.vd) * mla.lat); + defer a.free(kvb_w); + @memset(kvb_w, 0); + + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + var gpu = try c.Gpu.init(); + defer gpu.deinit(); + var l = try c.Launch.open(gpu, s, rows, q, kv, &w_rms, kvb_w, gate); + defer l.deinit(); + const aa = l.args(rows); + const cb = gpu.queue.commandBuffer(); + const e = cb.compute(.serial); + e.setPipeline(gpu.gate_expand); + e.setBuffer(l.b_g, 0, 0); + e.setBuffer(l.b_g2, 0, 1); + e.setValue(aa, 2); + e.dispatchThreads(mtl.Size.of(H * mla.vd, rows, 1), mtl.Size.of(128, 1, 1)); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |why| { + std.debug.print("gate_expand failed: {s}\n", .{why}); + return error.GpuFailed; + } + const g_bits = l.b_g.slice(u16, rows * H); + const want = try a.alloc(u16, rows * H * mla.vd); + defer a.free(want); + mla.expandGate(want, g_bits, rows, H); + try c.expectBitsEqual("gate_expand", l.b_g2.slice(u16, want.len), want); +} + +test "Ling rope_q GPT-J halves vs host rotate" { + try checkRopeQ(); +} + +test "Ling rope_cache GPT-J halves vs host rotate" { + try checkRopeCache(); +} + +test "Ling gate_expand (T,H) to (T,H*128) bits-equal" { + try checkExpand(); +} diff --git a/zig/tests/ling_mla_gpu_mixer.zig b/zig/tests/ling_mla_gpu_mixer.zig new file mode 100644 index 00000000000..9abd25f4fee --- /dev/null +++ b/zig/tests/ling_mla_gpu_mixer.zig @@ -0,0 +1,38 @@ +//! Ling MLA mixer on Metal vs mla.zig f64 and bf16-point. +const std = @import("std"); +const mtl = @import("metal"); +const mla = @import("mla"); +const c = @import("ling_mla_gpu_common.zig"); + +fn checkMixer(rows: u32) !void { + const a = std.testing.allocator; + const s = mla.Shape{ .heads = 16, .eps = mla.eps_tiny, .theta = mla.theta_tiny }; + const in = try c.Inputs.make(a, s, rows, 0x6d6c61); + defer in.free(a); + const n = rows * s.outWidth(); + const want64 = try a.alloc(f64, n); + defer a.free(want64); + const want_bf = try a.alloc(f64, n); + defer a.free(want_bf); + try mla.mixF64(a, want64, in.q, in.kv, in.w, in.kvb, in.g, s, rows, 0); + try mla.mixBf16(a, want_bf, in.q, in.kv, in.w, in.kvb, in.g, s, rows, 0); + + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + var g = try c.Gpu.init(); + defer g.deinit(); + var l = try c.Launch.open(g, s, rows, in.q, in.kv, in.w, in.kvb, in.g); + defer l.deinit(); + try l.dispatchMixer(g, 0, rows); + var buf: [64]u8 = undefined; + const tag = try std.fmt.bufPrint(&buf, "mla {d} rows", .{rows}); + try c.gateNamed(tag, l.y(), want64, want_bf); +} + +test "MLA mixer Metal vs f64 and bf16-point on 2 rows from pos 0" { + try checkMixer(2); +} + +test "MLA mixer Metal vs f64 and bf16-point on 4 rows from pos 0" { + try checkMixer(4); +} diff --git a/zig/tests/qwen27/glue_ab.zig b/zig/tests/qwen27/glue_ab.zig new file mode 100644 index 00000000000..a737cc574b1 --- /dev/null +++ b/zig/tests/qwen27/glue_ab.zig @@ -0,0 +1,146 @@ +//! The general glue against the flat kernels on real weights: rounds interleaved in one process, every byte compared. +const std = @import("std"); +const mtl = @import("metal"); +const tf = @import("tensorfold"); +const q = tf.qwen27; +const contract = tf.tree_round; +const Round = q.round_plan.Round; +const help = "tf-qwen27-glue-ab --model DIR --tokens IDS.json [--rounds 90] [--chunk 128]"; + +/// Two trees from real DFlash2 rounds: a width takes their leading rows. +const trees = [2][16]i32{ + .{ -1, 0, 1, 2, 3, 4, 3, 6, 5, 8, 7, 5, 9, 10, 12, 13 }, + .{ -1, 0, 0, 2, 1, 1, 0, 0, 6, 5, 7, 0, 0, 3, 1, 11 }, +}; +const widths = [_]u32{ 11, 13, 16 }; + +const Picks = struct { + ops: tf.tree_round_gpu.Ops, + out: mtl.Buffer, + logits: q.projection.Ref, + rows: u32, + vocab: u32, + + fn encode(ptr: *anyopaque, e: mtl.ComputeEncoder) anyerror!void { + const p: *Picks = @ptrCast(@alignCast(ptr)); + try p.ops.argmaxChunks(e, .{ .buf = p.logits.buffer, .off = p.logits.offset }, .{ .buf = p.out }, .{ .rows = p.rows, .vocab = p.vocab, .stride = p.vocab }); + e.barrier(); + } +}; + +fn median(values: []f64) f64 { + std.mem.sort(f64, values, {}, std.sort.asc(f64)); + return values[values.len / 2]; +} + +pub fn main(init: std.process.Init) !void { + const gpa = init.gpa; + const a = init.arena.allocator(); + const io = init.io; + const args = try init.minimal.args.toSlice(a); + var dir: ?[]const u8 = null; + var tokens: ?[]const u8 = null; + var rounds: usize = 90; + var chunk: u32 = 128; + var i: usize = 1; + while (i < args.len) : (i += 1) { + if (std.mem.eql(u8, args[i], "--help")) return std.debug.print("{s}\n", .{help}); + if (i + 1 >= args.len) return error.MissingValue; + i += 1; + if (std.mem.eql(u8, args[i - 1], "--model")) dir = args[i] else if (std.mem.eql(u8, args[i - 1], "--tokens")) tokens = args[i] else if (std.mem.eql(u8, args[i - 1], "--rounds")) rounds = try std.fmt.parseInt(usize, args[i], 10) else if (std.mem.eql(u8, args[i - 1], "--chunk")) chunk = try std.fmt.parseInt(u32, args[i], 10) else return error.UnknownFlag; + } + const text = try std.Io.Dir.cwd().readFileAlloc(io, tokens orelse return error.MissingTokens, a, .limited(16 << 20)); + const prompt = (try std.json.parseFromSlice([]u32, a, text, .{})).value; + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const m = try q.model.Model.load(gpa, io, dir orelse return error.MissingModel, 128, null); + defer m.deinit(); + const vocab: u32 = @intCast(m.config.vocab); + var runners: [2]q.decode_round.Runner = undefined; + for (&runners) |*r| r.* = try q.decode_round.Runner.init(gpa, m, 1, 4096); + defer for (&runners) |*r| r.deinit(); + var pending: u32 = 0; + for (&runners, 0..) |*r, k| { + q.decode_round.setFlatGlue(k == 1); + const s = q.session.Session{ .runner = r }; + try s.prefill(prompt, chunk); + const first = try s.greedy(); + if (k == 1 and first != pending) return error.PromptsDiffer; + pending = first; + } + var picks = Picks{ + .ops = try tf.tree_round_gpu.Ops.init(m.device), + .out = try m.device.buffer(contract.max_rows * @sizeOf(contract.Pick), mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked), + .logits = m.frame.get(.logits), + .rows = 0, + .vocab = vocab, + }; + defer picks.ops.deinit(); + defer picks.out.deinit(); + const saved = try gpa.alloc(u16, 16 * vocab); + defer gpa.free(saved); + var saved_picks: [16]contract.Pick = undefined; + const walls = try a.alloc(f64, 2 * widths.len * rounds); + const gpus = try a.alloc(f64, 2 * widths.len * rounds); + var counts: [widths.len]usize = @splat(0); + for (0..rounds + 4) |round| { + const w = round % widths.len; + const rows = widths[w]; + var ids: [16]u32 = undefined; + ids[0] = pending; + for (1..rows) |j| ids[j] = @intCast((j * 104729 + round * 31) % 150000 + 1000); + const parents = trees[round / widths.len % 2][0..rows]; + // Which variant runs first alternates, so neither always follows the other's caches. + for ([_]usize{ round % 2, 1 - round % 2 }, 0..) |k, order| { + const r = &runners[k]; + q.decode_round.setFlatGlue(k == 1); + picks.rows = rows; + var plan = try Round.init(gpa, &.{.{ .slot = 0, .start = r.offsets[0], .capacity = r.capacity, .ids = ids[0..rows], .parents = parents }}, @intCast(m.config.conv_kernel), r.slots, vocab); + defer plan.deinit(); + r.tail = .{ .ptr = &picks, .encode = Picks.encode }; + const began = mtl.clock.seconds(); + try r.verifyHead(&plan, .all); + const wall = mtl.clock.seconds() - began; + r.tail = null; + if (round >= 4) { + walls[(w * rounds + counts[w]) * 2 + k] = wall * 1e3; + gpus[(w * rounds + counts[w]) * 2 + k] = r.last_gpu_seconds * 1e3; + } + const logits = m.frame.get(.logits).buffer.slice(u16, rows * vocab); + const out = picks.out.slice(contract.Pick, rows); + if (order == 0) { + @memcpy(saved[0 .. rows * vocab], logits); + @memcpy(saved_picks[0..rows], out); + } else { + if (!std.mem.eql(u16, saved[0 .. rows * vocab], logits)) return error.LogitsDiffer; + for (saved_picks[0..rows], out) |x, y| if (x.token != y.token or x.nonfinite != y.nonfinite) return error.PicksDiffer; + } + for (out[0..rows], 0..) |pick, row| { + const host = contract.rowArgmax(logits[row * vocab ..][0..vocab]); + if (pick.token != host.token or pick.nonfinite != host.nonfinite) return error.PickAgainstHost; + } + if (order == 1) pending = out[0].token; + const root = [_]u32{0}; + try r.keep(&plan, &.{&root}); + } + if (round >= 4) counts[w] += 1; + } + std.debug.print("{d} rounds a side, every logit and pick equal, and every pick equal to the host's argmax\n", .{rounds + 4}); + std.debug.print("rows general wall (GPU) flat wall (GPU) wall saved\n", .{}); + for (widths, 0..) |rows, w| { + const n = counts[w]; + const general_wall = try a.alloc(f64, n); + const flat_wall = try a.alloc(f64, n); + const general_gpu = try a.alloc(f64, n); + const flat_gpu = try a.alloc(f64, n); + for (0..n) |at| { + general_wall[at] = walls[(w * rounds + at) * 2]; + flat_wall[at] = walls[(w * rounds + at) * 2 + 1]; + general_gpu[at] = gpus[(w * rounds + at) * 2]; + flat_gpu[at] = gpus[(w * rounds + at) * 2 + 1]; + } + const x = median(general_wall); + const y = median(flat_wall); + std.debug.print("{d:4} {d:6.2} ({d:6.2}) {d:6.2} ({d:6.2}) {d:5.2} ms, {d:4.1}%\n", .{ rows, x, median(general_gpu), y, median(flat_gpu), x - y, (x - y) / x * 100 }); + } +} diff --git a/zig/tests/qwen27/metal4_ab.zig b/zig/tests/qwen27/metal4_ab.zig new file mode 100644 index 00000000000..dcf603ed72b --- /dev/null +++ b/zig/tests/qwen27/metal4_ab.zig @@ -0,0 +1,149 @@ +//! Metal 3 against Metal 4 verify passes on real weights, interleaved in one process: the same kernels on both queues. +const std = @import("std"); +const mtl = @import("metal"); +const tf = @import("tensorfold"); +const q = tf.qwen27; +const contract = tf.tree_round; +const Round = q.round_plan.Round; +const help = "tf-qwen27-metal4-ab --model DIR --tokens IDS.json [--rounds 90] [--chunk 128]"; + +/// Two trees from real DFlash2 rounds: a width takes their leading rows. +const trees = [2][16]i32{ + .{ -1, 0, 1, 2, 3, 4, 3, 6, 5, 8, 7, 5, 9, 10, 12, 13 }, + .{ -1, 0, 0, 2, 1, 1, 0, 0, 6, 5, 7, 0, 0, 3, 1, 11 }, +}; +const widths = [_]u32{ 1, 8, 11, 13, 16 }; + +const Picks = struct { + ops: tf.tree_round_gpu.Ops, + out: mtl.Buffer, + logits: q.projection.Ref, + rows: u32, + vocab: u32, + + fn encode(ptr: *anyopaque, e: mtl.ComputeEncoder) anyerror!void { + const p: *Picks = @ptrCast(@alignCast(ptr)); + try p.ops.argmax(e, .{ .buf = p.logits.buffer, .off = p.logits.offset }, .{ .buf = p.out }, .{ .rows = p.rows, .vocab = p.vocab, .stride = p.vocab }); + e.barrier(); + } +}; + +fn median(values: []f64) f64 { + std.mem.sort(f64, values, {}, std.sort.asc(f64)); + return values[values.len / 2]; +} + +pub fn main(init: std.process.Init) !void { + const gpa = init.gpa; + const a = init.arena.allocator(); + const io = init.io; + const args = try init.minimal.args.toSlice(a); + var dir: ?[]const u8 = null; + var tokens: ?[]const u8 = null; + var rounds: usize = 90; + var chunk: u32 = 128; + var i: usize = 1; + while (i < args.len) : (i += 1) { + if (std.mem.eql(u8, args[i], "--help")) return std.debug.print("{s}\n", .{help}); + if (i + 1 >= args.len) return error.MissingValue; + i += 1; + if (std.mem.eql(u8, args[i - 1], "--model")) dir = args[i] else if (std.mem.eql(u8, args[i - 1], "--tokens")) tokens = args[i] else if (std.mem.eql(u8, args[i - 1], "--rounds")) rounds = try std.fmt.parseInt(usize, args[i], 10) else if (std.mem.eql(u8, args[i - 1], "--chunk")) chunk = try std.fmt.parseInt(u32, args[i], 10) else return error.UnknownFlag; + } + const text = try std.Io.Dir.cwd().readFileAlloc(io, tokens orelse return error.MissingTokens, a, .limited(16 << 20)); + const prompt = (try std.json.parseFromSlice([]u32, a, text, .{})).value; + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const m = try q.model.Model.load(gpa, io, dir orelse return error.MissingModel, 128, null); + defer m.deinit(); + if (m.metal4 == null) return error.NoMetal4; // TF_Q27_METAL4=0, or a Mac without a Metal 4 queue + const vocab: u32 = @intCast(m.config.vocab); + var runners: [2]q.decode_round.Runner = undefined; + for (&runners, 0..) |*r, k| { + r.* = try q.decode_round.Runner.init(gpa, m, 1, 4096); + r.metal4 = k == 1; + } + defer for (&runners) |*r| r.deinit(); + var pending: u32 = 0; + for (&runners, 0..) |*r, k| { + const s = q.session.Session{ .runner = r }; + try s.prefill(prompt, chunk); + const first = try s.greedy(); + if (k == 1 and first != pending) return error.PromptsDiffer; + pending = first; + } + var picks = Picks{ + .ops = try tf.tree_round_gpu.Ops.init(m.device), + .out = try m.device.buffer(contract.max_rows * @sizeOf(contract.Pick), mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked), + .logits = m.frame.get(.logits), + .rows = 0, + .vocab = vocab, + }; + defer picks.ops.deinit(); + defer picks.out.deinit(); + const saved = try gpa.alloc(u16, 16 * vocab); + defer gpa.free(saved); + var saved_picks: [16]contract.Pick = undefined; + const walls = try a.alloc(f64, 2 * widths.len * rounds); + const gpus = try a.alloc(f64, 2 * widths.len * rounds); + var counts: [widths.len]usize = @splat(0); + for (0..rounds + 4) |round| { + const w = round % widths.len; + const rows = widths[w]; + var ids: [16]u32 = undefined; + ids[0] = pending; + for (1..rows) |j| ids[j] = @intCast((j * 104729 + round * 31) % 150000 + 1000); + const parents = trees[round / widths.len % 2][0..rows]; + // Which kernel runs first alternates, so neither always follows the other's caches. + for ([_]usize{ round % 2, 1 - round % 2 }, 0..) |k, order| { + const r = &runners[k]; + picks.rows = rows; + var plan = try Round.init(gpa, &.{.{ .slot = 0, .start = r.offsets[0], .capacity = r.capacity, .ids = ids[0..rows], .parents = parents }}, @intCast(m.config.conv_kernel), r.slots, vocab); + defer plan.deinit(); + r.tail = .{ .ptr = &picks, .encode = Picks.encode }; + const began = mtl.clock.seconds(); + try r.verifyHead(&plan, .all); + const wall = mtl.clock.seconds() - began; + r.tail = null; + if (round >= 4) { + walls[(w * rounds + counts[w]) * 2 + k] = wall * 1e3; + gpus[(w * rounds + counts[w]) * 2 + k] = r.last_gpu_seconds * 1e3; + } + const logits = m.frame.get(.logits).buffer.slice(u16, rows * vocab); + const out = picks.out.slice(contract.Pick, rows); + if (order == 0) { + @memcpy(saved[0 .. rows * vocab], logits); + @memcpy(saved_picks[0..rows], out); + } else { + if (!std.mem.eql(u16, saved[0 .. rows * vocab], logits)) return error.LogitsDiffer; + for (saved_picks[0..rows], out) |x, y| if (x.token != y.token or x.nonfinite != y.nonfinite) return error.PicksDiffer; + } + for (out[0..rows], 0..) |pick, row| { + const host = contract.rowArgmax(logits[row * vocab ..][0..vocab]); + if (pick.token != host.token or pick.nonfinite != host.nonfinite) return error.PickAgainstHost; + } + if (order == 1) pending = out[0].token; + const root = [_]u32{0}; + try r.keep(&plan, &.{&root}); + } + if (round >= 4) counts[w] += 1; + } + std.debug.print("{d} rounds a side, every logit and pick equal, and every pick equal to the host's argmax\n", .{rounds + 4}); + std.debug.print("rows Metal 3 wall (GPU) Metal 4 wall (GPU) wall saved\n", .{}); + for (widths, 0..) |rows, w| { + const n = counts[w]; + if (n == 0) continue; + const m3_wall = try a.alloc(f64, n); + const m4_wall = try a.alloc(f64, n); + const m3_gpu = try a.alloc(f64, n); + const m4_gpu = try a.alloc(f64, n); + for (0..n) |at| { + m3_wall[at] = walls[(w * rounds + at) * 2]; + m4_wall[at] = walls[(w * rounds + at) * 2 + 1]; + m3_gpu[at] = gpus[(w * rounds + at) * 2]; + m4_gpu[at] = gpus[(w * rounds + at) * 2 + 1]; + } + const x = median(m3_wall); + const y = median(m4_wall); + std.debug.print("{d:4} {d:6.2} ({d:6.2}) {d:6.2} ({d:6.2}) {d:5.2} ms, {d:4.1}%\n", .{ rows, x, median(m3_gpu), y, median(m4_gpu), x - y, (x - y) / x * 100 }); + } +} diff --git a/zig/tests/qwen27/qk_ab.zig b/zig/tests/qwen27/qk_ab.zig new file mode 100644 index 00000000000..8f2e8376385 --- /dev/null +++ b/zig/tests/qwen27/qk_ab.zig @@ -0,0 +1,184 @@ +//! tf_lane_reg against qk on real weights, interleaved in one process: load leaves plain matrices, this copies them. +const std = @import("std"); +const mtl = @import("metal"); +const tf = @import("tensorfold"); +const q = tf.qwen27; +const lane = tf.lane_projection; +const contract = tf.tree_round; +const Round = q.round_plan.Round; +const help = "tf-qwen27-qk-ab --model DIR --tokens IDS.json [--rounds 90] [--chunk 128]"; + +/// Two trees from real DFlash2 rounds: a width takes their leading rows. +const trees = [2][16]i32{ + .{ -1, 0, 1, 2, 3, 4, 3, 6, 5, 8, 7, 5, 9, 10, 12, 13 }, + .{ -1, 0, 0, 2, 1, 1, 0, 0, 6, 5, 7, 0, 0, 3, 1, 11 }, +}; +const widths = [_]u32{ 1, 8, 11, 13, 16 }; + +const Picks = struct { + ops: tf.tree_round_gpu.Ops, + out: mtl.Buffer, + logits: q.projection.Ref, + rows: u32, + vocab: u32, + + fn encode(ptr: *anyopaque, e: mtl.ComputeEncoder) anyerror!void { + const p: *Picks = @ptrCast(@alignCast(ptr)); + try p.ops.argmax(e, .{ .buf = p.logits.buffer, .off = p.logits.offset }, .{ .buf = p.out }, .{ .rows = p.rows, .vocab = p.vocab, .stride = p.vocab }); + e.barrier(); + } +}; + +fn median(values: []f64) f64 { + std.mem.sort(f64, values, {}, std.sort.asc(f64)); + return values[values.len / 2]; +} + +/// tf_lane_reg's copy of every plain matrix, reordered on the GPU as load would have: the buffers stay in `owned`. +fn regCopies(a: std.mem.Allocator, device: mtl.Device, w: *q.gpu_weights.Weights, owned: *std.ArrayList(mtl.Buffer)) !usize { + var list: std.ArrayList(*q.projection.Linear) = .empty; + defer list.deinit(a); + for (w.layers) |*l| { + switch (l.mixer) { + .linear => |*g| try list.appendSlice(a, &.{ &g.qkv, &g.zba, &g.out }), + .attention => |*t| try list.appendSlice(a, &.{ &t.q, &t.kv, &t.out }), + } + try list.appendSlice(a, &.{ &l.gu, &l.down }); + } + try list.append(a, &w.head); + var jobs: std.ArrayList(lane.Order) = .empty; + defer jobs.deinit(a); + for (list.items) |p| { + if (!p.plain) continue; + const bytes = @as(usize, p.n) * p.k / 2; + const buf = try device.buffer(bytes, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); + try owned.append(a, buf); + @memcpy(buf.contents()[0..bytes], p.words.buffer.contents()[p.words.offset..][0..bytes]); + p.reg_copy = .{ .buffer = buf }; + try jobs.append(a, .{ .w = .{ .buf = buf }, .n = p.n, .k = p.k }); + } + if (jobs.items.len > 0) try lane.regOrder(device, jobs.items); + return jobs.items.len; +} + +pub fn main(init: std.process.Init) !void { + const gpa = init.gpa; + const a = init.arena.allocator(); + const io = init.io; + const args = try init.minimal.args.toSlice(a); + var dir: ?[]const u8 = null; + var tokens: ?[]const u8 = null; + var rounds: usize = 90; + var chunk: u32 = 128; + var i: usize = 1; + while (i < args.len) : (i += 1) { + if (std.mem.eql(u8, args[i], "--help")) return std.debug.print("{s}\n", .{help}); + if (i + 1 >= args.len) return error.MissingValue; + i += 1; + if (std.mem.eql(u8, args[i - 1], "--model")) dir = args[i] else if (std.mem.eql(u8, args[i - 1], "--tokens")) tokens = args[i] else if (std.mem.eql(u8, args[i - 1], "--rounds")) rounds = try std.fmt.parseInt(usize, args[i], 10) else if (std.mem.eql(u8, args[i - 1], "--chunk")) chunk = try std.fmt.parseInt(u32, args[i], 10) else return error.UnknownFlag; + } + const text = try std.Io.Dir.cwd().readFileAlloc(io, tokens orelse return error.MissingTokens, a, .limited(16 << 20)); + const prompt = (try std.json.parseFromSlice([]u32, a, text, .{})).value; + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const m = try q.model.Model.load(gpa, io, dir orelse return error.MissingModel, 128, null); + defer m.deinit(); + var owned: std.ArrayList(mtl.Buffer) = .empty; + defer { + for (owned.items) |b| b.deinit(); + owned.deinit(gpa); + } + const copied = try regCopies(gpa, m.device, &m.weights, &owned); + if (copied == 0) return error.NoPlainMatrices; // TF_Q27_QK=0, or a GPU that does not build qk + std.debug.print("{d} plain matrices, each with a reg copy\n", .{copied}); + const vocab: u32 = @intCast(m.config.vocab); + var runners: [2]q.decode_round.Runner = undefined; + for (&runners) |*r| r.* = try q.decode_round.Runner.init(gpa, m, 1, 4096); + defer for (&runners) |*r| r.deinit(); + var pending: u32 = 0; + for (&runners, 0..) |*r, k| { + q.quant_gpu.qk_rows = k == 1; + const s = q.session.Session{ .runner = r }; + try s.prefill(prompt, chunk); + const first = try s.greedy(); + if (k == 1 and first != pending) return error.PromptsDiffer; + pending = first; + } + var picks = Picks{ + .ops = try tf.tree_round_gpu.Ops.init(m.device), + .out = try m.device.buffer(contract.max_rows * @sizeOf(contract.Pick), mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked), + .logits = m.frame.get(.logits), + .rows = 0, + .vocab = vocab, + }; + defer picks.ops.deinit(); + defer picks.out.deinit(); + const saved = try gpa.alloc(u16, 16 * vocab); + defer gpa.free(saved); + var saved_picks: [16]contract.Pick = undefined; + const walls = try a.alloc(f64, 2 * widths.len * rounds); + const gpus = try a.alloc(f64, 2 * widths.len * rounds); + var counts: [widths.len]usize = @splat(0); + for (0..rounds + 4) |round| { + const w = round % widths.len; + const rows = widths[w]; + var ids: [16]u32 = undefined; + ids[0] = pending; + for (1..rows) |j| ids[j] = @intCast((j * 104729 + round * 31) % 150000 + 1000); + const parents = trees[round / widths.len % 2][0..rows]; + // Which kernel runs first alternates, so neither always follows the other's caches. + for ([_]usize{ round % 2, 1 - round % 2 }, 0..) |k, order| { + const r = &runners[k]; + q.quant_gpu.qk_rows = k == 1; + picks.rows = rows; + var plan = try Round.init(gpa, &.{.{ .slot = 0, .start = r.offsets[0], .capacity = r.capacity, .ids = ids[0..rows], .parents = parents }}, @intCast(m.config.conv_kernel), r.slots, vocab); + defer plan.deinit(); + r.tail = .{ .ptr = &picks, .encode = Picks.encode }; + const began = mtl.clock.seconds(); + try r.verifyHead(&plan, .all); + const wall = mtl.clock.seconds() - began; + r.tail = null; + if (round >= 4) { + walls[(w * rounds + counts[w]) * 2 + k] = wall * 1e3; + gpus[(w * rounds + counts[w]) * 2 + k] = r.last_gpu_seconds * 1e3; + } + const logits = m.frame.get(.logits).buffer.slice(u16, rows * vocab); + const out = picks.out.slice(contract.Pick, rows); + if (order == 0) { + @memcpy(saved[0 .. rows * vocab], logits); + @memcpy(saved_picks[0..rows], out); + } else { + if (!std.mem.eql(u16, saved[0 .. rows * vocab], logits)) return error.LogitsDiffer; + for (saved_picks[0..rows], out) |x, y| if (x.token != y.token or x.nonfinite != y.nonfinite) return error.PicksDiffer; + } + for (out[0..rows], 0..) |pick, row| { + const host = contract.rowArgmax(logits[row * vocab ..][0..vocab]); + if (pick.token != host.token or pick.nonfinite != host.nonfinite) return error.PickAgainstHost; + } + if (order == 1) pending = out[0].token; + const root = [_]u32{0}; + try r.keep(&plan, &.{&root}); + } + if (round >= 4) counts[w] += 1; + } + q.quant_gpu.qk_rows = true; + std.debug.print("{d} rounds a side, every logit and pick equal, and every pick equal to the host's argmax\n", .{rounds + 4}); + std.debug.print("rows tf_lane_reg wall (GPU) qk wall (GPU) wall saved\n", .{}); + for (widths, 0..) |rows, w| { + const n = counts[w]; + if (n == 0) continue; + const reg_wall = try a.alloc(f64, n); + const qk_wall = try a.alloc(f64, n); + const reg_gpu = try a.alloc(f64, n); + const qk_gpu = try a.alloc(f64, n); + for (0..n) |at| { + reg_wall[at] = walls[(w * rounds + at) * 2]; + qk_wall[at] = walls[(w * rounds + at) * 2 + 1]; + reg_gpu[at] = gpus[(w * rounds + at) * 2]; + qk_gpu[at] = gpus[(w * rounds + at) * 2 + 1]; + } + const x = median(reg_wall); + const y = median(qk_wall); + std.debug.print("{d:4} {d:6.2} ({d:6.2}) {d:6.2} ({d:6.2}) {d:5.2} ms, {d:4.1}%\n", .{ rows, x, median(reg_gpu), y, median(qk_gpu), x - y, (x - y) / x * 100 }); + } +} diff --git a/zig/tests/qwen27/stack_ab.zig b/zig/tests/qwen27/stack_ab.zig new file mode 100644 index 00000000000..6be29f82688 --- /dev/null +++ b/zig/tests/qwen27/stack_ab.zig @@ -0,0 +1,194 @@ +//! Stock kernels on Metal 3 against qk, flat glue and Metal 4 on real weights, interleaved round by round. +const std = @import("std"); +const mtl = @import("metal"); +const tf = @import("tensorfold"); +const q = tf.qwen27; +const lane = tf.lane_projection; +const contract = tf.tree_round; +const Round = q.round_plan.Round; +const help = "tf-qwen27-stack-ab --model DIR --tokens IDS.json [--rounds 90] [--chunk 128]"; + +/// Two trees from real DFlash2 rounds: a width takes their leading rows. +const trees = [2][16]i32{ + .{ -1, 0, 1, 2, 3, 4, 3, 6, 5, 8, 7, 5, 9, 10, 12, 13 }, + .{ -1, 0, 0, 2, 1, 1, 0, 0, 6, 5, 7, 0, 0, 3, 1, 11 }, +}; +const widths = [_]u32{ 1, 8, 11, 13, 16 }; + +const Picks = struct { + ops: tf.tree_round_gpu.Ops, + out: mtl.Buffer, + logits: q.projection.Ref, + rows: u32, + vocab: u32, + + fn encode(ptr: *anyopaque, e: mtl.ComputeEncoder) anyerror!void { + const p: *Picks = @ptrCast(@alignCast(ptr)); + try p.ops.argmax(e, .{ .buf = p.logits.buffer, .off = p.logits.offset }, .{ .buf = p.out }, .{ .rows = p.rows, .vocab = p.vocab, .stride = p.vocab }); + e.barrier(); + } +}; + +fn median(values: []f64) f64 { + std.mem.sort(f64, values, {}, std.sort.asc(f64)); + return values[values.len / 2]; +} + +/// tf_lane_reg's copy of every plain matrix, reordered on the GPU as load would have: the buffers stay in `owned`. +fn regCopies(a: std.mem.Allocator, device: mtl.Device, w: *q.gpu_weights.Weights, owned: *std.ArrayList(mtl.Buffer)) !usize { + var list: std.ArrayList(*q.projection.Linear) = .empty; + defer list.deinit(a); + for (w.layers) |*l| { + switch (l.mixer) { + .linear => |*g| try list.appendSlice(a, &.{ &g.qkv, &g.zba, &g.out }), + .attention => |*t| try list.appendSlice(a, &.{ &t.q, &t.kv, &t.out }), + } + try list.appendSlice(a, &.{ &l.gu, &l.down }); + } + try list.append(a, &w.head); + var jobs: std.ArrayList(lane.Order) = .empty; + defer jobs.deinit(a); + for (list.items) |p| { + if (!p.plain) continue; + const bytes = @as(usize, p.n) * p.k / 2; + const buf = try device.buffer(bytes, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); + try owned.append(a, buf); + @memcpy(buf.contents()[0..bytes], p.words.buffer.contents()[p.words.offset..][0..bytes]); + p.reg_copy = .{ .buffer = buf }; + try jobs.append(a, .{ .w = .{ .buf = buf }, .n = p.n, .k = p.k }); + } + if (jobs.items.len > 0) try lane.regOrder(device, jobs.items); + return jobs.items.len; +} + +/// Runner 0 takes TensorFold's kernels, runner 1 qk and the flat glue; each runner keeps its own Metal choice. +fn use(k: usize) void { + q.quant_gpu.qk_rows = k == 1; + q.decode_round.setFlatGlue(k == 1); +} + +pub fn main(init: std.process.Init) !void { + const gpa = init.gpa; + const a = init.arena.allocator(); + const io = init.io; + const args = try init.minimal.args.toSlice(a); + var dir: ?[]const u8 = null; + var tokens: ?[]const u8 = null; + var rounds: usize = 90; + var chunk: u32 = 128; + var i: usize = 1; + while (i < args.len) : (i += 1) { + if (std.mem.eql(u8, args[i], "--help")) return std.debug.print("{s}\n", .{help}); + if (i + 1 >= args.len) return error.MissingValue; + i += 1; + if (std.mem.eql(u8, args[i - 1], "--model")) dir = args[i] else if (std.mem.eql(u8, args[i - 1], "--tokens")) tokens = args[i] else if (std.mem.eql(u8, args[i - 1], "--rounds")) rounds = try std.fmt.parseInt(usize, args[i], 10) else if (std.mem.eql(u8, args[i - 1], "--chunk")) chunk = try std.fmt.parseInt(u32, args[i], 10) else return error.UnknownFlag; + } + const text = try std.Io.Dir.cwd().readFileAlloc(io, tokens orelse return error.MissingTokens, a, .limited(16 << 20)); + const prompt = (try std.json.parseFromSlice([]u32, a, text, .{})).value; + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const m = try q.model.Model.load(gpa, io, dir orelse return error.MissingModel, 128, null); + defer m.deinit(); + var owned: std.ArrayList(mtl.Buffer) = .empty; + defer { + for (owned.items) |b| b.deinit(); + owned.deinit(gpa); + } + const copied = try regCopies(gpa, m.device, &m.weights, &owned); + if (copied == 0) return error.NoPlainMatrices; // TF_Q27_QK=0, or a GPU that does not build qk + std.debug.print("{d} plain matrices, each with a reg copy\n", .{copied}); + const vocab: u32 = @intCast(m.config.vocab); + var runners: [2]q.decode_round.Runner = undefined; + if (m.metal4 == null) return error.NoMetal4; // TF_Q27_METAL4=0, or a Mac without a Metal 4 queue + for (&runners, 0..) |*r, k| { + r.* = try q.decode_round.Runner.init(gpa, m, 1, 4096); + r.metal4 = k == 1; + } + defer for (&runners) |*r| r.deinit(); + var pending: u32 = 0; + for (&runners, 0..) |*r, k| { + use(k); + const s = q.session.Session{ .runner = r }; + try s.prefill(prompt, chunk); + const first = try s.greedy(); + if (k == 1 and first != pending) return error.PromptsDiffer; + pending = first; + } + var picks = Picks{ + .ops = try tf.tree_round_gpu.Ops.init(m.device), + .out = try m.device.buffer(contract.max_rows * @sizeOf(contract.Pick), mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked), + .logits = m.frame.get(.logits), + .rows = 0, + .vocab = vocab, + }; + defer picks.ops.deinit(); + defer picks.out.deinit(); + const saved = try gpa.alloc(u16, 16 * vocab); + defer gpa.free(saved); + var saved_picks: [16]contract.Pick = undefined; + const walls = try a.alloc(f64, 2 * widths.len * rounds); + const gpus = try a.alloc(f64, 2 * widths.len * rounds); + var counts: [widths.len]usize = @splat(0); + for (0..rounds + 4) |round| { + const w = round % widths.len; + const rows = widths[w]; + var ids: [16]u32 = undefined; + ids[0] = pending; + for (1..rows) |j| ids[j] = @intCast((j * 104729 + round * 31) % 150000 + 1000); + const parents = trees[round / widths.len % 2][0..rows]; + // Which kernel runs first alternates, so neither always follows the other's caches. + for ([_]usize{ round % 2, 1 - round % 2 }, 0..) |k, order| { + const r = &runners[k]; + use(k); + picks.rows = rows; + var plan = try Round.init(gpa, &.{.{ .slot = 0, .start = r.offsets[0], .capacity = r.capacity, .ids = ids[0..rows], .parents = parents }}, @intCast(m.config.conv_kernel), r.slots, vocab); + defer plan.deinit(); + r.tail = .{ .ptr = &picks, .encode = Picks.encode }; + const began = mtl.clock.seconds(); + try r.verifyHead(&plan, .all); + const wall = mtl.clock.seconds() - began; + r.tail = null; + if (round >= 4) { + walls[(w * rounds + counts[w]) * 2 + k] = wall * 1e3; + gpus[(w * rounds + counts[w]) * 2 + k] = r.last_gpu_seconds * 1e3; + } + const logits = m.frame.get(.logits).buffer.slice(u16, rows * vocab); + const out = picks.out.slice(contract.Pick, rows); + if (order == 0) { + @memcpy(saved[0 .. rows * vocab], logits); + @memcpy(saved_picks[0..rows], out); + } else { + if (!std.mem.eql(u16, saved[0 .. rows * vocab], logits)) return error.LogitsDiffer; + for (saved_picks[0..rows], out) |x, y| if (x.token != y.token or x.nonfinite != y.nonfinite) return error.PicksDiffer; + } + for (out[0..rows], 0..) |pick, row| { + const host = contract.rowArgmax(logits[row * vocab ..][0..vocab]); + if (pick.token != host.token or pick.nonfinite != host.nonfinite) return error.PickAgainstHost; + } + if (order == 1) pending = out[0].token; + const root = [_]u32{0}; + try r.keep(&plan, &.{&root}); + } + if (round >= 4) counts[w] += 1; + } + use(1); + std.debug.print("{d} rounds a side, every logit and pick equal, and every pick equal to the host's argmax\n", .{rounds + 4}); + std.debug.print("rows stock wall (GPU) stack wall (GPU) wall saved\n", .{}); + for (widths, 0..) |rows, w| { + const n = counts[w]; + if (n == 0) continue; + const reg_wall = try a.alloc(f64, n); + const qk_wall = try a.alloc(f64, n); + const reg_gpu = try a.alloc(f64, n); + const qk_gpu = try a.alloc(f64, n); + for (0..n) |at| { + reg_wall[at] = walls[(w * rounds + at) * 2]; + qk_wall[at] = walls[(w * rounds + at) * 2 + 1]; + reg_gpu[at] = gpus[(w * rounds + at) * 2]; + qk_gpu[at] = gpus[(w * rounds + at) * 2 + 1]; + } + const x = median(reg_wall); + const y = median(qk_wall); + std.debug.print("{d:4} {d:6.2} ({d:6.2}) {d:6.2} ({d:6.2}) {d:5.2} ms, {d:4.1}%\n", .{ rows, x, median(reg_gpu), y, median(qk_gpu), x - y, (x - y) / x * 100 }); + } +} diff --git a/zig/tests/qwen35/serve_check.py b/zig/tests/qwen35/serve_check.py index b6139fa787b..537ef4f2899 100644 --- a/zig/tests/qwen35/serve_check.py +++ b/zig/tests/qwen35/serve_check.py @@ -17,6 +17,21 @@ ] +DRAFTS = {"accepted": {}, "plain": 0} # drafts accepted per temperature, and tokens drafted by plain replies + + +class Reply: + """A reply's token hash (reasoning included); equal only to the same hash, never when either has no token.""" + + def __init__(self, doc): + runtime, usage = doc.get("tensorfold") or {}, doc.get("usage") or {} + self.sha = runtime.get("token_sha256") if usage.get("completion_tokens") else None + self.text = doc["choices"][0]["message"]["content"] + + def __eq__(self, other): + return isinstance(other, Reply) and self.sha is not None and self.sha == other.sha + + def ask(messages, draft=True, temperature=0.0, seed=7, url=URL): body = {"model": MODEL, "messages": messages, "max_tokens": TOKENS, "temperature": temperature, "seed": seed, "draft": draft, "chat_template_kwargs": {"enable_thinking": False}} @@ -24,7 +39,12 @@ def ask(messages, draft=True, temperature=0.0, seed=7, url=URL): {"Content-Type": "application/json"}) with urllib.request.urlopen(request, timeout=900) as reply: doc = json.load(reply) - return doc["choices"][0]["message"]["content"], doc.get("usage", {}).get("prompt_tokens_details", {}) + spec = doc.get("speculative") or {} + if draft: + DRAFTS["accepted"][temperature] = DRAFTS["accepted"].get(temperature, 0) + (spec.get("accepted") or 0) + else: + DRAFTS["plain"] += spec.get("drafted") or 0 + return Reply(doc), doc.get("usage", {}).get("prompt_tokens_details", {}) def user(text): @@ -45,6 +65,8 @@ def run(i): return out +# the resumed chat's first turn: Qwen 3.5 keeps only prompts of 4,096 tokens or more (serve with --context 8192+) +DOCUMENT = "An inventory: " + " ".join(f"crate{i % 89}-{(i * 6151) % 997}" for i in range(900)) LONG = "Summarise this list in one sentence: " + " ".join(f"item{i % 97}x{(i * 7919) % 1013}" for i in range(500)) @@ -74,21 +96,29 @@ def check(name, same): print(("ok " if same else "FAIL ") + name, flush=True) +greedy = None for label, temperature in (("greedy", 0.0), ("t0.8", 0.8)): serial = [ask(user(p), False, temperature)[0] for p in PROMPTS] drafted = [ask(user(p), True, temperature)[0] for p in PROMPTS] - check(f"{label}: drafted == serial", drafted == serial) + accepted, plain = DRAFTS["accepted"].get(temperature, 0), DRAFTS["plain"] + check(f"{label}: drafted == serial ({accepted} drafts accepted, plain drafted {plain})", + drafted == serial and accepted > 0 and plain == 0) check(f"{label}: solo == together", together(True, temperature) == drafted) check(f"{label}: serial together == serial solo", together(False, temperature) == serial) again = [ask(user(p), True, temperature)[0] for p in PROMPTS] - check(f"{label}: the same twice", again == drafted) + if greedy is None: + greedy = drafted + check(f"{label}: the same twice", again == drafted) + else: # the same seed twice, and unlike greedy for some prompt: the sampler ran + check(f"{label}: the same twice, unlike greedy", again == drafted and drafted != greedy) # the long prompt first among the decoders (its prompt goes in a chunk a round), then alone (resumed from its cuts) mixed = among_decoders(True, temperature) check(f"{label}: decoders unchanged by a long prompt", mixed[:3] == drafted[:3]) check(f"{label}: long prompt among decoders == alone", mixed[3] == ask(user(LONG), True, temperature)[0]) check(f"{label}: serial long prompt among decoders == alone", among_decoders(False, temperature)[3] == mixed[3]) -first, _ = ask(user(PROMPTS[0]), True) -turn = user(PROMPTS[0]) + [{"role": "assistant", "content": first}, {"role": "user", "content": "Now say it shorter."}] +opening = user(DOCUMENT + "\n\n" + PROMPTS[0]) +first, _ = ask(opening, True) +turn = opening + [{"role": "assistant", "content": first.text}, {"role": "user", "content": "Now say it shorter."}] # the fresh side on a server that keeps no prompts; a fresh reply that restored tokens fails by name fresh, fresh_details = ask(turn, False, url=FRESH_URL) resumed, details = ask(turn, True) @@ -97,6 +127,8 @@ def check(name, same): check("resumed == fresh: the fresh reply has no prompt_tokens_details.cached_tokens", False) elif restored != 0: check(f"resumed == fresh: the fresh request resumed {restored} tokens (FRESH_URL: --prompt-cache-gib 0)", False) +elif not details.get("cached_tokens"): + check(f"resumed == fresh: the resumed request resumed no tokens (vacuous; cached {details})", False) else: check(f"resumed == fresh (cached {details})", resumed == fresh) print("failed", failed) diff --git a/zig/tests/server/golden/keys/full-model-id.json b/zig/tests/server/golden/keys/full-model-id.json new file mode 100644 index 00000000000..51b40507539 --- /dev/null +++ b/zig/tests/server/golden/keys/full-model-id.json @@ -0,0 +1,20 @@ +{ + "closed": "open", + "replies": [ + { + "status": "HTTP/1.1 200 OK", + "headers": [ + [ + "Content-Type", + "application/json" + ], + [ + "Content-Length", + "818" + ] + ], + "body": "{\"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/model-id-none.json b/zig/tests/server/golden/keys/model-id-none.json new file mode 100644 index 00000000000..aa79e9396e1 --- /dev/null +++ b/zig/tests/server/golden/keys/model-id-none.json @@ -0,0 +1,28 @@ +{ + "closed": "closed", + "replies": [ + { + "status": "HTTP/1.1 401 Unauthorized", + "headers": [ + [ + "WWW-Authenticate", + "Bearer" + ], + [ + "Content-Type", + "application/json" + ], + [ + "Content-Length", + "128" + ], + [ + "Connection", + "close" + ] + ], + "body": "{\"error\": {\"message\": \"A valid API key is required\", \"type\": \"invalid_request_error\", \"param\": null, \"code\": \"invalid_api_key\"}}", + "interim": "" + } + ] +} diff --git a/zig/tests/server/golden/models/alias.json b/zig/tests/server/golden/models/alias.json new file mode 100644 index 00000000000..51b40507539 --- /dev/null +++ b/zig/tests/server/golden/models/alias.json @@ -0,0 +1,20 @@ +{ + "closed": "open", + "replies": [ + { + "status": "HTTP/1.1 200 OK", + "headers": [ + [ + "Content-Type", + "application/json" + ], + [ + "Content-Length", + "818" + ] + ], + "body": "{\"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/models/bare.json b/zig/tests/server/golden/models/bare.json new file mode 100644 index 00000000000..5615f3cfa95 --- /dev/null +++ b/zig/tests/server/golden/models/bare.json @@ -0,0 +1,20 @@ +{ + "closed": "open", + "replies": [ + { + "status": "HTTP/1.1 200 OK", + "headers": [ + [ + "Content-Type", + "application/json" + ], + [ + "Content-Length", + "818" + ] + ], + "body": "{\"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\"]}", + "interim": "" + } + ] +} diff --git a/zig/tests/server/golden/models/served.json b/zig/tests/server/golden/models/served.json new file mode 100644 index 00000000000..5615f3cfa95 --- /dev/null +++ b/zig/tests/server/golden/models/served.json @@ -0,0 +1,20 @@ +{ + "closed": "open", + "replies": [ + { + "status": "HTTP/1.1 200 OK", + "headers": [ + [ + "Content-Type", + "application/json" + ], + [ + "Content-Length", + "818" + ] + ], + "body": "{\"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\"]}", + "interim": "" + } + ] +} diff --git a/zig/tests/server/golden/models/slash-escaped-lower.json b/zig/tests/server/golden/models/slash-escaped-lower.json new file mode 100644 index 00000000000..947187ea862 --- /dev/null +++ b/zig/tests/server/golden/models/slash-escaped-lower.json @@ -0,0 +1,20 @@ +{ + "closed": "open", + "replies": [ + { + "status": "HTTP/1.1 200 OK", + "headers": [ + [ + "Content-Type", + "application/json" + ], + [ + "Content-Length", + "830" + ] + ], + "body": "{\"id\": \"example-org/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\"]}", + "interim": "" + } + ] +} diff --git a/zig/tests/server/golden/models/slash-escaped.json b/zig/tests/server/golden/models/slash-escaped.json new file mode 100644 index 00000000000..947187ea862 --- /dev/null +++ b/zig/tests/server/golden/models/slash-escaped.json @@ -0,0 +1,20 @@ +{ + "closed": "open", + "replies": [ + { + "status": "HTTP/1.1 200 OK", + "headers": [ + [ + "Content-Type", + "application/json" + ], + [ + "Content-Length", + "830" + ] + ], + "body": "{\"id\": \"example-org/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\"]}", + "interim": "" + } + ] +} diff --git a/zig/tests/server/golden/models/slash-raw.json b/zig/tests/server/golden/models/slash-raw.json new file mode 100644 index 00000000000..947187ea862 --- /dev/null +++ b/zig/tests/server/golden/models/slash-raw.json @@ -0,0 +1,20 @@ +{ + "closed": "open", + "replies": [ + { + "status": "HTTP/1.1 200 OK", + "headers": [ + [ + "Content-Type", + "application/json" + ], + [ + "Content-Length", + "830" + ] + ], + "body": "{\"id\": \"example-org/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\"]}", + "interim": "" + } + ] +} diff --git a/zig/tests/server/golden/models/suffix-lists.json b/zig/tests/server/golden/models/suffix-lists.json new file mode 100644 index 00000000000..598373b6b0c --- /dev/null +++ b/zig/tests/server/golden/models/suffix-lists.json @@ -0,0 +1,20 @@ +{ + "closed": "open", + "replies": [ + { + "status": "HTTP/1.1 200 OK", + "headers": [ + [ + "Content-Type", + "application/json" + ], + [ + "Content-Length", + "2500" + ] + ], + "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\"]}, {\"id\": \"example-org/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\"]}]}", + "interim": "" + } + ] +} diff --git a/zig/tests/server/golden/models/unknown-escaped.json b/zig/tests/server/golden/models/unknown-escaped.json new file mode 100644 index 00000000000..228ed02a946 --- /dev/null +++ b/zig/tests/server/golden/models/unknown-escaped.json @@ -0,0 +1,20 @@ +{ + "closed": "open", + "replies": [ + { + "status": "HTTP/1.1 404 Not Found", + "headers": [ + [ + "Content-Type", + "application/json" + ], + [ + "Content-Length", + "150" + ] + ], + "body": "{\"error\": {\"message\": \"model 'example-org/missing' is not served here\", \"type\": \"invalid_request_error\", \"param\": \"model\", \"code\": \"model_not_found\"}}", + "interim": "" + } + ] +} diff --git a/zig/tests/server/golden/models/unknown.json b/zig/tests/server/golden/models/unknown.json new file mode 100644 index 00000000000..60bd4707545 --- /dev/null +++ b/zig/tests/server/golden/models/unknown.json @@ -0,0 +1,20 @@ +{ + "closed": "open", + "replies": [ + { + "status": "HTTP/1.1 404 Not Found", + "headers": [ + [ + "Content-Type", + "application/json" + ], + [ + "Content-Length", + "138" + ] + ], + "body": "{\"error\": {\"message\": \"model 'missing' is not served here\", \"type\": \"invalid_request_error\", \"param\": \"model\", \"code\": \"model_not_found\"}}", + "interim": "" + } + ] +} diff --git a/zig/tests/server/golden/scopes/app-model-id.json b/zig/tests/server/golden/scopes/app-model-id.json new file mode 100644 index 00000000000..51b40507539 --- /dev/null +++ b/zig/tests/server/golden/scopes/app-model-id.json @@ -0,0 +1,20 @@ +{ + "closed": "open", + "replies": [ + { + "status": "HTTP/1.1 200 OK", + "headers": [ + [ + "Content-Type", + "application/json" + ], + [ + "Content-Length", + "818" + ] + ], + "body": "{\"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/app-model-suffix.json b/zig/tests/server/golden/scopes/app-model-suffix.json new file mode 100644 index 00000000000..2ed39091352 --- /dev/null +++ b/zig/tests/server/golden/scopes/app-model-suffix.json @@ -0,0 +1,24 @@ +{ + "closed": "closed", + "replies": [ + { + "status": "HTTP/1.1 403 Forbidden", + "headers": [ + [ + "Content-Type", + "application/json" + ], + [ + "Content-Length", + "142" + ], + [ + "Connection", + "close" + ] + ], + "body": "{\"error\": {\"message\": \"This API key does not permit this operation\", \"type\": \"permission_error\", \"param\": null, \"code\": \"insufficient_scope\"}}", + "interim": "" + } + ] +} diff --git a/zig/tests/server/golden/scopes/read-model-id.json b/zig/tests/server/golden/scopes/read-model-id.json new file mode 100644 index 00000000000..5615f3cfa95 --- /dev/null +++ b/zig/tests/server/golden/scopes/read-model-id.json @@ -0,0 +1,20 @@ +{ + "closed": "open", + "replies": [ + { + "status": "HTTP/1.1 200 OK", + "headers": [ + [ + "Content-Type", + "application/json" + ], + [ + "Content-Length", + "818" + ] + ], + "body": "{\"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\"]}", + "interim": "" + } + ] +} diff --git a/zig/tests/server/golden/security-cases.json b/zig/tests/server/golden/security-cases.json index 3f6cf794fe5..cbe51132e64 100644 --- a/zig/tests/server/golden/security-cases.json +++ b/zig/tests/server/golden/security-cases.json @@ -1 +1 @@ -{"steps": [{"kind": "serve", "args": ["--api-key", "sk-cli"], "env": {}, "cases": [{"group": "keys", "name": "systemone-none", "raws": [{"b64": "UE9TVCAvc3lzdGVtb25lIEhUVFAvMS4xDQpIb3N0OiBsb2NhbGhvc3QNCkNvbnRlbnQtVHlwZTogdGV4dC9wbGFpbg0KQ29udGVudC1MZW5ndGg6IDExMA0KDQp7InN0YXRlIjogbnVsbCwgInF1ZXN0aW9ucyI6IHsicSI6IHsidHlwZSI6ICJjaG9pY2UiLCAiaW5zdHJ1Y3Rpb25zIjogImkiLCAiY3JpdGVyaWEiOiB7IkEiOiAiYSIsICJCIjogImIifX19fQ=="}], "opts": {}}, {"group": "keys", "name": "systemone-with-key", "raws": [{"b64": "UE9TVCAvc3lzdGVtb25lIEhUVFAvMS4xDQpIb3N0OiBsb2NhbGhvc3QNCngtYXBpLWtleTogc2stY2xpDQpDb250ZW50LVR5cGU6IHRleHQvcGxhaW4NCkNvbnRlbnQtTGVuZ3RoOiAxMTANCg0KeyJzdGF0ZSI6IG51bGwsICJxdWVzdGlvbnMiOiB7InEiOiB7InR5cGUiOiAiY2hvaWNlIiwgImluc3RydWN0aW9ucyI6ICJpIiwgImNyaXRlcmlhIjogeyJBIjogImEiLCAiQiI6ICJiIn19fX0="}], "opts": {}}, {"group": "keys", "name": "v1-systemone-none", "raws": [{"b64": "UE9TVCAvdjEvc3lzdGVtb25lIEhUVFAvMS4xDQpIb3N0OiBsb2NhbGhvc3QNCkNvbnRlbnQtVHlwZTogdGV4dC9wbGFpbg0KQ29udGVudC1MZW5ndGg6IDExMA0KDQp7InN0YXRlIjogbnVsbCwgInF1ZXN0aW9ucyI6IHsicSI6IHsidHlwZSI6ICJjaG9pY2UiLCAiaW5zdHJ1Y3Rpb25zIjogImkiLCAiY3JpdGVyaWEiOiB7IkEiOiAiYSIsICJCIjogImIifX19fQ=="}], "opts": {}}, {"group": "keys", "name": "v1-systemone-with-key", "raws": [{"b64": "UE9TVCAvdjEvc3lzdGVtb25lIEhUVFAvMS4xDQpIb3N0OiBsb2NhbGhvc3QNCngtYXBpLWtleTogc2stY2xpDQpDb250ZW50LVR5cGU6IHRleHQvcGxhaW4NCkNvbnRlbnQtTGVuZ3RoOiAxMTANCg0KeyJzdGF0ZSI6IG51bGwsICJxdWVzdGlvbnMiOiB7InEiOiB7InR5cGUiOiAiY2hvaWNlIiwgImluc3RydWN0aW9ucyI6ICJpIiwgImNyaXRlcmlhIjogeyJBIjogImEiLCAiQiI6ICJiIn19fX0="}], "opts": {}}, {"group": "keys", "name": "x-systemone-none", "raws": [{"b64": "UE9TVCAveC9zeXN0ZW1vbmUgSFRUUC8xLjENCkhvc3Q6IGxvY2FsaG9zdA0KQ29udGVudC1UeXBlOiB0ZXh0L3BsYWluDQpDb250ZW50LUxlbmd0aDogMTEwDQoNCnsic3RhdGUiOiBudWxsLCAicXVlc3Rpb25zIjogeyJxIjogeyJ0eXBlIjogImNob2ljZSIsICJpbnN0cnVjdGlvbnMiOiAiaSIsICJjcml0ZXJpYSI6IHsiQSI6ICJhIiwgIkIiOiAiYiJ9fX19"}], "opts": {}}, {"group": "keys", "name": "x-systemone-with-key", "raws": [{"b64": "UE9TVCAveC9zeXN0ZW1vbmUgSFRUUC8xLjENCkhvc3Q6IGxvY2FsaG9zdA0KeC1hcGkta2V5OiBzay1jbGkNCkNvbnRlbnQtVHlwZTogdGV4dC9wbGFpbg0KQ29udGVudC1MZW5ndGg6IDExMA0KDQp7InN0YXRlIjogbnVsbCwgInF1ZXN0aW9ucyI6IHsicSI6IHsidHlwZSI6ICJjaG9pY2UiLCAiaW5zdHJ1Y3Rpb25zIjogImkiLCAiY3JpdGVyaWEiOiB7IkEiOiAiYSIsICJCIjogImIifX19fQ=="}], "opts": {}}], "then": [{"kind": "terminate"}]}, {"kind": "serve", "args": [], "env": {}, "cases": [{"group": "origin", "name": "rebind-host", "raws": [{"b64": "R0VUIC9oZWFsdGggSFRUUC8xLjENCkhvc3Q6IHJlYmluZC5pbnZhbGlkDQoNCg=="}], "opts": {}}, {"group": "origin", "name": "cross-origin", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogbG9jYWxob3N0DQpPcmlnaW46IGh0dHBzOi8vZXZpbC5pbnZhbGlkDQpDb250ZW50LVR5cGU6IHRleHQvcGxhaW4NCkNvbnRlbnQtTGVuZ3RoOiAyDQoNCnt9"}], "opts": {}}, {"group": "origin", "name": "cross-origin-learn", "raws": [{"b64": "UE9TVCAvdjEvc2xpZGUvbGVhcm4gSFRUUC8xLjENCkhvc3Q6IGxvY2FsaG9zdA0KT3JpZ2luOiBodHRwczovL2V2aWwuaW52YWxpZA0KQ29udGVudC1UeXBlOiB0ZXh0L3BsYWluDQpDb250ZW50LUxlbmd0aDogMg0KDQp7fQ=="}], "opts": {}}, {"group": "origin", "name": "same-origin", "raws": [{"b64": "R0VUIC9oZWFsdGggSFRUUC8xLjENCkhvc3Q6IGxvY2FsaG9zdDo4MDAwDQpPcmlnaW46IGh0dHA6Ly9sb2NhbGhvc3Q6ODAwMA0KDQo="}], "opts": {}}, {"group": "origin", "name": "no-origin", "raws": [{"b64": "R0VUIC9oZWFsdGggSFRUUC8xLjENCkhvc3Q6IDEyNy4wLjAuMTo5MDAwDQoNCg=="}], "opts": {}}, {"group": "origin", "name": "null-origin", "raws": [{"b64": "R0VUIC9oZWFsdGggSFRUUC8xLjENCkhvc3Q6IGxvY2FsaG9zdA0KT3JpZ2luOiBudWxsDQoNCg=="}], "opts": {}}, {"group": "origin", "name": "missing-host", "raws": [{"b64": "R0VUIC9oZWFsdGggSFRUUC8xLjENCg0K"}], "opts": {}}, {"group": "origin", "name": "ipv6-loopback", "raws": [{"b64": "R0VUIC9oZWFsdGggSFRUUC8xLjENCkhvc3Q6IFs6OjFdOjgwDQpPcmlnaW46IGh0dHA6Ly9bOjoxXQ0KDQo="}], "opts": {}}, {"group": "origin", "name": "scheme-mismatch", "raws": [{"b64": "R0VUIC9oZWFsdGggSFRUUC8xLjENCkhvc3Q6IGxvY2FsaG9zdA0KT3JpZ2luOiBodHRwczovL2xvY2FsaG9zdA0KDQo="}], "opts": {}}, {"group": "origin", "name": "duplicate-host", "raws": [{"b64": "R0VUIC9oZWFsdGggSFRUUC8xLjENCkhvc3Q6IGxvY2FsaG9zdA0KaE9zVDogbG9jYWxob3N0DQoNCg=="}], "opts": {}}, {"group": "origin", "name": "duplicate-origin", "raws": [{"b64": "R0VUIC9oZWFsdGggSFRUUC8xLjENCkhvc3Q6IGxvY2FsaG9zdA0KT3JpZ2luOiBodHRwOi8vbG9jYWxob3N0DQpvUmlHaU46IGh0dHA6Ly9sb2NhbGhvc3QNCg0K"}], "opts": {}}], "then": [{"kind": "terminate"}]}, {"kind": "serve", "args": ["--allowed-host", "trusted-one.invalid", "--allowed-host=trusted-two.invalid", "--allowed-origin", "https://ui-one.invalid", "--allowed-origin=http://ui-two.invalid:8000"], "env": {}, "cases": [{"group": "origin", "name": "allowed-host-first", "raws": [{"b64": "R0VUIC9oZWFsdGggSFRUUC8xLjENCkhvc3Q6IHRydXN0ZWQtb25lLmludmFsaWQNCg0K"}], "opts": {}}, {"group": "origin", "name": "allowed-host-second", "raws": [{"b64": "R0VUIC9oZWFsdGggSFRUUC8xLjENCkhvc3Q6IHRydXN0ZWQtdHdvLmludmFsaWQNCg0K"}], "opts": {}}, {"group": "origin", "name": "allowed-origin-first", "raws": [{"b64": "R0VUIC9oZWFsdGggSFRUUC8xLjENCkhvc3Q6IGxvY2FsaG9zdA0KT3JpZ2luOiBodHRwczovL3VpLW9uZS5pbnZhbGlkOjQ0Mw0KDQo="}], "opts": {}}, {"group": "origin", "name": "allowed-origin-second", "raws": [{"b64": "R0VUIC9oZWFsdGggSFRUUC8xLjENCkhvc3Q6IGxvY2FsaG9zdA0KT3JpZ2luOiBodHRwOi8vdWktdHdvLmludmFsaWQ6ODAwMA0KDQo="}], "opts": {}}], "then": [{"kind": "terminate"}]}, {"kind": "serve", "args": ["--host", "0.0.0.0"], "env": {}, "cases": [{"group": "origin", "name": "nonloopback-host", "raws": [{"b64": "R0VUIC9oZWFsdGggSFRUUC8xLjENCkhvc3Q6IHB1YmxpYy5pbnZhbGlkDQoNCg=="}], "opts": {}}, {"group": "origin", "name": "nonloopback-cross-origin", "raws": [{"b64": "R0VUIC9oZWFsdGggSFRUUC8xLjENCkhvc3Q6IHB1YmxpYy5pbnZhbGlkDQpPcmlnaW46IGh0dHA6Ly9ldmlsLmludmFsaWQNCg0K"}], "opts": {}}, {"group": "origin", "name": "nonloopback-same-origin", "raws": [{"b64": "R0VUIC9oZWFsdGggSFRUUC8xLjENCkhvc3Q6IHB1YmxpYy5pbnZhbGlkDQpPcmlnaW46IGh0dHA6Ly9wdWJsaWMuaW52YWxpZA0KDQo="}], "opts": {}}], "then": [{"kind": "terminate"}]}, {"kind": "serve", "args": ["--api-key", "sk-cli"], "env": {}, "cases": [{"group": "origin", "name": "key-does-not-bypass-host", "raws": [{"b64": "R0VUIC9oZWFsdGggSFRUUC8xLjENCkhvc3Q6IHJlYmluZC5pbnZhbGlkDQp4LWFwaS1rZXk6IHNrLWNsaQ0KDQo="}], "opts": {}}, {"group": "origin", "name": "key-does-not-bypass-origin", "raws": [{"b64": "R0VUIC9oZWFsdGggSFRUUC8xLjENCkhvc3Q6IGxvY2FsaG9zdA0KT3JpZ2luOiBodHRwOi8vZXZpbC5pbnZhbGlkDQp4LWFwaS1rZXk6IHNrLWNsaQ0KDQo="}], "opts": {}}], "then": [{"kind": "terminate"}]}, {"kind": "serve", "args": ["--api-key", "sk-cli", "--api-key-file", "@KEYFILE@"], "env": {"TENSORFOLD_API_KEY": "sk-env"}, "key_file": "# keys\nclient: sk-file\nsk-bare\n", "cases": [{"group": "keys", "name": "full-get-response", "raws": [{"b64": "R0VUIC92MS9yZXNwb25zZXMvcmVzcF9taXNzaW5nIEhUVFAvMS4xDQpIb3N0OiBsb2NhbGhvc3QNCkF1dGhvcml6YXRpb246IEJlYXJlciBzay1jbGkNCg0K"}], "opts": {}}, {"group": "keys", "name": "full-delete-response", "raws": [{"b64": "REVMRVRFIC92MS9yZXNwb25zZXMvcmVzcF9taXNzaW5nIEhUVFAvMS4xDQpIb3N0OiBsb2NhbGhvc3QNCngtYXBpLWtleTogc2stZmlsZQ0KDQo="}], "opts": {}}, {"group": "keys", "name": "full-response-stored", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBsb2NhbGhvc3QNCkF1dGhvcml6YXRpb246IEJlYXJlciBzay1iYXJlDQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiA1Mw0KDQp7ImlucHV0IjogIkhpIEBzY3JpcHQ9cGxhaW4iLCAibWF4X291dHB1dF90b2tlbnMiOiAyfQ=="}], "opts": {}}, {"group": "keys", "name": "full-response-parent", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBsb2NhbGhvc3QNCngtYXBpLWtleTogc2stZW52DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiA1NQ0KDQp7ImlucHV0IjogIkhpIiwgInByZXZpb3VzX3Jlc3BvbnNlX2lkIjogInJlc3BfbWlzc2luZyJ9"}], "opts": {}}, {"group": "keys", "name": "full-alias-completions", "raws": [{"b64": "UE9TVCAvYWx0L2NvbXBsZXRpb25zIEhUVFAvMS4xDQpIb3N0OiBsb2NhbGhvc3QNCngtYXBpLWtleTogc2stZmlsZQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogNDYNCg0KeyJwcm9tcHQiOiAieCBAc2NyaXB0PXBsYWluIiwgIm1heF90b2tlbnMiOiAyfQ=="}], "opts": {}}, {"group": "keys", "name": "full-slide-learn", "raws": [{"b64": "UE9TVCAvdjEvc2xpZGUvbGVhcm4gSFRUUC8xLjENCkhvc3Q6IGxvY2FsaG9zdA0KQXV0aG9yaXphdGlvbjogQmVhcmVyIHNrLWNsaQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMg0KDQp7fQ=="}], "opts": {}}, {"group": "keys", "name": "full-slide-graph", "raws": [{"b64": "REVMRVRFIC92MS9zbGlkZS9ncmFwaCBIVFRQLzEuMQ0KSG9zdDogbG9jYWxob3N0DQp4LWFwaS1rZXk6IHNrLWVudg0KDQo="}], "opts": {}}, {"group": "keys", "name": "full-recall", "raws": [{"b64": "R0VUIC92MS9yZWNhbGwgSFRUUC8xLjENCkhvc3Q6IGxvY2FsaG9zdA0KeC1hcGkta2V5OiBzay1maWxlDQoNCg=="}], "opts": {}}, {"group": "keys", "name": "full-imprint-load", "raws": [{"b64": "UE9TVCAvdjEvaW1wcmludC9sb2FkIEhUVFAvMS4xDQpIb3N0OiBsb2NhbGhvc3QNCkF1dGhvcml6YXRpb246IEJlYXJlciBzay1iYXJlDQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAyDQoNCnt9"}], "opts": {}}, {"group": "keys", "name": "full-stats", "raws": [{"b64": "R0VUIC9zdGF0cyBIVFRQLzEuMQ0KSG9zdDogbG9jYWxob3N0DQpBdXRob3JpemF0aW9uOiBCZWFyZXIgc2stY2xpDQoNCg=="}], "opts": {}}, {"group": "keys", "name": "full-head", "raws": [{"b64": "SEVBRCAvdjEvbW9kZWxzIEhUVFAvMS4xDQpIb3N0OiBsb2NhbGhvc3QNCngtYXBpLWtleTogc2stZmlsZQ0KDQo="}], "opts": {}}, {"group": "keys", "name": "full-put", "raws": [{"b64": "UFVUIC92MS9tb2RlbHMgSFRUUC8xLjENCkhvc3Q6IGxvY2FsaG9zdA0KeC1hcGkta2V5OiBzay1lbnYNCg0K"}], "opts": {}}, {"group": "keys", "name": "full-future", "raws": [{"b64": "R0VUIC9mdXR1cmUvcHJpdmF0ZSBIVFRQLzEuMQ0KSG9zdDogbG9jYWxob3N0DQpBdXRob3JpemF0aW9uOiBCZWFyZXIgc2stYmFyZQ0KDQo="}], "opts": {}}, {"group": "keys", "name": "full-then-none", "raws": [{"b64": "R0VUIC92MS9tb2RlbHMgSFRUUC8xLjENCkhvc3Q6IGxvY2FsaG9zdA0KeC1hcGkta2V5OiBzay1maWxlDQoNCg=="}, {"b64": "REVMRVRFIC92MS9yZXNwb25zZXMvcmVzcF9taXNzaW5nIEhUVFAvMS4xDQpIb3N0OiBsb2NhbGhvc3QNCg0K"}], "opts": {}}], "then": [{"kind": "terminate"}]}, {"kind": "serve", "args": ["--api-key-file", "@KEYFILE@"], "env": {}, "key_file": "app[inference]: sk-app\nmonitor[read]: sk-read\nops: sk-ops\n", "cases": [{"group": "scopes", "name": "read-chat", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogbG9jYWxob3N0DQpBdXRob3JpemF0aW9uOiBCZWFyZXIgc2stcmVhZA0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogODYNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XX0="}], "opts": {}}, {"group": "scopes", "name": "read-messages", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IGxvY2FsaG9zdA0KQXV0aG9yaXphdGlvbjogQmVhcmVyIHNrLXJlYWQNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDgwDQoNCnsibWF4X3Rva2VucyI6IDIsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9cGxhaW4ifV19"}], "opts": {}}, {"group": "scopes", "name": "read-models", "raws": [{"b64": "R0VUIC92MS9tb2RlbHMgSFRUUC8xLjENCkhvc3Q6IGxvY2FsaG9zdA0KQXV0aG9yaXphdGlvbjogQmVhcmVyIHNrLXJlYWQNCg0K"}], "opts": {}}, {"group": "scopes", "name": "app-metrics", "raws": [{"b64": "R0VUIC9tZXRyaWNzIEhUVFAvMS4xDQpIb3N0OiBsb2NhbGhvc3QNCngtYXBpLWtleTogc2stYXBwDQoNCg=="}], "opts": {}}, {"group": "scopes", "name": "app-chat", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogbG9jYWxob3N0DQp4LWFwaS1rZXk6IHNrLWFwcA0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogODYNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XX0="}], "opts": {}}, {"group": "scopes", "name": "app-alias", "raws": [{"b64": "UE9TVCAvYWx0L2NvbXBsZXRpb25zIEhUVFAvMS4xDQpIb3N0OiBsb2NhbGhvc3QNCngtYXBpLWtleTogc2stYXBwDQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAyOQ0KDQp7InByb21wdCI6ICJ4IEBzY3JpcHQ9cGxhaW4ifQ=="}], "opts": {}}, {"group": "scopes", "name": "app-recall", "raws": [{"b64": "R0VUIC92MS9yZWNhbGwgSFRUUC8xLjENCkhvc3Q6IGxvY2FsaG9zdA0KeC1hcGkta2V5OiBzay1hcHANCg0K"}], "opts": {}}, {"group": "scopes", "name": "app-slide-graph", "raws": [{"b64": "REVMRVRFIC92MS9zbGlkZS9ncmFwaCBIVFRQLzEuMQ0KSG9zdDogbG9jYWxob3N0DQp4LWFwaS1rZXk6IHNrLWFwcA0KDQo="}], "opts": {}}, {"group": "scopes", "name": "app-learn-expect", "raws": [{"b64": "UE9TVCAvdjEvc2xpZGUvbGVhcm4gSFRUUC8xLjENCkhvc3Q6IGxvY2FsaG9zdA0KeC1hcGkta2V5OiBzay1hcHANCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDEzDQpFeHBlY3Q6IDEwMC1jb250aW51ZQ0KDQp7InRleHQiOiAieCJ9"}], "opts": {}}, {"group": "scopes", "name": "app-response-stored", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBsb2NhbGhvc3QNCngtYXBpLWtleTogc2stYXBwDQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAyOQ0KDQp7ImlucHV0IjogIkhpIEBzY3JpcHQ9cGxhaW4ifQ=="}], "opts": {}}, {"group": "scopes", "name": "app-response-parent", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBsb2NhbGhvc3QNCngtYXBpLWtleTogc2stYXBwDQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiA2NQ0KDQp7ImlucHV0IjogIkhpIiwgInN0b3JlIjogZmFsc2UsICJwcmV2aW91c19yZXNwb25zZV9pZCI6ICJyZXNwX3gifQ=="}], "opts": {}}, {"group": "scopes", "name": "app-response-stateless", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBsb2NhbGhvc3QNCngtYXBpLWtleTogc2stYXBwDQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiA2OQ0KDQp7ImlucHV0IjogIkhpIEBzY3JpcHQ9cGxhaW4iLCAic3RvcmUiOiBmYWxzZSwgIm1heF9vdXRwdXRfdG9rZW5zIjogMn0="}], "opts": {}}, {"group": "scopes", "name": "ops-slide-graph", "raws": [{"b64": "REVMRVRFIC92MS9zbGlkZS9ncmFwaCBIVFRQLzEuMQ0KSG9zdDogbG9jYWxob3N0DQp4LWFwaS1rZXk6IHNrLW9wcw0KDQo="}], "opts": {}}], "then": [{"kind": "terminate"}]}, {"kind": "serve", "args": [], "env": {}, "cases": [{"group": "admission", "name": "off-burst", "raws": [{"b64": "UE9TVCAvdjEvY29tcGxldGlvbnMgSFRUUC8xLjENCkhvc3Q6IGxvY2FsaG9zdA0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogNDYNCg0KeyJwcm9tcHQiOiAieCBAc2NyaXB0PXBsYWluIiwgIm1heF90b2tlbnMiOiAyfQ=="}, {"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogbG9jYWxob3N0DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiA4Ng0KDQp7Im1vZGVsIjogImZha2UtbW9kZWwiLCAibWVzc2FnZXMiOiBbeyJyb2xlIjogInVzZXIiLCAiY29udGVudCI6ICJIaSBAc2NyaXB0PXBsYWluIn1dfQ=="}, {"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IGxvY2FsaG9zdA0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTAzDQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogNCwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XX0="}, {"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBsb2NhbGhvc3QNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDUzDQoNCnsiaW5wdXQiOiAiSGkgQHNjcmlwdD1wbGFpbiIsICJtYXhfb3V0cHV0X3Rva2VucyI6IDJ9"}, {"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogbG9jYWxob3N0DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDINCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInN0cmVhbSI6IHRydWV9"}], "opts": {}}], "then": [{"kind": "terminate"}]}, {"kind": "serve", "args": ["--max-inflight", "0", "--max-inflight-per-key", "0", "--requests-per-second", "0", "--request-burst", "7"], "env": {}, "cases": [{"group": "admission", "name": "zero-burst", "raws": [{"b64": "UE9TVCAvdjEvY29tcGxldGlvbnMgSFRUUC8xLjENCkhvc3Q6IGxvY2FsaG9zdA0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogNDYNCg0KeyJwcm9tcHQiOiAieCBAc2NyaXB0PXBsYWluIiwgIm1heF90b2tlbnMiOiAyfQ=="}, {"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogbG9jYWxob3N0DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiA4Ng0KDQp7Im1vZGVsIjogImZha2UtbW9kZWwiLCAibWVzc2FnZXMiOiBbeyJyb2xlIjogInVzZXIiLCAiY29udGVudCI6ICJIaSBAc2NyaXB0PXBsYWluIn1dfQ=="}, {"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IGxvY2FsaG9zdA0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTAzDQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogNCwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XX0="}, {"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBsb2NhbGhvc3QNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDUzDQoNCnsiaW5wdXQiOiAiSGkgQHNjcmlwdD1wbGFpbiIsICJtYXhfb3V0cHV0X3Rva2VucyI6IDJ9"}, {"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogbG9jYWxob3N0DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDINCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInN0cmVhbSI6IHRydWV9"}], "opts": {}}], "then": [{"kind": "terminate"}]}]} +{"steps": [{"kind": "serve", "args": ["--api-key", "sk-cli"], "env": {}, "cases": [{"group": "keys", "name": "systemone-none", "raws": [{"b64": "UE9TVCAvc3lzdGVtb25lIEhUVFAvMS4xDQpIb3N0OiBsb2NhbGhvc3QNCkNvbnRlbnQtVHlwZTogdGV4dC9wbGFpbg0KQ29udGVudC1MZW5ndGg6IDExMA0KDQp7InN0YXRlIjogbnVsbCwgInF1ZXN0aW9ucyI6IHsicSI6IHsidHlwZSI6ICJjaG9pY2UiLCAiaW5zdHJ1Y3Rpb25zIjogImkiLCAiY3JpdGVyaWEiOiB7IkEiOiAiYSIsICJCIjogImIifX19fQ=="}], "opts": {}}, {"group": "keys", "name": "systemone-with-key", "raws": [{"b64": "UE9TVCAvc3lzdGVtb25lIEhUVFAvMS4xDQpIb3N0OiBsb2NhbGhvc3QNCngtYXBpLWtleTogc2stY2xpDQpDb250ZW50LVR5cGU6IHRleHQvcGxhaW4NCkNvbnRlbnQtTGVuZ3RoOiAxMTANCg0KeyJzdGF0ZSI6IG51bGwsICJxdWVzdGlvbnMiOiB7InEiOiB7InR5cGUiOiAiY2hvaWNlIiwgImluc3RydWN0aW9ucyI6ICJpIiwgImNyaXRlcmlhIjogeyJBIjogImEiLCAiQiI6ICJiIn19fX0="}], "opts": {}}, {"group": "keys", "name": "v1-systemone-none", "raws": [{"b64": "UE9TVCAvdjEvc3lzdGVtb25lIEhUVFAvMS4xDQpIb3N0OiBsb2NhbGhvc3QNCkNvbnRlbnQtVHlwZTogdGV4dC9wbGFpbg0KQ29udGVudC1MZW5ndGg6IDExMA0KDQp7InN0YXRlIjogbnVsbCwgInF1ZXN0aW9ucyI6IHsicSI6IHsidHlwZSI6ICJjaG9pY2UiLCAiaW5zdHJ1Y3Rpb25zIjogImkiLCAiY3JpdGVyaWEiOiB7IkEiOiAiYSIsICJCIjogImIifX19fQ=="}], "opts": {}}, {"group": "keys", "name": "v1-systemone-with-key", "raws": [{"b64": "UE9TVCAvdjEvc3lzdGVtb25lIEhUVFAvMS4xDQpIb3N0OiBsb2NhbGhvc3QNCngtYXBpLWtleTogc2stY2xpDQpDb250ZW50LVR5cGU6IHRleHQvcGxhaW4NCkNvbnRlbnQtTGVuZ3RoOiAxMTANCg0KeyJzdGF0ZSI6IG51bGwsICJxdWVzdGlvbnMiOiB7InEiOiB7InR5cGUiOiAiY2hvaWNlIiwgImluc3RydWN0aW9ucyI6ICJpIiwgImNyaXRlcmlhIjogeyJBIjogImEiLCAiQiI6ICJiIn19fX0="}], "opts": {}}, {"group": "keys", "name": "x-systemone-none", "raws": [{"b64": "UE9TVCAveC9zeXN0ZW1vbmUgSFRUUC8xLjENCkhvc3Q6IGxvY2FsaG9zdA0KQ29udGVudC1UeXBlOiB0ZXh0L3BsYWluDQpDb250ZW50LUxlbmd0aDogMTEwDQoNCnsic3RhdGUiOiBudWxsLCAicXVlc3Rpb25zIjogeyJxIjogeyJ0eXBlIjogImNob2ljZSIsICJpbnN0cnVjdGlvbnMiOiAiaSIsICJjcml0ZXJpYSI6IHsiQSI6ICJhIiwgIkIiOiAiYiJ9fX19"}], "opts": {}}, {"group": "keys", "name": "x-systemone-with-key", "raws": [{"b64": "UE9TVCAveC9zeXN0ZW1vbmUgSFRUUC8xLjENCkhvc3Q6IGxvY2FsaG9zdA0KeC1hcGkta2V5OiBzay1jbGkNCkNvbnRlbnQtVHlwZTogdGV4dC9wbGFpbg0KQ29udGVudC1MZW5ndGg6IDExMA0KDQp7InN0YXRlIjogbnVsbCwgInF1ZXN0aW9ucyI6IHsicSI6IHsidHlwZSI6ICJjaG9pY2UiLCAiaW5zdHJ1Y3Rpb25zIjogImkiLCAiY3JpdGVyaWEiOiB7IkEiOiAiYSIsICJCIjogImIifX19fQ=="}], "opts": {}}], "then": [{"kind": "terminate"}]}, {"kind": "serve", "args": [], "env": {}, "cases": [{"group": "origin", "name": "rebind-host", "raws": [{"b64": "R0VUIC9oZWFsdGggSFRUUC8xLjENCkhvc3Q6IHJlYmluZC5pbnZhbGlkDQoNCg=="}], "opts": {}}, {"group": "origin", "name": "cross-origin", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogbG9jYWxob3N0DQpPcmlnaW46IGh0dHBzOi8vZXZpbC5pbnZhbGlkDQpDb250ZW50LVR5cGU6IHRleHQvcGxhaW4NCkNvbnRlbnQtTGVuZ3RoOiAyDQoNCnt9"}], "opts": {}}, {"group": "origin", "name": "cross-origin-learn", "raws": [{"b64": "UE9TVCAvdjEvc2xpZGUvbGVhcm4gSFRUUC8xLjENCkhvc3Q6IGxvY2FsaG9zdA0KT3JpZ2luOiBodHRwczovL2V2aWwuaW52YWxpZA0KQ29udGVudC1UeXBlOiB0ZXh0L3BsYWluDQpDb250ZW50LUxlbmd0aDogMg0KDQp7fQ=="}], "opts": {}}, {"group": "origin", "name": "same-origin", "raws": [{"b64": "R0VUIC9oZWFsdGggSFRUUC8xLjENCkhvc3Q6IGxvY2FsaG9zdDo4MDAwDQpPcmlnaW46IGh0dHA6Ly9sb2NhbGhvc3Q6ODAwMA0KDQo="}], "opts": {}}, {"group": "origin", "name": "no-origin", "raws": [{"b64": "R0VUIC9oZWFsdGggSFRUUC8xLjENCkhvc3Q6IDEyNy4wLjAuMTo5MDAwDQoNCg=="}], "opts": {}}, {"group": "origin", "name": "null-origin", "raws": [{"b64": "R0VUIC9oZWFsdGggSFRUUC8xLjENCkhvc3Q6IGxvY2FsaG9zdA0KT3JpZ2luOiBudWxsDQoNCg=="}], "opts": {}}, {"group": "origin", "name": "missing-host", "raws": [{"b64": "R0VUIC9oZWFsdGggSFRUUC8xLjENCg0K"}], "opts": {}}, {"group": "origin", "name": "ipv6-loopback", "raws": [{"b64": "R0VUIC9oZWFsdGggSFRUUC8xLjENCkhvc3Q6IFs6OjFdOjgwDQpPcmlnaW46IGh0dHA6Ly9bOjoxXQ0KDQo="}], "opts": {}}, {"group": "origin", "name": "scheme-mismatch", "raws": [{"b64": "R0VUIC9oZWFsdGggSFRUUC8xLjENCkhvc3Q6IGxvY2FsaG9zdA0KT3JpZ2luOiBodHRwczovL2xvY2FsaG9zdA0KDQo="}], "opts": {}}, {"group": "origin", "name": "duplicate-host", "raws": [{"b64": "R0VUIC9oZWFsdGggSFRUUC8xLjENCkhvc3Q6IGxvY2FsaG9zdA0KaE9zVDogbG9jYWxob3N0DQoNCg=="}], "opts": {}}, {"group": "origin", "name": "duplicate-origin", "raws": [{"b64": "R0VUIC9oZWFsdGggSFRUUC8xLjENCkhvc3Q6IGxvY2FsaG9zdA0KT3JpZ2luOiBodHRwOi8vbG9jYWxob3N0DQpvUmlHaU46IGh0dHA6Ly9sb2NhbGhvc3QNCg0K"}], "opts": {}}], "then": [{"kind": "terminate"}]}, {"kind": "serve", "args": ["--allowed-host", "trusted-one.invalid", "--allowed-host=trusted-two.invalid", "--allowed-origin", "https://ui-one.invalid", "--allowed-origin=http://ui-two.invalid:8000"], "env": {}, "cases": [{"group": "origin", "name": "allowed-host-first", "raws": [{"b64": "R0VUIC9oZWFsdGggSFRUUC8xLjENCkhvc3Q6IHRydXN0ZWQtb25lLmludmFsaWQNCg0K"}], "opts": {}}, {"group": "origin", "name": "allowed-host-second", "raws": [{"b64": "R0VUIC9oZWFsdGggSFRUUC8xLjENCkhvc3Q6IHRydXN0ZWQtdHdvLmludmFsaWQNCg0K"}], "opts": {}}, {"group": "origin", "name": "allowed-origin-first", "raws": [{"b64": "R0VUIC9oZWFsdGggSFRUUC8xLjENCkhvc3Q6IGxvY2FsaG9zdA0KT3JpZ2luOiBodHRwczovL3VpLW9uZS5pbnZhbGlkOjQ0Mw0KDQo="}], "opts": {}}, {"group": "origin", "name": "allowed-origin-second", "raws": [{"b64": "R0VUIC9oZWFsdGggSFRUUC8xLjENCkhvc3Q6IGxvY2FsaG9zdA0KT3JpZ2luOiBodHRwOi8vdWktdHdvLmludmFsaWQ6ODAwMA0KDQo="}], "opts": {}}], "then": [{"kind": "terminate"}]}, {"kind": "serve", "args": ["--host", "0.0.0.0"], "env": {}, "cases": [{"group": "origin", "name": "nonloopback-host", "raws": [{"b64": "R0VUIC9oZWFsdGggSFRUUC8xLjENCkhvc3Q6IHB1YmxpYy5pbnZhbGlkDQoNCg=="}], "opts": {}}, {"group": "origin", "name": "nonloopback-cross-origin", "raws": [{"b64": "R0VUIC9oZWFsdGggSFRUUC8xLjENCkhvc3Q6IHB1YmxpYy5pbnZhbGlkDQpPcmlnaW46IGh0dHA6Ly9ldmlsLmludmFsaWQNCg0K"}], "opts": {}}, {"group": "origin", "name": "nonloopback-same-origin", "raws": [{"b64": "R0VUIC9oZWFsdGggSFRUUC8xLjENCkhvc3Q6IHB1YmxpYy5pbnZhbGlkDQpPcmlnaW46IGh0dHA6Ly9wdWJsaWMuaW52YWxpZA0KDQo="}], "opts": {}}], "then": [{"kind": "terminate"}]}, {"kind": "serve", "args": ["--api-key", "sk-cli"], "env": {}, "cases": [{"group": "origin", "name": "key-does-not-bypass-host", "raws": [{"b64": "R0VUIC9oZWFsdGggSFRUUC8xLjENCkhvc3Q6IHJlYmluZC5pbnZhbGlkDQp4LWFwaS1rZXk6IHNrLWNsaQ0KDQo="}], "opts": {}}, {"group": "origin", "name": "key-does-not-bypass-origin", "raws": [{"b64": "R0VUIC9oZWFsdGggSFRUUC8xLjENCkhvc3Q6IGxvY2FsaG9zdA0KT3JpZ2luOiBodHRwOi8vZXZpbC5pbnZhbGlkDQp4LWFwaS1rZXk6IHNrLWNsaQ0KDQo="}], "opts": {}}], "then": [{"kind": "terminate"}]}, {"kind": "serve", "args": ["--api-key", "sk-cli", "--api-key-file", "@KEYFILE@"], "env": {"TENSORFOLD_API_KEY": "sk-env"}, "key_file": "# keys\nclient: sk-file\nsk-bare\n", "cases": [{"group": "keys", "name": "full-get-response", "raws": [{"b64": "R0VUIC92MS9yZXNwb25zZXMvcmVzcF9taXNzaW5nIEhUVFAvMS4xDQpIb3N0OiBsb2NhbGhvc3QNCkF1dGhvcml6YXRpb246IEJlYXJlciBzay1jbGkNCg0K"}], "opts": {}}, {"group": "keys", "name": "full-delete-response", "raws": [{"b64": "REVMRVRFIC92MS9yZXNwb25zZXMvcmVzcF9taXNzaW5nIEhUVFAvMS4xDQpIb3N0OiBsb2NhbGhvc3QNCngtYXBpLWtleTogc2stZmlsZQ0KDQo="}], "opts": {}}, {"group": "keys", "name": "full-response-stored", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBsb2NhbGhvc3QNCkF1dGhvcml6YXRpb246IEJlYXJlciBzay1iYXJlDQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiA1Mw0KDQp7ImlucHV0IjogIkhpIEBzY3JpcHQ9cGxhaW4iLCAibWF4X291dHB1dF90b2tlbnMiOiAyfQ=="}], "opts": {}}, {"group": "keys", "name": "full-response-parent", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBsb2NhbGhvc3QNCngtYXBpLWtleTogc2stZW52DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiA1NQ0KDQp7ImlucHV0IjogIkhpIiwgInByZXZpb3VzX3Jlc3BvbnNlX2lkIjogInJlc3BfbWlzc2luZyJ9"}], "opts": {}}, {"group": "keys", "name": "full-alias-completions", "raws": [{"b64": "UE9TVCAvYWx0L2NvbXBsZXRpb25zIEhUVFAvMS4xDQpIb3N0OiBsb2NhbGhvc3QNCngtYXBpLWtleTogc2stZmlsZQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogNDYNCg0KeyJwcm9tcHQiOiAieCBAc2NyaXB0PXBsYWluIiwgIm1heF90b2tlbnMiOiAyfQ=="}], "opts": {}}, {"group": "keys", "name": "full-slide-learn", "raws": [{"b64": "UE9TVCAvdjEvc2xpZGUvbGVhcm4gSFRUUC8xLjENCkhvc3Q6IGxvY2FsaG9zdA0KQXV0aG9yaXphdGlvbjogQmVhcmVyIHNrLWNsaQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMg0KDQp7fQ=="}], "opts": {}}, {"group": "keys", "name": "full-slide-graph", "raws": [{"b64": "REVMRVRFIC92MS9zbGlkZS9ncmFwaCBIVFRQLzEuMQ0KSG9zdDogbG9jYWxob3N0DQp4LWFwaS1rZXk6IHNrLWVudg0KDQo="}], "opts": {}}, {"group": "keys", "name": "full-recall", "raws": [{"b64": "R0VUIC92MS9yZWNhbGwgSFRUUC8xLjENCkhvc3Q6IGxvY2FsaG9zdA0KeC1hcGkta2V5OiBzay1maWxlDQoNCg=="}], "opts": {}}, {"group": "keys", "name": "full-imprint-load", "raws": [{"b64": "UE9TVCAvdjEvaW1wcmludC9sb2FkIEhUVFAvMS4xDQpIb3N0OiBsb2NhbGhvc3QNCkF1dGhvcml6YXRpb246IEJlYXJlciBzay1iYXJlDQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAyDQoNCnt9"}], "opts": {}}, {"group": "keys", "name": "full-stats", "raws": [{"b64": "R0VUIC9zdGF0cyBIVFRQLzEuMQ0KSG9zdDogbG9jYWxob3N0DQpBdXRob3JpemF0aW9uOiBCZWFyZXIgc2stY2xpDQoNCg=="}], "opts": {}}, {"group": "keys", "name": "full-head", "raws": [{"b64": "SEVBRCAvdjEvbW9kZWxzIEhUVFAvMS4xDQpIb3N0OiBsb2NhbGhvc3QNCngtYXBpLWtleTogc2stZmlsZQ0KDQo="}], "opts": {}}, {"group": "keys", "name": "full-put", "raws": [{"b64": "UFVUIC92MS9tb2RlbHMgSFRUUC8xLjENCkhvc3Q6IGxvY2FsaG9zdA0KeC1hcGkta2V5OiBzay1lbnYNCg0K"}], "opts": {}}, {"group": "keys", "name": "full-future", "raws": [{"b64": "R0VUIC9mdXR1cmUvcHJpdmF0ZSBIVFRQLzEuMQ0KSG9zdDogbG9jYWxob3N0DQpBdXRob3JpemF0aW9uOiBCZWFyZXIgc2stYmFyZQ0KDQo="}], "opts": {}}, {"group": "keys", "name": "full-then-none", "raws": [{"b64": "R0VUIC92MS9tb2RlbHMgSFRUUC8xLjENCkhvc3Q6IGxvY2FsaG9zdA0KeC1hcGkta2V5OiBzay1maWxlDQoNCg=="}, {"b64": "REVMRVRFIC92MS9yZXNwb25zZXMvcmVzcF9taXNzaW5nIEhUVFAvMS4xDQpIb3N0OiBsb2NhbGhvc3QNCg0K"}], "opts": {}}, {"group": "keys", "name": "full-model-id", "raws": [{"b64": "R0VUIC92MS9tb2RlbHMvZmFrZS1hbGlhcyBIVFRQLzEuMQ0KSG9zdDogbG9jYWxob3N0DQpBdXRob3JpemF0aW9uOiBCZWFyZXIgc2stY2xpDQoNCg=="}], "opts": {}}, {"group": "keys", "name": "model-id-none", "raws": [{"b64": "R0VUIC92MS9tb2RlbHMvZmFrZS1tb2RlbCBIVFRQLzEuMQ0KSG9zdDogbG9jYWxob3N0DQoNCg=="}], "opts": {}}], "then": [{"kind": "terminate"}]}, {"kind": "serve", "args": ["--api-key-file", "@KEYFILE@"], "env": {}, "key_file": "app[inference]: sk-app\nmonitor[read]: sk-read\nops: sk-ops\n", "cases": [{"group": "scopes", "name": "read-chat", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogbG9jYWxob3N0DQpBdXRob3JpemF0aW9uOiBCZWFyZXIgc2stcmVhZA0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogODYNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XX0="}], "opts": {}}, {"group": "scopes", "name": "read-messages", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IGxvY2FsaG9zdA0KQXV0aG9yaXphdGlvbjogQmVhcmVyIHNrLXJlYWQNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDgwDQoNCnsibWF4X3Rva2VucyI6IDIsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9cGxhaW4ifV19"}], "opts": {}}, {"group": "scopes", "name": "read-models", "raws": [{"b64": "R0VUIC92MS9tb2RlbHMgSFRUUC8xLjENCkhvc3Q6IGxvY2FsaG9zdA0KQXV0aG9yaXphdGlvbjogQmVhcmVyIHNrLXJlYWQNCg0K"}], "opts": {}}, {"group": "scopes", "name": "read-model-id", "raws": [{"b64": "R0VUIC92MS9tb2RlbHMvZmFrZS1tb2RlbCBIVFRQLzEuMQ0KSG9zdDogbG9jYWxob3N0DQpBdXRob3JpemF0aW9uOiBCZWFyZXIgc2stcmVhZA0KDQo="}], "opts": {}}, {"group": "scopes", "name": "app-model-id", "raws": [{"b64": "R0VUIC9tb2RlbHMvZmFrZS1hbGlhcyBIVFRQLzEuMQ0KSG9zdDogbG9jYWxob3N0DQp4LWFwaS1rZXk6IHNrLWFwcA0KDQo="}], "opts": {}}, {"group": "scopes", "name": "app-model-suffix", "raws": [{"b64": "R0VUIC92MS9tb2RlbHMvZmFrZS1tb2RlbC9tb2RlbHMgSFRUUC8xLjENCkhvc3Q6IGxvY2FsaG9zdA0KeC1hcGkta2V5OiBzay1hcHANCg0K"}], "opts": {}}, {"group": "scopes", "name": "app-metrics", "raws": [{"b64": "R0VUIC9tZXRyaWNzIEhUVFAvMS4xDQpIb3N0OiBsb2NhbGhvc3QNCngtYXBpLWtleTogc2stYXBwDQoNCg=="}], "opts": {}}, {"group": "scopes", "name": "app-chat", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogbG9jYWxob3N0DQp4LWFwaS1rZXk6IHNrLWFwcA0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogODYNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XX0="}], "opts": {}}, {"group": "scopes", "name": "app-alias", "raws": [{"b64": "UE9TVCAvYWx0L2NvbXBsZXRpb25zIEhUVFAvMS4xDQpIb3N0OiBsb2NhbGhvc3QNCngtYXBpLWtleTogc2stYXBwDQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAyOQ0KDQp7InByb21wdCI6ICJ4IEBzY3JpcHQ9cGxhaW4ifQ=="}], "opts": {}}, {"group": "scopes", "name": "app-recall", "raws": [{"b64": "R0VUIC92MS9yZWNhbGwgSFRUUC8xLjENCkhvc3Q6IGxvY2FsaG9zdA0KeC1hcGkta2V5OiBzay1hcHANCg0K"}], "opts": {}}, {"group": "scopes", "name": "app-slide-graph", "raws": [{"b64": "REVMRVRFIC92MS9zbGlkZS9ncmFwaCBIVFRQLzEuMQ0KSG9zdDogbG9jYWxob3N0DQp4LWFwaS1rZXk6IHNrLWFwcA0KDQo="}], "opts": {}}, {"group": "scopes", "name": "app-learn-expect", "raws": [{"b64": "UE9TVCAvdjEvc2xpZGUvbGVhcm4gSFRUUC8xLjENCkhvc3Q6IGxvY2FsaG9zdA0KeC1hcGkta2V5OiBzay1hcHANCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDEzDQpFeHBlY3Q6IDEwMC1jb250aW51ZQ0KDQp7InRleHQiOiAieCJ9"}], "opts": {}}, {"group": "scopes", "name": "app-response-stored", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBsb2NhbGhvc3QNCngtYXBpLWtleTogc2stYXBwDQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAyOQ0KDQp7ImlucHV0IjogIkhpIEBzY3JpcHQ9cGxhaW4ifQ=="}], "opts": {}}, {"group": "scopes", "name": "app-response-parent", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBsb2NhbGhvc3QNCngtYXBpLWtleTogc2stYXBwDQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiA2NQ0KDQp7ImlucHV0IjogIkhpIiwgInN0b3JlIjogZmFsc2UsICJwcmV2aW91c19yZXNwb25zZV9pZCI6ICJyZXNwX3gifQ=="}], "opts": {}}, {"group": "scopes", "name": "app-response-stateless", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBsb2NhbGhvc3QNCngtYXBpLWtleTogc2stYXBwDQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiA2OQ0KDQp7ImlucHV0IjogIkhpIEBzY3JpcHQ9cGxhaW4iLCAic3RvcmUiOiBmYWxzZSwgIm1heF9vdXRwdXRfdG9rZW5zIjogMn0="}], "opts": {}}, {"group": "scopes", "name": "ops-slide-graph", "raws": [{"b64": "REVMRVRFIC92MS9zbGlkZS9ncmFwaCBIVFRQLzEuMQ0KSG9zdDogbG9jYWxob3N0DQp4LWFwaS1rZXk6IHNrLW9wcw0KDQo="}], "opts": {}}], "then": [{"kind": "terminate"}]}, {"kind": "serve", "args": ["--alias", "example-org/fake-model"], "env": {}, "cases": [{"group": "models", "name": "served", "raws": [{"b64": "R0VUIC92MS9tb2RlbHMvZmFrZS1tb2RlbCBIVFRQLzEuMQ0KSG9zdDogbG9jYWxob3N0DQoNCg=="}], "opts": {}}, {"group": "models", "name": "alias", "raws": [{"b64": "R0VUIC92MS9tb2RlbHMvZmFrZS1hbGlhcyBIVFRQLzEuMQ0KSG9zdDogbG9jYWxob3N0DQoNCg=="}], "opts": {}}, {"group": "models", "name": "bare", "raws": [{"b64": "R0VUIC9tb2RlbHMvZmFrZS1tb2RlbCBIVFRQLzEuMQ0KSG9zdDogbG9jYWxob3N0DQoNCg=="}], "opts": {}}, {"group": "models", "name": "slash-raw", "raws": [{"b64": "R0VUIC92MS9tb2RlbHMvZXhhbXBsZS1vcmcvZmFrZS1tb2RlbCBIVFRQLzEuMQ0KSG9zdDogbG9jYWxob3N0DQoNCg=="}], "opts": {}}, {"group": "models", "name": "slash-escaped", "raws": [{"b64": "R0VUIC92MS9tb2RlbHMvZXhhbXBsZS1vcmclMkZmYWtlLW1vZGVsIEhUVFAvMS4xDQpIb3N0OiBsb2NhbGhvc3QNCg0K"}], "opts": {}}, {"group": "models", "name": "slash-escaped-lower", "raws": [{"b64": "R0VUIC9tb2RlbHMvZXhhbXBsZS1vcmclMmZmYWtlLW1vZGVsLz94PTEgSFRUUC8xLjENCkhvc3Q6IGxvY2FsaG9zdA0KDQo="}], "opts": {}}, {"group": "models", "name": "unknown", "raws": [{"b64": "R0VUIC92MS9tb2RlbHMvbWlzc2luZyBIVFRQLzEuMQ0KSG9zdDogbG9jYWxob3N0DQoNCg=="}], "opts": {}}, {"group": "models", "name": "unknown-escaped", "raws": [{"b64": "R0VUIC92MS9tb2RlbHMvZXhhbXBsZS1vcmclMkZtaXNzaW5nIEhUVFAvMS4xDQpIb3N0OiBsb2NhbGhvc3QNCg0K"}], "opts": {}}, {"group": "models", "name": "suffix-lists", "raws": [{"b64": "R0VUIC92MS9tb2RlbHMvZmFrZS1tb2RlbC9tb2RlbHMgSFRUUC8xLjENCkhvc3Q6IGxvY2FsaG9zdA0KDQo="}], "opts": {}}], "then": [{"kind": "terminate"}]}, {"kind": "serve", "args": [], "env": {}, "cases": [{"group": "admission", "name": "off-burst", "raws": [{"b64": "UE9TVCAvdjEvY29tcGxldGlvbnMgSFRUUC8xLjENCkhvc3Q6IGxvY2FsaG9zdA0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogNDYNCg0KeyJwcm9tcHQiOiAieCBAc2NyaXB0PXBsYWluIiwgIm1heF90b2tlbnMiOiAyfQ=="}, {"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogbG9jYWxob3N0DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiA4Ng0KDQp7Im1vZGVsIjogImZha2UtbW9kZWwiLCAibWVzc2FnZXMiOiBbeyJyb2xlIjogInVzZXIiLCAiY29udGVudCI6ICJIaSBAc2NyaXB0PXBsYWluIn1dfQ=="}, {"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IGxvY2FsaG9zdA0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTAzDQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogNCwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XX0="}, {"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBsb2NhbGhvc3QNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDUzDQoNCnsiaW5wdXQiOiAiSGkgQHNjcmlwdD1wbGFpbiIsICJtYXhfb3V0cHV0X3Rva2VucyI6IDJ9"}, {"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogbG9jYWxob3N0DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDINCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInN0cmVhbSI6IHRydWV9"}], "opts": {}}], "then": [{"kind": "terminate"}]}, {"kind": "serve", "args": ["--max-inflight", "0", "--max-inflight-per-key", "0", "--requests-per-second", "0", "--request-burst", "7"], "env": {}, "cases": [{"group": "admission", "name": "zero-burst", "raws": [{"b64": "UE9TVCAvdjEvY29tcGxldGlvbnMgSFRUUC8xLjENCkhvc3Q6IGxvY2FsaG9zdA0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogNDYNCg0KeyJwcm9tcHQiOiAieCBAc2NyaXB0PXBsYWluIiwgIm1heF90b2tlbnMiOiAyfQ=="}, {"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogbG9jYWxob3N0DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiA4Ng0KDQp7Im1vZGVsIjogImZha2UtbW9kZWwiLCAibWVzc2FnZXMiOiBbeyJyb2xlIjogInVzZXIiLCAiY29udGVudCI6ICJIaSBAc2NyaXB0PXBsYWluIn1dfQ=="}, {"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IGxvY2FsaG9zdA0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTAzDQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogNCwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XX0="}, {"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBsb2NhbGhvc3QNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDUzDQoNCnsiaW5wdXQiOiAiSGkgQHNjcmlwdD1wbGFpbiIsICJtYXhfb3V0cHV0X3Rva2VucyI6IDJ9"}, {"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogbG9jYWxob3N0DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDINCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInN0cmVhbSI6IHRydWV9"}], "opts": {}}], "then": [{"kind": "terminate"}]}]} diff --git a/zig/tests/server/security_cases.py b/zig/tests/server/security_cases.py index e4c2dd93477..708662dcc61 100644 --- a/zig/tests/server/security_cases.py +++ b/zig/tests/server/security_cases.py @@ -52,6 +52,8 @@ def full_key_cases(): ("full-put", [raw("PUT", "/v1/models", headers=env)]), ("full-future", [raw("GET", "/future/private", headers=bare)]), ("full-then-none", [raw("GET", "/v1/models", headers=file), raw("DELETE", "/v1/responses/resp_missing")]), + ("full-model-id", [raw("GET", "/v1/models/fake-alias", headers=cli)]), + ("model-id-none", [raw("GET", "/v1/models/fake-model")]), ] return [{"group": "keys", "name": name, "raws": [{"b64": base64.b64encode(r).decode()} for r in raws], "opts": {}} for name, raws in items] @@ -66,6 +68,9 @@ def scope_cases(): ("read-chat", [raw("POST", "/v1/chat/completions", chat, read)]), ("read-messages", [raw("POST", "/v1/messages", {"max_tokens": 2, "messages": chat["messages"]}, read)]), ("read-models", [raw("GET", "/v1/models", headers=read)]), + ("read-model-id", [raw("GET", "/v1/models/fake-model", headers=read)]), + ("app-model-id", [raw("GET", "/models/fake-alias", headers=app)]), + ("app-model-suffix", [raw("GET", "/v1/models/fake-model/models", headers=app)]), ("app-metrics", [raw("GET", "/metrics", headers=app)]), ("app-chat", [raw("POST", "/v1/chat/completions", chat, app)]), ("app-alias", [raw("POST", "/alt/completions", {"prompt": "x @script=plain"}, app)]), @@ -81,6 +86,23 @@ def scope_cases(): for name, raws in items] +def model_cases(): + """One model's entry by its served name or an alias, raw or percent-escaped; any other id is a 404.""" + items = [ + ("served", "/v1/models/fake-model"), + ("alias", "/v1/models/fake-alias"), + ("bare", "/models/fake-model"), + ("slash-raw", "/v1/models/example-org/fake-model"), + ("slash-escaped", "/v1/models/example-org%2Ffake-model"), + ("slash-escaped-lower", "/models/example-org%2ffake-model/?x=1"), + ("unknown", "/v1/models/missing"), + ("unknown-escaped", "/v1/models/example-org%2Fmissing"), + ("suffix-lists", "/v1/models/fake-model/models"), + ] + return [{"group": "models", "name": name, "raws": [{"b64": base64.b64encode(raw("GET", path)).decode()}], "opts": {}} + for name, path in items] + + def admission_cases(stem): """Model requests on one connection, the stream last: admission off answers as before its flags existed.""" say = [{"role": "user", "content": "Hi @script=plain"}] @@ -130,6 +152,7 @@ def steps(): "key_file": "# keys\nclient: sk-file\nsk-bare\n", "cases": full_key_cases(), "then": [{"kind": "terminate"}]}, {"kind": "serve", "args": ["--api-key-file", "@KEYFILE@"], "env": {}, "key_file": "app[inference]: sk-app\nmonitor[read]: sk-read\nops: sk-ops\n", "cases": scope_cases(), "then": [{"kind": "terminate"}]}, + {"kind": "serve", "args": ["--alias", "example-org/fake-model"], "env": {}, "cases": model_cases(), "then": [{"kind": "terminate"}]}, {"kind": "serve", "args": [], "env": {}, "cases": admission_cases("off"), "then": [{"kind": "terminate"}]}, {"kind": "serve", "args": ["--max-inflight", "0", "--max-inflight-per-key", "0", "--requests-per-second", "0", "--request-burst", "7"], "env": {}, "cases": admission_cases("zero"), "then": [{"kind": "terminate"}]}, diff --git a/zig/tests/xpu/contract_live.zig b/zig/tests/xpu/contract_live.zig index 4d648bc00a3..513edd48a32 100644 --- a/zig/tests/xpu/contract_live.zig +++ b/zig/tests/xpu/contract_live.zig @@ -12,6 +12,7 @@ fn isControl(r: records.Record) bool { fn imageOf(name: []const u8) ?rig_.Image { if (std.mem.eql(u8, name, "glue")) return .glue; + if (std.mem.eql(u8, name, "tp")) return .tp; if (std.mem.eql(u8, name, "contract_controls")) return .controls; return null; } @@ -25,6 +26,15 @@ fn argsOf(symbol: []const u8) u32 { .{ "swiglu", 7 }, .{ "argmax", 3 }, .{ "embed", 6 }, + .{ "tp2_allreduce_f16", 4 }, + .{ "tp4_allreduce_f16", 6 }, + .{ "tp2_rs_f16", 5 }, + .{ "tp4_rs_f16", 7 }, + .{ "tp2_allreduce_bf16", 4 }, + .{ "tp4_allreduce_bf16", 6 }, + .{ "tp2_allreduce_f32", 4 }, + .{ "tp4_allreduce_f32", 6 }, + .{ "tp4_rs_f32", 7 }, }; for (table) |e| if (std.mem.eql(u8, e[0], symbol)) return e[1]; return 1; // gate 5's controls take one output pointer diff --git a/zig/tests/xpu/contract_rig.zig b/zig/tests/xpu/contract_rig.zig index 922fd756539..939daef61b2 100644 --- a/zig/tests/xpu/contract_rig.zig +++ b/zig/tests/xpu/contract_rig.zig @@ -8,23 +8,25 @@ const images = @import("xpu_contract_images"); pub const guard = 256; const pattern = 0xa5; -/// The image a kernel lives in: the Qwen3.8-27B glue, gate 5's controls, or gates 1 to 4's. -pub const Image = enum { glue, controls, gate }; +/// The image a kernel lives in: the Qwen3.8-27B glue, TP collectives, gate 5's controls, or gates 1 to 4's. +pub const Image = enum { glue, tp, controls, gate }; fn blob(i: Image) []const u8 { return switch (i) { .glue => &images.glue, + .tp => &images.tp, .controls => &images.controls, .gate => &images.gate_controls, }; } -/// One card, its context and stream, and the three images loaded native for it. +/// One card, its context and stream, and the contract images loaded native for it. pub const Dev = struct { drv: xpu.Driver, ctx: xpu.Context, s: xpu.Stream, glue: xpu.Module, + tp: xpu.Module, controls: ?xpu.Module, // the driver refuses the whole image when one control asks for more SLM than it has controls_err: ?anyerror = null, gate: xpu.Module, @@ -35,6 +37,7 @@ pub const Dev = struct { self.ctx = try xpu.Context.init(&self.drv, ordinal); self.s = try xpu.Stream.init(&self.ctx); self.glue = try xpu.Module.loadNative(&self.ctx, blob(.glue)); + self.tp = try xpu.Module.loadNative(&self.ctx, blob(.tp)); self.controls = xpu.Module.loadNative(&self.ctx, blob(.controls)) catch |e| blk: { self.controls_err = e; break :blk null; @@ -45,6 +48,7 @@ pub const Dev = struct { pub fn deinit(self: *Dev) void { self.gate.unload(); if (self.controls) |*m| m.unload(); + self.tp.unload(); self.glue.unload(); self.s.deinit(); self.ctx.deinit(); @@ -54,6 +58,7 @@ pub const Dev = struct { pub fn module(self: *Dev, i: Image) !*xpu.Module { return switch (i) { .glue => &self.glue, + .tp => &self.tp, .controls => if (self.controls) |*m| m else error.ControlsNotBuilt, .gate => &self.gate, }; diff --git a/zig/tests/xpu/contract_run.zig b/zig/tests/xpu/contract_run.zig index 28c5d96e8ef..d797a213e44 100644 --- a/zig/tests/xpu/contract_run.zig +++ b/zig/tests/xpu/contract_run.zig @@ -8,6 +8,7 @@ const norm_k = @import("contract_norm.zig"); const swiglu_k = @import("contract_swiglu.zig"); const argmax_k = @import("contract_argmax.zig"); const embed_k = @import("contract_embed.zig"); +const tp_k = @import("contract_tp.zig"); const controls_k = @import("contract_controls.zig"); const g = core.gates; @@ -51,6 +52,10 @@ pub fn main(init: std.process.Init) !u8 { var embed = try embed_k.Embed.init(a, &dev); defer embed.deinit(); try kernels.append(a, embed.kernel()); + var tps: [std.enums.values(tp_k.Which).len]tp_k.Tp = undefined; + for (&tps, std.enums.values(tp_k.Which)) |*x, w| x.* = try tp_k.Tp.init(a, &dev, w); + defer for (&tps) |*x| x.deinit(); + for (&tps) |*x| try kernels.append(a, x.kernel()); var controls: [std.enums.values(controls_k.Which).len]controls_k.Control = undefined; for (&controls, std.enums.values(controls_k.Which)) |*x, w| x.* = try controls_k.Control.init(a, &dev, w); defer for (&controls) |*x| x.deinit(); diff --git a/zig/tests/xpu/contract_tp.zig b/zig/tests/xpu/contract_tp.zig new file mode 100644 index 00000000000..cbf9f44f18d --- /dev/null +++ b/zig/tests/xpu/contract_tp.zig @@ -0,0 +1,215 @@ +//! Level Zero TP={2,4} collective kernels in tp.cl under the XPU kernel contract (gates 1 to 4). +const std = @import("std"); +const xpu = @import("xpu"); +const core = @import("core"); +const rig_ = @import("contract_rig.zig"); +const kit = @import("contract_kit.zig"); + +const c = core.spec; +const g = core.gates; +const rows = core.rows; + +/// All nine P2P collective kernels in zig/kernels/xpu/tp.cl. +pub const Which = enum { ar2_f16, ar4_f16, rs2_f16, rs4_f16, ar2_bf16, ar4_bf16, ar2_f32, ar4_f32, rs4_f32 }; + +const why_k2_f16 = "two fp16 inputs sum once directly to fp16 without an intermediate narrowing loss"; +const why_k2_bf16 = "two bf16 inputs sum once directly to bf16, while fp16 sums overflow at 65536"; + +fn symbol(w: Which) []const u8 { + return switch (w) { + .ar2_f16 => "tp2_allreduce_f16", + .ar4_f16 => "tp4_allreduce_f16", + .rs2_f16 => "tp2_rs_f16", + .rs4_f16 => "tp4_rs_f16", + .ar2_bf16 => "tp2_allreduce_bf16", + .ar4_bf16 => "tp4_allreduce_bf16", + .ar2_f32 => "tp2_allreduce_f32", + .ar4_f32 => "tp4_allreduce_f32", + .rs4_f32 => "tp4_rs_f32", + }; +} + +fn ranksOf(w: Which) usize { + return switch (w) { + .ar2_f16, .rs2_f16, .ar2_bf16, .ar2_f32 => 2, + else => 4, + }; +} + +fn kindOf(w: Which) kit.Kind { + return switch (w) { + .ar2_f16, .ar4_f16, .rs2_f16, .rs4_f16 => .f16, + .ar2_bf16, .ar4_bf16 => .bf16, + .ar2_f32, .ar4_f32, .rs4_f32 => .f32, + }; +} + +fn isRs(w: Which) bool { + return w == .rs2_f16 or w == .rs4_f16 or w == .rs4_f32; +} + +fn depth2(_: c.Shape) usize { + return 1; +} + +fn depth4(_: c.Shape) usize { + return 3; +} + +const served2 = [_]c.Shape{ + .{ .rows = 1, .n = 4, .k = 2 }, + .{ .rows = 1, .n = 1024, .k = 2 }, + .{ .rows = 1, .n = 4096, .k = 2 }, +}; + +const served4 = [_]c.Shape{ + .{ .rows = 1, .n = 4, .k = 4 }, + .{ .rows = 1, .n = 1024, .k = 4 }, + .{ .rows = 1, .n = 4096, .k = 4 }, +}; + +pub fn spec(w: Which) c.Spec { + const tp = ranksOf(w); + const kind = kindOf(w); + const sums: c.Sums = switch (w) { + .ar2_f16, .rs2_f16 => .{ .f16 = 0, .bf16 = 0, .why = why_k2_f16 }, + .ar2_bf16 => .{ .bf16 = 0, .why = why_k2_bf16 }, + else => .{}, + }; + return .{ + .name = symbol(w), + .accum = .f32, + .depth = if (tp == 2) depth2 else depth4, + .out = kit.elem(kind), + .tiles = .{ .{}, .{ .size = 1024, .step = 4, .min = 4 }, .{} }, + .served = if (tp == 2) &served2 else &served4, + .sums = sums, + }; +} + +/// Device buffers and host reference inputs for one tp.cl collective kernel. +pub const Tp = struct { + rig: rig_.Rig, + k: xpu.Kernel, + which: Which, + arena: std.heap.ArenaAllocator, + shape: c.Shape = undefined, + inputs: [4][]f64 = .{ &.{}, &.{}, &.{}, &.{} }, + devs: [4]?*anyopaque = .{ null, null, null, null }, + out: ?*anyopaque = null, + slice_off: usize = 0, + + pub fn init(a: std.mem.Allocator, dev: *rig_.Dev, which: Which) !Tp { + return .{ .rig = .{ .a = a, .dev = dev }, .k = try dev.kernelFor(.tp, symbol(which), a), .which = which, .arena = .init(a) }; + } + + pub fn deinit(self: *Tp) void { + self.k.deinit(); + self.arena.deinit(); + self.rig.deinit(); + } + + pub fn kernel(self: *Tp) g.Kernel { + return .{ .spec = spec(self.which), .ctx = self, .vt = &vt }; + } + + const vt = g.hooks(Tp); + + fn stressVals(w: Which) [4]f64 { + return switch (w) { + .ar2_f16, .rs2_f16 => .{ 4096, 16, 0, 0 }, + .ar2_bf16 => .{ 65536, 512, 0, 0 }, + .ar2_f32 => .{ 1048576, 4096, 0, 0 }, + .ar4_f16, .rs4_f16 => .{ 40000, 40000, -40000, -39936 }, + .ar4_bf16 => .{ 131072, 256, -131072, 0 }, + .ar4_f32, .rs4_f32 => .{ 1048576, 4096, -1048576, 0 }, + }; + } + + pub fn prepare(self: *Tp, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + const tp = ranksOf(self.which); + if (shape.rows == 0 or shape.n == 0 or shape.n % 4 != 0 or shape.k != tp) return false; + self.rig.reset(); + _ = self.arena.reset(.retain_capacity); + self.shape = shape; + const a = self.arena.allocator(); + const kind = kindOf(self.which); + const total = shape.rows * shape.n; + const full_n = if (isRs(self.which)) tp * total else total; + self.slice_off = if (isRs(self.which)) total else 0; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + for (0..tp) |r| { + self.inputs[r] = try a.alloc(f64, full_n); + if (fill == .stress) { + const sv = stressVals(self.which)[r]; + for (self.inputs[r]) |*v| v.* = kit.round(kind, sv); + } else { + for (self.inputs[r]) |*v| v.* = kit.round(kind, -4 + rng.float(f64) * 8); + } + } + if (fill == .nonfinite) { + const off = self.slice_off; + self.inputs[0][off] = std.math.nan(f64); + if (shape.rows > 1) self.inputs[1 % tp][off + shape.n] = std.math.inf(f64); + if (shape.rows > 2) self.inputs[0][off + 2 * shape.n] = -std.math.inf(f64); + if (shape.rows > 3) { + self.inputs[1 % tp][off + 3 * shape.n] = std.math.inf(f64); + self.inputs[0][off + 3 * shape.n] = -std.math.inf(f64); + } + } + for (0..tp) |r| { + const b = try kit.bytes(a, self.inputs[r], kind); + self.devs[r] = try self.rig.input(b); + } + self.out = try self.rig.output(total * kit.size(kind)); + return true; + } + + pub fn run(self: *Tp) !void { + const n4: i32 = @intCast((self.shape.rows * self.shape.n) / 4); + const off4: i32 = @intCast(self.slice_off / 4); + const groups: [3]u32 = .{ @intCast((@as(usize, @intCast(n4)) + 255) / 256), 1, 1 }; + const tp = ranksOf(self.which); + if (isRs(self.which)) { + if (tp == 2) { + try self.rig.launch(self.k, groups, .{ self.devs[0], self.devs[1], self.out, off4, n4 }); + } else { + try self.rig.launch(self.k, groups, .{ self.devs[0], self.devs[1], self.devs[2], self.devs[3], self.out, off4, n4 }); + } + } else if (tp == 2) { + try self.rig.launch(self.k, groups, .{ self.devs[0], self.devs[1], self.out, n4 }); + } else { + try self.rig.launch(self.k, groups, .{ self.devs[0], self.devs[1], self.devs[2], self.devs[3], self.out, n4 }); + } + } + + pub fn count(self: *Tp) usize { + return self.shape.rows * self.shape.n; + } + + pub fn reference(self: *Tp, want: []f64, mag: []f64) !void { + const tp = ranksOf(self.which); + const kind = kindOf(self.which); + for (0..self.count()) |i| { + var s: f64 = 0; + var abs: f64 = 0; + for (0..tp) |r| { + const v = self.inputs[r][self.slice_off + i]; + s += v; + abs += @abs(v); + } + want[i] = kit.round(kind, s); + mag[i] = abs; + } + } + + pub fn simulate(self: *Tp, acc: c.Accum, order: g.Order, out: []f64) !void { + const tp = ranksOf(self.which); + var terms: [4]f64 = undefined; + for (0..self.count()) |i| { + for (0..tp) |r| terms[r] = self.inputs[r][self.slice_off + i]; + out[i] = rows.sumIn(acc, order, terms[0..tp]); + } + } +};