diff --git a/CHANGELOG.md b/CHANGELOG.md index 92b9624b2a8..f6dd40cb87d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,9 +4,66 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- Server: a grammar over 512 KiB is refused with HTTP 400 before it is compiled, so one oversized schema can no longer hold the grammar compiler for a minute (#3038). + +- Qwen3.8-27B on XPU: the target's and the DFlash2 drafter's RoPE tables come from core's exact helper, so they hold the reference's fp32 words; 15 of 32 and 18 of 64 values move by 1 ulp (#2000, part of #1852). + +- Tests: `zig build test-lane-explore-host` explores the lane host's schedules from a seed (arrivals, cancels at every stage, the backend's room for live lanes and memory pressure) around a fake target, so ordering bugs show up without hand-picked orders (#3233). + +- Qwen3.5 on CUDA: `qwen3_5` and `qwen3_5_moe` declare warm turns, so the server prefills a follow-up's prompt in the background and the next turn resumes past the previous reply, with replies unchanged (#2824). Thanks to @devopsfortunato. + +- Server: tool-call markup quoted in Markdown inline code spans and fenced code blocks stays prose, in whole replies and in streaming, instead of opening, hiding or running as a live tool call (#3588). Thanks to @gilby. + +- Lanes: shared draft pricing prices a chain-cut, unmeasured tail by the rule's rates instead of as a measured zero, and the cache's cut marker survives allocation errors (#2979). Thanks to @devopsfortunato. + +- Docs: the Nemotron 3.5 Lightning recipe gains a "Native HIP on a Strix Halo iGPU" section with its configuration, memory footprint, throughput, prefill and exactness checks, and the intro lists HIP beside Metal and CUDA (#3560). Thanks to @gilby. + +- Qwen3.5-2B on Metal: the engine declares `warm_turns` from its prompt cache, so a follow-up that re-renders earlier rows resumes the reply instead of prefilling the whole conversation again (#3662, from #3457). Thanks to @EugeneClaw. + +- DeepSeek V4.1 on CUDA: a prompt whose prefill segment is 18 to 32 rows no longer replies with repeated begin-of-sentence tokens, because the second streams buffer is now planned for 32 rows; replies at every other length are unchanged (#3366, #3388). Thanks to @sx4im for the fix, @laudney for the sweep test (#3529) and @BadAd84 for the trace and the GB10 pair receipts. + +- App: the built-in agent's `web_search` and `web_fetch` accept `provider: "keenable"`, an opt-in Keenable provider with no account or key; only the query or URL goes to Keenable, and the defaults are unchanged (#3637, from #2752). Thanks to @ilya-bogin-keenable. + +- Nemotron on Metal: row projections over windows of 4 or more rows run 8 rows at a time, then 4, 2 and 1, so each weight code is unpacked once for up to eight rows; every row's sum keeps its order, bit-equal to one row alone (#3129). + +- Flash Next on Metal (M1 through M4): the scale index is now the default for 4-bit experts in groups of 32, and `TF_FLASHNEXT_SCALE_INDEX=0` turns it off. Prompt passes and grouped decode windows read each group's scale and bias through the index too, and the routed experts' stored scales and biases are released once indexed; every kernel gets the same values, so replies keep their tokens. On an M3 Ultra with the MLX 4-bit checkpoint, memory in use once loaded falls from 129.6 to 122.5 GiB, drafted decode on one stream is 2.0% to 4.2% faster (prose 138.6 to 142.0 tok/s, a copy-heavy edit 282.0 to 293.8), four streams are 2.6% faster (203.1 to 208.3 tok/s) and a cold prompt's first token arrives about 1% sooner; load takes about 0.7 s longer (#2805, part of #2751). + + + + + + + + + +- Kolibri-1: the tree-attention cache offsets are signed, so a server with default flags no longer panics with an integer overflow on its first request when a cache sits below the origin (#3561). Thanks to @jschmied. + +- H3 on Metal: `Model.load` reads every transformer shard ahead of its mappings and fails the load on a missing or short shard; `TF_LOAD_PREFETCH` sets the reader count and `0` turns read-ahead off (#2999). Thanks to @plotarmordev. + +- App: an idle task's disabled Planning only control opens the model picker on Local, so a planning provider no longer strands the user; the ordinary model button still opens All (#3357). Thanks to @garvrao80. + +- Studio: local benchmark receipts with the optional `hardware.form_factor` field are accepted, kept in saved history and exports, while unknown labels, raw product IDs and extra hardware keys are still rejected (#2693). Thanks to @garvrao80. + +- Templates: the chat template compiler accepts Jinja's `float` filter, `float(value, default=0.0)`, instead of refusing the template, and reads text as ASCII only (#3577). Thanks to @Nipale-ai. + +- Tests: `tf-nemotron-hip-test invariance` checks Nemotron-H within-path bit invariance on HIP (prompt chunk cuts with the single-row first-token head, decode window widths and multi-stream grouping, and served prompt-cache resume against fresh prefill) (#3580, refs #3409). + +- Qwen3.8-Flash-Next on HIP: `tf_fn_idx_scores` exits inactive decode-graph tiles before synchronization and stages each tile's q rows once in LDS before walking the four key-position slots, cutting kernel time from 276.0 ms to 141.5 ms at 8K and 2,873.9 ms to 2,091.4 ms at 32K on gfx1151 with identical tokens (#3601). + +- Tests: the kernel contract checks each qwen27 control's source edit on every chip, for both tensor-unit settings, so a run on a chip without tensor units fails on a stale M5 edit too (#3343, follow-up to #2106). Thanks to @cshintov. + +- GLM-5.3-Flash on Metal: checkpoints whose routed experts are not 4/64 read each expert once a drafted window for every row that picked it, and the shared expert once; replies are unchanged, and on an M5 Ultra an 8-bit build's greedy decode goes from 50.0 to 53.0 tok/s and sampled from 46.5 to 48.8 (#3631). +- GLM-5.3-Flash on Metal: a checkpoint that stores `layers.45.shared_head.head` drafts MTP tokens through it on one Mac while `lm_head` verifies every token, so replies are unchanged (#3632). +- Tests: `tf-glm-run`'s `GLM_PROMPT_NLL` scores every prompt token through GLM-5.3-Flash's prompt path, the gate for prompt kernels that are not bit-identical (#3633). +- Tests: `tf-glm-run`'s `GLM_PROMPT_NLL` scores every prompt token's loss through GLM-5.3-Flash's prompt path, a dev-tool check for comparing builds whose weights differ (#3633). +- Qwen3.8-27B on CUDA: with paged KV and the shared prompt store, streams resumed from one prompt read each shared prefix key tile once a forward instead of once a stream, through join variants of the rows kernels that only such forwards take; on a GB10 at a 32K shared prefix, decode is 57% faster at eight streams and 28% at four with every reply equal to main's, and every other forward runs main's kernels byte for byte (#3653). +- Docs: `docs/openclaw.md` shows how to use TensorFold from OpenClaw through the [openclaw-tensorfold](https://github.com/ashhart/openclaw-tensorfold) plugin: OpenClaw starts `tensorfold serve` on demand through its local model service and stops it when OpenClaw exits or the server sits idle, or connects to a server you run; each model's context window, image input and reasoning efforts come from `/v1/models`. Checked on Metal with Nemotron 3.5 Lightning and Qwen3.8-27B (#3341). + - Docs: the GLM-5.3-Flash CUDA recipe's Verified copy drafts section lists, for one checkpoint at TP=2 with `--parallel 4`, the loads that `TF_GLM_COPIES=1` sped up and the ones it slowed, and says the default stays off (#3335). Thanks to @Bizuayeu. - Tests: the Qwen 3.8 27B Metal residency fixtures compile again on macOS after the DFlash2 target became a value (#3572). - Tests: the kernel contract's Llama `gemm_untransposed` control edits the `TF_GEMM_NAX_KERNEL` instance line again, so its planted fault fails as it should (#3157, thanks @gilby, who found and fixed it first). +- Docs: the GLM-5.3-Flash recipe covers long agent sessions: reasoning the client sends back was about 330K of a 494K-token omp session, the model repeats itself past about 300K, and omp's `replayReasoningContent: false` keeps the prompt to messages and tool results; 1.2.9 and later GLM builds gave byte-identical replies at 458K +- Docs: the GLM-5.3-Flash recipe covers long agent sessions: reasoning the client sends back was about 330K of a 494K-token omp session, the model repeats itself past about 300K, and omp's `replayReasoningContent: false` keeps the prompt to messages and tool results; 1.2.9 and later GLM builds gave byte-identical replies at 458K (#3576) - Docs: the GLM-5.3-Flash recipe records the FP8 latent cache's diagnostics on FP4-Local at TP=2 on two GB10s, with its bytes a token and fixed per-stream state, and says it is not qualified (#3432). Thanks to @laudney. @@ -63,6 +120,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Nemotron on Metal: a new prompt is filled a chunk at a time between other streams' decode rounds, instead of stalling them for its whole prefill. Chunks are cut exactly as before, so replies are unchanged (#3054, part of #3021). - Nemotron Metal keeps the prompt IDs and one queued chunk across consecutive prefill steps. Cancellation publishes the landed prefix before keeping it and credits that work before retirement. +- Flash Next on CUDA: `TF_FLASHNEXT_CHUNK` and `TF_FLASHNEXT_CHUNK_SOLO` are checked by name when the engine loads, so a malformed value names the variable, the supplied text and the accepted range, and a value that is empty or only spaces and tabs now reads as unset like every other setting; valid values and defaults are unchanged (#3308, #3591). + - Ling-3.0-tiny on Metal: the KDA mixer uses Kimi's existing `k3_kda` kernel (full-width gate, D=128, 4 taps) wired to Ling-tiny's 16 heads. Host `mixF64` is checked against a float64 dump of `oracle/kda_inner.py` (a stdlib copy of `ling_forward.py` Model.kda from conv through y, r = identity; that file is not imported and is not edited) on 16 heads x 2 and 4 rows (worst 8.3e-10 and 1.1e-9). The copy equals Model.kda at worst abs 2.8e-14 on those shapes (fake Ckpt, r = identity, `oracle/kda_vs_model.py`). `k3_kda` versus the dump is 0.0102 at 2 rows and 0.0119 at 4 rows, gated at 2 x (2^-7 of the largest |y|); true bf16 steps at those magnitudes are about 1.3 and 1.5 (values in [1, 2) share one step of 2^-7). `k3_kda` versus the f32 mixer is 0.001953 at 2 and 4 rows (gated under 0.01). `mix`/`mixF64` return `error.KdaWidthTooWide` when W > 2048 (ReleaseFast-safe; the stack conv window is 3 x 2048). Fixture inputs regenerate byte-identical; committed y matches a regenerate to within one float64 ulp, so they are numerically reproducible, not hash-reproducible. Every check uses r = identity and a fake Ckpt. No new kernel (for #1247). - Ling-3.0-tiny: a host KDA reference, and a Metal check that Kimi's `k3_kda` matches it at Ling-tiny's shape; nothing is served yet (part of #1247). - GLM-5.3-Flash on CUDA loads NVFP4_NZ5 checkpoints, whose block-32 routed experts read E2M1's code 0b1000 as +5; every other recipe and mix is refused by name, and E2M1 checkpoints load exactly as before (#2894). Thanks to @Bizuayeu. diff --git a/app/README.md b/app/README.md index 50e1603736e..2228ee9dd39 100644 --- a/app/README.md +++ b/app/README.md @@ -70,6 +70,15 @@ an opaque conversation ID across search, fetch and follow-up turns; a new chat g after 20 seconds and stop when the owning run is cancelled. Fetches return excerpts rather than a complete page; `max_chars` still caps the displayed text. +### Optional Keenable web research + +Ask the built-in agent to “Use Keenable to search the web” or “Use Keenable to read this URL.” +The `web_search` and `web_fetch` tools accept `provider: "keenable"` for the +[Keenable API](https://docs.keenable.ai/api-reference): general web results with page text, +and pages as Markdown, with no account or API key. Anonymous use has service rate limits. +Queries and requested URLs, with the app name `TensorFold`, go to Keenable when this provider is selected. +The same defaults, permissions, local-only restrictions, 20-second timeout and cancellation apply as above. + ### Browser demo mode Open `http://localhost:5173` in a browser (no Electron) and TensorFold runs in **demo mode** with diff --git a/app/electron/agent/engine/benchmark/controller.test.ts b/app/electron/agent/engine/benchmark/controller.test.ts index bbefdde0118..33d1fac03ba 100644 --- a/app/electron/agent/engine/benchmark/controller.test.ts +++ b/app/electron/agent/engine/benchmark/controller.test.ts @@ -4,9 +4,10 @@ import { syntheticBenchmarkReceipt } from './fixtures' import type { SavedModelBenchmark } from './storage' import type { BenchmarkProcessResult } from './process' import { BENCHMARK_ENGINE_VERSION } from './version' +import { parseBenchmarkReceipt, type BenchmarkFormFactor } from './receipt' const input = { id: 'benchmark_synthetic_0001', model: 'example-org/synthetic-model' } -function fixture() { +function fixture(formFactor?: BenchmarkFormFactor | null) { let records: SavedModelBenchmark[] = [] let valid = true; let missing = false; let saveFails = false; let listFails = false; let restoreFails = false let pauses = 0; let restores = 0; let releases = 0; let processes = 0; let cleanups = 0 @@ -18,7 +19,12 @@ function fixture() { reserve: async () => ({ previousModel: 'example-org/prior-model', pause: async () => { pauses++ }, restore: async () => { restores++; if (restoreFails) throw new Error('/private/operator/restore') }, release: () => { releases++ } }), workspace: async () => ({ directory: '/private/synthetic-workspace', receiptPath: '/private/synthetic-workspace/receipt.json', remove: async () => { cleanups++ } }), process: () => { processes++; return { done: new Promise(resolve => { finish = resolve }), cancel: () => finish({ code: 130, cancelled: true, overflow: false, failed: false }) } }, - readReceipt: async () => missing ? null : syntheticBenchmarkReceipt(input.model), + readReceipt: async () => { + if (missing) return null + const receipt = syntheticBenchmarkReceipt(input.model) + if (formFactor !== undefined) Object.assign(receipt.hardware, { form_factor: formFactor }) + return receipt + }, store, } const controller = new ModelBenchmarks(deps) @@ -29,6 +35,15 @@ async function running(f: ReturnType) { throw new Error('Synthetic benchmark did not reach running') } const normal = fixture() +for (const family of [null, 'Mac mini', 'Mac Studio', 'MacBook Pro', 'MacBook Air', 'iMac', 'Mac Pro'] as const) { + const f = fixture(family) + await f.controller.start(input); await running(f); f.finish(); await f.controller.settle() + assert.equal((await f.controller.snapshot())?.state, 'complete', 'A known Mac family cannot break a finished local benchmark') + assert.equal(Reflect.get((await f.controller.snapshot())!.metadata!.hardware, 'form_factor'), family) + assert.equal(parseBenchmarkReceipt(JSON.stringify(await f.controller.receiptForExport(input.id))).hardware.form_factor, family) + const reopened = new ModelBenchmarks(f.deps) + assert.equal(parseBenchmarkReceipt(JSON.stringify(await reopened.receiptForExport(input.id))).hardware.form_factor, family, 'Saved controller history retains validated product families') +} const first = await normal.controller.start(input) assert.equal(first.state, 'preparing') await assert.rejects(normal.controller.start({ ...input, id: 'benchmark_synthetic_0002' }), /current local benchmark/) diff --git a/app/electron/agent/engine/benchmark/receipt.test.ts b/app/electron/agent/engine/benchmark/receipt.test.ts index 1e4a545d3a9..4b16b0fde03 100644 --- a/app/electron/agent/engine/benchmark/receipt.test.ts +++ b/app/electron/agent/engine/benchmark/receipt.test.ts @@ -54,3 +54,26 @@ assert.equal(benchmarkCells(parseBenchmarkReceipt(JSON.stringify(buffered)))[0]. const unknown = structuredClone(receipt); unknown.hardware.gpus = []; unknown.hardware.gpu_count = null; unknown.hardware.source = 'unavailable' assert.equal(benchmarkProtocolComplete(parseBenchmarkReceipt(JSON.stringify(unknown))), false) console.log('Benchmark strict receipt, privacy, exact samples, complete-only aggregates, earlyEOS, warmup errors and unknown metrics passed') + +for (const family of [null, 'Mac mini', 'Mac Studio', 'MacBook Pro', 'MacBook Air', 'iMac', 'Mac Pro'] as const) { + const withFamily = structuredClone(receipt) + Object.assign(withFamily.hardware, { form_factor: family }) + const result = parseBenchmarkReceipt(JSON.stringify(withFamily), { model: receipt.model.repo_id, serial: false }) + assert.equal(result.hardware.form_factor, family) + assert.deepEqual(result, withFamily, 'The app preserves the accepted metadata for storage and export') + assert.deepEqual(benchmarkCells(result), benchmarkCells(parsed), 'A product family cannot alter measured benchmark cells') + assert.equal(benchmarkProtocolComplete(result), true) +} +assert.equal(Object.hasOwn(parsed.hardware, 'form_factor'), false, 'Old receipts keep the field absent') +for (const family of ['', 'Mac17,16', 'mac mini', 'Mac mini M5 Pro', 'Mac mini\n', true, 7, [], {}, ['Mac mini']]) { + const invalid = structuredClone(receipt) as any + invalid.hardware.form_factor = family + assert.throws(() => parseBenchmarkReceipt(JSON.stringify(invalid)), /invalid|unsupported/) +} +for (const formFactor of [undefined, null, 'Mac mini']) { + const invalid = structuredClone(receipt) as any + if (formFactor !== undefined) invalid.hardware.form_factor = formFactor + invalid.hardware.model_identifier = 'Mac17,16' + assert.throws(() => parseBenchmarkReceipt(JSON.stringify(invalid)), /invalid|unsupported/, 'The optional key cannot admit unrelated hardware fields') +} +console.log('Studio accepts absent, null and six coarse product families, preserves metadata and rejects raw IDs, extra keys and invalid values.') diff --git a/app/electron/agent/engine/benchmark/receipt.ts b/app/electron/agent/engine/benchmark/receipt.ts index fdaa19fc498..9514ac60557 100644 --- a/app/electron/agent/engine/benchmark/receipt.ts +++ b/app/electron/agent/engine/benchmark/receipt.ts @@ -5,6 +5,8 @@ import { supportedBenchmarkReceiptVersion } from './version' export const BENCHMARK_SUITE_SHA = '9bb717da00666b90b4006174abd9ed46108affc37456b43c64a224a9c938d5be' export const BENCHMARK_RECEIPT_MAX_BYTES = 1024 * 1024 +export type BenchmarkFormFactor = 'Mac mini' | 'Mac Studio' | 'MacBook Pro' | 'MacBook Air' | 'iMac' | 'Mac Pro' +export type ParsedBenchmarkReceipt = ModelBenchmarkReceipt & { hardware: ModelBenchmarkReceipt['hardware'] & { form_factor?: BenchmarkFormFactor | null } } const SAMPLE_KEYS = ['fixture_id', 'temperature', 'repeat', 'seed', 'status', 'prompt_tokens', 'completion_tokens', 'cached_tokens', 'delivery_seconds', 'delivery_tps', 'ttft_seconds', 'end_to_end_seconds', 'server_decode_tps', 'server_decode_seconds', 'prefill_seconds', 'token_sha', 'error_code'] const ERROR_CODES = new Set(['http_error', 'connection_error', 'timeout', 'cancelled', 'server_error', 'invalid_stream', 'truncated_stream', 'missing_usage', 'invalid_usage', 'empty_output', 'unexpected_finish', 'token_count_mismatch', 'unmeasured_delivery']) function invalid(): never { throw new Error('The local benchmark receipt is invalid or contains unsupported fields.') } @@ -20,7 +22,7 @@ function number(value: unknown, nullable = true, integer = false, max = 1e15): v if (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > max || integer && !Number.isSafeInteger(value)) invalid() } function digest(value: unknown, sizes = [64]): void { if (value !== null && (typeof value !== 'string' || !sizes.includes(value.length) || !/^[a-f0-9]+$/.test(value))) invalid() } -export function parseBenchmarkReceipt(raw: string, expected?: { model: string; serial: boolean; engineVersion?: string }, now = Date.now()): ModelBenchmarkReceipt { +export function parseBenchmarkReceipt(raw: string, expected?: { model: string; serial: boolean; engineVersion?: string }, now = Date.now()): ParsedBenchmarkReceipt { if (Buffer.byteLength(raw) > BENCHMARK_RECEIPT_MAX_BYTES) invalid() let value: any try { value = strictBenchmarkJson(raw) } catch { invalid() } @@ -41,7 +43,9 @@ export function parseBenchmarkReceipt(raw: string, expected?: { model: string; s digest(model.revision, [40, 64]); digest(model.config_sha256); digest(model.tokenizer_sha256) text(model.family, true); text(model.quantization, true) const hardware = value.hardware - object(hardware, ['cpu_model', 'system_memory_bytes', 'memory_type', 'gpus', 'gpu_count', 'source']) + const hasFormFactor = hardware != null && Object.hasOwn(hardware, 'form_factor') + object(hardware, ['cpu_model', 'system_memory_bytes', 'memory_type', 'gpus', 'gpu_count', 'source', ...(hasFormFactor ? ['form_factor'] : [])]) + if (hasFormFactor && hardware.form_factor !== null && !['Mac mini', 'Mac Studio', 'MacBook Pro', 'MacBook Air', 'iMac', 'Mac Pro'].includes(hardware.form_factor)) invalid() text(hardware.cpu_model, true); number(hardware.system_memory_bytes, true, true); number(hardware.gpu_count, true, true, 256) if (!['unified', 'dedicated', 'unknown'].includes(hardware.memory_type) || !['detected', 'partial', 'unavailable'].includes(hardware.source) || !Array.isArray(hardware.gpus) || hardware.gpus.length > 256) invalid() for (const gpu of hardware.gpus) { object(gpu, ['name', 'memory_bytes', 'cores']); text(gpu.name); number(gpu.memory_bytes, true, true); number(gpu.cores, true, true, 100_000) } @@ -70,7 +74,7 @@ export function parseBenchmarkReceipt(raw: string, expected?: { model: string; s if (sample.status === 'ok' && (sample.completion_tokens !== 256 || sample.delivery_tps === null || sample.error_code !== null)) invalid() if (sample.status === 'early_eos' && (sample.completion_tokens === null || sample.completion_tokens >= 256)) invalid() } - return value as ModelBenchmarkReceipt + return value as ParsedBenchmarkReceipt } function spread(values: (number | null)[], complete: boolean): ModelBenchmarkSpread | null { if (!complete || values.some(value => value === null)) return null diff --git a/app/electron/agent/tool-keenable-search.test.ts b/app/electron/agent/tool-keenable-search.test.ts new file mode 100644 index 00000000000..56fcebe6618 --- /dev/null +++ b/app/electron/agent/tool-keenable-search.test.ts @@ -0,0 +1,177 @@ +import assert from 'node:assert/strict' +import { randomUUID } from 'node:crypto' +import { readFile } from 'node:fs/promises' +import { createServer } from 'node:http' +import { mock } from 'node:test' +import ts from 'typescript' +import { executeTool, TOOL_SCHEMAS } from './tools' +import { runAgent } from './loop' +import { installDnsFixture } from './test-fixtures/dns' +import type { Thread } from './types' + +const searchEndpoint = 'https://api.keenable.ai/v1/search/public' +const fetchEndpoint = 'https://api.keenable.ai/v1/fetch/public' +const publicPage = 'https://93.184.216.34/article' +const originalFetch = globalThis.fetch +const requests: Array<{ url: URL; method: string; body: any; headers: Headers }> = [] +let fault = '' + +// Execute the production creation handler with inert persistence and renderer collaborators. +const source = await readFile(new URL('../main/host/ipc/workspace-ipc.ts', import.meta.url), 'utf8') +const tree = ts.createSourceFile('workspace-ipc.ts', source, ts.ScriptTarget.ES2022, true) +let createExpression: ts.Node | undefined +function visit(node: ts.Node): void { + if (ts.isCallExpression(node) && node.expression.getText(tree) === 'handle' && node.arguments[0]?.getText(tree) === "'threads:create'") createExpression = node.arguments[1] + ts.forEachChild(node, visit) +} +visit(tree) +assert.ok(createExpression) +const handler = ts.createPrinter().printNode(ts.EmitHint.Expression, createExpression, tree) +const compiled = ts.transpileModule(`const create = ${handler};`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText +const store: any = { threads: [], projects: [], settings: { providers: [], activeProviderId: null, activeModel: null } } +const create = new Function('store', 'randomUUID', 'requireSecurityRole', 'spine', 'persistThreads', 'remoteServer', `${compiled}\nreturn create;`)(store, randomUUID, () => {}, () => ({ executeCommand() {} }), () => {}, { publish() {} }) +const newChat = (): Promise => create(null, { cwd: '', kind: 'chat' }) + +const json = (value: unknown): Response => new Response(JSON.stringify(value), { headers: { 'Content-Type': 'application/json' } }) + +globalThis.fetch = async (input, init) => { + if (String(input).startsWith('https://news.google.com/rss/search?')) return new Response('Default news sourcehttps://example.org/news') + if (String(input) === publicPage) return new Response('Direct page

Direct page text.

', { headers: { 'Content-Type': 'text/html' } }) + const url = new URL(String(input)) + if (`${url.origin}${url.pathname}` !== searchEndpoint && `${url.origin}${url.pathname}` !== fetchEndpoint) return originalFetch(input, init) + const headers = new Headers(init?.headers) + const method = init?.method ?? 'GET' + requests.push({ url, method, body: init?.body ? JSON.parse(String(init.body)) : null, headers }) + assert.equal(init?.redirect, 'error') + assert.equal(headers.get('Authorization'), null) + assert.equal(headers.get('X-API-Key'), null) + assert.equal(headers.get('X-Keenable-Title'), 'TensorFold') + assert.equal(headers.get('User-Agent'), 'TensorFold/1.0 (+https://github.com/ashhart/TensorFold)') + if (fault === 'stall') return new Promise((_resolve, reject) => { + init!.signal!.addEventListener('abort', () => reject(init!.signal!.reason), { once: true }) + }) + if (fault === 'http') return new Response('{"error":"rate limited"}', { status: 429 }) + if (fault === 'invalid') return new Response('invalid JSON', { headers: { 'Content-Type': 'application/json' } }) + if (fault === 'size') return new Response('x'.repeat(1024 * 1024 + 1)) + if (url.pathname.endsWith('/fetch/public')) { + assert.equal(method, 'GET') + if (fault === 'empty') return json({ url: url.searchParams.get('url'), title: '', content: '', description: '' }) + return json({ url: url.searchParams.get('url'), title: 'Fetched article', content: '# Fetched article\n\nThe page as Markdown.', description: '' }) + } + assert.equal(method, 'POST') + assert.equal(headers.get('Content-Type'), 'application/json') + if (fault === 'shape') return json({ results: 'invalid' }) + const results = [ + { title: 'Example source', url: publicPage, description: '', snippet: `Useful public text.\n${'y'.repeat(5000)}`, acquired_at: '2026-11-01T00:00:00Z' }, + { title: 'Another source', url: 'https://example.org/', description: '', snippet: 'Second page text.', acquired_at: '2026-11-01T00:00:00Z' }, + ] + if (fault === 'private-result') results[0].url = 'http://127.0.0.1/secret' + return json({ query: requests.at(-1)!.body.query, results: fault === 'empty' ? [] : results }) +} + +const search = (thread: Thread, extra: Record = {}, context: any = {}) => executeTool('web_search', { query: 'public research question', provider: 'keenable', ...extra }, { cwd: '', currentThread: thread, ...context }) +const restoreDns = installDnsFixture({ 'news.google.com': '8.8.8.8' }) +try { + process.env.KEENABLE_API_KEY = 'synthetic-ignored-key' + for (const name of ['web_search', 'web_fetch']) { + const schema: any = TOOL_SCHEMAS.find((schema) => schema.function?.name === name) + assert.ok(schema.function.parameters.properties.provider.enum.includes('keenable'), 'the maintained tool schema exposes Keenable') + } + const a = await newChat() + for (const provider of [undefined, 'google_news']) { + const news = await executeTool('web_search', { query: 'news', provider }, { cwd: '', currentThread: a }) + assert.equal(news.ok, true, news.output) + assert.match(news.output, /Default news source/) + } + for (const provider of [undefined, 'direct']) { + const page = await executeTool('web_fetch', { url: publicPage, provider }, { cwd: '', currentThread: a }) + assert.equal(page.ok, true, page.output) + assert.match(page.output, /Direct page text/) + } + assert.equal(requests.length, 0, 'omitted and explicit existing providers never reach Keenable') + + const first = await search(a, { limit: 1 }) + assert.equal(first.ok, true, first.output) + assert.equal(first.meta, 'Keenable') + assert.match(first.output, /^Example source\nhttps:\/\/93\.184\.216\.34\/article\nUseful public text\./) + assert.doesNotMatch(first.output, /Another source/) + assert.deepEqual(requests.at(-1)!.body, { query: 'public research question', max_results: 1 }) + const both = await search(a, { limit: 50 }) + assert.match(both.output, /Another source\nhttps:\/\/example\.org\/\nSecond page text\./) + assert.ok(both.output.length < 2000 + 200, 'long snippets are capped so every requested result fits') + assert.equal(requests.at(-1)!.body.max_results, 8, 'the shared limit cap applies') + + const fetched = await executeTool('web_fetch', { url: publicPage, provider: 'keenable', max_chars: 500 }, { cwd: '', currentThread: a }) + assert.equal(fetched.ok, true, fetched.output) + assert.equal(fetched.title, 'Fetched article') + assert.match(fetched.output, /The page as Markdown\./) + assert.equal(requests.at(-1)!.url.searchParams.get('url'), publicPage) + + fault = 'http' + assert.match((await search(a)).output, /HTTP 429 \(rate limit reached\)/) + for (const [kind, message] of [['invalid', /JSON|Unexpected/], ['size', /limit/], ['shape', /invalid search result/], ['private-result', /private|local/]]) { + fault = kind as string + assert.match((await search(a)).output, message as RegExp) + } + fault = 'empty' + assert.equal((await search(a)).output, 'No web results found.') + assert.match((await executeTool('web_fetch', { provider: 'keenable', url: publicPage }, { cwd: '', currentThread: a })).output, /could not extract/) + fault = '' + + const beforeBlocked = requests.length + for (const ctx of [{ disabledToolNames: ['web_search'] }, { disabledCapabilityIds: ['tool:web'] }, { networkCapabilityAllowed: false }, { allowedToolNames: [] }, { phoneLocalOnly: true }]) { + assert.equal((await search(a, {}, ctx)).ok, false) + } + assert.equal((await search({ ...a, googleLocalOnly: true })).ok, false) + assert.equal((await search(a, { provider: 'unknown' })).ok, false) + assert.equal((await search(a, { query: '' })).ok, false) + for (const url of ['http://127.0.0.1/secret', 'http://169.254.169.254/latest', 'file:///etc/passwd']) { + assert.equal((await executeTool('web_fetch', { url, provider: 'keenable' }, { cwd: '', currentThread: a })).ok, false) + } + assert.equal(requests.length, beforeBlocked, 'blocked calls never reach the provider') + + fault = 'stall' + const controller = new AbortController() + const pending = search(a, {}, { signal: controller.signal }) + await new Promise((resolve) => setImmediate(resolve)) + controller.abort(new Error('Synthetic cancellation')) + assert.match((await pending).output, /Synthetic cancellation/) + mock.timers.enable({ apis: ['setTimeout'] }) + try { + const timeout = search(a) + await new Promise((resolve) => setImmediate(resolve)) + mock.timers.tick(20_000) + assert.match((await timeout).output, /timed out/) + } finally { mock.timers.reset() } + fault = '' + + // A scripted model requests the optional provider and consumes the real dispatcher's result on its next turn. + const modelRequests: any[] = [] + const server = createServer((request, response) => { + let raw = '' + request.on('data', (chunk) => { raw += chunk }) + request.on('end', () => { + modelRequests.push(JSON.parse(raw)) + const delta = modelRequests.length === 1 + ? { tool_calls: [{ index: 0, id: 'search-call', type: 'function', function: { name: 'web_search', arguments: JSON.stringify({ query: 'public research question', provider: 'keenable' }) } }] } + : { content: 'The public text answers the question.' } + response.writeHead(200, { 'Content-Type': 'text/event-stream' }) + response.end(`data: ${JSON.stringify({ choices: [{ delta, finish_reason: modelRequests.length === 1 ? 'tool_calls' : 'stop' }] })}\n\ndata: [DONE]\n\n`) + }) + }) + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) + try { + const thread = await newChat() + thread.apiMessages.push({ role: 'user', content: 'Use Keenable to research this question.' }) + await runAgent({ thread, provider: { id: 'scripted', name: 'Scripted fixture', kind: 'local', transport: 'chat-completions', baseUrl: `http://127.0.0.1:${(server.address() as any).port}/v1`, apiKey: '', models: ['scripted'] }, model: 'scripted', approvalMode: 'readonly', temperature: 0, reasoningEffort: 'low', signal: new AbortController().signal, persist() {}, autoCompact: false, maxSteps: 3, requestApproval: async () => 'deny', emit() {} }) + assert.equal(modelRequests.length, 2) + assert.ok(modelRequests[1].messages.some((message: any) => message.role === 'tool' && message.content.includes('Useful public text.'))) + assert.ok(thread.apiMessages.some((message) => message.role === 'assistant' && String(message.content).includes('answers the question'))) + } finally { await new Promise((resolve) => server.close(() => resolve())) } + console.log('Keenable caller checks passed: dispatch, scripted loop consumption, request shape, permissions, errors, timeout and cancellation.') +} finally { + restoreDns() + globalThis.fetch = originalFetch + delete process.env.KEENABLE_API_KEY + mock.timers.reset() +} diff --git a/app/electron/agent/tool-keenable-search.ts b/app/electron/agent/tool-keenable-search.ts new file mode 100644 index 00000000000..a4c57c1fa0b --- /dev/null +++ b/app/electron/agent/tool-keenable-search.ts @@ -0,0 +1,68 @@ +import { readBoundedResponseText } from './bounded-response' +import { assertFetchableUrl, safePublicWebUrl } from './tool-web' +import type { ToolContext, ToolResult } from './tools' + +const API = 'https://api.keenable.ai/v1' +const APP_TITLE = 'TensorFold' +const USER_AGENT = 'TensorFold/1.0 (+https://github.com/ashhart/TensorFold)' +const TIMEOUT_MS = 20_000 +const RESPONSE_LIMIT = 1024 * 1024 +const SNIPPET_CHARS = 2000 + +async function callKeenable(url: URL, body: object | null, signal?: AbortSignal): Promise { + const controller = new AbortController() + const cancel = () => controller.abort(signal?.reason) + if (signal?.aborted) cancel() + else signal?.addEventListener('abort', cancel, { once: true }) + const timer = setTimeout(() => controller.abort(new Error('Keenable request timed out.')), TIMEOUT_MS) + try { + const response = await fetch(url, { + method: body ? 'POST' : 'GET', redirect: 'error', signal: controller.signal, + headers: { + Accept: 'application/json', 'User-Agent': USER_AGENT, 'X-Keenable-Title': APP_TITLE, + ...(body ? { 'Content-Type': 'application/json' } : {}), + }, + ...(body ? { body: JSON.stringify(body) } : {}), + }) + const text = await readBoundedResponseText(response, 'Keenable', RESPONSE_LIMIT) + if (!response.ok) throw new Error(`Keenable request failed: HTTP ${response.status}${response.status === 429 ? ' (rate limit reached)' : ''}.`) + return JSON.parse(text) + } finally { + clearTimeout(timer) + signal?.removeEventListener('abort', cancel) + } +} + +async function fetchPage(args: Record, signal?: AbortSignal): Promise { + const target = await assertFetchableUrl(String(args.url ?? '')) + const endpoint = new URL(`${API}/fetch/public`) + endpoint.searchParams.set('url', target.href) + const data = await callKeenable(endpoint, null, signal) + const content = typeof data?.content === 'string' ? data.content.trim() : '' + if (!content) throw new Error('Keenable could not extract this page.') + const rawMax = Number(args.max_chars ?? 6000) + const maxChars = Math.max(500, Math.min(12_000, Number.isFinite(rawMax) ? Math.floor(rawMax) : 6000)) + const title = String(data.title || target.hostname) + return { ok: true, output: [title, target.href, content].join('\n').slice(0, maxChars), title, path: target.href, meta: 'Keenable' } +} + +export async function executeKeenableWebTool(name: 'web_search' | 'web_fetch', args: Record, ctx: ToolContext): Promise { + if (ctx.networkCapabilityAllowed === false || ctx.disabledCapabilityIds?.includes('tool:web') || ctx.disabledToolNames?.includes(name)) { + throw new Error('Public web access is disabled for this run.') + } + ctx.signal?.throwIfAborted() + if (name === 'web_fetch') return await fetchPage(args, ctx.signal) + const query = String(args.query ?? '').trim() + if (!query) throw new Error('Search query is required.') + const rawLimit = Number(args.limit ?? 5) + const limit = Math.max(1, Math.min(8, Number.isFinite(rawLimit) ? Math.floor(rawLimit) : 5)) + const data = await callKeenable(new URL(`${API}/search/public`), { query, max_results: limit }, ctx.signal) + if (!data || !Array.isArray(data.results)) throw new Error('Keenable returned an invalid search result.') + // Snippets are page text of a few thousand characters; the cap keeps every requested result in the output. + const rows = data.results.slice(0, limit).map((row: any) => { + const target = safePublicWebUrl(String(row.url ?? '')) + const snippet = typeof row.snippet === 'string' ? row.snippet.trim().slice(0, SNIPPET_CHARS) : '' + return [String(row.title || target.hostname), target.href, snippet].filter(Boolean).join('\n') + }) + return { ok: true, output: rows.join('\n\n').slice(0, 25_000) || 'No web results found.', title: query, meta: 'Keenable' } +} diff --git a/app/electron/agent/tool-schemas.ts b/app/electron/agent/tool-schemas.ts index 64d590fe72d..a8f1a9c1005 100644 --- a/app/electron/agent/tool-schemas.ts +++ b/app/electron/agent/tool-schemas.ts @@ -130,7 +130,7 @@ const WEB_SEARCH_SCHEMA = { type: 'object', properties: { query: { type: 'string' }, - provider: { type: 'string', enum: ['google_news', 'parallel'], description: 'Defaults to Google News RSS. Choose parallel when the user requests Parallel for general web results and excerpts, with no account or API key.' }, + provider: { type: 'string', enum: ['google_news', 'parallel', 'keenable'], description: 'Defaults to Google News RSS. Choose parallel when the user requests Parallel for general web results and excerpts, with no account or API key. Choose keenable when the user requests Keenable for general web results and page text, with no account or API key.' }, limit: { type: 'number', description: 'Maximum results to return. Defaults to 5, capped at 8.' }, }, required: ['query'], @@ -147,7 +147,7 @@ const WEB_FETCH_SCHEMA = { type: 'object', properties: { url: { type: 'string' }, - provider: { type: 'string', enum: ['direct', 'parallel'], description: 'Defaults to direct page fetching. Choose parallel when the user requests Parallel for readable page excerpts.' }, + provider: { type: 'string', enum: ['direct', 'parallel', 'keenable'], description: 'Defaults to direct page fetching. Choose parallel when the user requests Parallel for readable page excerpts. Choose keenable when the user requests Keenable for the page as Markdown.' }, max_chars: { type: 'number', description: 'Maximum readable characters to return. Defaults to 6000, capped at 12000.' }, }, required: ['url'], diff --git a/app/electron/agent/tools.ts b/app/electron/agent/tools.ts index b1b0a771f6e..7c4ec971ba3 100644 --- a/app/electron/agent/tools.ts +++ b/app/electron/agent/tools.ts @@ -42,6 +42,7 @@ export { safeResolve } from './tool-paths' import { collectFiles, combinedDiff, DEFAULT_GLOB_RESULTS, MAX_GLOB_RESULTS, parseApplyPatchText, patchSummary, replaceLiteral, replacementHunksFromArgs, SKIP_DIRS, stagePatchOperations, stageReplacementHunks, validateRelativePattern, writeAppliedChanges } from './tool-patch' import { assertFetchableUrl, fetchText, parseNewsRss, safePublicWebUrl, stripHtml } from './tool-web' import { executeParallelWebTool } from './tool-parallel-search' +import { executeKeenableWebTool } from './tool-keenable-search' import { connectorName, formatMarkdownTable, formatToolNumber, normalizePersonalMessageConnector, parseStringList, personalMessageDraftEvent } from './tool-labels' import { filterNonSensitiveRetrievalKinds, normalizeVisualizationSpec } from './tool-visualization' import { isManagedOutputRef } from './context-governance' @@ -585,6 +586,7 @@ export async function executeTool(name: string, args: Record, ctx: case 'web_search': { if (args.provider === 'parallel') return await executeParallelWebTool(name, args, ctx) + if (args.provider === 'keenable') return await executeKeenableWebTool(name, args, ctx) if (args.provider != null && args.provider !== 'google_news') return { ok: false, output: 'Unknown web search provider.' } const query = String(args.query ?? '').trim() if (!query) return { ok: false, output: 'Search query is required.', title: 'Web search' } @@ -610,6 +612,7 @@ export async function executeTool(name: string, args: Record, ctx: case 'web_fetch': { if (args.provider === 'parallel') return await executeParallelWebTool(name, args, ctx) + if (args.provider === 'keenable') return await executeKeenableWebTool(name, args, ctx) if (args.provider != null && args.provider !== 'direct') return { ok: false, output: 'Unknown web fetch provider.' } // assertFetchableUrl validates the host string AND DNS-resolves it, so a // public name that resolves to an internal/metadata IP is rejected before diff --git a/app/src/components/Composer.tsx b/app/src/components/Composer.tsx index c61c08c47f1..c295baabd8c 100644 --- a/app/src/components/Composer.tsx +++ b/app/src/components/Composer.tsx @@ -255,6 +255,7 @@ export function Composer({ mode, thread, seed }: { mode: 'home' | 'thread'; thre : null const localOnly = !!policyProject?.localOnly || !!thread?.phoneLocalOnly || !!thread?.googleLocalOnly const pickerProviders = allowedProviders(settings.providers, policyProject) + const [modelPickerScope, setModelPickerScope] = useState<'all' | 'local' | null>(null) const [remoteBrowseOpen, setRemoteBrowseOpen] = useState(false) const [remoteBrowse, setRemoteBrowse] = useState(null) const [remoteBrowseBusy, setRemoteBrowseBusy] = useState(false) @@ -359,6 +360,8 @@ export function Composer({ mode, thread, seed }: { mode: 'home' | 'thread'; thre const st = thread ? status[thread.id] : undefined const busy = st != null && ['thinking', 'streaming', 'tool', 'awaiting'].includes(st) + const modelPickerDisabled = busy || submitting || !!thread?.bot + useEffect(() => { setModelPickerScope(null) }, [thread?.id, mode, modelPickerDisabled]) const botPreset = thread?.bot ? settings.agentPresets.find((preset) => preset.id === thread.bot!.presetId) : null const recoveryBlocked = !!thread?.runRecovery && (!thread.runRecovery.canStartNewRun && !busy || thread.runRecovery.retry === 'requires_review' && thread.runRecoveryReviewedId !== thread.runRecovery.runId) const botBlocked = !!thread?.bot && (!botPreset || !!botPreset.paused || !!botPreset.archivedAt) @@ -1200,7 +1203,7 @@ export function Composer({ mode, thread, seed }: { mode: 'home' | 'thread'; thre {!isChat && ( - + setModelPickerScope('local')} modelPickerDisabled={modelPickerDisabled} modelPickerOpen={!modelPickerDisabled && modelPickerScope !== null} /> )} {/* A task needs a folder: keep a small way to pick one in sight. */} @@ -1248,7 +1251,10 @@ export function Composer({ mode, thread, seed }: { mode: 'home' | 'thread'; thre requirements={taskRequirements} pickerProviders={pickerProviders} recentModels={recentModels} - disabled={busy || submitting || !!thread?.bot} + disabled={modelPickerDisabled} + open={!modelPickerDisabled && modelPickerScope !== null} + onOpenChange={(open) => setModelPickerScope(open ? 'all' : null)} + initialScope={modelPickerScope ?? 'all'} usageSnapshot={usageSnapshot} usageSummary={usageSummary} rateLimitStatus={rateLimitStatus} diff --git a/app/src/components/composer/ApprovalMenu.tsx b/app/src/components/composer/ApprovalMenu.tsx index fa6493c1a05..52ff87fc341 100644 --- a/app/src/components/composer/ApprovalMenu.tsx +++ b/app/src/components/composer/ApprovalMenu.tsx @@ -31,17 +31,21 @@ export interface ApprovalMenuProps { onSetApproval: (mode: ApprovalMode) => void /** External provider selected: it only plans, so approvals don't apply. */ planningOnly?: boolean + onChooseModel?: () => void + modelPickerDisabled?: boolean + modelPickerOpen?: boolean } const PLANNING_ONLY_REASON = 'External models only plan: no tools, no file access. Pick a local model to choose approvals.' -export function ApprovalMenu({ approvalMode, onSetApproval, planningOnly }: ApprovalMenuProps) { +export function ApprovalMenu({ approvalMode, onSetApproval, planningOnly, onChooseModel, modelPickerDisabled, modelPickerOpen }: ApprovalMenuProps) { const tx = useAuthoredText() const approval = APPROVAL.find((a) => a.value === approvalMode)! if (planningOnly) return ( - ) return ( diff --git a/app/src/components/composer/ModelPickerMenu.favourites.test.tsx b/app/src/components/composer/ModelPickerMenu.favourites.test.tsx index f7a953afb6b..69dcce3907e 100644 --- a/app/src/components/composer/ModelPickerMenu.favourites.test.tsx +++ b/app/src/components/composer/ModelPickerMenu.favourites.test.tsx @@ -91,3 +91,48 @@ assert.doesNotMatch(blankLabel, /Select model/) for (const model of ['Settings', 'Select model']) assert.ok(renderToStaticMarkup(outer(model)).includes(model), 'A real model whose name resembles UI text stays original') assert.equal(picked.length, 1, 'Rendering translated model labels cannot start model work') console.log('Actual model trigger localizes an empty selection while preserving real model names and avoiding selection or loading.') + +uiLocale = 'en'; slots = []; preferenceError = null +const planningProps = { provider: cloud, model: 'work-model', providerAccountId: 'work', initialScope: 'local' } +menu = render(planningProps) +const choiceButton = (tree: any, providerId: string, model: string, accountId: string | null = null) => descendants(tree, item => item.type === 'button' && item.props['data-model-choice'] === modelPicker.modelChoiceKey(providerId, model, accountId))[0] +assert.ok(choiceButton(menu, local.id, 'small'), 'The planning shortcut offers a usable local replacement') +assert.equal(choiceButton(menu, local.id, 'large').props.disabled, true, 'The shortcut cannot bypass memory admission') +assert.equal(choiceButton(menu, cloud.id, 'work-model', 'work'), undefined, 'The shortcut initially filters external routes') +const beforePick = picked.length, beforeClose = closes +choiceButton(menu, local.id, 'small').props.onClick() +for (let index = 0; index < 10; index++) await Promise.resolve() +assert.equal(picked.length, beforePick + 1) +assert.deepEqual(picked.at(-1), [local, 'small', null]) +assert.equal(closes, beforeClose + 1) +menu = render(planningProps) +descendants(menu, item => item.type === 'button' && item.props.children === 'All')[0].props.onClick() +menu = render(planningProps) +assert.ok(choiceButton(menu, cloud.id, 'work-model', 'work'), 'The optional local scope does not hide the All escape hatch') +const closeBeforeFailure = closes +menu = render({ ...planningProps, onPickModel: async () => { throw new Error('Synthetic route save failed') } }) +choiceButton(menu, cloud.id, 'work-model', 'work').props.onClick() +for (let index = 0; index < 10; index++) await Promise.resolve() +menu = render(planningProps) +assert.match(renderToStaticMarkup(menu), /Could not switch models:.*Synthetic route save failed/) +assert.equal(closes, closeBeforeFailure, 'A failed route save keeps the picker open for another choice') +assert.equal(choiceButton(menu, local.id, 'small').props.disabled, false, 'A failed pick releases the selection lock') +let prevented = false, stopped = false +menu.props.onKeyDown({ key: 'Escape', nativeEvent: { isComposing: false }, preventDefault() { prevented = true }, stopPropagation() { stopped = true } }) +assert.ok(prevented && stopped) +assert.equal(closes, closeBeforeFailure + 1, 'Escape dismisses the planning shortcut without selecting a route') +console.log('Actual planning shortcut filters local replacements, preserves hardware gates, allows all routes, reports failed saves and supports keyboard dismissal.') + +slots = [] +const lan = { ...cloud, id: 'lan-fixture', kind: 'local', source: 'custom', transport: 'chat-completions', accounts: [], baseUrl: 'http://192.0.2.42:8888/v1', models: ['lan-model'] } as Provider +const lanProps = { ...planningProps, pickerProviders: [local, cloud, lan] } +menu = render(lanProps) +assert.equal(choiceButton(menu, lan.id, 'lan-model'), undefined) +descendants(menu, item => item.type === 'button' && item.props.children === 'All')[0].props.onClick() +menu = render(lanProps) +const lanButton = choiceButton(menu, lan.id, 'lan-model') +assert.ok(lanButton && !lanButton.props.disabled, 'A LAN route remains selectable through All') +lanButton.props.onClick() +for (let index = 0; index < 10; index++) await Promise.resolve() +assert.deepEqual(picked.at(-1), [lan, 'lan-model', null]) +assert.equal(isExternalProvider(lan), true, 'Selecting a LAN provider never promotes it to trusted-local') diff --git a/app/src/components/composer/ModelPickerMenu.tsx b/app/src/components/composer/ModelPickerMenu.tsx index e8d3195fe86..965f323415f 100644 --- a/app/src/components/composer/ModelPickerMenu.tsx +++ b/app/src/components/composer/ModelPickerMenu.tsx @@ -41,6 +41,9 @@ export interface ModelPickerMenuProps { settings?: React.ReactNode detail?: string disabled?: boolean + open?: boolean + onOpenChange?: (open: boolean) => void + initialScope?: 'all' | 'local' ownerId?: string | null requirements?: ModelTaskRequirements qualifications?: ModelQualificationReport[] @@ -58,7 +61,7 @@ function ModelPickerBody({ close, ...props }: ModelPickerMenuProps & { close: () const { snapshot: learning } = useLearning() const setView = useStore((s) => s.setView) const [query, setQuery] = useState('') - const [scope, setScope] = useState<'all' | 'local' | 'external'>('all') + const [scope, setScope] = useState<'all' | 'local' | 'external'>(props.initialScope ?? 'all') const [showSettings, setShowSettings] = useState(false) const [pending, setPending] = useState(null) const [error, setError] = useState('') @@ -164,9 +167,9 @@ export function ModelPickerMenu(props: ModelPickerMenuProps) { const trigger = useRef(null) const label = !model?.trim() ? tx('Choose a model') : provider.source === 'tensorfold' && model ? snapshot?.installed.find((entry) => entry.repo === model)?.title ?? statsModelLabel(model, provider, snapshot?.suggestions) : modelDisplayName(provider, model) const account = accountLabel(provider, providerAccountId) - return }> - {(close) => { close(); requestAnimationFrame(() => trigger.current?.focus()) }} />} + {(close) => { close(); requestAnimationFrame(() => trigger.current?.focus()) }} />} } diff --git a/app/src/components/search/composer-active-fit.integration.test.tsx b/app/src/components/search/composer-active-fit.integration.test.tsx index bb3d7a5aa9a..cdfe3a1d3ef 100644 --- a/app/src/components/search/composer-active-fit.integration.test.tsx +++ b/app/src/components/search/composer-active-fit.integration.test.tsx @@ -17,8 +17,9 @@ import * as workspace from '../../lib/thread-workspace' import * as execution from '../../lib/execution-target' import * as attachmentsModule from '../../lib/attachments' import * as format from '../../lib/format' +import * as botLabels from '../../lib/bot-labels' import { modelPickerChoices } from '../../lib/model-picker' -import { find, harness, jsx, settle } from '../reading/reading-test-harness' +import { find, harness, jsx, load as loadComponent, settle } from '../reading/reading-test-harness' function load(file: string, overrides: Record) { const source = readFileSync(file, 'utf8'), ast = ts.createSourceFile(file, source, ts.ScriptTarget.ES2022, true), imports: Record = {} @@ -35,16 +36,18 @@ function load(file: string, overrides: Record) { } const local: any = { id: 'fit-local', name: 'Synthetic local model', kind: 'local', source: 'custom', transport: 'chat-completions', baseUrl: 'http://127.0.0.1:12345/v1', apiKey: '', models: ['selected'] } const image: any = { id: 'synthetic-image', kind: 'image', name: 'Synthetic.png', mime: 'image/png', status: 'ready', dataUrl: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=' } -async function scenario(provider: any, attached: any[], visionState = 'failed', task = false) { +async function scenario(provider: any, attached: any[], visionState = 'failed', task = false, alternatives: any[] = []) { const hooks = harness(), stateHook = hooks.hooks.useState let stateCalls = 0, sends = 0, cleared = 0 hooks.hooks.useLayoutEffect = hooks.hooks.useEffect hooks.hooks.useState = (initial: any) => stateHook(stateCalls++ === 0 ? { ready: true, reason: null, message: 'Synthetic model ready.' } : initial) const thread: any = { id: 'selected-thread', kind: task ? 'task' : 'chat', title: 'Synthetic selected model', cwd: task ? '/synthetic/workspace' : '', providerId: provider.id, providerAccountId: null, model: 'selected', timeline: [], apiMessages: [], status: 'idle' } - const settings: any = { providers: [provider], activeProviderId: provider.id, activeProviderAccountId: null, activeModel: 'selected', approvalMode: 'suggest', reasoningEffort: 'low', contextLimit: 8192, localContextLimit: 8192, defaultCwd: '', voice: { enabled: false }, agentPresets: [], remoteOrchestrators: [], defaultExecutionTarget: 'local', capabilities: {} } + const settings: any = { providers: [provider, ...alternatives], activeProviderId: provider.id, activeProviderAccountId: null, activeModel: 'selected', approvalMode: 'suggest', reasoningEffort: 'low', contextLimit: 8192, localContextLimit: 8192, defaultCwd: '', voice: { enabled: false }, agentPresets: [], remoteOrchestrators: [], defaultExecutionTarget: 'local', capabilities: {} } const notices: any[] = [] const state: any = { settings, status: {}, projects: [], terminals: {}, activeTerminalId: {}, sshHosts: [], sshStatus: {}, pendingMention: null, composerSeed: null, send: async () => { sends++; return true }, launch: async () => { sends++; return { ok: true } }, setNotice: (notice: any) => notices.push(notice), setView() {}, + setThreadProvider: async (_id: string, providerId: string, model: string, providerAccountId: string | null) => { Object.assign(thread, { providerId, model, providerAccountId }) }, + noteModelChange: async () => {}, saveSettings: async (next: any) => { state.settings = next }, } const useStore = Object.assign((select: any) => select(state), { getState: () => state, setState: (patch: any) => { if (patch.notice) notices.push(patch.notice); Object.assign(state, patch) } }) const reports: any[] = [{ providerId: provider.id, accountId: null, model: 'selected', key: fit.modelQualificationKey({ providerId: provider.id, accountId: null, model: 'selected' }), probeRevision: fit.MODEL_PROBE_REVISION, revision: 1, checkedAt: 1, checks: { ...fit.emptyModelChecks(), text: { state: 'observed', message: 'Synthetic text qualified.' }, vision: { state: visionState, message: 'Synthetic image evidence.' } } }] @@ -55,8 +58,8 @@ async function scenario(provider: any, attached: any[], visionState = 'failed', '../lib/policy': policy, '../lib/assistant-model': modelSelection, '../lib/provider-accounts': providerAccounts, '../lib/provider-model-metadata': providerMetadata, '../lib/thread-workspace': workspace, '../lib/execution-target': execution, '../lib/attachments': attachmentsModule, '../lib/format': format, '../lib/use-conversation-draft': { useConversationDraft: () => ({ ...captured, ready: true, error: '', scopeKey: 'synthetic-scope', setText() {}, setAttachments() {}, capture: () => captured, clearAccepted: async () => { cleared++ } }) }, '../lib/desktop-drafts': { desktopDraftPort: null }, '../lib/composer-estimate': { boundedComposerEstimate: () => ({ tokens: 10, partial: false }) }, '../lib/engine': { useEngineContextTokens: () => null }, '../lib/provider-usage': { providerUsageSummary: () => null }, '../lib/provider-status': { providerStatusViewFor: () => null }, - '../lib/composer-budget': composerBudgetModule, '../lib/composer-keyboard': composerKeyboard, - '../lib/recent-models': { loadRecentModels: () => [] }, '../lib/capabilities': { BUILTIN_CAPABILITIES: [] }, './composer/ModelPickerMenu': { ModelPickerMenu: 'model-picker-fixture' }, './composer/TaskStarters': { TASK_STARTERS: [], TaskStarters: 'task-starters-fixture' }, + '../lib/composer-budget': composerBudgetModule, '../lib/composer-keyboard': composerKeyboard, '../lib/bot-labels': botLabels, + '../lib/recent-models': { loadRecentModels: () => [], pushRecentModel: () => [] }, '../lib/capabilities': { BUILTIN_CAPABILITIES: [] }, './composer/ModelPickerMenu': { ModelPickerMenu: 'model-picker-fixture' }, './composer/ApprovalMenu': { ApprovalMenu: 'approval-fixture' }, './composer/TaskStarters': { TASK_STARTERS: [], TaskStarters: 'task-starters-fixture' }, }) const tree = hooks.render(() => Composer({ mode: 'thread', thread })) const picker = find(tree, (node) => node.type === 'model-picker-fixture') @@ -64,7 +67,7 @@ async function scenario(provider: any, attached: any[], visionState = 'failed', const choices = modelPickerChoices([provider], null, { requirements: picker.props.requirements, qualifications: reports }) find(tree, (node) => node.type === 'button' && node.props['aria-label'] === 'Send').props.onClick() await settle() - return { sends, cleared, notices, picker: picker.props, choice: choices[0] } + return { sends, cleared, notices, picker: picker.props, choice: choices[0], state, thread, render: () => hooks.render(() => Composer({ mode: 'thread', thread })) } } const failedImage = await scenario(local, [image]) assert.match(failedImage.choice.disabledReason!, /vision check/, 'The real picker already rejects this exact active provider/account/model for the attached image') @@ -80,3 +83,55 @@ for (const transport of ['chat-completions', 'codex-cli']) { assert.equal(planning.sends, 1, 'A workspace path alone must not forbid the existing external planning-only route') } console.log('Actual Composer active selection uses the same required-evidence refusal as its picker while preserving drafts, text-only work, unknown evidence and external planning routes.') + +const { ApprovalMenu } = loadComponent('src/components/composer/ApprovalMenu.tsx', { + 'react/jsx-runtime': jsx, clsx, '../../lib/icons': { Icon: 'icon-fixture' }, '../ui': { Menu: 'menu-fixture' }, +}) +const planner = { ...local, id: 'planning-fixture', kind: 'cloud', transport: 'claude-cli', baseUrl: '' } +const switching = await scenario(planner, [], 'unknown', true, [local]) +const approval = () => find(switching.render(), node => node.type === 'approval-fixture').props +const picker = () => find(switching.render(), node => node.type === 'model-picker-fixture').props +const planningButton = ApprovalMenu(approval()) +assert.ok(!planningButton.props.disabled, 'Planning-only guidance must be actionable on an idle task') +assert.equal(planningButton.props.type, 'button', 'Opening the picker must not submit the composer') +planningButton.props.onClick() +assert.equal(picker().open, true, 'The real Composer must open its existing model picker') +assert.equal(ApprovalMenu(approval()).props['aria-expanded'], true) +assert.equal(picker().initialScope, 'local', 'Planning-only guidance starts with trusted local choices') +assert.equal(switching.state.settings.approvalMode, 'suggest', 'Opening a picker must not elevate approvals') +await picker().onPickModel(local, 'selected', null) +assert.equal(approval().planningOnly, false, 'Planning-only follows the selected provider rather than sticking to the conversation') +assert.equal(picker().provider.id, local.id) +await picker().onPickModel(planner, 'selected', null) +assert.equal(approval().planningOnly, true, 'Returning to an external provider restores planning-only restrictions') +switching.state.setThreadProvider = async () => { throw new Error('Synthetic selection save failed') } +await assert.rejects(() => picker().onPickModel(local, 'selected', null), /selection save failed/) +assert.equal(approval().planningOnly, true, 'A failed save cannot present a local route as active') +for (const status of ['thinking', 'streaming', 'tool', 'awaiting']) { + switching.state.status[switching.thread.id] = status + assert.equal(ApprovalMenu(approval()).props.disabled, true, 'The shortcut honours the same active-run lock as the model button') + assert.equal(picker().open, false) +} +switching.state.status[switching.thread.id] = 'error' +assert.ok(!ApprovalMenu(approval()).props.disabled, 'A failed planning run must not strand the next model selection') +picker().onOpenChange(false) +assert.equal(picker().open, false) +picker().onOpenChange(true) +assert.equal(picker().initialScope, 'all', 'The ordinary model button retains all permitted routes') +switching.state.status[switching.thread.id] = 'idle' +let finishSubmit!: (accepted: boolean) => void +switching.state.send = () => new Promise(resolve => { finishSubmit = resolve }) +find(switching.render(), node => node.type === 'button' && node.props['aria-label'] === 'Send').props.onClick() +await settle() +assert.equal(ApprovalMenu(approval()).props.disabled, true, 'A pending submission locks the shortcut before run status arrives') +assert.equal(picker().disabled, true) +assert.equal(picker().open, false) +finishSubmit(true) +await settle() +assert.ok(!ApprovalMenu(approval()).props.disabled, 'Submission completion releases the picker lock') +switching.thread.bot = { presetId: 'synthetic-bot-preset' } +assert.equal(ApprovalMenu(approval()).props.disabled, true, 'A bot-owned route cannot be changed through the shortcut') +assert.equal(picker().disabled, true) +assert.equal(picker().open, false) +assert.equal(switching.state.settings.approvalMode, 'suggest') +console.log('Actual Composer planning-only shortcut opens its local picker, follows successful provider changes and preserves approval, failure and active-run boundaries.') diff --git a/app/src/components/ui-menu.test.tsx b/app/src/components/ui-menu.test.tsx new file mode 100644 index 00000000000..969e06c96bf --- /dev/null +++ b/app/src/components/ui-menu.test.tsx @@ -0,0 +1,78 @@ +import assert from 'node:assert/strict' +import clsx from 'clsx' +import { find, harness, jsx, load } from './reading/reading-test-harness' + +const originalDocument = Object.getOwnPropertyDescriptor(globalThis, 'document') +const originalWindow = Object.getOwnPropertyDescriptor(globalThis, 'window') +const listeners = new Map void>() +Object.defineProperty(globalThis, 'document', { configurable: true, value: { + body: {}, addEventListener: (name: string, callback: any) => listeners.set(name, callback), + removeEventListener: (name: string, callback: any) => { if (listeners.get(name) === callback) listeners.delete(name) }, +} }) +Object.defineProperty(globalThis, 'window', { configurable: true, value: { + innerWidth: 1024, innerHeight: 768, + requestAnimationFrame: () => 1, cancelAnimationFrame() {}, addEventListener() {}, removeEventListener() {}, +} }) + +try { + for (const controlled of [false, true]) { + const hooks = harness() + hooks.hooks.useCallback = (callback: any) => callback + hooks.hooks.useLayoutEffect = hooks.hooks.useEffect + const { Menu } = load('src/components/ui.tsx', { + react: hooks.hooks, 'react/jsx-runtime': jsx, 'react-dom': { createPortal: (node: any) => node }, clsx, + '../lib/icons': { Icon: 'icon-fixture' }, + }) + let open = false, focus = 0, content: any, triggerOpen = false + const changes: boolean[] = [] + const props = { + ...(controlled ? { onOpenChange: (value: boolean) => { changes.push(value); open = value } } : {}), + trigger: (value: boolean) => { triggerOpen = value; return jsx.jsx('button', { children: 'Choose model' }, null) }, + children: (close: () => void) => { content = { close }; return jsx.jsx('div', { role: 'dialog' }, null) }, + } + if (controlled) Object.defineProperty(props, 'open', { get: () => open }) + const render = () => { + const tree = hooks.render(() => Menu(props)) + tree.ref.current = { contains: (node: unknown) => node === 'trigger', querySelector: () => ({ focus: () => focus++ }), + getBoundingClientRect: () => ({ top: 600, bottom: 632, left: 400, right: 600 }) } + hooks.flush() + return tree + } + let tree = render() + assert.equal(triggerOpen, false) + assert.equal(find(tree, node => node.props.role === 'dialog'), undefined) + find(tree, node => node.type === 'div' && node.props.onClick).props.onClick() + tree = render() + assert.equal(triggerOpen, true) + assert.ok(find(tree, node => node.props.role === 'dialog')) + listeners.get('mousedown')!({ target: 'trigger' }) + assert.ok(find(render(), node => node.props.role === 'dialog'), 'Trigger clicks are not mistaken for outside clicks') + let prevented = false + listeners.get('keydown')!({ key: 'Escape', defaultPrevented: false, preventDefault() { prevented = true } }) + tree = render() + assert.ok(prevented) + assert.equal(focus, 1, 'Keyboard dismissal restores focus to the model trigger') + assert.equal(find(tree, node => node.props.role === 'dialog'), undefined) + if (controlled) open = true + else find(tree, node => node.type === 'div' && node.props.onClick).props.onClick() + tree = render() + assert.ok(find(tree, node => node.props.role === 'dialog'), 'A controlled menu can open from another composer button') + content.close() + tree = render() + assert.equal(find(tree, node => node.props.role === 'dialog'), undefined, 'Successful selection closes the controlled menu') + find(tree, node => node.type === 'div' && node.props.onClick).props.onClick() + render() + listeners.get('mousedown')!({ target: 'outside' }) + tree = render() + assert.equal(find(tree, node => node.props.role === 'dialog'), undefined, 'Outside dismissal updates the owner of a controlled menu') + if (controlled) assert.deepEqual(changes, [true, false, false, true, false]) + hooks.cleanup() + assert.equal(listeners.size, 0) + } +} finally { + if (originalDocument) Object.defineProperty(globalThis, 'document', originalDocument) + else delete (globalThis as any).document + if (originalWindow) Object.defineProperty(globalThis, 'window', originalWindow) + else delete (globalThis as any).window +} +console.log('Actual controlled and standalone menus preserve trigger toggling, external opening, selection close, Escape focus and outside dismissal.') diff --git a/app/src/components/ui.tsx b/app/src/components/ui.tsx index ed936b5ac9a..3807201f621 100644 --- a/app/src/components/ui.tsx +++ b/app/src/components/ui.tsx @@ -1,4 +1,4 @@ -import React, { useEffect, useLayoutEffect, useRef, useState } from 'react' +import React, { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react' import { createPortal } from 'react-dom' import clsx from 'clsx' import { Icon, type IconName } from '../lib/icons' @@ -61,14 +61,23 @@ export function Menu({ align = 'start', width = 240, placement = 'auto', + open: controlledOpen, + onOpenChange, }: { trigger: (open: boolean) => React.ReactNode children: (close: () => void) => React.ReactNode align?: 'start' | 'end' width?: number placement?: 'auto' | 'bottom' | 'top' + open?: boolean + onOpenChange?: (open: boolean) => void }) { - const [open, setOpen] = useState(false) + const [internalOpen, setInternalOpen] = useState(false) + const open = controlledOpen ?? internalOpen + const setOpen = useCallback((value: boolean) => { + setInternalOpen(value) + onOpenChange?.(value) + }, [onOpenChange]) const [menuStyle, setMenuStyle] = useState(null) const ref = useRef(null) const menuRef = useRef(null) @@ -89,7 +98,7 @@ export function Menu({ document.addEventListener('mousedown', onDown) document.addEventListener('keydown', onEsc) return () => { document.removeEventListener('mousedown', onDown); document.removeEventListener('keydown', onEsc) } - }, [open]) + }, [open, setOpen]) // Position the menu in a portal with fixed (viewport) coordinates derived from the // trigger rect, so it is never clipped or scroll-trapped by an ancestor's overflow // (e.g. the sidebar's scrolling project list) — the cause of menus colliding with the @@ -132,7 +141,7 @@ export function Menu({ }, [open, placement, width, align]) return (
-
setOpen((o) => !o)}>{trigger(open)}
+
setOpen(!open)}>{trigger(open)}
{open && createPortal(
globals.localStorage = { getItem: () => null, setItem: () => {}, removeItem: () => {} } @@ -15,7 +15,7 @@ async function main() { const before = useStore.getState() const originalConfigure = api.configureThread const originalSave = before.saveSettings - const provider = { id: 'local', name: 'Local', kind: 'local', baseUrl: 'http://127.0.0.1:1234/v1', apiKey: '', models: ['old', 'new'] } + const provider: Provider = { id: 'local', name: 'Local', kind: 'local', baseUrl: 'http://127.0.0.1:1234/v1', apiKey: '', models: ['old', 'new'] } const thread = { id: 'selection-fixture', providerId: 'local', providerAccountId: null, model: 'old' } as Thread const settings = { providers: [provider], activeProviderId: 'local', activeProviderAccountId: null, activeModel: 'old' } as Settings try { @@ -26,6 +26,18 @@ async function main() { api.configureThread = async () => {} await useStore.getState().setThreadProvider(thread.id, 'local', 'new', null) assert.equal(useStore.getState().threads[0].model, 'new') + const planner: Provider = { ...provider, id: 'planner', kind: 'cloud', transport: 'claude-cli', models: ['plan'] } + useStore.setState({ settings: { ...settings, providers: [planner, provider], approvalMode: 'readonly' }, + threads: [{ ...thread, providerId: planner.id, model: 'plan' }] }) + api.configureThread = async () => { throw new Error('Synthetic provider switch failed') } + await assert.rejects(() => useStore.getState().setThreadProvider(thread.id, provider.id, 'new', null), /provider switch failed/) + assert.equal(useStore.getState().threads[0].providerId, planner.id, 'An external-to-local save failure preserves the persisted route') + let configured: unknown[] = [] + api.configureThread = async (...args) => { configured = args } + await useStore.getState().setThreadProvider(thread.id, provider.id, 'new', null) + assert.deepEqual(configured, [thread.id, provider.id, 'new', null]) + assert.equal(useStore.getState().threads[0].providerId, provider.id) + assert.equal(useStore.getState().settings?.approvalMode, 'readonly', 'Leaving a planning provider must not silently grant broader approvals') } finally { api.configureThread = originalConfigure; useStore.setState({ settings: before.settings, threads: before.threads, saveSettings: originalSave }) } console.log('Thread model selection persistence checks passed.') } diff --git a/docs/api.md b/docs/api.md index d612bfcc570..cfb29edaa1b 100644 --- a/docs/api.md +++ b/docs/api.md @@ -761,9 +761,13 @@ token-level, budgeted, captured or left-recursive rules. The masks follow from x thinking on they start after the think end. HTTP 400 comes before any token for a malformed field, a grammar xgrammar cannot compile (with xgrammar's reason), a -server without xgrammar (with the install command; on the native server, a server that cannot load `libtfgrammar`), -a grammar sent with `tool_choice: "required"` or a named function. A reply whose -grammar fails while decoding ends with HTTP 500 (an error event when streaming); the other requests go on. +grammar over 512 KiB on the native server, a server without xgrammar (with the install command; on the native server, a +server that cannot load `libtfgrammar`), a grammar sent with `tool_choice: "required"` or a named function. A sent grammar is measured as the server compiles it: +a JSON schema or a list of choices as the server re-serializes it (which can differ from its size as sent), a regex or grammar as sent. Tools are +measured by the grammar for one call to any of them, which holds each tool's name and parameter schema once (every +tool's schema under `tool_choice: "required"` or a named function, the strict tools' under `"auto"`); the grammar for +parallel calls repeats that call and is not measured again, and its 400 names `tools`. A reply whose grammar fails while +decoding ends with HTTP 500 (an error event when streaming); the other requests go on. ## Reasoning @@ -813,6 +817,8 @@ gives the template `clear_thinking` false on every render, and `TF_GLM_CLEAR_THI from @MiaAI-Lab's [#236](https://github.com/ashhart/TensorFold/pull/236); any value but 0 or 1 refuses to load. A request's `chat_template_kwargs.clear_thinking` (true or false) overrides the server's setting for that request, as the model card advises `true` for plain chat; any other value is a 400, and other families' templates never receive it. +`true` keeps the reasoning after the last user message, so an autonomous tool loop keeps most of it; the +[GLM-5.3-Flash recipe](recipes/glm-5.3-flash.md#long-agent-sessions) covers long agent sessions. A tool call written before the think block closes is the reply's tool call when the reply ends inside the block, on both backends; the reasoning stops where the call starts, and streamed reasoning never carries the call's markup. diff --git a/docs/environment.md b/docs/environment.md index 8054cf749b6..e5b9b4e3544 100644 --- a/docs/environment.md +++ b/docs/environment.md @@ -50,7 +50,7 @@ Diagnostics quote and escape the supplied text so it cannot create another termi | `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_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`; `1` has the 4-bit expert kernels read each group's scale and bias through a 16-bit index into its tensor's table of pairs, the same values with fewer weight bytes; default 0 | +| `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` | | `TF_FLASHNEXT_GROUPED_ROWS` | Flash Next on Metal without tensor units: `0`, or the rows (`1` through `32`) from which a decode window runs its 4-bit experts grouped by expert, with the same output bits; default 5; ignored with `--ssd-experts` and in speed-up mode | | `TF_QWEN27_SLOT_RESUME` | Qwen3.8-27B on Metal: exactly `0` or `1`; `0` stops slot 0 resuming a later prompt; unset or blank keeps it on | | `TF_QWEN27_METAL_KV_PAGES` | Qwen3.8-27B on Metal: exactly `0` or `1`; `1` puts keys and values in core-pool pages (refused on Macs with tensor units); unset or blank is `0` | @@ -96,7 +96,7 @@ Direct family readers also refuse malformed values when called without the serve ## Flash Next -Flash Next checks these 29 settings when its engine loads, before any device or checkpoint work: a malformed value +Flash Next checks these 31 settings when its engine loads, before any device or checkpoint work: a malformed value stops the start with the variable, the supplied text and the accepted forms. | Variable | Accepted explicit value | @@ -126,6 +126,8 @@ stops the start with the variable, the supplied text and the accepted forms. | `TF_FLASHNEXT_GREEDY_WIDE` | Whole round width; default 4 | | `TF_FLASHNEXT_WINDOW_ROWS` | Whole row count; default the shared round's rows, capped by them | | `TF_FLASHNEXT_READOUT_ROWS` | Whole row count; default 64; `0` never takes the tiles | +| `TF_FLASHNEXT_CHUNK` | Whole prompt rows a pass, 1 through 16384; default 1536 | +| `TF_FLASHNEXT_CHUNK_SOLO` | Whole prompt rows a pass with no stream decoding, from the chunk `TF_FLASHNEXT_CHUNK` resolves to through 16384; unset or blank is the larger of that chunk and 8192 on a server of one stream, and that chunk elsewhere | | `TF_FLASHNEXT_FACT_ROWS` | Whole row count; default 64; `0` never takes the tiles | | `TF_FLASHNEXT_KV_PAGE_TEST` | Whole page size the kernels take: whole blocks of the indexer's ratio up to the window; unset or blank leaves the plain caches | | `TF_FLASHNEXT_CONFIDENCE` | Finite number, negative values included; default -0.4, the chain's own stop | @@ -133,6 +135,11 @@ stops the start with the variable, the supplied text and the accepted forms. An on-by-default switch keeps the same kernels and bits as off; only the launch count changes. The two row counts and the two draft counts keep their existing clamps after parsing. +The two chunk settings keep their cross-setting rule in the family, which the table cannot state on its own: the family +checks a solo chunk reaches at least the chunk `TF_FLASHNEXT_CHUNK` resolves to, and its refusal names that setting and +the rows it must reach. An unset or blank solo chunk is the larger of that chunk and 8192 on a server of one stream +(`--parallel 1` on one rank), and that chunk elsewhere, where solo passes are off. An empty or whitespace-only value of +either setting takes the unset default above, like every other setting here. ## Existing lenient switches diff --git a/docs/kernel-contract.md b/docs/kernel-contract.md index b8150c94d4a..af23031944c 100644 --- a/docs/kernel-contract.md +++ b/docs/kernel-contract.md @@ -350,6 +350,10 @@ is bit-equal to the chain it replaces (`tf_conv_prefill`, `tf_copy_cols`, `tf_rm Four controls: the recurrence one row short of the prompt and with one key head, and the prework norming q with k's weights and writing gate and beta to each other's outputs. +HIP also checks Flash Next's indexer block score kernel (`tf_fn_idx_scores`, `contract_idx_scores.zig`, record in +`hip_records_sparse.zig`): staging each tile's rows of `q` in LDS when `heads * dims <= 512`, checked against the +fp64 relu-summed head dots with one control leaving out each row's last head (`shapes`). + On gfx12, HIP also checks the WMMA dense tile (`dense_wmma12_gemm`, both block geometries, fp32 and BF16 out). The small block meets its depth-k bound. The big block (64-deep K steps over swizzled LDS rows) replaces the 32-deep block it was before #2245's second lever, byte for byte: gate 3 runs a frozen copy of that block (`tf_ref_wmma12_k32`, in the diff --git a/docs/openclaw.md b/docs/openclaw.md new file mode 100644 index 00000000000..79ea2d4c285 --- /dev/null +++ b/docs/openclaw.md @@ -0,0 +1,80 @@ +# Use TensorFold with OpenClaw + +The [openclaw-tensorfold](https://github.com/ashhart/openclaw-tensorfold) plugin makes TensorFold a model provider in +[OpenClaw](https://github.com/openclaw/openclaw). OpenClaw starts `tensorfold serve` when a request needs it and stops +it when OpenClaw exits or the server sits idle; it can also connect to a server you run yourself. The plugin is on +ClawHub and npm (Apache-2.0) and needs OpenClaw 2026.11.3 or later. + +- **Models:** the provider lists what the server's `/v1/models` reports, not a list written by hand. Each model gets + its context window, image input when the server reports vision, and the reasoning efforts its chat template names. +- **Thinking:** OpenClaw's thinking levels reach the server as `reasoning_effort`. Off sends `none` when the template + can switch thinking off, and sends nothing when it can't. + +The plugin registers one provider and no tools, hooks or background services; starting and stopping the server is +OpenClaw's own [local model service](https://docs.openclaw.ai/gateway/local-model-services). It changes nothing in the +engine's requests or tokens. + +## Let OpenClaw start TensorFold + +```sh +brew install ashhart/tensorfold/tensorfold +openclaw plugins install clawhub:openclaw-tensorfold +openclaw onboard --auth-choice tensorfold-local +``` + +Use a checkpoint already qualified for your platform, following its [model recipe](recipes/). Setup asks for the model +(checkpoints already in the Hugging Face cache are listed first; a folder or a Hugging Face id also works), the context +window (65,536 tokens by default) and whether to stop the server after an idle time. It starts TensorFold once to read +the model's window and reasoning efforts, stops it, and writes `models.providers.tensorfold.localService`. + +After that, the first request for the model starts `tensorfold serve` on `127.0.0.1` (a free port from 18180 up) and +waits for `/health`, which answers once the model has loaded. The server and OpenClaw share one key, kept in +`tensorfold/server.keys` (mode 0600) under OpenClaw's state folder, and the server uses the +[key-file format](api.md#api-keys) with an `inference,read` scope. + +The plugin looks for `tensorfold` on `PATH` and in Homebrew's folders; `TENSORFOLD_BINARY` names another build by its +absolute path. Unattended setup reads `TENSORFOLD_MODEL`, and optionally `TENSORFOLD_CONTEXT` and +`TENSORFOLD_IDLE_STOP_MINUTES`: + +```sh +TENSORFOLD_MODEL=TensorFold/Qwen3.8-27B-MLX-4bit openclaw onboard --non-interactive --accept-risk --mode local \ + --skip-health --auth-choice tensorfold-local +``` + +## Connect to a server you run + +```sh +tensorfold serve /path/to/checkpoint --name my-model --host 127.0.0.1 --port 8080 --api-key-file /path/to/server.keys +export TENSORFOLD_API_KEY='YOUR_KEY_FROM_SERVER_KEYS' +openclaw onboard --auth-choice tensorfold-api-key +openclaw models list --provider tensorfold --refresh +``` + +A key scoped to `inference` is enough: chat and `/v1/models` are both inference routes. A server without keys works +too, but OpenClaw still wants a key to register the provider, so give it any value. Onboarding saves the key and makes +the first served model the default. The plugin uses `http://127.0.0.1:8080/v1` unless `TENSORFOLD_BASE_URL` or +`models.providers.tensorfold.baseUrl` names another address; a bare `http://host:8080` gets `/v1` added. A model list +written under `models.providers.tensorfold.models` is left as it is, and the plugin then skips discovery. + +## Thinking levels + +| What `/v1/models` reports | What OpenClaw sends | +|---|---| +| `reasoning.supported_efforts`, such as Qwen3.8's `low`, `medium`, `xhigh` and `none` | the chosen level as `reasoning_effort`, rounded down to one the template names; off sends `none` | +| a thinking switch without levels, such as Nemotron 3.5 | off sends `none`; any other level sends nothing, so the template's default applies | +| reasoning that can't be switched off | nothing | + +## Checked + +On an Apple M5 Max (Metal) with the TensorFold 1.2.8 release archive and OpenClaw 2026.11.3: + +| Check | Result | +|---|---| +| Unattended `onboard --auth-choice tensorfold-local`, Nemotron 3.5 Lightning 30B-A3B | 17 s: started and stopped TensorFold once, wrote the service with the 65,536-token window | +| Agent turn with no server running: write a script, run it, report the output | OpenClaw started TensorFold (ready in 3.0 s), the right output, the server stopped when OpenClaw exited; 20 s | +| Install from ClawHub, and from npm, into an empty OpenClaw | loaded, provider `tensorfold` | +| Connecting to a running server: an agent turn with tools | written, run, the right output, 14 s | +| `--thinking off` and `high` on Nemotron | thinking off, then the template's default | +| `--thinking low`, `medium`, `xhigh` and `off` on Qwen3.8-27B | the server heard `low`, `medium`, `xhigh`, then thinking off | + +Not run yet: the idle stop inside a long-running OpenClaw Gateway, and a CUDA server. diff --git a/docs/optimization-ledger.md b/docs/optimization-ledger.md index c15a893a1ab..967a44cc099 100644 --- a/docs/optimization-ledger.md +++ b/docs/optimization-ledger.md @@ -76,7 +76,7 @@ last two hold the families with only a Metal, HIP or scoring backend. | 25. TP ranks | done H[#655] | done C[#1771] H[#817] | done [#855] | yes | done¹ | | 26. Pipeline | open [#2115] | yes | yes | yes | yes | | 27. Profiles | done [#1944] | done [#1944] | done [#1959] | done [#1944] | done [#2061] | -| 28. Scale index | ? | open M[#2760] | ? | ? | ? | +| 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) | | Optimization | kol1 | spk25 | dory | mm3 | dsv41 | @@ -469,8 +469,10 @@ below; these are estimates for planning a port, not results. 28. **Scale index.** An affine checkpoint stores a bf16 scale and bias beside every group's codes, a fifth of the bytes at 4 bits in groups of 32, and a tensor holds few distinct pairs. A 16-bit index a group into the tensor's table of pairs gives a kernel the same two values from fewer bytes. Flash Next's 4-bit expert kernels read it on - Macs before tensor units behind `TF_FLASHNEXT_SCALE_INDEX` ([#2760], plan in [#2751]); the prompt gathers and the - dense rows still read the stored arrays. `?` cells: the same count has not been run on those checkpoints. + Macs before tensor units ([#2760], plan in [#2751]); its prompt gathers and grouped expert kernels read it too, + the routed experts' stored arrays are released and it is the default, `TF_FLASHNEXT_SCALE_INDEX=0` turning it + off ([#2805]). The dense rows still read the stored arrays. `?` cells: the same count has not been run on those + checkpoints. 29. **DSpine drafter.** Tencent's DSpine-b16 for Qwen3.8-27B, opt-in by `--drafter` with its folder, never the default. It reuses DFlash2's taps and tap ring and adds a code bridge and an exact-sender table. @@ -628,3 +630,4 @@ below; these are estimates for planning a port, not results. [#2784]: https://github.com/ashhart/TensorFold/pull/2784 [#2764]: https://github.com/ashhart/TensorFold/issues/2764 [#2977]: https://github.com/ashhart/TensorFold/pull/2977 +[#2805]: https://github.com/ashhart/TensorFold/pull/2805 diff --git a/docs/recipes/flash-next-cuda.md b/docs/recipes/flash-next-cuda.md index 03c9f7fdc1f..8815ec610af 100644 --- a/docs/recipes/flash-next-cuda.md +++ b/docs/recipes/flash-next-cuda.md @@ -98,6 +98,8 @@ tensorfold-native serve /path/to/checkpoint --temperature 0 - `TF_FLASHNEXT_CHUNK_SOLO` (`TF_FLASHNEXT_CHUNK` to 16,384) is the chunk a pass takes when no other stream is decoding as it starts; with one decoding, the pass takes `TF_FLASHNEXT_CHUNK`. Unset, it's 8,192 at `--parallel 1` on one GPU, and every other server's passes take `TF_FLASHNEXT_CHUNK`. See [Prompt chunk size](#prompt-chunk-size). + Both settings are checked by name when the engine loads, with a blank value read as unset + ([environment](../environment.md#flash-next)). - `TF_FLASHNEXT_DRAFTS` (1 to 15, default 6) and `TF_FLASHNEXT_CONFIDENCE` (default -0.4) set the head's chain. A negative value keeps drafting while the drafts' probabilities multiply to at least its size (0.4 by default), a positive value keeps a later draft only at or above it, and 0 keeps every draft. diff --git a/docs/recipes/glm-5.3-flash.md b/docs/recipes/glm-5.3-flash.md index f2e7a68c365..57d2b93cff1 100644 --- a/docs/recipes/glm-5.3-flash.md +++ b/docs/recipes/glm-5.3-flash.md @@ -290,6 +290,29 @@ mx.set_cache_limit(8 * 2**30) # the server # ... per request: run, then mx.clear_cache() ``` +## Long agent sessions + +When the client sends earlier turns' reasoning back, the chat template keeps all of it in the prompt, so an agent's +prompt grows with its thinking as well as its messages and tool results. In one omp session on an M5 Ultra (native +server, the 4-bit checkpoint, thinking on), about 330K of the prompt's 494K tokens were earlier reasoning. +Past about 300K tokens the model starts to repeat itself: filler words were 2-3% of a reply's words at 334-356K, +about 15% near 390K and 20-50% past 410K, and the looping turns then go back into the prompt and are copied. +The build is not the cause: at a 458K-token prompt, release 1.2.9 and a build with the later GLM decode changes +gave byte-identical greedy replies, and a recall test over 22,000 similar records found 9 of 11. + +`TF_GLM_CLEAR_THINKING=1`, or a request's `chat_template_kwargs.clear_thinking: true`, drops only the reasoning +before the last user message, so an autonomous tool loop keeps most of it. To keep a long session's prompt to its +messages and tool results, have the client stop sending reasoning back. omp sends it by default to servers on +loopback or private addresses; set this in the provider's `compat` in `~/.omp/agent/models.yml`: + +```json +"compat": { "replayReasoningContent": false } +``` + +The next request renders the previous reply without its reasoning, so the server resumes from the previous +request's prompt and prefills that reply again. A session that is already long renders shorter once, at the cost of +one cold prefill. + ## Responses and exactness When thinking is disabled, the server closes the template's open think block so the response reaches diff --git a/docs/recipes/minimax-h3-metal.md b/docs/recipes/minimax-h3-metal.md index b5d2e7f895b..2da4ef6e197 100644 --- a/docs/recipes/minimax-h3-metal.md +++ b/docs/recipes/minimax-h3-metal.md @@ -122,6 +122,33 @@ keyframe level, as a first frame's are), the audio rows with the references' cle video. Its geometry has an eighth count, the reference audio rows: they enter on every pass at timestep 1 and are never stepped. `steps=N` on the released weights makes their own grid of N + 1 points (video shift 12, audio 3). +## Cold start: weights read ahead + +`Model.load` reads the transformer shards into the page cache before the first forward, using core's +`checkpoint_read_ahead` reader with spans of at most 8 MiB. Metal then reads the unchanged bf16 weights through the +same zero-copy mappings. Missing or truncated shards fail the load before any forward runs. + +`TF_LOAD_PREFETCH` selects 0–16 reader threads (16 by default); `0` disables read-ahead and leaves page faults to the +mapping. This affects only transformer loading, not the prompt encoder or decoder. + +Receipt, `tf-h3-dit` at main against this branch, alternating, on an M5 Ultra with macOS 27.0: FastH3-8-Step-V2 +(revision `3da2ddfe`), 8 steps, 22 frames, seed 2077, audio rows on. Cold evicts the 66 GB of shards from the page +cache first; warm reads them in. Seconds, load + first step / whole run: + +| Case | main | read-ahead | +|---|---|---| +| 2048 cold, run 1 | 33.6 / 151.7 | 34.2 / 168.5 | +| 2048 cold, run 2 | 48.9 / 163.3 | 31.8 / 159.3 | +| 2048 warm | 20.7 / 158.7 | 22.1 / 152.2 | +| 4096 cold | 160.8 / 1270.7 | 167.8 / 1315.4 | +| 4096 warm | 136.3 / 1255.5 | 157.8 / 1286.2 | + +Video and audio outputs are byte-identical between main and the branch in every run. Read-ahead moves main's +first-step page faults into the load; it shows no net cold-start win here. The second 2048 warm pair is not run. + +`zig build test-h3-read-ahead` checks multi-piece, multi-file byte counts, truncated and missing files, and disabled +read-ahead. The nightly macOS host checks run this target. + ## Not done - No exporter in the tree, so the tool cannot be exercised from this repository alone. diff --git a/docs/recipes/nemotron-3.5.md b/docs/recipes/nemotron-3.5.md index 6c104380a39..4398789ba46 100644 --- a/docs/recipes/nemotron-3.5.md +++ b/docs/recipes/nemotron-3.5.md @@ -1,7 +1,7 @@ # Nemotron 3.5 Lightning -The model combines Mamba-2, attention and MoE blocks. The native family is `zig/src/families/nemotron/`, on Metal -and CUDA; the native prompt reuse, routed experts and shared rounds sections below describe it, and the +The model combines Mamba-2, attention and MoE blocks. The native family is `zig/src/families/nemotron/`, on Metal, +CUDA and HIP; the native prompt reuse, routed experts, shared rounds and HIP sections below describe it, and the [README](../../README.md#qualified-models) lists its qualified checkpoints and hardware. The MLX execution, CUDA, draft vocabulary and measurements sections describe the Python engine, @@ -21,7 +21,7 @@ The checkpoint includes `mtp-4bit.safetensors`; `pull` and `serve` check that it `--no-drafts` or request field `"draft": false` selects serial decoding. In the Python engine, MLX supports affine 4-bit projections and experts in groups of 32 or 64; unsupported formats are refused before weight downloads and checked again at load. CUDA supports the named 4-bit/group-64 checkpoint. The native engine serves the named -checkpoint on Metal and CUDA, and NVIDIA's NVFP4 export on CUDA. +checkpoint on Metal, CUDA and HIP, and NVIDIA's NVFP4 export on CUDA. On Metal the native engine also serves MLX checkpoints at a width per module (2, 3, 4, 5, 6 or 8 bits, not 7, in groups of 32, 64 or 128), such as `TensorFold/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-oQ4`, `-oQ6` and `-oQ8`, the three @@ -31,8 +31,8 @@ width-general gathers; dense matrices in other groups stay on the row kernels. T `mtp-4bit.safetensors` from the 4-bit checkpoint into the folder to draft; without it each round decodes one token. With the head on an M3 Ultra, greedy prose decodes at 162 tok/s with oQ4, 117 with oQ6 and 111 with oQ8, against 188 with the 4-bit checkpoint, and prompts of 8,192 to 32,768 tokens read at 0.96x to 0.99x mlx_lm's rate on the same checkpoint; a -server's first 2,048-token prompt after it starts reads at 0.78x to 0.90x. For MLX affine checkpoints, CUDA, the Intel -GPU engine and `--slide` refuse widths other than 4-bit group 64 and name the first such module. +server's first 2,048-token prompt after it starts reads at 0.78x to 0.90x. For MLX affine checkpoints, CUDA, HIP, the +Intel GPU engine and `--slide` refuse widths other than 4-bit group 64 and name the first such module. ## MLX execution and exactness @@ -92,8 +92,8 @@ for checkpoint requirements, request parts, limits and qualification status. This section describes the Python 0.6.6 engine's list, [`src/tensorfold/families/nemotron_h/draft_ids.txt`](https://github.com/ashhart/TensorFold/blob/v0.6.6/src/tensorfold/families/nemotron_h/draft_ids.txt). -The native engine embeds its own 49,152-ID list, `zig/src/families/nemotron/draft_ids.txt`, on Metal and CUDA; the -rebuild below does not produce it. +The native engine embeds its own 49,152-ID list, `zig/src/families/nemotron/draft_ids.txt`, on Metal, CUDA and HIP; +the rebuild below does not produce it. The shipped `draft_ids.txt` contains 32,768 sorted IDs. It can be rebuilt byte for byte from CPython 3.14.5's standard-library Python files, excluding `site-packages`, plus tracked Python and Markdown @@ -233,3 +233,33 @@ with 4,096 reply tokens takes 13 pages (45.5 MiB) instead of a whole window. A r until a stream ends. The attention kernels read the pages through a table at a fixed device address, so the graphs keep their addresses. The startup line shows the pool. `TF_KV_PAGES=0` gives every stream a window again; `TF_KV_PAGES=all` puts every stream on pages (for checks). + +## Native HIP on a Strix Halo iGPU + +The native HIP build serves `TensorFold/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-MLX-4bit` (`d9d758fb`, MLX affine 4-bit +in groups of 64 with `mtp-4bit.safetensors`) on gfx1151 (AMD Ryzen AI MAX+ 395, Radeon 8060S, 128 GB unified +LPDDR5X-8000, 512 MiB carve-out + 115 GiB GTT). At `--context 131072 --parallel 4 --prompt-cache-gib 0`, it plans +17.34 GiB of model weights plus 1.15 GiB per stream (24.42 GiB GTT in use after load), runs 4-row verify windows with +up to 3 MTP drafts sized by measured costs, prefills prompts in 2,048-row chunks (`prefill_step=4096` default +clamped to the family's chunk width), and replays captured round graphs on lone-stream rounds. `--mtp-drafts` caps +the draft count at up to 3. `--mtp-confidence` and mixed-width oQ checkpoints are refused by name on main. + +```bash +zig build native-hip -Dhip=true -Dhip-arch=gfx1151 -Dhipcc=/usr/bin/hipcc -Doptimize=ReleaseFast +TENSORFOLD_MEMORY_RESERVE_GIB=4 ./zig-out/native-hip/bin/tensorfold-native serve \ + ./NVIDIA-Nemotron-3.5-Lightning-30B-A3B-MLX-4bit --context 131072 --parallel 4 --prompt-cache-gib 0 +``` + +Measured on TensorFold `6c5cef894` (HIP 7.1, clang 21, Zig 0.17.0, power mode `performance`, fresh servers with the page +cache dropped before each run; `tools/bench_openai.py --tokens 256 --reps 3`, +`tools/bench_concurrent.py --levels 1,2,4 --reps 3 --alone --serial --temperatures 1.0,0 --prompts tools/bench_prompts.json`, +and `tools/bench_cache.py --require-cold --tokens 16 --repeats 1` over raw Nemotron-tokenized prompts; two full +servers plus one `--no-drafts` server): + +| Workload | Metric | T=1.0 | T=0 | Notes | +|---|---|---|---|---| +| `bench_openai` code (drafts on) | median tok/s | 117.1 / 117.1 | 122.7 / 124.6 | 2.78 / 2.84 (`T=1.0`) and 2.84 / 2.56 (`T=0`) tokens/round | +| `bench_openai` chat (drafts on) | median tok/s | 92.4 / 91.8 | 99.0 / 98.5 | 1.68 (`T=1.0`) and 1.84 (`T=0`) tokens/round | +| `bench_openai` code / chat (`--no-drafts`) | median tok/s | 86.2 / 86.1 | 87.9 / 87.9 | 1.00 token/round (1.828 GB read/token, ~160.7 GB/s greedy) | +| `bench_concurrent` 1 / 2 / 4 streams | aggregate tok/s | 124.4 / 136.0-137.0 / 168.4-168.9 | 131.5-132.4 / 146.5 / 175.5-176.4 | 84/84 concurrent=alone; 48/48 alone=`"draft": false` | +| `bench_cache` 2,048 / 7,099 / 28,333 tokens | cold TTFT (s) | — | 0.731-0.732 / 2.672-2.676 / 13.130-13.205 | 2,797-2,800 / 2,653-2,657 / 2,146-2,158 tok/s (repeated cold) | diff --git a/docs/recipes/qwen3.8-flash-next.md b/docs/recipes/qwen3.8-flash-next.md index 5aeacfa3660..e0bc830e067 100644 --- a/docs/recipes/qwen3.8-flash-next.md +++ b/docs/recipes/qwen3.8-flash-next.md @@ -58,11 +58,12 @@ the lane matmul; M1 through M4 use the per-row projection and hyper-connection k restore recurrent state, n-gram history and attention state, including incomplete pooled blocks. The load-time row check disables drafting when windows do not reproduce serial steps. -`TF_FLASHNEXT_SCALE_INDEX=1` (off by default; M1 through M4, 4-bit experts in groups of 32) has the expert kernels read -each group's scale and bias through a 16-bit index into its tensor's table of distinct pairs, built at load. The -kernels get the same two values from 10% fewer weight bytes, so every reply keeps its tokens. Prompt passes still read -the stored scales and biases, so the index is held beside them. The setting does nothing with tensor units, -`--ssd-experts` or speed-up mode, and a tensor with more than 65,536 distinct pairs turns it off with a warning. +On M1 through M4, expert projections stored at 4 bits in groups of 32 are read through a scale index: at load each +tensor's (scale, bias) pairs become a table and a 16-bit index a group, and the decode, grouped and prompt-gather +expert kernels read each group's pair through it. They get the same two values from 10% fewer weight bytes, so every +reply keeps its tokens, and the routed experts' stored scales and biases are released once indexed. +`TF_FLASHNEXT_SCALE_INDEX=0` keeps and reads the stored arrays instead. The index is not built with tensor units or +`--ssd-experts`, nor for 6-bit packs, and a tensor with more than 65,536 distinct pairs turns it off with a warning. On M1 through M4, a decode window of five rows or more runs its 4-bit experts grouped by expert: rows that picked the same expert share its launch, so a copy or repeat stretch reads each expert's weights once instead of once a diff --git a/tools/zig/template_parity.py b/tools/zig/template_parity.py index 59410fa82ce..9dae96b7a1a 100644 --- a/tools/zig/template_parity.py +++ b/tools/zig/template_parity.py @@ -206,6 +206,12 @@ def assistant(text, **extra): "{{ ['b', 'a'] | sort | join }}{{ [{'n': 'b'}, {'n': 'a'}] | sort(attribute='n') | map(attribute='n') | join }}{{ [{'n': 1}] | map(attribute='m', default='d') | join }}", "{% for x in 'ab' %}{{ x }}{{ loop.index0 }}{% endfor %}|{% for k in {'p': 1, 'q': 2} %}{{ k }}{% endfor %}|{% for x in none %}{% endfor %}", "{%- for m in messages -%}\n {%- set content = m.content | trim -%}\n {{- '<' + m.role + '>' + content -}}\n{%- endfor %}\nx", + "{{ '0.5'|float }}|{{ 3|float }}|{{ 'abc'|float }}|{{ 'abc'|float(2.5) }}|{{ true|float }}|{{ ' 7 '|float }}|{{ none|float }}|{{ 0.9|float }}|{{ '1e3'|float }}|{{ ''|float }}|{{ '0x10'|float }}", + "{{ '1_0'|float }}|{{ '1__0'|float }}|{{ '_1'|float }}|{{ '1_'|float }}|{{ '1_0.5_5'|float }}|{{ [1]|float }}|{{ {}|float(7) }}|{{ 'x'|float(default=2.5) }}", + "{{ '1.'|float }}|{{ '.5'|float }}|{{ '+3'|float }}|{{ '-0'|float }}|{{ 'inf'|float }}|{{ 'nan'|float }}|{{ '1e'|float }}|{{ '1e1_0'|float }}|{{ '1_.5'|float }}", + "{{ 1|float(2, 3) }}", + "{{ 1|float(boolean=true) }}", + "{{ undefined_name|float }}", ] # Jinja2 features the native engine refuses on purpose; parity here means the native render fails loudly. UNSUPPORTED = [ diff --git a/zig/build/cuda.zig b/zig/build/cuda.zig index 6c77cec0c68..c2e027ffb79 100644 --- a/zig/build/cuda.zig +++ b/zig/build/cuda.zig @@ -353,7 +353,7 @@ pub fn hostTests(b: *std.Build, draft_ids: *std.Build.Module, build_options: *st const open_object = b.addObject(.{ .name = "omni-video-native-compile", .root_module = b.createModule(.{ .root_source_file = b.path("zig/tests/omni_video_compile.zig"), .target = cuda_target, .link_libc = true, .imports = &.{.{ .name = "native", .module = compile_modules.engines }} }) }); _ = open_object.getEmittedBin(); b.step("compile-omni-video-host", "Compile actual native CUDA startup and offer for Linux without images or GPU execution").dependOn(&open_object.step); - const h3_checkpoint = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/checkpoint.zig"), .target = host, .optimize = .debug, .link_libc = true, .imports = &.{.{ .name = "safetensors", .module = @import("h3_host.zig").safetensors(b, host) }} }); + const h3_checkpoint = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/checkpoint.zig"), .target = host, .optimize = .debug, .link_libc = true, .imports = &.{.{ .name = "core", .module = @import("h3_host.zig").coreModule(b, host) }} }); // the checkpoint maps its file with mmap: not Windows if (host.result.os.tag != .windows) step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = h3_checkpoint })).step); @import("pull_tests.zig").add(b, host, .debug, native_modules.engines, mods.core, step); diff --git a/zig/build/cuda_family_host.zig b/zig/build/cuda_family_host.zig index f8e304e1b19..b819922aed6 100644 --- a/zig/build/cuda_family_host.zig +++ b/zig/build/cuda_family_host.zig @@ -23,6 +23,9 @@ pub fn steps(b: *std.Build, cuda: *std.Build.Module, mods: anytype, step: *std.B const prefill = b.addRunArtifact(b.addTest(.{ .root_module = mods.qwen35, .filters = &.{ "Qwen stepped prefill:", "Qwen whole prefill:", "Qwen prefill opening:", "a yielded pass keeps its completed prefix" } })); b.step("test-qwen35-prefill-host", "Stepped, whole, opening and interrupted prompt lifecycle without devices").dependOn(&prefill.step); step.dependOn(&prefill.step); + const warm_turns = b.addRunArtifact(b.addTest(.{ .root_module = mods.qwen35, .filters = &.{"Qwen warm turns:"} })); + b.step("test-qwen35-warm-turns-host", "Qwen3.5's warm turn wait and usable ends declared for both CUDA entry points without devices").dependOn(&warm_turns.step); + step.dependOn(&warm_turns.step); const draft_config = b.addRunArtifact(b.addTest(.{ .root_module = mods.qwen35, .filters = &.{"Qwen DFlash2 config:"} })); b.step("test-qwen35-draft-config-host", "DFlash2 attention declarations agree with the CUDA kernels before loading").dependOn(&draft_config.step); step.dependOn(&draft_config.step); @@ -216,6 +219,9 @@ pub fn steps(b: *std.Build, cuda: *std.Build.Module, mods: anytype, step: *std.B pub fn registerCopyFamilies(b: *std.Build, native: *std.Build.Module, step: *std.Build.Step) void { b.step("test-glm-formats-host", "CUDA GLM EXL3 offer reaches the published family registry without a GPU").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = native, .filters = &.{"GLM capabilities:"} })).step); b.step("test-request-starts-host", "Opt-in CUDA message starts without GPU execution").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = native, .filters = &.{"request starts:"} })).step); + const warm_rules = b.addRunArtifact(b.addTest(.{ .root_module = native, .filters = &.{"CUDA warm rules:"} })); + b.step("test-cuda-warm-rules-host", "A family's warm rules and its own quiet wait without devices").dependOn(&warm_rules.step); + step.dependOn(&warm_rules.step); b.step("test-glm-window-prices-host", "GLM timed lone and unchanged shared price values without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = native, .filters = &.{"GLM window prices:"} })).step); const family_copies = b.addRunArtifact(b.addTest(.{ .root_module = native, .filters = &.{"CUDA lane copies:"} })); b.step("test-family-copies-host", "Actual CUDA family copy policies through the lane core").dependOn(&family_copies.step); diff --git a/zig/build/cuda_server_host.zig b/zig/build/cuda_server_host.zig index f9597f0ec19..9c8f9480a1f 100644 --- a/zig/build/cuda_server_host.zig +++ b/zig/build/cuda_server_host.zig @@ -71,6 +71,8 @@ pub fn steps(b: *std.Build, host: std.Build.ResolvedTarget, cuda: *std.Build.Mod 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-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); const server_test = b.addRunArtifact(b.addTest(.{ .root_module = server_tests })); + // the 512 KiB grammar limit: a sent grammar by its text, tools by the grammar for one call (#3038) + b.step("test-grammar-size-host", "Grammar and tool size limits before compiling, with the fake grammar library").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{ "a grammar over the size limit", "tools count once" } })).step); @import("request_starts_host.zig").steps(b, native_modules.engines, server_tests); const json_test = b.addRunArtifact(b.addTest(.{ .root_module = server_json })); const publication = b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{"benchmark publication:"} })); diff --git a/zig/build/h3_host.zig b/zig/build/h3_host.zig index 9c2283030dc..f494dd5347b 100644 --- a/zig/build/h3_host.zig +++ b/zig/build/h3_host.zig @@ -2,8 +2,8 @@ const std = @import("std"); pub fn tests(b: *std.Build, target: std.Build.ResolvedTarget, test_step: *std.Build.Step) void { - const st = b.createModule(.{ .root_source_file = b.path("zig/src/core/safetensors.zig"), .target = target }); - const root = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/geometry_test.zig"), .target = target, .imports = &.{.{ .name = "safetensors", .module = st }} }); + const core = coreModule(b, target); + const root = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/geometry_test.zig"), .target = target, .imports = &.{.{ .name = "core", .module = core }} }); const filter = b.option([]const u8, "h3-filter", "Run one H3 host regression"); const cases = b.addTest(.{ .root_module = root, .filters = if (filter) |f| &.{f} else &.{} }); const run = b.addRunArtifact(cases); @@ -18,16 +18,25 @@ pub fn tests(b: *std.Build, target: std.Build.ResolvedTarget, test_step: *std.Bu @import("h3_image_encoder.zig").compileHost(b, target, metal); const sources = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/sources.zig") }); const kernels = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/h3/kernels.zig") }); - const model = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/h3.zig"), .target = target, .optimize = .Debug, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "safetensors", .module = st }, .{ .name = "kernel_sources", .module = sources }, .{ .name = "h3_kernels", .module = kernels }, .{ .name = "gpu_turn", .module = b.createModule(.{ .root_source_file = b.path("zig/src/server/gpu_turn.zig"), .target = target }) } } }); + const model = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/h3.zig"), .target = target, .optimize = .Debug, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "core", .module = core }, .{ .name = "kernel_sources", .module = sources }, .{ .name = "h3_kernels", .module = kernels }, .{ .name = "gpu_turn", .module = b.createModule(.{ .root_source_file = b.path("zig/src/server/gpu_turn.zig"), .target = target }) } } }); const tool = b.addExecutable(.{ .name = "tf-h3-host-compile", .root_module = b.createModule(.{ .root_source_file = b.path("zig/tests/h3_dit.zig"), .target = target, .optimize = .Debug, .link_libc = true, .imports = &.{ .{ .name = "h3", .module = model }, .{ .name = "metal", .module = metal } } }) }); - const picture_tool = b.addExecutable(.{ .name = "tf-h3-image-host-compile", .root_module = b.createModule(.{ .root_source_file = b.path("zig/tests/h3_image.zig"), .target = target, .optimize = .Debug, .link_libc = true, .imports = &.{ .{ .name = "h3", .module = model }, .{ .name = "metal", .module = metal }, .{ .name = "safetensors", .module = st }, .{ .name = "checkpoint_fixture", .module = b.createModule(.{ .root_source_file = b.path("zig/src/core/checkpoint_fixture.zig"), .target = target }) } } }) }); + const picture_tool = b.addExecutable(.{ .name = "tf-h3-image-host-compile", .root_module = b.createModule(.{ .root_source_file = b.path("zig/tests/h3_image.zig"), .target = target, .optimize = .Debug, .link_libc = true, .imports = &.{ .{ .name = "h3", .module = model }, .{ .name = "metal", .module = metal }, .{ .name = "core", .module = core }, .{ .name = "checkpoint_fixture", .module = fixture(b, core) } } }) }); const compile = b.step("compile-h3-host", "Compile the actual H3 tools (tf-h3-dit, tf-h3-image) without compiling or executing shaders"); compile.dependOn(&tool.step); compile.dependOn(&picture_tool.step); - const modulation = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/modulation.zig"), .target = target, .optimize = .Debug, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "safetensors", .module = st }, .{ .name = "kernel_sources", .module = sources }, .{ .name = "h3_kernels", .module = kernels } } }); + const modulation = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/modulation.zig"), .target = target, .optimize = .Debug, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "core", .module = core }, .{ .name = "kernel_sources", .module = sources }, .{ .name = "h3_kernels", .module = kernels } } }); const rounding = b.addRunArtifact(b.addTest(.{ .root_module = modulation, .filters = &.{"modulation bf16:"} })); b.step("test-h3-modulation-bf16", "H3's host bf16 rounding against the copy it replaced, no GPU").dependOn(&rounding.step); test_step.dependOn(&rounding.step); + const ahead = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/read_ahead.zig"), .target = target, .optimize = .Debug, .link_libc = true, .imports = &.{.{ .name = "core", .module = core }} }); + const read_test = b.addTest(.{ .root_module = ahead }); + const read_step = b.step("test-h3-read-ahead", "H3 whole-shard reads, truncated or missing files, and prefetch disabled"); + for ([_][]const u8{ "16", "0" }) |count| { + const reads = b.addRunArtifact(read_test); + reads.setEnvironmentVariable("TF_LOAD_PREFETCH", count); + read_step.dependOn(&reads.step); + } + test_step.dependOn(read_step); } pub fn targets(b: *std.Build, cuda: *std.Build.Module, all: *std.Build.Step) void { @@ -56,7 +65,7 @@ pub fn targets(b: *std.Build, cuda: *std.Build.Module, all: *std.Build.Step) voi } fn module(b: *std.Build, target: std.Build.ResolvedTarget, cuda: *std.Build.Module) *std.Build.Module { - const m = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/cuda_lib.zig"), .target = target, .optimize = .debug, .link_libc = true, .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "safetensors", .module = safetensors(b, target) } } }); + const m = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/cuda_lib.zig"), .target = target, .optimize = .debug, .link_libc = true, .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "core", .module = coreModule(b, target) } } }); m.addAnonymousImport("fatbin_h3", .{ .root_source_file = b.addWriteFiles().add("h3-compile-only.fatbin", "") }); m.addCSourceFile(.{ .file = b.path("zig/tests/cuda/h3_abi_test.c"), .flags = &.{"-std=c11"} }); return m; @@ -75,13 +84,19 @@ pub fn library(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu .target = target, .optimize = optimize, .link_libc = true, - .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "safetensors", .module = safetensors(b, target) } }, + .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "core", .module = coreModule(b, target) } }, }) }); lib.root_module.addAnonymousImport("fatbin_h3", .{ .root_source_file = image }); step.dependOn(&b.addInstallArtifact(lib, .{}).step); } -/// core's safetensors reader alone, for the CUDA side's checkpoint (h3/checkpoint.zig). -pub fn safetensors(b: *std.Build, target: std.Build.ResolvedTarget) *std.Build.Module { - return b.createModule(.{ .root_source_file = b.path("zig/src/core/safetensors.zig"), .target = target }); +/// The core files H3 reads, for every H3 module (core/h3_core.zig). +pub fn coreModule(b: *std.Build, target: std.Build.ResolvedTarget) *std.Build.Module { + return b.createModule(.{ .root_source_file = b.path("zig/src/core/h3_core.zig"), .target = target, .link_libc = true }); +} + +/// `checkpoint_fixture` for a tool that also holds `core`, which owns the fixture's file. +pub fn fixture(b: *std.Build, core: *std.Build.Module) *std.Build.Module { + const file = b.addWriteFiles().add("h3_fixture_alias.zig", "pub const Entry = f.Entry;\npub const image = f.image;\npub const aligned = f.aligned;\npub const write = f.write;\nconst f = @import(\"core\").checkpoint_fixture;\n"); + return b.createModule(.{ .root_source_file = file, .imports = &.{.{ .name = "core", .module = core }} }); } diff --git a/zig/build/h3_image_cuda.zig b/zig/build/h3_image_cuda.zig index 8d2458b2060..1939c198436 100644 --- a/zig/build/h3_image_cuda.zig +++ b/zig/build/h3_image_cuda.zig @@ -5,19 +5,19 @@ const std = @import("std"); pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, opts: @import("options.zig").Cuda, test_step: *std.Build.Step) void { const image = if (opts.nvcc) |nvcc| @import("cuda_fatbin.zig").fatbin(b, nvcc, b.addSystemCommand(&.{ nvcc, "--version" }).captureStdOut(.{}), .{ .name = "h3", .flags = &.{"-O3"} }, opts.sms) else b.addWriteFiles().add("h3-compile-only.fatbin", ""); const cuda = @import("cuda.zig").runtime(b, target, optimize, &.{}); - const st = @import("h3_host.zig").safetensors(b, target); - const h3 = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/cuda.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "safetensors", .module = st } } }); + const core = @import("h3_host.zig").coreModule(b, target); + const h3 = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/cuda.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "core", .module = core } } }); h3.addAnonymousImport("fatbin_h3", .{ .root_source_file = image }); const modulation = if (opts.nvcc) |nvcc| @import("cuda_fatbin.zig").fatbin(b, nvcc, b.addSystemCommand(&.{ nvcc, "--version" }).captureStdOut(.{}), .{ .name = "h3_image_modulation", .flags = &.{ "-O3", "--fmad=false" } }, opts.sms) else b.addWriteFiles().add("h3-modulation-compile-only.fatbin", ""); h3.addAnonymousImport("fatbin_h3_modulation", .{ .root_source_file = modulation }); const exe = b.addExecutable(.{ .name = "tf-h3-image-cuda", .root_module = b.createModule(.{ .root_source_file = b.path("zig/tests/h3_image_cuda.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "h3cuda", .module = h3 }, - .{ .name = "safetensors", .module = st }, + .{ .name = "core", .module = core }, } }) }); b.step("tf-h3-image-cuda", "MiniMax-H3-Image's free run: a prompt case to a latent on the CUDA transformer blocks").dependOn(&b.addInstallArtifact(exe, .{}).step); // the host ports' hand-checked values, and the sharded checkpoint reader, no GPU anywhere - const ports = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/rows_reference.zig"), .target = b.graph.host, .imports = &.{.{ .name = "safetensors", .module = @import("h3_host.zig").safetensors(b, b.graph.host) }} }); + const ports = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/rows_reference.zig"), .target = b.graph.host, .imports = &.{.{ .name = "core", .module = @import("h3_host.zig").coreModule(b, b.graph.host) }} }); b.step("test-h3-image-cuda-host", "The host ports of the H3 row kernels and the shard reader, no GPU").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = ports })).step); - test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/checkpoint.zig"), .target = b.graph.host, .imports = &.{.{ .name = "safetensors", .module = @import("h3_host.zig").safetensors(b, b.graph.host) }} }) })).step); + test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/checkpoint.zig"), .target = b.graph.host, .imports = &.{.{ .name = "core", .module = @import("h3_host.zig").coreModule(b, b.graph.host) }} }) })).step); } diff --git a/zig/build/h3_image_decoder.zig b/zig/build/h3_image_decoder.zig index e1e1c803da7..7912c786005 100644 --- a/zig/build/h3_image_decoder.zig +++ b/zig/build/h3_image_decoder.zig @@ -2,16 +2,16 @@ const std = @import("std"); /// The decoder on the CPU (image_decoder_host.zig): the reference chain over tiles, the PNG writer. -fn host(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, st: *std.Build.Module, writer: *std.Build.Module) *std.Build.Module { - return b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/image_decoder_host.zig"), .target = target, .optimize = optimize, .imports = &.{ .{ .name = "safetensors", .module = st }, .{ .name = "picture_writer", .module = writer } } }); +fn host(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, core: *std.Build.Module, writer: *std.Build.Module) *std.Build.Module { + return b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/image_decoder_host.zig"), .target = target, .optimize = optimize, .imports = &.{ .{ .name = "core", .module = core }, .{ .name = "picture_writer", .module = writer } } }); } /// The tool on `metal`: the decoder and its kernels' source, and the picture writer (PNG and resampler). fn module(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, metal: *std.Build.Module) *std.Build.Module { - const st = b.createModule(.{ .root_source_file = b.path("zig/src/core/safetensors.zig"), .target = target, .optimize = optimize }); + const core = @import("h3_host.zig").coreModule(b, target); const kernels = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/h3/image_decoder.zig") }); const writer = b.createModule(.{ .root_source_file = b.path("zig/src/picture_writer.zig"), .target = target, .optimize = optimize }); - const decoder = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/image_decoder_metal.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "safetensors", .module = st }, .{ .name = "h3_image_decoder_kernels", .module = kernels }, .{ .name = "picture_writer", .module = writer }, .{ .name = "gpu_turn", .module = b.createModule(.{ .root_source_file = b.path("zig/src/server/gpu_turn.zig"), .target = target, .optimize = optimize }) } } }); + const decoder = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/image_decoder_metal.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "core", .module = core }, .{ .name = "h3_image_decoder_kernels", .module = kernels }, .{ .name = "picture_writer", .module = writer }, .{ .name = "gpu_turn", .module = b.createModule(.{ .root_source_file = b.path("zig/src/server/gpu_turn.zig"), .target = target, .optimize = optimize }) } } }); return b.createModule(.{ .root_source_file = b.path("zig/tests/h3_image_decoder.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "h3_image_decoder", .module = decoder } } }); } @@ -35,13 +35,13 @@ pub fn compileHost(b: *std.Build, target: std.Build.ResolvedTarget) void { /// `zig build tf-h3-image-decoder-host` (any target, no GPU), and its tiling/blend regression on this host. pub fn hostSteps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, test_step: *std.Build.Step) void { - const st = b.createModule(.{ .root_source_file = b.path("zig/src/core/safetensors.zig"), .target = target }); + const core = @import("h3_host.zig").coreModule(b, target); const writer = b.createModule(.{ .root_source_file = b.path("zig/src/picture_writer.zig"), .target = target, .optimize = optimize }); - const exe = b.addExecutable(.{ .name = "tf-h3-image-decoder-host", .root_module = b.createModule(.{ .root_source_file = b.path("zig/tests/h3_image_decoder_host.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "h3_image_decoder_host", .module = host(b, target, optimize, st, writer) }} }) }); + const exe = b.addExecutable(.{ .name = "tf-h3-image-decoder-host", .root_module = b.createModule(.{ .root_source_file = b.path("zig/tests/h3_image_decoder_host.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "h3_image_decoder_host", .module = host(b, target, optimize, core, writer) }} }) }); b.step("tf-h3-image-decoder-host", "MiniMax-H3-Image's image decoder on the CPU: a latent to a PNG, no GPU").dependOn(&b.addInstallArtifact(exe, .{}).step); const native = b.graph.host; const cases = b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/image_decoder_host_test.zig"), .target = native, .optimize = .ReleaseFast, .imports = &.{ - .{ .name = "safetensors", .module = b.createModule(.{ .root_source_file = b.path("zig/src/core/safetensors.zig"), .target = native }) }, + .{ .name = "core", .module = @import("h3_host.zig").coreModule(b, native) }, .{ .name = "picture_writer", .module = b.createModule(.{ .root_source_file = b.path("zig/src/picture_writer.zig"), .target = native }) }, } }) }); const run = b.addRunArtifact(cases); diff --git a/zig/build/h3_image_decoder_cuda.zig b/zig/build/h3_image_decoder_cuda.zig index 7d41fb5b6b4..3c59229649a 100644 --- a/zig/build/h3_image_decoder_cuda.zig +++ b/zig/build/h3_image_decoder_cuda.zig @@ -5,9 +5,9 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil // no FMA contraction: the norms', attention's and SwiGLU's fp32 multiply-adds round as the host reference's do const image = if (opts.nvcc) |nvcc| @import("cuda_fatbin.zig").fatbin(b, nvcc, b.addSystemCommand(&.{ nvcc, "--version" }).captureStdOut(.{}), .{ .name = "h3_image_decoder", .flags = &.{ "-O3", "--fmad=false" }, .min_sm = 80 }, opts.sms) else b.addWriteFiles().add("h3-image-decoder-compile-only.fatbin", ""); const cuda = @import("cuda.zig").runtime(b, target, optimize, &.{}); - const st = @import("h3_host.zig").safetensors(b, target); + const core = @import("h3_host.zig").coreModule(b, target); const writer = b.createModule(.{ .root_source_file = b.path("zig/src/picture_writer.zig"), .target = target, .optimize = optimize }); - const decoder = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/image_decoder_cuda.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "safetensors", .module = st }, .{ .name = "picture_writer", .module = writer } } }); + const decoder = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/image_decoder_cuda.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "core", .module = core }, .{ .name = "picture_writer", .module = writer } } }); decoder.addAnonymousImport("fatbin_h3_image_decoder", .{ .root_source_file = image }); const exe = b.addExecutable(.{ .name = "tf-h3-image-decoder-cuda", .root_module = b.createModule(.{ .root_source_file = b.path("zig/tests/h3_image_decoder_cuda.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "h3_image_decoder_cuda", .module = decoder }, diff --git a/zig/build/h3_image_encoder.zig b/zig/build/h3_image_encoder.zig index 22eb497a781..e55dfbd6dbc 100644 --- a/zig/build/h3_image_encoder.zig +++ b/zig/build/h3_image_encoder.zig @@ -2,9 +2,9 @@ const std = @import("std"); fn module(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, metal: *std.Build.Module) *std.Build.Module { - const st = b.createModule(.{ .root_source_file = b.path("zig/src/core/safetensors.zig"), .target = target, .optimize = optimize }); + const core = @import("h3_host.zig").coreModule(b, target); const kernels = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/h3/image_encoder.zig") }); - const encoder = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/image_encoder.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "safetensors", .module = st }, .{ .name = "h3_image_encoder_kernels", .module = kernels } } }); + const encoder = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/image_encoder.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "core", .module = core }, .{ .name = "h3_image_encoder_kernels", .module = kernels } } }); const codec = b.createModule(.{ .root_source_file = b.path("zig/src/core/picture/picture.zig"), .target = target, .optimize = optimize, .link_libc = true }); const noise = b.createModule(.{ .root_source_file = b.path("zig/src/families/moss_image/noise.zig"), .target = target, .optimize = optimize }); return b.createModule(.{ .root_source_file = b.path("zig/tests/h3_image_encoder.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "h3_image_encoder", .module = encoder }, .{ .name = "picture_codec", .module = codec }, .{ .name = "torch_noise", .module = noise } } }); diff --git a/zig/build/h3_image_prompt.zig b/zig/build/h3_image_prompt.zig index 967381b9a35..b57d8e60d3c 100644 --- a/zig/build/h3_image_prompt.zig +++ b/zig/build/h3_image_prompt.zig @@ -31,10 +31,10 @@ pub fn install(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu } fn tool(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, metal: *std.Build.Module) *std.Build.Module { - const st = b.createModule(.{ .root_source_file = b.path("zig/src/core/safetensors.zig"), .target = target, .optimize = optimize }); + const core = @import("h3_host.zig").coreModule(b, target); const kernels = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/h3/prompt_kernels.zig") }); - const fixture = b.createModule(.{ .root_source_file = b.path("zig/src/core/checkpoint_fixture.zig"), .target = target, .optimize = optimize }); - const prompt = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/prompt.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "safetensors", .module = st }, .{ .name = "h3_prompt_kernels", .module = kernels }, .{ .name = "qwen_vl_rope", .module = rope(b, target) }, .{ .name = "checkpoint_fixture", .module = fixture }, .{ .name = "picture", .module = picture(b, target) }, .{ .name = "gpu_turn", .module = b.createModule(.{ .root_source_file = b.path("zig/src/server/gpu_turn.zig"), .target = target, .optimize = optimize }) } } }); + const fixture = @import("h3_host.zig").fixture(b, core); + const prompt = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/prompt.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "core", .module = core }, .{ .name = "h3_prompt_kernels", .module = kernels }, .{ .name = "qwen_vl_rope", .module = rope(b, target) }, .{ .name = "checkpoint_fixture", .module = fixture }, .{ .name = "picture", .module = picture(b, target) }, .{ .name = "gpu_turn", .module = b.createModule(.{ .root_source_file = b.path("zig/src/server/gpu_turn.zig"), .target = target, .optimize = optimize }) } } }); const tokenizer = b.createModule(.{ .root_source_file = b.path("zig/src/core/tokenizer/tokenizer.zig"), .target = target, .optimize = optimize, .link_libc = true }); return b.createModule(.{ .root_source_file = b.path("zig/tests/h3_image_prompt.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "h3_prompt", .module = prompt }, .{ .name = "tokenizer", .module = tokenizer }, .{ .name = "checkpoint_fixture", .module = fixture }, .{ .name = "moss_noise", .module = b.createModule(.{ .root_source_file = b.path("zig/src/families/moss_image/noise.zig"), .target = target, .optimize = optimize }) } } }); } diff --git a/zig/build/h3_image_prompt_cuda.zig b/zig/build/h3_image_prompt_cuda.zig index 13eefaad27d..cd4593d26d6 100644 --- a/zig/build/h3_image_prompt_cuda.zig +++ b/zig/build/h3_image_prompt_cuda.zig @@ -10,8 +10,8 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil else b.addWriteFiles().add("h3-image-prompt-compile-only.fatbin", ""); const cuda = @import("cuda.zig").runtime(b, target, optimize, &.{}); - const st = b.createModule(.{ .root_source_file = b.path("zig/src/core/safetensors.zig"), .target = target, .optimize = optimize }); - const fixture = b.createModule(.{ .root_source_file = b.path("zig/src/core/checkpoint_fixture.zig"), .target = target, .optimize = optimize }); + const core = @import("h3_host.zig").coreModule(b, target); + const fixture = @import("h3_host.zig").fixture(b, core); const rope = @import("h3_image_prompt.zig").rope(b, target); const prompt = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/prompt_cuda.zig"), @@ -20,7 +20,7 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil .link_libc = true, .imports = &.{ .{ .name = "cuda", .module = cuda }, - .{ .name = "safetensors", .module = st }, + .{ .name = "core", .module = core }, .{ .name = "qwen_vl_rope", .module = rope }, .{ .name = "checkpoint_fixture", .module = fixture }, }, diff --git a/zig/build/h3_image_prompt_host.zig b/zig/build/h3_image_prompt_host.zig index 45f8359e514..d3c5b67813c 100644 --- a/zig/build/h3_image_prompt_host.zig +++ b/zig/build/h3_image_prompt_host.zig @@ -27,6 +27,7 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil /// The tool's module: the prompt path's host pieces (its Metal-only parts stay unanalyzed), the host checkpoint /// reader, the tokenizer and torch's randn. fn tool(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode) *std.Build.Module { + const core = @import("h3_host.zig").coreModule(b, target); const host_prompt = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/prompt.zig"), .target = target, @@ -34,7 +35,7 @@ fn tool(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.O .link_libc = true, .imports = &.{ .{ .name = "qwen_vl_rope", .module = prompt.rope(b, target) }, - .{ .name = "checkpoint_fixture", .module = fixture(b, target, optimize) }, + .{ .name = "checkpoint_fixture", .module = @import("h3_host.zig").fixture(b, core) }, }, }); const checkpoint = b.createModule(.{ @@ -42,7 +43,7 @@ fn tool(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.O .target = target, .optimize = optimize, .link_libc = true, - .imports = &.{.{ .name = "safetensors", .module = b.createModule(.{ .root_source_file = b.path("zig/src/core/safetensors.zig"), .target = target, .optimize = optimize }) }}, + .imports = &.{.{ .name = "core", .module = core }}, }); return b.createModule(.{ .root_source_file = b.path("zig/tests/h3_image_prompt_host.zig"), diff --git a/zig/build/h3_image_server.zig b/zig/build/h3_image_server.zig index ba00c34db18..6a91e51a30a 100644 --- a/zig/build/h3_image_server.zig +++ b/zig/build/h3_image_server.zig @@ -3,15 +3,15 @@ const std = @import("std"); const prompt = @import("h3_image_prompt.zig"); pub fn tool(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, metal: *std.Build.Module, h3_kernels: *std.Build.Module, sources: *std.Build.Module, test_step: *std.Build.Step) void { - const st = b.createModule(.{ .root_source_file = b.path("zig/src/core/safetensors.zig"), .target = target, .optimize = optimize }); + const core = @import("h3_host.zig").coreModule(b, target); // core's picture files have one owner: the PNG writer, which the prompt path's Qwen copy reads them through const writer = b.createModule(.{ .root_source_file = b.path("zig/src/picture_writer.zig"), .target = target, .optimize = optimize, .link_libc = true }); // one fixture module for the image module's prompt case writer and the tool's edit entries - const fixture = b.createModule(.{ .root_source_file = b.path("zig/src/core/checkpoint_fixture.zig"), .target = target, .optimize = optimize }); + const fixture = @import("h3_host.zig").fixture(b, core); // one module over the transformer, prompt path and decoder: they share source files const image = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/image.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, - .{ .name = "safetensors", .module = st }, + .{ .name = "core", .module = core }, .{ .name = "h3_kernels", .module = h3_kernels }, .{ .name = "kernel_sources", .module = sources }, .{ .name = "h3_prompt_kernels", .module = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/h3/prompt_kernels.zig") }) }, @@ -27,7 +27,7 @@ pub fn tool(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.built .{ .name = "h3", .module = image }, .{ .name = "h3_prompt", .module = image }, .{ .name = "h3_image_decoder", .module = image }, - .{ .name = "safetensors", .module = st }, + .{ .name = "core", .module = core }, .{ .name = "tokenizer", .module = b.createModule(.{ .root_source_file = b.path("zig/src/core/tokenizer/tokenizer.zig"), .target = target, .optimize = optimize, .link_libc = true }) }, .{ .name = "checkpoint_fixture", .module = fixture }, .{ .name = "moss_noise", .module = b.createModule(.{ .root_source_file = b.path("zig/src/families/moss_image/noise.zig"), .target = target, .optimize = optimize }) }, diff --git a/zig/build/host_ci.zig b/zig/build/host_ci.zig index 70e53996817..02fce89473c 100644 --- a/zig/build/host_ci.zig +++ b/zig/build/host_ci.zig @@ -187,6 +187,7 @@ const linux_host = [_][]const u8{ "test-inc4-round-host", "test-inc4-rows-host", "test-kernel-seed-host", + "test-lane-explore-host", "test-lane-halt-host", "test-lane-interrupted-host", "test-lane-lone-host", @@ -280,6 +281,7 @@ const macos_adapters = [_][]const u8{ "test-flashnext-pack-cache", "test-gguf-linux-compile", "test-h3-modulation-bf16", + "test-h3-read-ahead", "test-masked-values-host", "test-metal-counters-host", "test-minimax-info-host", diff --git a/zig/build/lane_halt_host.zig b/zig/build/lane_halt_host.zig index 20c9ec1aba5..848782b113e 100644 --- a/zig/build/lane_halt_host.zig +++ b/zig/build/lane_halt_host.zig @@ -6,6 +6,13 @@ pub fn steps(b: *std.Build) void { const api = b.createModule(.{ .root_source_file = b.path("zig/src/core/engine_api.zig"), .target = b.graph.host, .optimize = .debug, .link_libc = true, .imports = &.{.{ .name = "lanes", .module = lanes }} }); const interrupted = b.createModule(.{ .root_source_file = b.path("zig/src/core/lane_host_interrupted_test.zig"), .target = b.graph.host, .optimize = .debug, .link_libc = true, .imports = &.{.{ .name = "lanes", .module = lanes }} }); b.step("test-lane-interrupted-host", "Interrupted prompt retention and clean retries without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = interrupted, .filters = &.{"interrupted prefill:"} })).step); + const seeds = b.addOptions(); // -Dexplore-seeds=N sweeps N schedules; -Dexplore-seed=S replays one + seeds.addOption(u32, "seeds", b.option(u32, "explore-seeds", "Schedules test-lane-explore-host runs a scenario") orelse 200); + seeds.addOption(?u64, "seed", b.option(u64, "explore-seed", "One lane host schedule to replay (a failure prints it)")); + seeds.addOption(bool, "tally", b.option(bool, "explore-tally", "Print what the explored schedules did") orelse false); + const explore = b.createModule(.{ .root_source_file = b.path("zig/src/core/lane_host_explore_test.zig"), .target = b.graph.host, .optimize = .debug, .link_libc = true, .imports = &.{.{ .name = "lanes", .module = lanes }} }); + explore.addOptions("explore_options", seeds); + b.step("test-lane-explore-host", "Lane host invariants under seeded arrivals, cancels, room and pressure, without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = explore, .filters = &.{"explore:"} })).step); const safe_lanes = b.createModule(.{ .root_source_file = b.path("zig/src/core/lanes/lanes.zig"), .target = b.graph.host, .optimize = .safe, .link_libc = true }); const strand = b.createModule(.{ .root_source_file = b.path("zig/src/core/lane_host_strand_test.zig"), .target = b.graph.host, .optimize = .safe, .link_libc = true, .imports = &.{.{ .name = "lanes", .module = safe_lanes }} }); b.step("test-lane-strand-host", "Refused, cancelled and failed requests give back every lane, page and slot without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = strand, .filters = &.{"lane strand:"} })).step); diff --git a/zig/build/metal_targets.zig b/zig/build/metal_targets.zig index dd521c63b04..0658d51b36a 100644 --- a/zig/build/metal_targets.zig +++ b/zig/build/metal_targets.zig @@ -429,8 +429,8 @@ pub fn metalTargets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: s // MiniMax H3 / FastH3's transformer: the packed rows' denoising forwards against a case file (M5 tensor units). const h3_kernels = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/h3/kernels.zig") }); - const h3_safetensors = b.createModule(.{ .root_source_file = b.path("zig/src/core/safetensors.zig"), .target = target, .optimize = optimize }); - const h3_mod = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/h3.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "safetensors", .module = h3_safetensors }, .{ .name = "h3_kernels", .module = h3_kernels }, .{ .name = "kernel_sources", .module = sources }, .{ .name = "gpu_turn", .module = b.createModule(.{ .root_source_file = b.path("zig/src/server/gpu_turn.zig"), .target = target, .optimize = optimize }) } } }); + const h3_core = @import("h3_host.zig").coreModule(b, target); + const h3_mod = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/h3.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "core", .module = h3_core }, .{ .name = "h3_kernels", .module = h3_kernels }, .{ .name = "kernel_sources", .module = sources }, .{ .name = "gpu_turn", .module = b.createModule(.{ .root_source_file = b.path("zig/src/server/gpu_turn.zig"), .target = target, .optimize = optimize }) } } }); const h3_dit = b.addExecutable(.{ .name = "tf-h3-dit", .root_module = b.createModule(.{ .root_source_file = b.path("zig/tests/h3_dit.zig"), .target = target, @@ -445,7 +445,7 @@ pub fn metalTargets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: s .target = target, .optimize = optimize, .link_libc = true, - .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "h3", .module = h3_mod }, .{ .name = "safetensors", .module = h3_safetensors }, .{ .name = "checkpoint_fixture", .module = b.createModule(.{ .root_source_file = b.path("zig/src/core/checkpoint_fixture.zig"), .target = target, .optimize = optimize }) } }, + .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "h3", .module = h3_mod }, .{ .name = "core", .module = h3_core }, .{ .name = "checkpoint_fixture", .module = @import("h3_host.zig").fixture(b, h3_core) } }, }) }); b.step("tf-h3-image", "MiniMax-H3-Image's Metal transformer on a picture case: six distilled steps, teacher-forced and gated").dependOn(&b.addInstallArtifact(h3_image, .{}).step); @import("h3_image_encoder.zig").tool(b, target, optimize, metal); diff --git a/zig/build/xpu.zig b/zig/build/xpu.zig index 88c14c82e38..85a9f272760 100644 --- a/zig/build/xpu.zig +++ b/zig/build/xpu.zig @@ -354,6 +354,12 @@ pub fn hostTests(b: *std.Build, step: *std.Build.Step) void { // xpu/safetensors.zig's own tests, on the same `core` const st_tests = b.createModule(.{ .root_source_file = b.path("zig/src/xpu/safetensors.zig"), .target = host, .imports = &.{.{ .name = "core", .module = core }} }); for ([_]*std.Build.Module{ xpu, mods.nemotron, cliModule(b, host, .debug, xpu, mods), zeModule(b, host, .debug), st_tests }) |m| step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = m })).step); + // the 27B runner's RoPE tables on core's rope_freq, printed beside the expressions they replaced + const rope = b.createModule(.{ .root_source_file = b.path("zig/src/xpu/rope_table.zig"), .target = host }); + rope.addImport("core", core); + const rope_tests = b.addRunArtifact(b.addTest(.{ .root_module = rope })); + b.step("test-rope-xpu-host", "The XPU 27B runner's RoPE tables on core's rope_freq, without devices or ocloc").dependOn(&rope_tests.step); + step.dependOn(&rope_tests.step); // the Gemma 4 E4B runner's admission, over the family config (which takes `core` by name) const gemma4 = b.createModule(.{ .root_source_file = b.path("zig/src/families/gemma4/xpu_config.zig"), .target = host, .optimize = .debug }); gemma4.addImport("core", core); diff --git a/zig/dense_serving_test.zig b/zig/dense_serving_test.zig index ad5cd3f2441..52ca01e701e 100644 --- a/zig/dense_serving_test.zig +++ b/zig/dense_serving_test.zig @@ -17,8 +17,8 @@ test "dense serving: owned CUDA images retain their reviewed lane and decode byt try std.testing.expectEqualStrings("ceff4ee13e97b5aa93cbe7a1edc9a524c78aaa145dd1e5c82dcb05a3011aae23", &hash(group[0..16095])); try std.testing.expectEqualStrings("8780fd710be3ce2f04e53fa1e69eb062809d3bec6391d9bd49983d0588e374d0", &hash(group)); try std.testing.expectEqualStrings("45ab2be277c7c17e6cdc6041db45611f2554c6e88f09a295e88751b1c51be1f5", &hash(@embedFile("kernels/cuda/qmm_prefill.cu"))); - // #2933's bytes: served one-row steps skip the rollback copy nothing reads (#2908); replies unchanged - try std.testing.expectEqualStrings("f16fa3d48336cfe7bcdc071ef791247d8ef3c06e26a9eaa95a54e1febd803332", &hash(@embedFile("kernels/cuda/qwen35.cu"))); + // the join variant's bytes: tf_q35_attn_rows_join for streams on shared pages; main's kernels' SASS unchanged + try std.testing.expectEqualStrings("77ac41e5764a79cca2313ecd09664479b8b4736747c79188e1ad5cae29fd03e4", &hash(@embedFile("kernels/cuda/qwen35.cu"))); // #1879's bytes: a comment names cuda_scratch.zig, where max_chunks moved; the code is unchanged try std.testing.expectEqualStrings("f9e4a040cf219aac8db211df25d264dba390fce4a7e8da45557652c6ff0f28ba", &hash(@embedFile("kernels/cuda/qwen35.cuh"))); // 67711a6aa7's bytes: the opt-in DSpine draft kernels (#2633); default serving unchanged diff --git a/zig/flashnext_host.zig b/zig/flashnext_host.zig index 01c153ccd96..0ad1612e341 100644 --- a/zig/flashnext_host.zig +++ b/zig/flashnext_host.zig @@ -7,6 +7,7 @@ test { _ = @import("src/families/flashnext/rows_w.zig"); _ = @import("src/families/flashnext/experts4.zig"); _ = @import("src/families/flashnext/scale_pairs.zig"); + _ = @import("src/families/flashnext/prompt_index_source.zig"); _ = @import("src/families/flashnext/tree.zig"); _ = @import("src/families/flashnext/gate.zig"); _ = @import("src/families/flashnext/gx.zig"); diff --git a/zig/kernels/cuda/qwen35.cu b/zig/kernels/cuda/qwen35.cu index 86fe27c82ca..3412166b1a2 100644 --- a/zig/kernels/cuda/qwen35.cu +++ b/zig/kernels/cuda/qwen35.cu @@ -550,6 +550,15 @@ extern "C" __global__ void __launch_bounds__(256) tf_q35_attn_rows(Geo geo, cons tf_q35_tc::attn_rows<4, tf_q35_tc::Bf16Tiles<256>>({attn_tiles, nullptr, nullptr, nullptr}, geo, Q, segs, rowseg, rowanc, layer, P, scale, total, PM, PL, PO); } +// tf_q35_attn_rows for a forward whose streams share pages (cuda_cache.anyShares): rows on one page run join. +extern "C" __global__ void __launch_bounds__(256) tf_q35_attn_rows_join(Geo geo, const __nv_bfloat16* __restrict__ Q, const Seg* __restrict__ segs, + const int* __restrict__ rowseg, const Ancestor* __restrict__ rowanc, int layer, + const int* __restrict__ P, float scale, int total, + float* __restrict__ PM, float* __restrict__ PL, float* __restrict__ PO) { + extern __shared__ __align__(16) uint4 attn_tiles[]; + tf_q35_tc::attn_rows<4, tf_q35_tc::Bf16Tiles<256>, true>({attn_tiles, nullptr, nullptr, nullptr}, geo, Q, segs, rowseg, rowanc, layer, P, scale, total, PM, PL, PO); +} + extern "C" __global__ void __launch_bounds__(128) tf_q35_attn_partial_whole(Geo geo, const __nv_bfloat16* __restrict__ Q, const Seg* __restrict__ segs, const int* __restrict__ rowseg, const Ancestor* __restrict__ rowanc, int layer, const int* __restrict__ P, float scale, diff --git a/zig/kernels/cuda/qwen35_attn_tc.cuh b/zig/kernels/cuda/qwen35_attn_tc.cuh index ee784b20d4a..e5dfbaa4b4c 100644 --- a/zig/kernels/cuda/qwen35_attn_tc.cuh +++ b/zig/kernels/cuda/qwen35_attn_tc.cuh @@ -197,8 +197,31 @@ __device__ __forceinline__ void attn_one(TileStore store, Geo geo, const __nv_bf } } +// A paged row's first page over [k0, k1) when it holds the span below its length (-1: it can't share it). +template +__device__ __forceinline__ int first_page(const Seg& sg, int k0, int k1) { + if constexpr (!Tiles::paged_layout) return -1; + else return sg.pt == 0 || k1 <= k0 || k1 > sg.len ? -1 : reinterpret_cast(sg.pt)[k0 / sg.ptok]; +} + +// Stream b's rows join a class of stream a's over [k0, k1): both hold the span below their length, in the same pages. +template +__device__ __forceinline__ bool same_pages(const Seg* __restrict__ segs, int a, int b, int k0, int k1, int k1b) { + if constexpr (!Tiles::paged_layout) return false; + else { + if (b < 0 || k1 != k1b || k1 <= k0) return false; + const Seg &sa = segs[a], &sb = segs[b]; + if (sa.pt == 0 || sb.pt == 0 || sa.kv != sb.kv || sa.ps != sb.ps || sa.ptok != sb.ptok) return false; + if (k1 > sa.len || k1 > sb.len) return false; + const int *pa = reinterpret_cast(sa.pt), *pb = reinterpret_cast(sb.pt); + for (int p = k0 / sa.ptok; p <= (k1 - 1) / sa.ptok; p++) + if (pa[p] != pb[p]) return false; + return true; + } +} + // RB rows a block (MT m16 tiles of query heads); a stream's rows of one chunk width read each key tile once. -template +template // JOIN: another stream's rows join over the same pages __device__ __forceinline__ void attn_rows(TileStore store, Geo geo, const __nv_bfloat16* __restrict__ Q, const Seg* __restrict__ segs, const int* __restrict__ rowseg, const Ancestor* __restrict__ rowanc, int layer, const int* __restrict__ P, float scale, int total, @@ -207,6 +230,8 @@ __device__ __forceinline__ void attn_rows(TileStore store, Geo geo, const __nv_b __shared__ __align__(16) __nv_bfloat16 pt[LINES][TK + 8]; __shared__ float red[2][LINES], alpha[LINES]; __shared__ int r_k0[32], r_k1[32], r_seg[32], r_ck[32]; + __shared__ int r_p0[32]; // JOIN: a paged row's first page over its chunk + __shared__ unsigned r_mate[32]; // JOIN: row i's class when it leads __shared__ Ancestor r_anc[32]; const int QH = geo.qh, KVH = geo.kvh, G = QH / KVH, RB = LINES / G; const int tid = threadIdx.x, warp = tid >> 5, lane = tid & 31, g = lane >> 2, qd = lane & 3; @@ -216,6 +241,7 @@ __device__ __forceinline__ void attn_rows(TileStore store, Geo geo, const __nv_b if (tid < RB) { const int m = m0 + tid; r_seg[tid] = -1; + if constexpr (JOIN) r_p0[tid] = -1; if (m < total && !past_rows(P, m) && segs[rowseg[m]].len >= GROUP_LEN) { const Seg sg = segs[rowseg[m]]; const Ancestor anc = rowanc[m]; @@ -225,6 +251,20 @@ __device__ __forceinline__ void attn_rows(TileStore store, Geo geo, const __nv_b r_k0[tid] = c * ck; r_k1[tid] = min(c * ck + ck, keys); r_anc[tid] = anc; + if constexpr (JOIN) r_p0[tid] = first_page(sg, r_k0[tid], r_k1[tid]); + } + } + // JOIN: row tid's class when it leads (its stream's rows of its width, another's on the same pages) + if constexpr (JOIN) { + __syncwarp(); + if (tid < RB && r_seg[tid] >= 0) { + unsigned mate = 0; + for (int j = tid; j < RB; j++) + if (r_seg[j] >= 0 && r_ck[j] == r_ck[tid] && + (r_seg[j] == r_seg[tid] || + (r_p0[j] >= 0 && r_p0[j] == r_p0[tid] && same_pages(segs, r_seg[tid], r_seg[j], r_k0[tid], r_k1[tid], r_k1[j])))) + mate |= 1u << j; + r_mate[tid] = mate; } } __syncthreads(); @@ -259,7 +299,7 @@ __device__ __forceinline__ void attn_rows(TileStore store, Geo geo, const __nv_b unsigned cls = 0; int kend = 0; for (int j = lead; j < RB; j++) - if (r_seg[j] == r_seg[lead] && r_ck[j] == r_ck[lead]) { + if (JOIN ? !(done >> j & 1) && (r_mate[lead] >> j & 1) : r_seg[j] == r_seg[lead] && r_ck[j] == r_ck[lead]) { cls |= 1u << j; kend = max(kend, r_k1[j]); } diff --git a/zig/kernels/cuda/qwen35_kv8.cu b/zig/kernels/cuda/qwen35_kv8.cu index a2e130c57e3..cf6fbc5a68b 100644 --- a/zig/kernels/cuda/qwen35_kv8.cu +++ b/zig/kernels/cuda/qwen35_kv8.cu @@ -312,6 +312,16 @@ extern "C" __global__ void __launch_bounds__(256) tf_q35_attn_rows8(Geo geo, con tf_q35_tc::attn_rows<4, tf_q35_tc::Fp8Tiles<256>>({kt, vt, ksc, vsc}, geo, Q, segs, rowseg, rowanc, layer, P, scale, total, PM, PL, PO); } +// tf_q35_attn_rows8 for a forward whose streams share pages (cuda_cache.anyShares): rows on one page run join. +extern "C" __global__ void __launch_bounds__(256) tf_q35_attn_rows8_join(Geo geo, const __nv_bfloat16* __restrict__ Q, const Seg* __restrict__ segs, + const int* __restrict__ rowseg, const Ancestor* __restrict__ rowanc, int layer, + const int* __restrict__ P, float scale, int total, + float* __restrict__ PM, float* __restrict__ PL, float* __restrict__ PO) { + __shared__ __align__(16) uint4 kt[tf_q35_tc::TK * tf_q35_tc::CH], vt[tf_q35_tc::TK * tf_q35_tc::CH]; + __shared__ float ksc[tf_q35_tc::TK], vsc[tf_q35_tc::TK]; + tf_q35_tc::attn_rows<4, tf_q35_tc::Fp8Tiles<256>, true>({kt, vt, ksc, vsc}, geo, Q, segs, rowseg, rowanc, layer, P, scale, total, PM, PL, PO); +} + extern "C" __global__ void __launch_bounds__(128) tf_q35_attn_partial8_whole(Geo geo, const __nv_bfloat16* __restrict__ Q, const Seg* __restrict__ segs, const int* __restrict__ rowseg, const Ancestor* __restrict__ rowanc, int layer, const int* __restrict__ P, float scale, diff --git a/zig/kernels/hip/flashnext/indexer.hpp b/zig/kernels/hip/flashnext/indexer.hpp index 1c1b75d2083..6947c47ce9c 100644 --- a/zig/kernels/hip/flashnext/indexer.hpp +++ b/zig/kernels/hip/flashnext/indexer.hpp @@ -47,10 +47,23 @@ extern "C" __global__ void __launch_bounds__(kFnThreads) tf_fn_idx_scores(const float* q, const void* pooled, const int* complete, float* scores, int kind, int rows, int heads, int dims, int blocks, long long stride, int top) { constexpr int kMost = 8; + // the block's rows of q, staged once for its eight waves when they fit + constexpr int kStage = 512; + __shared__ float qs[8 * kStage]; const int lane = threadIdx.x & 31; - const int b = blockIdx.x * kFnWaves + (threadIdx.x >> 5); + const int b0 = blockIdx.x * kFnWaves, b = b0 + (threadIdx.x >> 5); const int r0 = blockIdx.y * 8, r1 = min(rows, r0 + 8); - bool wanted = false; // a graph launches over a bound of blocks: those no row scores read nothing + bool tile = false; // a graph launches over a bound of blocks: those no row scores read nothing + if (b0 < blocks) + for (int r = r0; r < r1; ++r) tile = tile || (complete[r] > top && b0 < complete[r]); + if (!tile) return; + const int width = heads * dims; + const bool staged = width <= kStage; + if (staged) + for (int i = threadIdx.x; i < (r1 - r0) * width; i += kFnThreads) + qs[i] = q[static_cast(r0) * width + i]; + __syncthreads(); + bool wanted = false; for (int r = r0; r < r1; ++r) wanted = wanted || (complete[r] > top && b < complete[r]); if (b >= blocks || !wanted) return; float key[kMost]; @@ -64,7 +77,8 @@ tf_fn_idx_scores(const float* q, const void* pooled, const int* complete, float* if (complete[r] <= top || b >= complete[r]) continue; float total = 0.f; for (int h = 0; h < heads; ++h) { - const float* qh = q + (static_cast(r) * heads + h) * dims; + const float* qh = staged ? qs + ((r - r0) * heads + h) * dims + : q + (static_cast(r) * heads + h) * dims; float dot = 0.f; #pragma unroll for (int i = 0; i < kMost; ++i) { diff --git a/zig/kernels/metal/core/row_projection.metal b/zig/kernels/metal/core/row_projection.metal index 7f18976ac2b..e29c619bb26 100644 --- a/zig/kernels/metal/core/row_projection.metal +++ b/zig/kernels/metal/core/row_projection.metal @@ -2,6 +2,11 @@ #include using namespace metal; +// The kernel contract's planted control (TF_RP_BAD_ROWS 1) gives every SHARED row row 0's inputs. +#ifndef TF_RP_BAD_ROWS +#define TF_RP_BAD_ROWS 0 +#endif + // 2^-e, exact: a code read in place at bit e times its input scaled by 2^-e is the same product. inline float tf_rp_p2(int e) { return as_type(uint(127 - e) << 23); } @@ -102,10 +107,10 @@ inline void tf_rp_qdot16(const device uint8_t* w, const thread X (*xt)[16], floa } } -// RPS columns of MB rows at x.x[b], lanes splitting K by 16 (512 a pass); 3 hold bf16, 4+ go in pairs; same sums. +// RPS columns of MB rows at x.x[b], K split by 16 (512 a pass); 3 or SHARED hold bf16, 4+ else in pairs; same sums. template struct TfRpRows { const device bfloat* x[MB]; }; -template +template inline void tf_rp_rows_at(const device uint8_t* w, const device bfloat* sc, const device bfloat* bi, thread const TfRpRows& x, int K, int GS, uint lane, thread float (*acc)[RPS]) { typedef typename metal::conditional<(MB >= 3), bfloat, float>::type X; @@ -123,7 +128,7 @@ inline void tf_rp_rows_at(const device uint8_t* w, const device bfloat* sc, cons for (int b = 0; b < MB; b++) acc[b][j] = 0.0f; for (int k0 = 0; k0 <= FULL; k0 += 512) { if (k0 == FULL && !(FULL < K && int(lane) < (K - FULL) / 16)) break; - if (MB > 3) { + if (MB > 3 && !SHARED) { for (int p = 0; p < MB; p += 2) { float xt[2][16]; float sum[2]; @@ -152,12 +157,12 @@ inline void tf_rp_rows_at(const device uint8_t* w, const device bfloat* sc, cons } // Contiguous callers use the same reduction with their original row starts. -template +template inline void tf_rp_rows(const device uint8_t* w, const device bfloat* sc, const device bfloat* bi, const device bfloat* x0, int K, int GS, uint lane, thread float (*acc)[RPS]) { TfRpRows x; - for (int b = 0; b < MB; b++) x.x[b] = x0 + b * K; - tf_rp_rows_at(w, sc, bi, x, K, GS, lane, acc); + for (int b = 0; b < MB; b++) x.x[b] = x0 + (SHARED && TF_RP_BAD_ROWS ? 0 : b) * K; + tf_rp_rows_at(w, sc, bi, x, K, GS, lane, acc); } // A value out: bf16, relu squared with RELU2. @@ -171,16 +176,11 @@ inline bfloat tf_rp_out(float v) { } // dims: K, N, GS, rows, OUT's row stride when STRIDED (else N). X [rows, K]; W [N, K*BITS/32] words; S, B [N, K/GS]. -template -[[kernel]] void tf_row_projection(const device bfloat* X [[buffer(0)]], - const device uint32_t* W [[buffer(1)]], - const device bfloat* S [[buffer(2)]], - const device bfloat* B [[buffer(3)]], - constant int* dims [[buffer(4)]], - device bfloat* OUT [[buffer(5)]], - uint simdgroup_index_in_threadgroup [[simdgroup_index_in_threadgroup]], - uint thread_index_in_simdgroup [[thread_index_in_simdgroup]], - uint3 threadgroup_position_in_grid [[threadgroup_position_in_grid]]) { +template +inline void tf_row_projection_body(const device bfloat* X, const device uint32_t* W, + const device bfloat* S, const device bfloat* B, constant int* dims, + device bfloat* OUT, uint simdgroup_index_in_threadgroup, + uint thread_index_in_simdgroup, uint3 threadgroup_position_in_grid) { const int K = dims[0], N = dims[1], GS = dims[2], rows = dims[3], LD = STRIDED ? dims[4] : N; const uint lane = thread_index_in_simdgroup; const int row0 = (int(threadgroup_position_in_grid.x) * SG + int(simdgroup_index_in_threadgroup)) * RPS; @@ -193,11 +193,27 @@ template (wr, sr, br, X + size_t(m) * K, K, GS, lane, acc); + tf_rp_rows(wr, sr, br, X + size_t(m) * K, K, GS, lane, acc); if (lane == 0) for (int b = 0; b < MB; b++) for (int j = 0; j < RPS; j++) OUT[size_t(m + b) * LD + row0 + j] = tf_rp_out(acc[b][j]); } + if (WIDE && m + 4 <= rows) { + float acc[4][RPS]; + tf_rp_rows(wr, sr, br, X + size_t(m) * K, K, GS, lane, acc); + if (lane == 0) + for (int b = 0; b < 4; b++) + for (int j = 0; j < RPS; j++) OUT[size_t(m + b) * LD + row0 + j] = tf_rp_out(acc[b][j]); + m += 4; + } + if (WIDE && m + 2 <= rows) { + float acc[2][RPS]; + tf_rp_rows(wr, sr, br, X + size_t(m) * K, K, GS, lane, acc); + if (lane == 0) + for (int b = 0; b < 2; b++) + for (int j = 0; j < RPS; j++) OUT[size_t(m + b) * LD + row0 + j] = tf_rp_out(acc[b][j]); + m += 2; + } #pragma clang loop unroll(disable) for (; m < rows; m++) { float acc[1][RPS]; @@ -207,6 +223,36 @@ template +[[kernel]] void tf_row_projection(const device bfloat* X [[buffer(0)]], + const device uint32_t* W [[buffer(1)]], + const device bfloat* S [[buffer(2)]], + const device bfloat* B [[buffer(3)]], + constant int* dims [[buffer(4)]], + device bfloat* OUT [[buffer(5)]], + uint simdgroup_index_in_threadgroup [[simdgroup_index_in_threadgroup]], + uint thread_index_in_simdgroup [[thread_index_in_simdgroup]], + uint3 threadgroup_position_in_grid [[threadgroup_position_in_grid]]) { + tf_row_projection_body(X, W, S, B, dims, OUT, + simdgroup_index_in_threadgroup, thread_index_in_simdgroup, threadgroup_position_in_grid); +} + +// Windows of 4+ rows (core/row_projection.zig picks it): 8s, then a 4, a 2 and a last row; 64 threads reserved. +template +[[max_total_threads_per_threadgroup(64)]] +[[kernel]] void tf_row_projection_wide(const device bfloat* X [[buffer(0)]], + const device uint32_t* W [[buffer(1)]], + const device bfloat* S [[buffer(2)]], + const device bfloat* B [[buffer(3)]], + constant int* dims [[buffer(4)]], + device bfloat* OUT [[buffer(5)]], + uint simdgroup_index_in_threadgroup [[simdgroup_index_in_threadgroup]], + uint thread_index_in_simdgroup [[thread_index_in_simdgroup]], + uint3 threadgroup_position_in_grid [[threadgroup_position_in_grid]]) { + tf_row_projection_body(X, W, S, B, dims, OUT, + simdgroup_index_in_threadgroup, thread_index_in_simdgroup, threadgroup_position_in_grid); +} + // K, N, GS, slots, experts, repeat; W, S, B pack experts; slot y: expert ids[y], x row y/repeat (past the count: zero). template [[kernel]] void tf_row_projection_indexed(const device bfloat* X [[buffer(0)]], @@ -300,3 +346,39 @@ template [[host_name("tf_row_projection_strided_q6_f32")]] [[kernel]] decltype(t template [[host_name("tf_row_projection_strided_q6_bf16")]] [[kernel]] decltype(tf_row_projection<4, 2, 2, false, 6, true, true>) tf_row_projection<4, 2, 2, false, 6, true, true>; template [[host_name("tf_row_projection_strided_q8_f32")]] [[kernel]] decltype(tf_row_projection<4, 2, 2, false, 8, false, true>) tf_row_projection<4, 2, 2, false, 8, false, true>; template [[host_name("tf_row_projection_strided_q8_bf16")]] [[kernel]] decltype(tf_row_projection<4, 2, 2, false, 8, true, true>) tf_row_projection<4, 2, 2, false, 8, true, true>; +template [[host_name("tf_row_projection_wide_q2_f32")]] [[kernel]] decltype(tf_row_projection_wide<4, 2, false, 2, false, false>) tf_row_projection_wide<4, 2, false, 2, false, false>; +template [[host_name("tf_row_projection_wide_relu2_q2_f32")]] [[kernel]] decltype(tf_row_projection_wide<4, 2, true, 2, false, false>) tf_row_projection_wide<4, 2, true, 2, false, false>; +template [[host_name("tf_row_projection_wide_strided_q2_f32")]] [[kernel]] decltype(tf_row_projection_wide<4, 2, false, 2, false, true>) tf_row_projection_wide<4, 2, false, 2, false, true>; +template [[host_name("tf_row_projection_wide_q2_bf16")]] [[kernel]] decltype(tf_row_projection_wide<4, 2, false, 2, true, false>) tf_row_projection_wide<4, 2, false, 2, true, false>; +template [[host_name("tf_row_projection_wide_relu2_q2_bf16")]] [[kernel]] decltype(tf_row_projection_wide<4, 2, true, 2, true, false>) tf_row_projection_wide<4, 2, true, 2, true, false>; +template [[host_name("tf_row_projection_wide_strided_q2_bf16")]] [[kernel]] decltype(tf_row_projection_wide<4, 2, false, 2, true, true>) tf_row_projection_wide<4, 2, false, 2, true, true>; +template [[host_name("tf_row_projection_wide_q3_f32")]] [[kernel]] decltype(tf_row_projection_wide<4, 2, false, 3, false, false>) tf_row_projection_wide<4, 2, false, 3, false, false>; +template [[host_name("tf_row_projection_wide_relu2_q3_f32")]] [[kernel]] decltype(tf_row_projection_wide<4, 2, true, 3, false, false>) tf_row_projection_wide<4, 2, true, 3, false, false>; +template [[host_name("tf_row_projection_wide_strided_q3_f32")]] [[kernel]] decltype(tf_row_projection_wide<4, 2, false, 3, false, true>) tf_row_projection_wide<4, 2, false, 3, false, true>; +template [[host_name("tf_row_projection_wide_q3_bf16")]] [[kernel]] decltype(tf_row_projection_wide<4, 2, false, 3, true, false>) tf_row_projection_wide<4, 2, false, 3, true, false>; +template [[host_name("tf_row_projection_wide_relu2_q3_bf16")]] [[kernel]] decltype(tf_row_projection_wide<4, 2, true, 3, true, false>) tf_row_projection_wide<4, 2, true, 3, true, false>; +template [[host_name("tf_row_projection_wide_strided_q3_bf16")]] [[kernel]] decltype(tf_row_projection_wide<4, 2, false, 3, true, true>) tf_row_projection_wide<4, 2, false, 3, true, true>; +template [[host_name("tf_row_projection_wide_q4_f32")]] [[kernel]] decltype(tf_row_projection_wide<4, 2, false, 4, false, false>) tf_row_projection_wide<4, 2, false, 4, false, false>; +template [[host_name("tf_row_projection_wide_relu2_q4_f32")]] [[kernel]] decltype(tf_row_projection_wide<4, 2, true, 4, false, false>) tf_row_projection_wide<4, 2, true, 4, false, false>; +template [[host_name("tf_row_projection_wide_strided_q4_f32")]] [[kernel]] decltype(tf_row_projection_wide<4, 2, false, 4, false, true>) tf_row_projection_wide<4, 2, false, 4, false, true>; +template [[host_name("tf_row_projection_wide_q4_bf16")]] [[kernel]] decltype(tf_row_projection_wide<4, 2, false, 4, true, false>) tf_row_projection_wide<4, 2, false, 4, true, false>; +template [[host_name("tf_row_projection_wide_relu2_q4_bf16")]] [[kernel]] decltype(tf_row_projection_wide<4, 2, true, 4, true, false>) tf_row_projection_wide<4, 2, true, 4, true, false>; +template [[host_name("tf_row_projection_wide_strided_q4_bf16")]] [[kernel]] decltype(tf_row_projection_wide<4, 2, false, 4, true, true>) tf_row_projection_wide<4, 2, false, 4, true, true>; +template [[host_name("tf_row_projection_wide_q5_f32")]] [[kernel]] decltype(tf_row_projection_wide<4, 2, false, 5, false, false>) tf_row_projection_wide<4, 2, false, 5, false, false>; +template [[host_name("tf_row_projection_wide_relu2_q5_f32")]] [[kernel]] decltype(tf_row_projection_wide<4, 2, true, 5, false, false>) tf_row_projection_wide<4, 2, true, 5, false, false>; +template [[host_name("tf_row_projection_wide_strided_q5_f32")]] [[kernel]] decltype(tf_row_projection_wide<4, 2, false, 5, false, true>) tf_row_projection_wide<4, 2, false, 5, false, true>; +template [[host_name("tf_row_projection_wide_q5_bf16")]] [[kernel]] decltype(tf_row_projection_wide<4, 2, false, 5, true, false>) tf_row_projection_wide<4, 2, false, 5, true, false>; +template [[host_name("tf_row_projection_wide_relu2_q5_bf16")]] [[kernel]] decltype(tf_row_projection_wide<4, 2, true, 5, true, false>) tf_row_projection_wide<4, 2, true, 5, true, false>; +template [[host_name("tf_row_projection_wide_strided_q5_bf16")]] [[kernel]] decltype(tf_row_projection_wide<4, 2, false, 5, true, true>) tf_row_projection_wide<4, 2, false, 5, true, true>; +template [[host_name("tf_row_projection_wide_q6_f32")]] [[kernel]] decltype(tf_row_projection_wide<4, 2, false, 6, false, false>) tf_row_projection_wide<4, 2, false, 6, false, false>; +template [[host_name("tf_row_projection_wide_relu2_q6_f32")]] [[kernel]] decltype(tf_row_projection_wide<4, 2, true, 6, false, false>) tf_row_projection_wide<4, 2, true, 6, false, false>; +template [[host_name("tf_row_projection_wide_strided_q6_f32")]] [[kernel]] decltype(tf_row_projection_wide<4, 2, false, 6, false, true>) tf_row_projection_wide<4, 2, false, 6, false, true>; +template [[host_name("tf_row_projection_wide_q6_bf16")]] [[kernel]] decltype(tf_row_projection_wide<4, 2, false, 6, true, false>) tf_row_projection_wide<4, 2, false, 6, true, false>; +template [[host_name("tf_row_projection_wide_relu2_q6_bf16")]] [[kernel]] decltype(tf_row_projection_wide<4, 2, true, 6, true, false>) tf_row_projection_wide<4, 2, true, 6, true, false>; +template [[host_name("tf_row_projection_wide_strided_q6_bf16")]] [[kernel]] decltype(tf_row_projection_wide<4, 2, false, 6, true, true>) tf_row_projection_wide<4, 2, false, 6, true, true>; +template [[host_name("tf_row_projection_wide_q8_f32")]] [[kernel]] decltype(tf_row_projection_wide<4, 2, false, 8, false, false>) tf_row_projection_wide<4, 2, false, 8, false, false>; +template [[host_name("tf_row_projection_wide_relu2_q8_f32")]] [[kernel]] decltype(tf_row_projection_wide<4, 2, true, 8, false, false>) tf_row_projection_wide<4, 2, true, 8, false, false>; +template [[host_name("tf_row_projection_wide_strided_q8_f32")]] [[kernel]] decltype(tf_row_projection_wide<4, 2, false, 8, false, true>) tf_row_projection_wide<4, 2, false, 8, false, true>; +template [[host_name("tf_row_projection_wide_q8_bf16")]] [[kernel]] decltype(tf_row_projection_wide<4, 2, false, 8, true, false>) tf_row_projection_wide<4, 2, false, 8, true, false>; +template [[host_name("tf_row_projection_wide_relu2_q8_bf16")]] [[kernel]] decltype(tf_row_projection_wide<4, 2, true, 8, true, false>) tf_row_projection_wide<4, 2, true, 8, true, false>; +template [[host_name("tf_row_projection_wide_strided_q8_bf16")]] [[kernel]] decltype(tf_row_projection_wide<4, 2, false, 8, true, true>) tf_row_projection_wide<4, 2, false, 8, true, true>; diff --git a/zig/kernels/metal/core/row_projection_legacy.metal b/zig/kernels/metal/core/row_projection_legacy.metal new file mode 100644 index 00000000000..7f18976ac2b --- /dev/null +++ b/zig/kernels/metal/core/row_projection_legacy.metal @@ -0,0 +1,302 @@ +// Affine 2- to 8-bit row projections without tensor units: RPS columns a simdgroup, MB rows a pass over the weights. +#include +using namespace metal; + +// 2^-e, exact: a code read in place at bit e times its input scaled by 2^-e is the same product. +inline float tf_rp_p2(int e) { return as_type(uint(127 - e) << 23); } + +// An input in its code's place, exact: at 4 bits divided by 16^(i % 4), at 2 bits by 4^i. +template +inline float tf_rp_x(float v, int i) { + if (BITS == 4) return i % 4 == 0 ? v : i % 4 == 1 ? v / 16.0f : i % 4 == 2 ? v / 256.0f : v / 4096.0f; + if (BITS == 2) return v * tf_rp_p2(2 * i); + return v; +} + +// Four more inputs into a group sum: fp32 in order, or rounded to bf16 at each add (BF16SUM, Nemotron's experts). +template +inline float tf_rp_sum4(float sum, bfloat a, bfloat b, bfloat c, bfloat d) { + if (BF16SUM) return sum + float(bfloat(float(bfloat(float(bfloat(float(a) + float(b))) + float(c))) + float(d))); + sum += float(a); sum += float(b); sum += float(c); sum += float(d); + return sum; +} + +// 16 bf16 inputs and their group sum: as floats in their codes' places, or as bf16 (tf_rp_in places them where used). +template +inline float tf_rp_load16(const device bfloat* x, thread float* xt) { + float sum = 0.0f; + for (int i = 0; i < 16; i += 4) { + const bfloat a = x[i], b = x[i + 1], c = x[i + 2], d = x[i + 3]; + sum = tf_rp_sum4(sum, a, b, c, d); + xt[i] = tf_rp_x(float(a), i); + xt[i + 1] = tf_rp_x(float(b), i + 1); + xt[i + 2] = tf_rp_x(float(c), i + 2); + xt[i + 3] = tf_rp_x(float(d), i + 3); + } + return sum; +} + +template +inline float tf_rp_load16(const device bfloat* x, thread bfloat* xt) { + float sum = 0.0f; + for (int i = 0; i < 16; i += 4) { + const bfloat a = x[i], b = x[i + 1], c = x[i + 2], d = x[i + 3]; + sum = tf_rp_sum4(sum, a, b, c, d); + xt[i] = a; xt[i + 1] = b; xt[i + 2] = c; xt[i + 3] = d; + } + return sum; +} + +// A loaded input as a float in its code's place. +template +inline float tf_rp_in(float v, int) { return v; } +template +inline float tf_rp_in(bfloat v, int i) { return tf_rp_x(float(v), i); } + +// MB rows' dots with 16 codes (3, 5, 6 bits: 8, 8, 4 codes in 3, 5, 3 bytes), unpacked once; sums in one order. +template +inline void tf_rp_qdot16(const device uint8_t* w, const thread X (*xt)[16], float scale, float bias, + const thread float* sum, thread float* out) { + float q[16]; + if (BITS == 2) { + const uint v = *(const device uint*)w; + for (int i = 0; i < 16; i++) q[i] = float(v & (3u << (2 * i))); + } else if (BITS == 4) { + const device uint16_t* ws = (const device uint16_t*)w; + for (int i = 0; i < 4; i++) { + const int v = ws[i]; + q[4 * i] = float(v & 0x000f); q[4 * i + 1] = float(v & 0x00f0); q[4 * i + 2] = float(v & 0x0f00); q[4 * i + 3] = float(v & 0xf000); + } + } else if (BITS == 6) { + for (int i = 0; i < 4; i++) { + const device uint8_t* p = w + 3 * i; + q[4 * i] = float(p[0] & 0x3f); + q[4 * i + 1] = float(((p[0] >> 6) & 0x03) | ((p[1] & 0x0f) << 2)); + q[4 * i + 2] = float(((p[1] >> 4) & 0x0f) | ((p[2] & 0x03) << 4)); + q[4 * i + 3] = float((p[2] >> 2) & 0x3f); + } + } else if (BITS == 3) { + for (int i = 0; i < 2; i++) { + const device uint8_t* p = w + 3 * i; + const uint v = uint(p[0]) | (uint(p[1]) << 8) | (uint(p[2]) << 16); + for (int j = 0; j < 8; j++) q[8 * i + j] = float((v >> (3 * j)) & 7u); + } + } else if (BITS == 5) { + for (int i = 0; i < 2; i++) { + const device uint8_t* p = w + 5 * i; + const uint lo = uint(p[0]) | (uint(p[1]) << 8) | (uint(p[2]) << 16) | (uint(p[3]) << 24), hi = p[4]; + for (int j = 0; j < 6; j++) q[8 * i + j] = float((lo >> (5 * j)) & 31u); + q[8 * i + 6] = float(((lo >> 30) | (hi << 2)) & 31u); + q[8 * i + 7] = float(hi >> 3); + } + } else { + for (int i = 0; i < 16; i++) q[i] = float(w[i]); + } + for (int b = 0; b < MB; b++) { + float accum = 0.0f; + for (int i = 0; i < 4; i++) + accum += (tf_rp_in(xt[b][4 * i], 4 * i) * q[4 * i] + tf_rp_in(xt[b][4 * i + 1], 4 * i + 1) * q[4 * i + 1] + + tf_rp_in(xt[b][4 * i + 2], 4 * i + 2) * q[4 * i + 2] + + tf_rp_in(xt[b][4 * i + 3], 4 * i + 3) * q[4 * i + 3]); + out[b] += scale * accum + sum[b] * bias; + } +} + +// RPS columns of MB rows at x.x[b], lanes splitting K by 16 (512 a pass); 3 hold bf16, 4+ go in pairs; same sums. +template struct TfRpRows { const device bfloat* x[MB]; }; + +template +inline void tf_rp_rows_at(const device uint8_t* w, const device bfloat* sc, const device bfloat* bi, thread const TfRpRows& x, + int K, int GS, uint lane, thread float (*acc)[RPS]) { + typedef typename metal::conditional<(MB >= 3), bfloat, float>::type X; + static_assert(MB <= 3 || MB % 2 == 0, "4+ rows run in pairs"); + const int KB = K * BITS / 8; + const int KG = K / GS; + const int FULL = K / 512 * 512; + const int per_lane = GS / 16; + w += lane * (16 * BITS / 8); + sc += lane / per_lane; + bi += lane / per_lane; + const int xl = int(lane) * 16; + float col[MB]; + for (int j = 0; j < RPS; j++) + for (int b = 0; b < MB; b++) acc[b][j] = 0.0f; + for (int k0 = 0; k0 <= FULL; k0 += 512) { + if (k0 == FULL && !(FULL < K && int(lane) < (K - FULL) / 16)) break; + if (MB > 3) { + for (int p = 0; p < MB; p += 2) { + float xt[2][16]; + float sum[2]; + for (int b = 0; b < 2; b++) sum[b] = tf_rp_load16(x.x[p + b] + xl + k0, xt[b]); + for (int j = 0; j < RPS; j++) { + float two[2] = {acc[p][j], acc[p + 1][j]}; + tf_rp_qdot16<2, BITS>(w + j * KB, xt, float(sc[j * KG]), float(bi[j * KG]), sum, two); + acc[p][j] = two[0]; + acc[p + 1][j] = two[1]; + } + } + } else { + X xt[MB][16]; + float sum[MB]; + for (int b = 0; b < MB; b++) sum[b] = tf_rp_load16(x.x[b] + xl + k0, xt[b]); + for (int j = 0; j < RPS; j++) { + for (int b = 0; b < MB; b++) col[b] = acc[b][j]; + tf_rp_qdot16(w + j * KB, xt, float(sc[j * KG]), float(bi[j * KG]), sum, col); + for (int b = 0; b < MB; b++) acc[b][j] = col[b]; + } + } + w += 512 * BITS / 8; sc += 512 / GS; bi += 512 / GS; + } + for (int j = 0; j < RPS; j++) + for (int b = 0; b < MB; b++) acc[b][j] = simd_sum(acc[b][j]); +} + +// Contiguous callers use the same reduction with their original row starts. +template +inline void tf_rp_rows(const device uint8_t* w, const device bfloat* sc, const device bfloat* bi, const device bfloat* x0, + int K, int GS, uint lane, thread float (*acc)[RPS]) { + TfRpRows x; + for (int b = 0; b < MB; b++) x.x[b] = x0 + b * K; + tf_rp_rows_at(w, sc, bi, x, K, GS, lane, acc); +} + +// A value out: bf16, relu squared with RELU2. +template +inline bfloat tf_rp_out(float v) { + if (RELU2) { + const float h = metal::max(float(bfloat(v)), 0.0f); + return bfloat(h * h); + } + return bfloat(v); +} + +// dims: K, N, GS, rows, OUT's row stride when STRIDED (else N). X [rows, K]; W [N, K*BITS/32] words; S, B [N, K/GS]. +template +[[kernel]] void tf_row_projection(const device bfloat* X [[buffer(0)]], + const device uint32_t* W [[buffer(1)]], + const device bfloat* S [[buffer(2)]], + const device bfloat* B [[buffer(3)]], + constant int* dims [[buffer(4)]], + device bfloat* OUT [[buffer(5)]], + uint simdgroup_index_in_threadgroup [[simdgroup_index_in_threadgroup]], + uint thread_index_in_simdgroup [[thread_index_in_simdgroup]], + uint3 threadgroup_position_in_grid [[threadgroup_position_in_grid]]) { + const int K = dims[0], N = dims[1], GS = dims[2], rows = dims[3], LD = STRIDED ? dims[4] : N; + const uint lane = thread_index_in_simdgroup; + const int row0 = (int(threadgroup_position_in_grid.x) * SG + int(simdgroup_index_in_threadgroup)) * RPS; + if (row0 >= N) return; + const size_t at = size_t(row0); + const device uint8_t* wr = (const device uint8_t*)W + at * (K * BITS / 8); + const device bfloat* sr = S + at * (K / GS); + const device bfloat* br = B + at * (K / GS); + int m = 0; + #pragma clang loop unroll(disable) + for (; m + MB <= rows; m += MB) { + float acc[MB][RPS]; + tf_rp_rows(wr, sr, br, X + size_t(m) * K, K, GS, lane, acc); + if (lane == 0) + for (int b = 0; b < MB; b++) + for (int j = 0; j < RPS; j++) OUT[size_t(m + b) * LD + row0 + j] = tf_rp_out(acc[b][j]); + } + #pragma clang loop unroll(disable) + for (; m < rows; m++) { + float acc[1][RPS]; + tf_rp_rows(wr, sr, br, X + size_t(m) * K, K, GS, lane, acc); + if (lane == 0) + for (int j = 0; j < RPS; j++) OUT[size_t(m) * LD + row0 + j] = tf_rp_out(acc[0][j]); + } +} + +// K, N, GS, slots, experts, repeat; W, S, B pack experts; slot y: expert ids[y], x row y/repeat (past the count: zero). +template +[[kernel]] void tf_row_projection_indexed(const device bfloat* X [[buffer(0)]], + const device uint32_t* W [[buffer(1)]], + const device bfloat* S [[buffer(2)]], + const device bfloat* B [[buffer(3)]], + constant int* dims [[buffer(4)]], + device bfloat* OUT [[buffer(5)]], + const device uint* ids [[buffer(6)]], + uint simdgroup_index_in_threadgroup [[simdgroup_index_in_threadgroup]], + uint thread_index_in_simdgroup [[thread_index_in_simdgroup]], + uint3 threadgroup_position_in_grid [[threadgroup_position_in_grid]]) { + const int K = dims[0], N = dims[1], GS = dims[2], experts = dims[4], repeat = dims[5]; + const uint lane = thread_index_in_simdgroup; + const int row0 = (int(threadgroup_position_in_grid.x) * SG + int(simdgroup_index_in_threadgroup)) * RPS; + if (row0 >= N) return; + const uint slot = threadgroup_position_in_grid.y; + const uint expert = ids[slot]; + device bfloat* out = OUT + size_t(slot) * N + row0; + if (expert >= uint(experts)) { + if (lane < uint(RPS)) out[lane] = bfloat(0.0f); + return; + } + const size_t at = size_t(expert) * N + size_t(row0); + const device uint8_t* wr = (const device uint8_t*)W + at * (K * BITS / 8); + const device bfloat* sr = S + at * (K / GS); + const device bfloat* br = B + at * (K / GS); + float acc[1][RPS]; + tf_rp_rows(wr, sr, br, X + size_t(slot / repeat) * K, K, GS, lane, acc); + if (lane == 0) + for (int j = 0; j < RPS; j++) out[j] = tf_rp_out(acc[0][j]); +} + +template [[host_name("tf_row_projection_q2_f32")]] [[kernel]] decltype(tf_row_projection<4, 2, 2, false, 2, false>) tf_row_projection<4, 2, 2, false, 2, false>; +template [[host_name("tf_row_projection_indexed_q2_f32")]] [[kernel]] decltype(tf_row_projection_indexed<4, 2, false, 2, false>) tf_row_projection_indexed<4, 2, false, 2, false>; +template [[host_name("tf_row_projection_relu2_q2_f32")]] [[kernel]] decltype(tf_row_projection<4, 2, 2, true, 2, false>) tf_row_projection<4, 2, 2, true, 2, false>; +template [[host_name("tf_row_projection_indexed_relu2_q2_f32")]] [[kernel]] decltype(tf_row_projection_indexed<4, 2, true, 2, false>) tf_row_projection_indexed<4, 2, true, 2, false>; +template [[host_name("tf_row_projection_q2_bf16")]] [[kernel]] decltype(tf_row_projection<4, 2, 2, false, 2, true>) tf_row_projection<4, 2, 2, false, 2, true>; +template [[host_name("tf_row_projection_indexed_q2_bf16")]] [[kernel]] decltype(tf_row_projection_indexed<4, 2, false, 2, true>) tf_row_projection_indexed<4, 2, false, 2, true>; +template [[host_name("tf_row_projection_relu2_q2_bf16")]] [[kernel]] decltype(tf_row_projection<4, 2, 2, true, 2, true>) tf_row_projection<4, 2, 2, true, 2, true>; +template [[host_name("tf_row_projection_indexed_relu2_q2_bf16")]] [[kernel]] decltype(tf_row_projection_indexed<4, 2, true, 2, true>) tf_row_projection_indexed<4, 2, true, 2, true>; +template [[host_name("tf_row_projection_q4_f32")]] [[kernel]] decltype(tf_row_projection<4, 2, 2, false, 4, false>) tf_row_projection<4, 2, 2, false, 4, false>; +template [[host_name("tf_row_projection_indexed_q4_f32")]] [[kernel]] decltype(tf_row_projection_indexed<4, 2, false, 4, false>) tf_row_projection_indexed<4, 2, false, 4, false>; +template [[host_name("tf_row_projection_relu2_q4_f32")]] [[kernel]] decltype(tf_row_projection<4, 2, 2, true, 4, false>) tf_row_projection<4, 2, 2, true, 4, false>; +template [[host_name("tf_row_projection_indexed_relu2_q4_f32")]] [[kernel]] decltype(tf_row_projection_indexed<4, 2, true, 4, false>) tf_row_projection_indexed<4, 2, true, 4, false>; +template [[host_name("tf_row_projection_q4_bf16")]] [[kernel]] decltype(tf_row_projection<4, 2, 2, false, 4, true>) tf_row_projection<4, 2, 2, false, 4, true>; +template [[host_name("tf_row_projection_indexed_q4_bf16")]] [[kernel]] decltype(tf_row_projection_indexed<4, 2, false, 4, true>) tf_row_projection_indexed<4, 2, false, 4, true>; +template [[host_name("tf_row_projection_relu2_q4_bf16")]] [[kernel]] decltype(tf_row_projection<4, 2, 2, true, 4, true>) tf_row_projection<4, 2, 2, true, 4, true>; +template [[host_name("tf_row_projection_indexed_relu2_q4_bf16")]] [[kernel]] decltype(tf_row_projection_indexed<4, 2, true, 4, true>) tf_row_projection_indexed<4, 2, true, 4, true>; +template [[host_name("tf_row_projection_q6_f32")]] [[kernel]] decltype(tf_row_projection<4, 2, 2, false, 6, false>) tf_row_projection<4, 2, 2, false, 6, false>; +template [[host_name("tf_row_projection_indexed_q6_f32")]] [[kernel]] decltype(tf_row_projection_indexed<4, 2, false, 6, false>) tf_row_projection_indexed<4, 2, false, 6, false>; +template [[host_name("tf_row_projection_relu2_q6_f32")]] [[kernel]] decltype(tf_row_projection<4, 2, 2, true, 6, false>) tf_row_projection<4, 2, 2, true, 6, false>; +template [[host_name("tf_row_projection_indexed_relu2_q6_f32")]] [[kernel]] decltype(tf_row_projection_indexed<4, 2, true, 6, false>) tf_row_projection_indexed<4, 2, true, 6, false>; +template [[host_name("tf_row_projection_q6_bf16")]] [[kernel]] decltype(tf_row_projection<4, 2, 2, false, 6, true>) tf_row_projection<4, 2, 2, false, 6, true>; +template [[host_name("tf_row_projection_indexed_q6_bf16")]] [[kernel]] decltype(tf_row_projection_indexed<4, 2, false, 6, true>) tf_row_projection_indexed<4, 2, false, 6, true>; +template [[host_name("tf_row_projection_relu2_q6_bf16")]] [[kernel]] decltype(tf_row_projection<4, 2, 2, true, 6, true>) tf_row_projection<4, 2, 2, true, 6, true>; +template [[host_name("tf_row_projection_indexed_relu2_q6_bf16")]] [[kernel]] decltype(tf_row_projection_indexed<4, 2, true, 6, true>) tf_row_projection_indexed<4, 2, true, 6, true>; +template [[host_name("tf_row_projection_q8_f32")]] [[kernel]] decltype(tf_row_projection<4, 2, 2, false, 8, false>) tf_row_projection<4, 2, 2, false, 8, false>; +template [[host_name("tf_row_projection_indexed_q8_f32")]] [[kernel]] decltype(tf_row_projection_indexed<4, 2, false, 8, false>) tf_row_projection_indexed<4, 2, false, 8, false>; +template [[host_name("tf_row_projection_relu2_q8_f32")]] [[kernel]] decltype(tf_row_projection<4, 2, 2, true, 8, false>) tf_row_projection<4, 2, 2, true, 8, false>; +template [[host_name("tf_row_projection_indexed_relu2_q8_f32")]] [[kernel]] decltype(tf_row_projection_indexed<4, 2, true, 8, false>) tf_row_projection_indexed<4, 2, true, 8, false>; +template [[host_name("tf_row_projection_q8_bf16")]] [[kernel]] decltype(tf_row_projection<4, 2, 2, false, 8, true>) tf_row_projection<4, 2, 2, false, 8, true>; +template [[host_name("tf_row_projection_indexed_q8_bf16")]] [[kernel]] decltype(tf_row_projection_indexed<4, 2, false, 8, true>) tf_row_projection_indexed<4, 2, false, 8, true>; +template [[host_name("tf_row_projection_relu2_q8_bf16")]] [[kernel]] decltype(tf_row_projection<4, 2, 2, true, 8, true>) tf_row_projection<4, 2, 2, true, 8, true>; +template [[host_name("tf_row_projection_indexed_relu2_q8_bf16")]] [[kernel]] decltype(tf_row_projection_indexed<4, 2, true, 8, true>) tf_row_projection_indexed<4, 2, true, 8, true>; +template [[host_name("tf_row_projection_q3_f32")]] [[kernel]] decltype(tf_row_projection<4, 2, 2, false, 3, false>) tf_row_projection<4, 2, 2, false, 3, false>; +template [[host_name("tf_row_projection_indexed_q3_f32")]] [[kernel]] decltype(tf_row_projection_indexed<4, 2, false, 3, false>) tf_row_projection_indexed<4, 2, false, 3, false>; +template [[host_name("tf_row_projection_relu2_q3_f32")]] [[kernel]] decltype(tf_row_projection<4, 2, 2, true, 3, false>) tf_row_projection<4, 2, 2, true, 3, false>; +template [[host_name("tf_row_projection_indexed_relu2_q3_f32")]] [[kernel]] decltype(tf_row_projection_indexed<4, 2, true, 3, false>) tf_row_projection_indexed<4, 2, true, 3, false>; +template [[host_name("tf_row_projection_q3_bf16")]] [[kernel]] decltype(tf_row_projection<4, 2, 2, false, 3, true>) tf_row_projection<4, 2, 2, false, 3, true>; +template [[host_name("tf_row_projection_indexed_q3_bf16")]] [[kernel]] decltype(tf_row_projection_indexed<4, 2, false, 3, true>) tf_row_projection_indexed<4, 2, false, 3, true>; +template [[host_name("tf_row_projection_relu2_q3_bf16")]] [[kernel]] decltype(tf_row_projection<4, 2, 2, true, 3, true>) tf_row_projection<4, 2, 2, true, 3, true>; +template [[host_name("tf_row_projection_indexed_relu2_q3_bf16")]] [[kernel]] decltype(tf_row_projection_indexed<4, 2, true, 3, true>) tf_row_projection_indexed<4, 2, true, 3, true>; +template [[host_name("tf_row_projection_q5_f32")]] [[kernel]] decltype(tf_row_projection<4, 2, 2, false, 5, false>) tf_row_projection<4, 2, 2, false, 5, false>; +template [[host_name("tf_row_projection_indexed_q5_f32")]] [[kernel]] decltype(tf_row_projection_indexed<4, 2, false, 5, false>) tf_row_projection_indexed<4, 2, false, 5, false>; +template [[host_name("tf_row_projection_relu2_q5_f32")]] [[kernel]] decltype(tf_row_projection<4, 2, 2, true, 5, false>) tf_row_projection<4, 2, 2, true, 5, false>; +template [[host_name("tf_row_projection_indexed_relu2_q5_f32")]] [[kernel]] decltype(tf_row_projection_indexed<4, 2, true, 5, false>) tf_row_projection_indexed<4, 2, true, 5, false>; +template [[host_name("tf_row_projection_q5_bf16")]] [[kernel]] decltype(tf_row_projection<4, 2, 2, false, 5, true>) tf_row_projection<4, 2, 2, false, 5, true>; +template [[host_name("tf_row_projection_indexed_q5_bf16")]] [[kernel]] decltype(tf_row_projection_indexed<4, 2, false, 5, true>) tf_row_projection_indexed<4, 2, false, 5, true>; +template [[host_name("tf_row_projection_relu2_q5_bf16")]] [[kernel]] decltype(tf_row_projection<4, 2, 2, true, 5, true>) tf_row_projection<4, 2, 2, true, 5, true>; +template [[host_name("tf_row_projection_indexed_relu2_q5_bf16")]] [[kernel]] decltype(tf_row_projection_indexed<4, 2, true, 5, true>) tf_row_projection_indexed<4, 2, true, 5, true>; +template [[host_name("tf_row_projection_strided_q2_f32")]] [[kernel]] decltype(tf_row_projection<4, 2, 2, false, 2, false, true>) tf_row_projection<4, 2, 2, false, 2, false, true>; +template [[host_name("tf_row_projection_strided_q2_bf16")]] [[kernel]] decltype(tf_row_projection<4, 2, 2, false, 2, true, true>) tf_row_projection<4, 2, 2, false, 2, true, true>; +template [[host_name("tf_row_projection_strided_q3_f32")]] [[kernel]] decltype(tf_row_projection<4, 2, 2, false, 3, false, true>) tf_row_projection<4, 2, 2, false, 3, false, true>; +template [[host_name("tf_row_projection_strided_q3_bf16")]] [[kernel]] decltype(tf_row_projection<4, 2, 2, false, 3, true, true>) tf_row_projection<4, 2, 2, false, 3, true, true>; +template [[host_name("tf_row_projection_strided_q4_f32")]] [[kernel]] decltype(tf_row_projection<4, 2, 2, false, 4, false, true>) tf_row_projection<4, 2, 2, false, 4, false, true>; +template [[host_name("tf_row_projection_strided_q4_bf16")]] [[kernel]] decltype(tf_row_projection<4, 2, 2, false, 4, true, true>) tf_row_projection<4, 2, 2, false, 4, true, true>; +template [[host_name("tf_row_projection_strided_q5_f32")]] [[kernel]] decltype(tf_row_projection<4, 2, 2, false, 5, false, true>) tf_row_projection<4, 2, 2, false, 5, false, true>; +template [[host_name("tf_row_projection_strided_q5_bf16")]] [[kernel]] decltype(tf_row_projection<4, 2, 2, false, 5, true, true>) tf_row_projection<4, 2, 2, false, 5, true, true>; +template [[host_name("tf_row_projection_strided_q6_f32")]] [[kernel]] decltype(tf_row_projection<4, 2, 2, false, 6, false, true>) tf_row_projection<4, 2, 2, false, 6, false, true>; +template [[host_name("tf_row_projection_strided_q6_bf16")]] [[kernel]] decltype(tf_row_projection<4, 2, 2, false, 6, true, true>) tf_row_projection<4, 2, 2, false, 6, true, true>; +template [[host_name("tf_row_projection_strided_q8_f32")]] [[kernel]] decltype(tf_row_projection<4, 2, 2, false, 8, false, true>) tf_row_projection<4, 2, 2, false, 8, false, true>; +template [[host_name("tf_row_projection_strided_q8_bf16")]] [[kernel]] decltype(tf_row_projection<4, 2, 2, false, 8, true, true>) tf_row_projection<4, 2, 2, false, 8, true, true>; diff --git a/zig/kernels/metal/glm_rows.metal b/zig/kernels/metal/glm_rows.metal index df29f3fd0ba..feff030cdb1 100644 --- a/zig/kernels/metal/glm_rows.metal +++ b/zig/kernels/metal/glm_rows.metal @@ -170,6 +170,71 @@ template // RPS columns } } +// glm_moe_rows by unique expert (uids, umem, ucount): a simdgroup a pick, z = slots the shared; glm_moe_rows's sums. +#define GLM_MAXR 16 +template +[[max_total_threads_per_threadgroup(32 * GLM_MAXR)]] +[[kernel]] void glm_moe_rows_u(const device bfloat* X [[buffer(0)]], const device uint32_t* W [[buffer(1)]], + const device bfloat* S [[buffer(2)]], const device bfloat* B [[buffer(3)]], + constant GlmPickDims& d [[buffer(4)]], device bfloat* OUT [[buffer(5)]], + const device int* uids [[buffer(6)]], const device uint32_t* W2 [[buffer(7)]], + const device bfloat* S2 [[buffer(8)]], const device bfloat* B2 [[buffer(9)]], + const device bfloat* X2 [[buffer(10)]], const device uint32_t* SW [[buffer(11)]], + const device bfloat* SS [[buffer(12)]], const device bfloat* SB [[buffer(13)]], + device bfloat* OUT2 [[buffer(14)]], const device int* umem [[buffer(15)]], + const device int* ucount [[buffer(16)]], + uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], + uint nsg [[simdgroups_per_threadgroup]], uint3 tg [[threadgroup_position_in_grid]]) { + const int row0 = int(tg.x) * RPS; + if (row0 >= d.n) return; + const int z = int(tg.y); + const int m = int(sg); + const int cols = metal::min(RPS, d.n - row0); + const int K = d.k; + const size_t kg = size_t(K / d.group); + if (z < d.slots) { + if (z >= ucount[0]) return; + const int pick = umem[z * GLM_MAXR + m]; + if (pick < 0) return; + device bfloat* out = OUT + size_t(pick) * d.ldo + row0; + const size_t at = size_t(uids[z]) * d.n + row0; + const size_t kb = size_t(K) * BITS / 8; + const device bfloat* x = X + size_t(pick / d.repeat) * K; + float acc[1][RPS]; + tf_rp_rows((const device uint8_t*)W + at * kb, S + at * kg, B + at * kg, x, K, d.group, lane, + acc); + if (GLU) { + float up[1][RPS]; + tf_rp_rows((const device uint8_t*)W2 + at * kb, S2 + at * kg, B2 + at * kg, x, K, d.group, + lane, up); + if (lane == 0) + for (int j = 0; j < cols; j++) out[j] = glm_rows_glu(acc[0][j], up[0][j], d.lim); + } else if (lane == 0) { + for (int j = 0; j < cols; j++) out[j] = bfloat(acc[0][j]); + } + return; + } + const int r = m; + if (r >= int(nsg)) return; + const size_t skb = size_t(K) * SBITS / 8; + const device bfloat* x = X2 + size_t(r) * K; + device bfloat* out = OUT2 + size_t(r) * d.n + row0; + const device uint8_t* gw = (const device uint8_t*)SW + size_t(row0) * skb; + const device bfloat* gs = SS + size_t(row0) * kg; + const device bfloat* gb = SB + size_t(row0) * kg; + float acc[1][RPS]; + tf_rp_rows(gw, gs, gb, x, K, d.group, lane, acc); + if (GLU) { + const size_t up_at = size_t(d.n); + float up[1][RPS]; + tf_rp_rows(gw + up_at * skb, gs + up_at * kg, gb + up_at * kg, x, K, d.group, lane, up); + if (lane == 0) + for (int j = 0; j < cols; j++) out[j] = glm_rows_glu(acc[0][j], up[0][j], d.lim); + } else if (lane == 0) { + for (int j = 0; j < cols; j++) out[j] = bfloat(acc[0][j]); + } +} + // Expert e's sorted pairs: GLU x row order[i] / repeat to out row i, else x row i to row order[i]; grid (n / 8, e). template [[kernel]] void glm_rows_sorted(const device bfloat* X [[buffer(0)]], const device uint32_t* W [[buffer(1)]], @@ -326,7 +391,11 @@ GLM_ROWS_AT(8) template [[host_name("glm_moe_rows_q" #B "_s8")]] [[kernel]] \ decltype(glm_moe_rows) glm_moe_rows; \ template [[host_name("glm_moe_rows_glu_q" #B "_s8")]] [[kernel]] \ - decltype(glm_moe_rows) glm_moe_rows; + decltype(glm_moe_rows) glm_moe_rows; \ + template [[host_name("glm_moe_rows_u_q" #B "_s8")]] [[kernel]] \ + decltype(glm_moe_rows_u) glm_moe_rows_u; \ + template [[host_name("glm_moe_rows_glu_u_q" #B "_s8")]] [[kernel]] \ + decltype(glm_moe_rows_u) glm_moe_rows_u; GLM_MOE_AT(2) GLM_MOE_AT(3) GLM_MOE_AT(4) diff --git a/zig/kernels/metal/sources.zig b/zig/kernels/metal/sources.zig index 83b232d74f6..ee5748d68e6 100644 --- a/zig/kernels/metal/sources.zig +++ b/zig/kernels/metal/sources.zig @@ -44,6 +44,7 @@ pub const lfm3_projection = @embedFile("lfm3/projection.metal"); /// Our glue kernels around them: embedding, MLX's RMS arithmetic, argmax, layout moves. pub const nemotron_glue = @embedFile("nemotron_glue.metal"); pub const core_row_projection = @embedFile("core/row_projection.metal"); +pub const core_row_projection_legacy = @embedFile("core/row_projection_legacy.metal"); pub const core_binned_projection = @embedFile("core/binned_projection.metal"); pub const core_tile_qmm = @embedFile("core/tile_qmm.metal") ++ @embedFile("core/tile_qmv.metal") ++ @embedFile("core/tile_qmv_rows.metal"); diff --git a/zig/qwen35_cost_open_host.zig b/zig/qwen35_cost_open_host.zig index 98a0689a652..b918a25b0c4 100644 --- a/zig/qwen35_cost_open_host.zig +++ b/zig/qwen35_cost_open_host.zig @@ -62,7 +62,7 @@ fn open(root: []const u8, expected: usize, capacity: usize) ![64]f64 { h.* = .{ .gpa = a, .gpu = null, .family = &probe, .release = Probe.release, .inner = backend.backend(), .vtable = undefined, .cfg = undefined, .clock = undefined, .core = undefined, .host = undefined, .served = .{ .backend = backend.backend(), .facts = facts, .stream_bytes = 0, .prepare = .{ .ctx = &probe, .run = Probe.run } } }; Probe.opening = true; defer Probe.opening = false; - try h.serve(io, facts, 64, .{ .lanes = 1 }, null); + try h.serve(io, facts, 64, .{ .lanes = 1 }, null, 0); defer { h.host.stop(); h.core.deinit(); diff --git a/zig/src/core/checkpoint_read_ahead.zig b/zig/src/core/checkpoint_read_ahead.zig index 54db727f08f..7492ab6e8d2 100644 --- a/zig/src/core/checkpoint_read_ahead.zig +++ b/zig/src/core/checkpoint_read_ahead.zig @@ -3,6 +3,7 @@ const std = @import("std"); const prefetch = @import("checkpoint_prefetch.zig"); const Checkpoint = @import("checkpoint.zig").Checkpoint; pub const Span = prefetch.Span; +pub const chunk = prefetch.chunk; pub const readerCount = prefetch.readerCount; const none = std.math.maxInt(usize); diff --git a/zig/src/core/contract.zig b/zig/src/core/contract.zig index a942e5ab3ed..af4435ba6e5 100644 --- a/zig/src/core/contract.zig +++ b/zig/src/core/contract.zig @@ -44,6 +44,7 @@ test { _ = @import("contract/simd_pairs_records.zig"); _ = @import("contract/simd_half_records.zig"); _ = @import("contract/glm_rows_records.zig"); + _ = @import("contract/row_wide_records.zig"); _ = @import("contract/nemotron_experts_records.zig"); _ = @import("contract/moss_image_records.zig"); _ = @import("contract/metal_pair_records.zig"); diff --git a/zig/src/core/contract/glm_rows_records.zig b/zig/src/core/contract/glm_rows_records.zig index 8dcf7e7e9b9..ed6250b307a 100644 --- a/zig/src/core/contract/glm_rows_records.zig +++ b/zig/src/core/contract/glm_rows_records.zig @@ -1,4 +1,4 @@ -//! GLM-5.3-Flash's decode-window row kernels: each source reserves the 64 threads a group it launches. +//! GLM-5.3-Flash's decode-window row kernels: each reserves the threads a group it launches (unique-expert: 32 a row). const std = @import("std"); const M = @import("limits.zig").MetalLaunch; pub const records = [_]M{ @@ -14,6 +14,18 @@ pub const records = [_]M{ .{ .name = "glm rows wide q6 glm_rows_wide_q6", .threads = 64, .tg_memory = 0, .reserved = 64 }, .{ .name = "glm rows q8 glm_rows_q8", .threads = 64, .tg_memory = 0, .reserved = 64 }, .{ .name = "glm rows wide q8 glm_rows_wide_q8", .threads = 64, .tg_memory = 0, .reserved = 64 }, + .{ .name = "glm moe rows u q2 glm_moe_rows_u_q2_s8", .threads = 512, .tg_memory = 0, .reserved = 512 }, + .{ .name = "glm moe rows glu u q2 glm_moe_rows_glu_u_q2_s8", .threads = 512, .tg_memory = 0, .reserved = 512 }, + .{ .name = "glm moe rows u q3 glm_moe_rows_u_q3_s8", .threads = 512, .tg_memory = 0, .reserved = 512 }, + .{ .name = "glm moe rows glu u q3 glm_moe_rows_glu_u_q3_s8", .threads = 512, .tg_memory = 0, .reserved = 512 }, + .{ .name = "glm moe rows u q4 glm_moe_rows_u_q4_s8", .threads = 512, .tg_memory = 0, .reserved = 512 }, + .{ .name = "glm moe rows glu u q4 glm_moe_rows_glu_u_q4_s8", .threads = 512, .tg_memory = 0, .reserved = 512 }, + .{ .name = "glm moe rows u q5 glm_moe_rows_u_q5_s8", .threads = 512, .tg_memory = 0, .reserved = 512 }, + .{ .name = "glm moe rows glu u q5 glm_moe_rows_glu_u_q5_s8", .threads = 512, .tg_memory = 0, .reserved = 512 }, + .{ .name = "glm moe rows u q6 glm_moe_rows_u_q6_s8", .threads = 512, .tg_memory = 0, .reserved = 512 }, + .{ .name = "glm moe rows glu u q6 glm_moe_rows_glu_u_q6_s8", .threads = 512, .tg_memory = 0, .reserved = 512 }, + .{ .name = "glm moe rows u q8 glm_moe_rows_u_q8_s8", .threads = 512, .tg_memory = 0, .reserved = 512 }, + .{ .name = "glm moe rows glu u q8 glm_moe_rows_glu_u_q8_s8", .threads = 512, .tg_memory = 0, .reserved = 512 }, }; test "the GLM row launches fit every Apple family" { diff --git a/zig/src/core/contract/hip_records_sparse.zig b/zig/src/core/contract/hip_records_sparse.zig index 5f3ad18bb0e..d0a849bf435 100644 --- a/zig/src/core/contract/hip_records_sparse.zig +++ b/zig/src/core/contract/hip_records_sparse.zig @@ -1,5 +1,7 @@ -//! Gate 5's records of Flash Next's lanes sparse attention (tf_fn_sparse_lanes12_*). -const Record = @import("hip_records.zig").Record; +//! Gate 5's records of Flash Next's indexer block scores and sparse attention on HIP. +const std = @import("std"); +const hip_records = @import("hip_records.zig"); +const Record = hip_records.Record; /// Flash Next's lanes sparse attention, 12 query heads a kv head, one cache kind (`early` VGPRs: gfx1030, gfx1100). fn sparseLanes(comptime kind: []const u8, comptime early: u32, comptime late: u32) Record { @@ -16,6 +18,30 @@ fn sparseLanes(comptime kind: []const u8, comptime early: u32, comptime late: u3 } pub const records = [_]Record{ + .{ + .launch = .{ + .name = "flashnext tf_fn_idx_scores", + .symbol = "tf_fn_idx_scores", + .image = "flashnext", + .threads = 256, + }, + .usage = .{ + .{ .vgprs = 24, .sgprs = 39, .lds = 16384, .private = 0, .bound = 256, .wave = 32 }, + .{ .vgprs = 24, .sgprs = 39, .lds = 16384, .private = 0, .bound = 256, .wave = 32 }, + .{ .vgprs = 24, .sgprs = 39, .lds = 16384, .private = 0, .bound = 256, .wave = 32 }, + .{ .vgprs = 23, .sgprs = 40, .lds = 16384, .private = 0, .bound = 256, .wave = 32 }, + }, + }, sparseLanes("f16", 74, 72), sparseLanes("bf16", 84, 83), }; + +test "tf_fn_idx_scores carries its LDS-staged Gate 5 record and fits every served RDNA chip" { + var found: ?Record = null; + for (hip_records.records) |r| if (std.mem.eql(u8, r.launch.symbol, "tf_fn_idx_scores")) { + found = r; + }; + const rec = found orelse return error.MissingRecord; + try std.testing.expectEqual(@as(u32, 16384), rec.usage[0].lds); + try std.testing.expectEqual(@as(usize, 0), try hip_records.check(std.testing.allocator, &.{rec}, true)); +} diff --git a/zig/src/core/contract/prompt_index_records.zig b/zig/src/core/contract/prompt_index_records.zig new file mode 100644 index 00000000000..1aa95c7b15d --- /dev/null +++ b/zig/src/core/contract/prompt_index_records.zig @@ -0,0 +1,15 @@ +//! The indexed prompt gathers: the 128-thread groups the patched text reserves, and the gathers' dequantized tiles. +const M = @import("limits.zig").MetalLaunch; +const tile = @import("fsr_records.zig").gather_memory; +pub const metal = [_]M{ + .{ .name = "flashnext prompt index tf_gather_qmmw_nax_32", .threads = 128, .tg_memory = tile, .reserved = 128 }, + .{ .name = "flashnext prompt index tf_gather_qmmw_nax_64", .threads = 128, .tg_memory = tile, .reserved = 128 }, + .{ .name = "flashnext prompt index tf_gather_qmmw_nax_128", .threads = 128, .tg_memory = tile, .reserved = 128 }, + .{ .name = "flashnext prompt index tf_gather_guw_nax_32", .threads = 128, .tg_memory = 2 * tile, .reserved = 128 }, + .{ .name = "flashnext prompt index tf_gather_guw_nax_64", .threads = 128, .tg_memory = 2 * tile, .reserved = 128 }, + .{ .name = "flashnext grouped index gx_pick", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "flashnext grouped index gx_list", .threads = 512, .tg_memory = 7488, .reserved = 512 }, + .{ .name = "flashnext grouped index gx_gateup", .threads = 64, .tg_memory = 0, .reserved = 64 }, + .{ .name = "flashnext grouped index gx_down_one", .threads = 64, .tg_memory = 0, .reserved = 64 }, + .{ .name = "flashnext grouped index gx_down_tile", .threads = 64, .tg_memory = 1280, .reserved = 64 }, +}; diff --git a/zig/src/core/contract/qwen_whole_records.zig b/zig/src/core/contract/qwen_whole_records.zig index 01c4fcb2e82..6ef0f1b5014 100644 --- a/zig/src/core/contract/qwen_whole_records.zig +++ b/zig/src/core/contract/qwen_whole_records.zig @@ -1,4 +1,4 @@ -//! nvcc 13.0 five-SM usage for separate whole-window and paged prompt ABIs. +//! nvcc 13.0 five-SM usage for separate whole-window, paged prompt and join rows ABIs. const std = @import("std"); const reg = @import("registry.zig"); pub const records = [_]reg.CudaRecord{ @@ -32,6 +32,20 @@ pub const records = [_]reg.CudaRecord{ .{ .regs = 243, .static = 39936, .bound = 256 }, .{ .regs = 243, .static = 39936, .bound = 256 }, }, .later_pending = true }, + .{ .launch = .{ .name = "tf_q35_attn_rows_join", .symbol = "tf_q35_attn_rows_join", .image = "qwen35", .threads = 256, .dynamic = 65536, .opt_in = true, .min_sm = 80 }, .usage = .{ + .{ .regs = 255, .static = 7168, .bound = 256 }, + .{ .regs = 255, .static = 7168, .bound = 256 }, + .{ .regs = 255, .static = 7168, .bound = 256 }, + .{ .regs = 249, .static = 7168, .bound = 256 }, + .{ .regs = 249, .static = 7168, .bound = 256 }, + }, .later_pending = true }, + .{ .launch = .{ .name = "tf_q35_attn_rows8_join", .symbol = "tf_q35_attn_rows8_join", .image = "qwen35_kv8", .threads = 256, .dynamic = 0, .opt_in = false, .min_sm = 80 }, .usage = .{ + .{ .regs = 254, .static = 40192, .bound = 256 }, + .{ .regs = 254, .static = 40192, .bound = 256 }, + .{ .regs = 255, .static = 40192, .bound = 256 }, + .{ .regs = 243, .static = 40192, .bound = 256 }, + .{ .regs = 243, .static = 40192, .bound = 256 }, + }, .later_pending = true }, .{ .launch = .{ .name = "_ZN20tf_prefill_attention19hpattn_whole_kernelILi256ELi8ELi2ELi2EEEvPK13__nv_bfloat16S3_S3_PS1_iiiiifi", .symbol = "_ZN20tf_prefill_attention19hpattn_whole_kernelILi256ELi8ELi2ELi2EEEvPK13__nv_bfloat16S3_S3_PS1_iiiiifi", .image = "prefill_attention", .threads = 256, .dynamic = 98304, .opt_in = true, .min_sm = 80 }, .usage = .{ .{ .regs = 254, .static = 0, .bound = 256 }, .{ .regs = 254, .static = 0, .bound = 256 }, diff --git a/zig/src/core/contract/registry_joins.zig b/zig/src/core/contract/registry_joins.zig index 43b1970217d..5810602cbc1 100644 --- a/zig/src/core/contract/registry_joins.zig +++ b/zig/src/core/contract/registry_joins.zig @@ -63,8 +63,10 @@ pub const all_metal = @import("lane_q8_records.zig").records ++ @import("simd_half_records.zig").records ++ @import("metal_pair_records.zig").records ++ @import("glm_rows_records.zig").records ++ + @import("row_wide_records.zig").records ++ @import("weight_only_records.zig").metal ++ @import("grouped_records.zig").metal ++ + @import("prompt_index_records.zig").metal ++ @import("hc_activation_records.zig").metal ++ @import("qwen4_records.zig").metal ++ @import("lfm2_records.zig").records ++ diff --git a/zig/src/core/contract/row_wide_records.zig b/zig/src/core/contract/row_wide_records.zig new file mode 100644 index 00000000000..d9e3cc2e7a5 --- /dev/null +++ b/zig/src/core/contract/row_wide_records.zig @@ -0,0 +1,19 @@ +//! Wide row launches reserve their 64 threads in source; no measured compiler limits are inferred. +const std = @import("std"); +const M = @import("limits.zig").MetalLaunch; +pub const records = blk: { + var out: [36]M = undefined; + var i: usize = 0; + for ([_]u8{ 2, 3, 4, 5, 6, 8 }) |bits| for (.{ "f32", "bf16" }) |sum| { + for (.{ "", "_relu2", "_strided" }) |style| { + out[i] = .{ .name = std.fmt.comptimePrint("row projection wide tf_row_projection_wide{s}_q{d}_{s}", .{ style, bits, sum }), .threads = 64, .tg_memory = 0, .reserved = 64 }; + i += 1; + } + }; + break :blk out; +}; + +test "wide row launch declarations cover all new symbols and fit every Apple family" { + try std.testing.expectEqual(@as(usize, 36), records.len); + try std.testing.expectEqual(@as(usize, 0), try @import("registry.zig").checkMetal(std.testing.allocator, &records, true)); +} diff --git a/zig/src/core/h3_core.zig b/zig/src/core/h3_core.zig new file mode 100644 index 00000000000..335d14de700 --- /dev/null +++ b/zig/src/core/h3_core.zig @@ -0,0 +1,5 @@ +//! The core files H3 reads (safetensors, the checked read-ahead and its fixture), one module: the H3 image tools also +//! take core's pictures, the Qwen-VL tower and its rotary table as modules of their own, so they cannot share core's root. +pub const safetensors = @import("safetensors.zig"); +pub const checkpoint_read_ahead = @import("checkpoint_read_ahead.zig"); +pub const checkpoint_fixture = @import("checkpoint_fixture.zig"); diff --git a/zig/src/core/lane_host.zig b/zig/src/core/lane_host.zig index a4e73a0bb8a..c0cf7231390 100644 --- a/zig/src/core/lane_host.zig +++ b/zig/src/core/lane_host.zig @@ -160,6 +160,12 @@ pub const LaneHost = struct { return .{ .ctx = h, .vtable = if (vt.score != null and vt.decide != null) &decided_vtable else if (vt.score != null) &scored_vtable else &plain_vtable }; } + /// Advertise the cache capabilities: warm turns follow the store, so a cache-less start claims none. + pub fn advertiseCache(h: *LaneHost, store: ?*pc.Store) void { + h.info_.prompt_cache = store != null; + h.info_.warm_turns = store != null; + } + const plain_vtable: Engine.VTable = .{ .info = infoFn, .submit = submitFn, diff --git a/zig/src/core/lane_host_explore_test.zig b/zig/src/core/lane_host_explore_test.zig new file mode 100644 index 00000000000..d724fa31441 --- /dev/null +++ b/zig/src/core/lane_host_explore_test.zig @@ -0,0 +1,403 @@ +//! Schedule exploration for the lane host: a seed picks arrivals, cancels, room and pressure at each backend call. +const std = @import("std"); +const lanes = @import("lanes"); +const api = @import("engine_api.zig"); +const fill = @import("lane_host_fill.zig"); +const pressure = @import("memory_pressure.zig"); +const options = @import("explore_options"); +const be = lanes.backend; +const Reason = api.Reason; +const gpa = std.testing.allocator; +const io = std.testing.io; + +/// Where the fake target yields: a prompt call, a prompt step, a batched pass, a first draw, a one-token step, a round. +const Point = enum { prefill, step, many, first, queue, verify }; + +/// What the seed may do at a yield point. +const Act = enum { none, arrive, cancel, room, pressure }; + +/// An invariant a yield point saw broken, reported once the schedule ends. +const Broken = error{ ChunkOutOfOrder, LanesPastHost, RowsPastBudget }; + +/// One request as its client saw it: tokens, finished events, and whether the explorer cancelled it. +const Box = struct { + mutex: std.Io.Mutex = .init, + tokens: std.ArrayList(u32) = .empty, + done: ?Reason = null, + ends: u32 = 0, // finished events: exactly one + late: bool = false, // an event came after the finish + cancel_sent: bool = false, + + fn event(ctx: *anyopaque, _: api.Id, e: *const api.Event) void { + const b: *Box = @ptrCast(@alignCast(ctx)); + b.mutex.lockUncancelable(io); + defer b.mutex.unlock(io); + if (b.ends > 0) b.late = true; + switch (e.*) { + .tokens => |t| b.tokens.appendSlice(gpa, t) catch {}, + .finished => |f| { + b.done = f.reason; + b.ends += 1; + }, + else => {}, + } + } + + fn finished(b: *Box) bool { + b.mutex.lockUncancelable(io); + defer b.mutex.unlock(io); + return b.ends > 0; + } +}; + +/// The seeded scheduler: requests not yet sent, and the choices it makes on the engine thread at each yield point. +const Explorer = struct { + rng: std.Random.DefaultPrng, + mutex: std.Io.Mutex = .init, // `next`: the engine thread's arrivals at yield points, the test thread's when idle + engine: api.Engine, + core: *lanes.Engine, + target: *lanes.fake.Fake, + requests: []const api.Request, + boxes: []Box, + calls: []usize, // each request's prompt calls so far (its chunk index next) + next: usize = 0, // the next request to arrive + lanes: usize, // the host's lanes: the backend never holds more + budget: u64, // prompt rows a visit beside decoders (0: none) + rows: u64 = 0, // prompt rows stepped beside a decoder since the core's last round + steps: u64 = 0, // the core's rounds when `rows` last counted + dial: pressure.Level = .normal, // the memory pressure the host reads + broken: ?Broken = null, // the first invariant a yield point saw broken + digest: std.hash.Wyhash, // every yield point and act, then every reply: a replay must match it + tally: *Tally, + + fn below(x: *Explorer, n: usize) usize { + return x.rng.random().uintLessThan(usize, n); + } + + fn fail(x: *Explorer, e: Broken) void { + if (x.broken == null) x.broken = e; + } + + fn mix(x: *Explorer, values: []const u64) void { + x.digest.update(std.mem.sliceAsBytes(values)); + } + + fn sent(x: *Explorer) usize { + x.mutex.lockUncancelable(io); + defer x.mutex.unlock(io); + return x.next; + } + + /// The next request, from the engine thread at a yield point or the test thread while the engine idles. + fn send(x: *Explorer) void { + x.mutex.lockUncancelable(io); + defer x.mutex.unlock(io); + if (x.next >= x.requests.len) return; + const i = x.next; + x.next += 1; + const b = &x.boxes[i]; + x.engine.submit(@intCast(i + 1), &x.requests[i], .{ .ctx = b, .event = Box.event }) catch { + b.mutex.lockUncancelable(io); + defer b.mutex.unlock(io); + b.done = .failed; // refused: the check after the schedule fails it + b.ends += 1; + }; + } + + /// One yield point: the backend's lanes checked against the host's, then the act the seed picks there. + fn point(x: *Explorer, at: Point) void { + if (x.target.lanes.count() > x.lanes) x.fail(error.LanesPastHost); + var act: Act = switch (x.below(20)) { + 0...5 => .arrive, + 6, 7 => .cancel, + 8 => .room, + 9 => .pressure, + else => .none, + }; + var arg: u64 = 0; + switch (act) { + .none => {}, + .arrive => if (x.sent() < x.requests.len) x.send() else { + act = .none; + }, + .cancel => if (x.sent() > 0) { + const i = x.below(x.sent()); // a request still queued, filling, decoding or already ended + x.boxes[i].cancel_sent = true; + x.engine.cancel(@intCast(i + 1)); + arg = i; + } else { + act = .none; + }, + // the backend's room for live lanes moves, as when other memory comes and goes: a pass past it is refused + .room => { + arg = x.below(4); + x.target.memory_lanes = if (arg < 3) arg + 1 else null; + }, + .pressure => { + arg = x.below(2); + x.dial = if (arg == 0) .warning else .normal; // warning: one stream admitted at a time + }, + } + x.tally.acts[@backingInt(at)][@backingInt(act)] += 1; + x.mix(&.{ @backingInt(at), @backingInt(act), arg }); + } + + /// Before a prompt step: rows stepped beside a decoder since the core's last round stay under the budget. + fn stepBegins(x: *Explorer) bool { + var decoding = false; + for (x.core.live.items) |s| decoding = decoding or (!s.finished and !s.paused); + if (!decoding or x.core.steps != x.steps) x.rows = 0; // a visit with no decoder counts none, as the host's + x.steps = x.core.steps; + if (x.budget > 0 and x.rows >= x.budget) x.fail(error.RowsPastBudget); + return decoding; + } + + /// The host's memory pressure reading: the dial the seed turns. + fn reading(ctx: ?*anyopaque) ?pressure.Level { + const x: *Explorer = @ptrCast(@alignCast(ctx.?)); + return x.dial; + } + + /// Whether every request sent has ended; if so, and some are left, the test thread sends the next (true: all done). + fn idle(x: *Explorer) bool { + const n = x.sent(); + for (x.boxes[0..n]) |*b| if (!b.finished()) return false; + if (n == x.requests.len) return true; + x.send(); // no yield point comes while nothing is in flight: this send races none of the engine thread's + return false; + } + + /// A prompt call for `s`: its chunk index must be its request's next (named by its prompt's last token). + fn chunk(ctx: *anyopaque, s: *lanes.Stream, at: usize) void { + const x: *Explorer = @ptrCast(@alignCast(ctx)); + const p = s.prompt(); + const i: usize = p[p.len - 1] - first_token; + if (i < x.calls.len) { + if (x.calls[i] != at and at != 0) x.fail(error.ChunkOutOfOrder); // a retry starts over at 0 + x.calls[i] = at + 1; + } + } +}; + +/// What a sweep's schedules did, so a run shows what it explored. +const Tally = struct { + acts: [6][5]usize = @splat(@splat(0)), // by yield point, then act + shared: usize = 0, // rounds verified for several streams together + drafted: usize = 0, // verified windows with draft rows + refused: usize = 0, // prompt passes refused for room + cancelled: usize = 0, // requests that ended cancelled + + fn print(t: *const Tally, kind: Kind, seeds: usize) void { + std.debug.print("lane host explore ({s}): {d} seeds, {d} shared rounds, {d} drafted windows, {d} room refusals, {d} ended cancelled\n", .{ @tagName(kind), seeds, t.shared, t.drafted, t.refused, t.cancelled }); + for (t.acts, 0..) |row, p| { + var all: usize = 0; + for (row) |n| all += n; + std.debug.print(" {s}: {d} yields, {d} arrivals, {d} cancels, {d} room, {d} pressure\n", .{ @tagName(@as(Point, @fromBackingInt(@intCast(p)))), all, row[1], row[2], row[3], row[4] }); + } + } +}; + +/// The explorer the wrapped target calls (one schedule runs at a time). +var current: ?*Explorer = null; + +/// The target's own vtable, which the wrapped one calls through. +var inner_vt: *const be.Backend.VTable = undefined; + +/// The target's own vtable with a yield point before each call a schedule can interleave with. +const Wrapped = struct { + fn yield(at: Point) void { + if (current) |x| x.point(at); + } + fn refused(e: anyerror) anyerror { + if (e == error.LaneMemory) if (current) |x| { + x.tally.refused += 1; + }; + return e; + } + fn prefill(ptr: *anyopaque, s: *lanes.Stream) anyerror!void { + yield(.prefill); + return inner_vt.prefill(ptr, s) catch |e| refused(e); + } + fn prefillStep(ptr: *anyopaque, s: *lanes.Stream, max_rows: u32) anyerror!bool { + yield(.step); + const x = current orelse return inner_vt.prefill_step.?(ptr, s, max_rows); + const decoding = x.stepBegins(); + const from = s.fill_at.load(.monotonic); + const done = inner_vt.prefill_step.?(ptr, s, max_rows) catch |e| return refused(e); + if (decoding) x.rows += s.fill_at.load(.monotonic) -| from; + return done; + } + fn prefillMany(ptr: *anyopaque, ss: []const *lanes.Stream) anyerror!bool { + yield(.many); + const took = try inner_vt.prefill_many.?(ptr, ss); + if (!took) if (current) |x| { + x.tally.refused += 1; + }; + return took; + } + fn first(ptr: *anyopaque, s: *lanes.Stream, position: u64) anyerror!u64 { + yield(.first); + return inner_vt.first(ptr, s, position); + } + fn queue(ptr: *anyopaque, s: *lanes.Stream, feed: be.Feed, position: u64) anyerror!u64 { + yield(.queue); + return inner_vt.queue(ptr, s, feed, position); + } + fn verify(ptr: *anyopaque, windows: []const be.Window, out: []be.Verified) anyerror!void { + yield(.verify); + if (current) |x| { + x.tally.shared += @intFromBool(windows.len > 1); + for (windows) |w| x.tally.drafted += @intFromBool(w.held > 0 or w.tokens.len > 0); + } + return inner_vt.verify(ptr, windows, out); + } + /// `inner` with its calls wrapped (`inner_vt` set to its own table). + fn of(inner: be.Backend, table: *be.Backend.VTable) be.Backend { + inner_vt = inner.vtable; + table.* = inner.vtable.*; + table.prefill = prefill; + if (inner.vtable.prefill_step != null) table.prefill_step = prefillStep; + if (inner.vtable.prefill_many != null) table.prefill_many = prefillMany; + table.first = first; + table.queue = queue; + table.verify = verify; + var out = inner; + out.vtable = table; + return out; + } +}; + +/// Prompts end in `first_token + i` for request i: the hook names a stream's request by it. +const first_token = 40; + +/// A reply as a solo run of its request gives it: the fake target's own continuation (a cancelled one's prefix). +fn expectOwn(q: api.Request, tokens: []const u32) !void { + var history: std.ArrayList(u32) = .empty; + defer history.deinit(gpa); + try history.appendSlice(gpa, q.prompt); + for (tokens) |t| { + try std.testing.expectEqual(lanes.fake.next(history.items, q.sampling, history.items.len), t); + try history.append(gpa, t); + } +} + +const Kind = enum { many, service }; + +/// One schedule: the scenario's requests sent as the seed says, then every invariant; the schedule's digest. +fn explore(kind: Kind, seed: u64, tally: *Tally) !u64 { + var setup = std.Random.DefaultPrng.init(seed ^ 0x9e3779b97f4a7c15); + const r = setup.random(); + const many = kind == .many; + const head = r.boolean(); // a draft head: drafted rounds whose wrong drafts roll back + var cfg = try lanes.Config.init(gpa, .{ .exact_width = 8, .gpu_tokens = r.boolean(), .hidden_rows = true, .mtp = head, .speculate = head, .speculate_early = r.boolean(), .drafts = 3, .draft_streams = r.boolean() }, 8, 7); + defer cfg.deinit(gpa); + var target: lanes.fake.Fake = .{ .gpa = gpa, .prefill_chunks = if (many) 0 else 2 + r.uintLessThan(usize, 3) }; + defer target.deinit(); + const inner = switch (kind) { + .many => if (r.boolean()) target.batched() else target.batchedSteps(), + .service => target.stepped(), + }; + var table: be.Backend.VTable = undefined; + var clock: lanes.fake.FixedClock = .{}; + var core = lanes.Engine.init(gpa, &cfg, Wrapped.of(inner, &table), clock.clock()); + defer core.deinit(); + const slots = 1 + r.uintLessThan(u32, 4); + var host = api.LaneHost.init(gpa, io, &core, .{ .lanes = slots }); + // the environment's prompt order, share and waits pinned: a seed is one schedule on any machine + const budgets = [_]u64{ 0, 24, fill.Share.short_rows }; + host.share = .{ .rows = if (many) 0 else budgets[r.uintLessThan(usize, budgets.len)] }; + host.srpt = .{}; + host.prefix = .{ .ns = 0 }; + const n = 2 + r.uintLessThan(usize, 5); + var prompts: [6][48]u32 = undefined; + var requests: [6]api.Request = undefined; + var boxes: [6]Box = @splat(.{}); + defer for (&boxes) |*b| b.tokens.deinit(gpa); + var calls: [6]usize = @splat(0); + const drafts = r.boolean(); + for (0..n) |i| { + const len: usize = if (many) 5 else if (i == 0) 4 else 48; + @memset(prompts[i][0..len], @intCast(2 + i % 5)); + prompts[i][len - 1] = @intCast(first_token + i); + const sampling: ?api.Sampling = if (r.boolean()) .{ .seed = seed +% i, .temperature = 0.8, .top_k = 8 } else null; + requests[i] = .{ .prompt = prompts[i][0..len], .max_tokens = if (!many and i == 0) 24 else 8, .drafts = drafts, .sampling = sampling }; + } + var x: Explorer = .{ .rng = .init(seed), .engine = host.engine(), .core = &core, .target = &target, .requests = requests[0..n], .boxes = boxes[0..n], .calls = calls[0..n], .lanes = slots, .budget = host.share.rows, .digest = .init(seed), .tally = tally }; + host.pressure = .{ .source = .{ .ctx = &x, .read = Explorer.reading }, .calm_ns = 0, .every_ns = 0 }; + target.prefill_hook = Explorer.chunk; + target.prefill_hook_ctx = &x; + current = &x; + defer current = null; + for (0..1 + r.uintLessThan(usize, n)) |_| x.send(); + try host.start(); + var running = true; + defer if (running) host.stop(); + // the test thread sends the rest only when nothing is in flight: the engine thread's own sends stay seeded + var waited: usize = 0; + while (!x.idle()) : (waited += 1) { + if (waited > 20_000) return error.ScheduleStalled; + std.Io.sleep(io, .fromMilliseconds(1), .awake) catch {}; + } + host.stop(); + running = false; + if (x.broken) |e| return e; + for (boxes[0..n], requests[0..n]) |*b, q| { + if (b.ends != 1 or b.late) return error.NotFinishedOnce; + const reason = b.done.?; + switch (reason) { + .length => try std.testing.expectEqual(@as(usize, q.max_tokens), b.tokens.items.len), + .cancelled => if (!b.cancel_sent) return error.CancelledUnasked, + else => return error.UnexpectedReason, + } + if (b.tokens.items.len > q.max_tokens) return error.TokensPastMax; + tally.cancelled += @intFromBool(reason == .cancelled); + try expectOwn(q, b.tokens.items); + x.mix(&.{ @backingInt(reason), b.tokens.items.len }); + x.digest.update(std.mem.sliceAsBytes(b.tokens.items)); + } + try std.testing.expectEqual(@as(usize, 0), target.lanes.count()); // every lane released + try std.testing.expectEqual(@as(usize, 0), core.activeCount()); + return x.digest.final(); +} + +/// The sweep's seeds: `options.seeds` of them from here. +const first_seed: u64 = 0x5eed_0000; + +/// Every seed in the sweep (or the one -Dexplore-seed names); a failure names its seed so it replays. +fn sweep(kind: Kind) !void { + const level = std.testing.log_level; + std.testing.log_level = .err; // a refused batched pass logs a warning + defer std.testing.log_level = level; + var tally: Tally = .{}; + if (options.seed) |s| return failing(kind, s, explore(kind, s, &tally)); + for (0..options.seeds) |i| try failing(kind, first_seed + i, explore(kind, first_seed + i, &tally)); + if (options.tally) tally.print(kind, options.seeds); +} + +/// A schedule's result, its seed and replay line printed when it failed. +fn failing(kind: Kind, seed: u64, result: anyerror!u64) !void { + _ = result catch |err| { + std.debug.print("lane host explore ({s}): seed {d} failed ({s}); replay: zig build test-lane-explore-host -Dexplore-seed={d}\n", .{ @tagName(kind), seed, @errorName(err), seed }); + return err; + }; +} + +test "explore: queued requests through batched prompt passes, under seeded arrivals, cancels, room and pressure" { + try sweep(.many); +} + +test "explore: a decoder beside chunked prompts and the prompt-row budget, under seeded arrivals, cancels, room and pressure" { + try sweep(.service); +} + +test "explore: a seed replays its schedule, every yield point's act and every reply the same" { + const level = std.testing.log_level; + std.testing.log_level = .err; + defer std.testing.log_level = level; + var tally: Tally = .{}; + for ([_]Kind{ .many, .service }) |kind| for (0..if (options.seed == null) @min(options.seeds, 16) else 1) |i| { + const seed = options.seed orelse first_seed + i; + const a = explore(kind, seed, &tally) catch |err| return failing(kind, seed, err); + if (a != try explore(kind, seed, &tally)) return failing(kind, seed, error.ScheduleNotReplayed); + }; +} diff --git a/zig/src/core/lane_host_warm_test.zig b/zig/src/core/lane_host_warm_test.zig index d987e1bfb5e..3d2d2b97054 100644 --- a/zig/src/core/lane_host_warm_test.zig +++ b/zig/src/core/lane_host_warm_test.zig @@ -3,6 +3,7 @@ const std = @import("std"); const lanes = @import("lanes"); const api = @import("engine_api.zig"); const LaneHost = @import("lane_host.zig").LaneHost; +const prompt_cache = @import("prompt_cache.zig"); const Reason = api.Reason; const Id = api.Id; const Event = api.Event; @@ -235,6 +236,58 @@ test "a warm_usable store keeps a warm pass's grid mark but not its end off the } } +test "a one-snapshot store keeps the warm pass's usable mark over an unusable end; the next request resumes the mark" { + const gpa = std.testing.allocator; + const pc = api.prompt_cache; + const Snaps = struct { + fn bytes(_: *anyopaque, at: u32) u64 { + return 64 + 4 * @as(u64, at); + } + fn save(ptr: *anyopaque, owner: ?*anyopaque, at: u32) anyerror!pc.Saved { + const f: *lanes.fake.Fake = @ptrCast(@alignCast(ptr)); + return f.save(@ptrCast(@alignCast(owner.?)), at); + } + fn restore(_: *anyopaque, _: ?*anyopaque, _: pc.Saved) anyerror!void { + return error.BackendRestores; + } + fn drop(ptr: *anyopaque, saved: pc.Saved) void { + const f: *lanes.fake.Fake = @ptrCast(@alignCast(ptr)); + f.drop(saved); + } + }; + for ([_]bool{ true, false }) |usable| { + var cfg = try lanes.Config.init(gpa, .{ .exact_width = 8, .gpu_tokens = true, .hidden_rows = true }, 8, 7); + defer cfg.deinit(gpa); + var target: lanes.fake.Fake = .{ .gpa = gpa }; + defer target.deinit(); + var clock: lanes.fake.FixedClock = .{}; + var core = lanes.Engine.init(gpa, &cfg, target.backend(), clock.clock()); + defer core.deinit(); + + // The 128-row cut and 192-row warm end, scaled to a grid of 4: the end at 6 is off it. + + // A budget of one snapshot (88 B) fits either state, never both. + var store = pc.Store.init(gpa, .{ .ptr = &target, .vtable = &.{ .bytes = Snaps.bytes, .save = Snaps.save, .restore = Snaps.restore, .drop = Snaps.drop } }, .{ .planned = true, .grid = 4, .warm = .on, .warm_usable = usable }, 100); + defer store.deinit(); + var host = LaneHost.init(gpa, std.testing.io, &core, .{ .lanes = 2, .warm_turns = true }); + host.cache = &store; + try host.start(); + defer host.stop(); + const prompt = [_]u32{ 2, 7, 1, 8, 2, 8 }; + var warm: Box = .{}; + const warm_request: Request = .{ .prompt = &prompt, .max_tokens = 0, .background = true, .history_len = prompt.len, .born = 4 }; + try host.engine().submit(1, &warm_request, .{ .ctx = &warm, .event = Box.event }); + try std.testing.expectEqual(Reason.length, warm.wait()); + host.engine().drain(); + + // The unusable end must not cost the usable mark: a follow-up resumes the grid mark, or nothing. + const longer = [_]u32{ 2, 7, 1, 8, 2, 8, 3, 1 }; + const follow = try store.lookup(gpa, &longer, longer.len, &.{}, &.{}, &.{}); + defer gpa.free(follow.marks); + try std.testing.expectEqual(if (usable) @as(u32, 4) else @as(u32, 0), if (follow.entry) |e| e.at else 0); + } +} + /// Status polls taken at each prompt chunk, the warm pass's apart from the request's. const FillPolls = struct { engine: Engine = undefined, @@ -373,3 +426,13 @@ test "a kept warm end supersedes its history at either lookahead and regeneratio try std.testing.expect(got.same); } } + +test "a host advertises warm turns only beside a kept-state store" { + var host: LaneHost = undefined; + host.info_ = .{}; + host.advertiseCache(null); + try std.testing.expect(!host.info_.prompt_cache and !host.info_.warm_turns); + var store: prompt_cache.Store = undefined; + host.advertiseCache(&store); + try std.testing.expect(host.info_.prompt_cache and host.info_.warm_turns); +} diff --git a/zig/src/core/lanes/backend.zig b/zig/src/core/lanes/backend.zig index 48e2c8ffa23..8e8d9e6a628 100644 --- a/zig/src/core/lanes/backend.zig +++ b/zig/src/core/lanes/backend.zig @@ -117,7 +117,7 @@ pub const Backend = struct { clear_proposals: ?*const fn (*anyopaque, *Stream) void = null, /// Undo an early speculation whose round was cut (the drafts come from a late request instead). unspeculate: ?*const fn (ptr: *anyopaque, s: *Stream) anyerror!void = null, - /// Each held draft's chance of landing, for heads that give them; false when it has none. + /// Each held draft's chance, or false; also marks s.draft_chances_cut at the first unmeasured chance. probabilities: ?*const fn (ptr: *anyopaque, s: *Stream, out: []f64) anyerror!bool = null, /// A tree head's held drafts as host tokens and parents (gpa-owned), read where Python reads them. tree: ?*const fn (ptr: *anyopaque, s: *Stream, gpa: std.mem.Allocator) anyerror!?Held = null, diff --git a/zig/src/core/lanes/lanes.zig b/zig/src/core/lanes/lanes.zig index 79e83a57eb2..f9b284af8ae 100644 --- a/zig/src/core/lanes/lanes.zig +++ b/zig/src/core/lanes/lanes.zig @@ -79,6 +79,7 @@ test { _ = @import("root_copy_test.zig"); _ = @import("drafted_grammar_test.zig"); _ = @import("windows_grammar_test.zig"); + _ = @import("windows_chances_test.zig"); _ = @import("grammar_time_test.zig"); _ = @import("grammar_parallel_test.zig"); _ = @import("pricing_test.zig"); diff --git a/zig/src/core/lanes/shared_drafts.zig b/zig/src/core/lanes/shared_drafts.zig index d0b005bb997..f886081ceac 100644 --- a/zig/src/core/lanes/shared_drafts.zig +++ b/zig/src/core/lanes/shared_drafts.zig @@ -37,10 +37,10 @@ pub fn budgets(e: *Engine, plans: []const win.Plan, heads: []const usize, out: [ if (most == 0) continue; head.* = true; const cached = s.draft_chances.items; - // a legacy cap prices by the rule's rates; granted depths keep the drafter's own chances under their bound - if (cached.len > 0 and (limits == null or e.cfg.granted_depth)) { + // a legacy cap prices by the rule's rates; a cut never starts the tail, so the measured prefix prices the rest + const known = @min(s.draft_chances_cut orelse cached.len, cached.len, most); + if (known > 0 and (limits == null or e.cfg.granted_depth)) { const prices = try a.alloc(f64, most); - const known = @min(cached.len, most); @memcpy(prices[0..known], cached[0..known]); const rates = try e.rule.rates(win.who(s)); var chance = cached[known - 1]; @@ -187,3 +187,36 @@ test "shared draft prices: plain forced streams cost one row and paused streams try budgets(&e, &plans, &.{0}, &out); try std.testing.expectEqual(@as(i64, 7), out[0]); } + +test "shared draft prices: a cut chance tail prices by the rule's rates, not as a measured zero" { + const a = std.testing.allocator; + const Cfg = @import("config.zig"); + const S = @import("stream.zig").Stream; + var cfg = try Cfg.Config.init(a, .{ .exact_width = 32, .drafts = 5, .batch_rows = 11 }, 32, 5); + defer cfg.deinit(a); + var fake: @import("fake.zig").Fake = .{ .gpa = a }; + defer fake.deinit(); + var clock: @import("fake.zig").FixedClock = .{}; + var e = Engine.init(a, &cfg, fake.backend(), clock.clock()); + defer e.deinit(); + var cut = try S.init(a, .{ .id = "cut", .prompt = &.{ 7, 13, 29 }, .max_new = 64 }); + defer cut.deinit(a); + var zero = try S.init(a, .{ .id = "zero", .prompt = &.{ 7, 13, 29 }, .max_new = 64 }); + defer zero.deinit(a); + var grown = try S.init(a, .{ .id = "grown", .prompt = &.{ 7, 13, 29 }, .max_new = 64 }); + defer grown.deinit(a); + try cut.draft_chances.appendSlice(a, &.{ 0.9, 0.4, 0, 0, 0 }); + cut.draft_chances_cut = 2; // the chain cut left the last three chances unknown + try zero.draft_chances.appendSlice(a, &.{ 0.9, 0.4, 0, 0, 0 }); // main's rule: that tail priced as measured zeros + const rates = try e.rule.rates(win.who(&grown)); + var continuation = [_]f64{ 0.9, 0.4, 0, 0, 0 }; + for (continuation[2..], 2..) |*c, j| c.* = continuation[j - 1] * rates[@min(j, rates.len - 1)]; + try grown.draft_chances.appendSlice(a, &continuation); + const cutp: win.Plan = .{ .stream = &cut, .position = 0, .kind = .none }; + const zerop: win.Plan = .{ .stream = &zero, .position = 0, .kind = .none }; + const grownp: win.Plan = .{ .stream = &grown, .position = 0, .kind = .none }; + var out: [3]i64 = undefined; + try budgets(&e, &.{ cutp, grownp, zerop }, &.{ 0, 1, 2 }, &out); + try std.testing.expect(out[0] > out[2]); // main's rule prices the cut tail as measured zeros + try std.testing.expectEqual(out[1], out[0]); // the cut stream prices as the rate continuation +} diff --git a/zig/src/core/lanes/stream.zig b/zig/src/core/lanes/stream.zig index baff3bd3100..2c0c773add5 100644 --- a/zig/src/core/lanes/stream.zig +++ b/zig/src/core/lanes/stream.zig @@ -245,6 +245,7 @@ pub const Stream = struct { grant_short: bool = false, // the last grant verified fewer drafts than the stream held grant_gain: ?f64 = null, // the drafts its last grant expected to keep (the chances it was priced by) draft_chances: std.ArrayList(f64) = .empty, // last full head prices, retained through zero-row rounds + draft_chances_cut: ?usize = null, // first chance a cut left unknown (null: measured); a chances hook marks it copy_width: ?u32 = null, pub fn init(gpa: Allocator, spec: Spec) !Stream { @@ -319,6 +320,7 @@ pub const Stream = struct { s.grant_gain = null; s.draft_chances.deinit(gpa); s.draft_chances = .empty; + s.draft_chances_cut = null; s.copy_width = null; s.proposal_depth = null; } diff --git a/zig/src/core/lanes/windows.zig b/zig/src/core/lanes/windows.zig index f9f0b3ddb72..75c1db8788b 100644 --- a/zig/src/core/lanes/windows.zig +++ b/zig/src/core/lanes/windows.zig @@ -254,7 +254,11 @@ pub fn allocate(e: *Engine, plans: []Plan) !void { const a = e.arena.allocator(); const fixed = try a.alloc(u32, plans.len); const probs = try a.alloc([]const f64, plans.len); - for (plans, fixed, probs) |p, *fx, *pr| { + const cuts = try a.alloc(?usize, plans.len); // the cut each plan's chances hook marked, committed with its cache + for (plans, fixed, probs, cuts) |p, *fx, *pr, *mark| { + const prior = p.stream.draft_chances_cut; + p.stream.draft_chances_cut = null; + errdefer p.stream.draft_chances_cut = prior; const n = p.count(); if (p.kind == .forced or n == 0) { fx.* = 1 + @as(u32, @intCast(if (p.kind == .forced) n else 0)); @@ -269,15 +273,19 @@ pub fn allocate(e: *Engine, plans: []Plan) !void { const controls = @import("mtp_policy.zig").Controls{ .cap = e.cfg.most_drafts, .floor = e.cfg.draft_confidence }; pr.* = if (p.kind == .head and e.cfg.draft_confidence != null) chances[0..controls.prefix(chances)] else chances; } + mark.* = p.stream.draft_chances_cut; + p.stream.draft_chances_cut = prior; } - if (e.cfg.allocate_shared_drafts) for (plans, probs) |p, chances| { + if (e.cfg.allocate_shared_drafts) for (plans, probs, cuts) |p, chances, mark| { if (p.kind == .copy or p.context_copy) { p.stream.draft_chances.clearRetainingCapacity(); + p.stream.draft_chances_cut = null; continue; } if (p.kind != .head or chances.len == 0) continue; p.stream.draft_chances.clearRetainingCapacity(); try p.stream.draft_chances.appendSlice(e.gpa, chances); + p.stream.draft_chances_cut = if (mark) |first| @min(first, chances.len) else null; }; const untimed: @import("table.zig").Table = .{}; const explicit = e.cfg.draft_confidence != null; diff --git a/zig/src/core/lanes/windows_chances_test.zig b/zig/src/core/lanes/windows_chances_test.zig new file mode 100644 index 00000000000..88d116f4898 --- /dev/null +++ b/zig/src/core/lanes/windows_chances_test.zig @@ -0,0 +1,224 @@ +//! windows.allocate's shared-round commit of a stream's cached draft chances and their cut marker, per window kind. +const std = @import("std"); +const Config = @import("config.zig").Config; +const Model = @import("config.zig").Model; +const Engine = @import("engine.zig").Engine; +const Stream = @import("stream.zig").Stream; +const be = @import("backend.zig"); +const fake = @import("fake.zig"); +const win = @import("windows.zig"); + +const a = std.testing.allocator; + +/// The chain chances a three-draft head reports, the two its confidence prefix keeps, and a stream's earlier prices. +const chain = [_]f64{ 0.9, 0.8, 0.7 }; +const prefix = [_]f64{ 0.9, 0.8 }; +const earlier = [_]f64{ 0.25, 0.2 }; + +const Hook = *const fn (ptr: *anyopaque, s: *Stream, out: []f64) anyerror!bool; + +/// A three-draft head's chances, marking the third as the first one a cut left unmeasured. +fn chainChances(_: *anyopaque, s: *Stream, out: []f64) anyerror!bool { + if (out.len != chain.len) return false; + @memcpy(out, &chain); + s.draft_chances_cut = 2; + return true; +} + +/// Five cumulative chances whose mark sits past the confidence prefix, so the commit has to clamp it. +fn deepChances(_: *anyopaque, s: *Stream, out: []f64) anyerror!bool { + const all = [_]f64{ 0.9, 0.8, 0.4, 0.3, 0.2 }; + if (out.len != all.len) return false; + @memcpy(out, &all); + s.draft_chances_cut = 5; + return true; +} + +/// A head that marks its cut and then fails, as a partially read logits buffer does. +fn markThenFail(_: *anyopaque, s: *Stream, out: []f64) anyerror!bool { + _ = out; + s.draft_chances_cut = 3; + return error.NoDraftProbabilities; +} + +/// A head with no chances to give, which a confidence floor turns into a refusal. +fn noChances(_: *anyopaque, _: *Stream, _: []f64) anyerror!bool { + return false; +} + +/// One engine on the fake target with this round's chances hook, and the shared commit enabled. +const Round = struct { + cfg: Config = undefined, + target: fake.Fake = undefined, + clock: fake.FixedClock = .{}, + vtable: be.Backend.VTable = undefined, + engine: Engine = undefined, + + fn start(r: *Round, m: Model, max_draft: u32, hook: ?Hook) !void { + r.cfg = try Config.init(a, m, 32, max_draft); + r.target = .{ .gpa = a }; + const plain = r.target.backend(); + r.vtable = plain.vtable.*; + r.vtable.probabilities = hook; + r.engine = Engine.init(a, &r.cfg, .{ .ptr = plain.ptr, .vtable = &r.vtable, .chunk_invariant = plain.chunk_invariant }, r.clock.clock()); + } + + fn finish(r: *Round) void { + r.engine.deinit(); + r.target.deinit(); + r.cfg.deinit(a); + } +}; + +/// The shared-round model: the head prices its drafts and their prices are committed per stream. +const shared_model = Model{ .exact_width = 32, .drafts = 5, .batch_rows = 32, .allocate_shared_drafts = true, .draft_probabilities = true }; + +fn headStream(s: *Stream) !void { + try s.draft_chances.appendSlice(a, &earlier); + s.draft_chances_cut = 1; +} + +test "cached draft cuts: a head round commits the head's chances and its marked cut" { + var r: Round = .{}; + try r.start(shared_model, 5, chainChances); + defer r.finish(); + var s = try Stream.init(a, .{ .id = "head", .prompt = &.{ 7, 13, 29 }, .max_new = 64 }); + defer s.deinit(a); + try headStream(&s); + const tokens = [_]u32{ 11, 12, 13 }; + var plans = [_]win.Plan{.{ .stream = &s, .position = 3, .kind = .head, .tokens = &tokens }}; + try win.allocate(&r.engine, &plans); + try std.testing.expectEqualSlices(f64, &chain, s.draft_chances.items); + try std.testing.expectEqual(@as(?usize, 2), s.draft_chances_cut); +} + +test "cached draft cuts: a confidence prefix commits its rows and clamps the marker to them" { + var r: Round = .{}; + var m = shared_model; + m.draft_confidence = 0.5; // keeps 0.9 and 0.8, so the head's mark of 5 is past what was committed + try r.start(m, 5, deepChances); + defer r.finish(); + var s = try Stream.init(a, .{ .id = "floor", .prompt = &.{ 7, 13, 29 }, .max_new = 64 }); + defer s.deinit(a); + try headStream(&s); + const tokens = [_]u32{ 11, 12, 13, 14, 15 }; + var plans = [_]win.Plan{.{ .stream = &s, .position = 5, .kind = .head, .tokens = &tokens }}; + try win.allocate(&r.engine, &plans); + try std.testing.expectEqualSlices(f64, &prefix, s.draft_chances.items); + try std.testing.expectEqual(@as(?usize, 2), s.draft_chances_cut); +} + +test "cached draft cuts: a forced round keeps the previous chances and marker" { + var r: Round = .{}; + try r.start(shared_model, 5, chainChances); + defer r.finish(); + var s = try Stream.init(a, .{ .id = "forced", .prompt = &.{ 7, 13, 29 }, .max_new = 64 }); + defer s.deinit(a); + try headStream(&s); + const tokens = [_]u32{ 11, 12 }; + var plans = [_]win.Plan{.{ .stream = &s, .position = 2, .kind = .forced, .tokens = &tokens, .forced = &tokens }}; + try win.allocate(&r.engine, &plans); + try std.testing.expectEqualSlices(f64, &earlier, s.draft_chances.items); + try std.testing.expectEqual(@as(?usize, 1), s.draft_chances_cut); +} + +test "cached draft cuts: an empty round keeps the previous chances and marker" { + var r: Round = .{}; + try r.start(shared_model, 5, chainChances); + defer r.finish(); + var s = try Stream.init(a, .{ .id = "empty", .prompt = &.{ 7, 13, 29 }, .max_new = 64 }); + defer s.deinit(a); + try headStream(&s); + var plans = [_]win.Plan{.{ .stream = &s, .position = 1, .kind = .none }}; + try win.allocate(&r.engine, &plans); + try std.testing.expectEqualSlices(f64, &earlier, s.draft_chances.items); + try std.testing.expectEqual(@as(?usize, 1), s.draft_chances_cut); +} + +test "cached draft cuts: a grafted round is no head, so it keeps the previous chances and marker" { + var r: Round = .{}; + try r.start(shared_model, 5, chainChances); + defer r.finish(); + var s = try Stream.init(a, .{ .id = "fill", .prompt = &.{ 7, 13, 29 }, .max_new = 64 }); + defer s.deinit(a); + try headStream(&s); + const tokens = [_]u32{ 11, 12, 13 }; + var plans = [_]win.Plan{.{ .stream = &s, .position = 3, .kind = .fill, .tokens = &tokens }}; + try win.allocate(&r.engine, &plans); + try std.testing.expectEqualSlices(f64, &earlier, s.draft_chances.items); + try std.testing.expectEqual(@as(?usize, 1), s.draft_chances_cut); +} + +test "cached draft cuts: a head with no priced rows keeps the previous chances and marker" { + var r: Round = .{}; + var m = shared_model; + m.draft_confidence = 0.5; + try r.start(m, 0, chainChances); // most_drafts 0: the confidence prefix keeps nothing for this head + defer r.finish(); + var s = try Stream.init(a, .{ .id = "unpriced", .prompt = &.{ 7, 13, 29 }, .max_new = 64 }); + defer s.deinit(a); + try headStream(&s); + const tokens = [_]u32{ 11, 12, 13 }; + var plans = [_]win.Plan{.{ .stream = &s, .position = 3, .kind = .head, .tokens = &tokens }}; + try win.allocate(&r.engine, &plans); + try std.testing.expectEqualSlices(f64, &earlier, s.draft_chances.items); + try std.testing.expectEqual(@as(?usize, 1), s.draft_chances_cut); +} + +test "cached draft cuts: a copy round clears both the chances and the marker" { + var r: Round = .{}; + try r.start(shared_model, 5, chainChances); + defer r.finish(); + var s = try Stream.init(a, .{ .id = "copy", .prompt = &.{ 7, 13, 29 }, .max_new = 64 }); + defer s.deinit(a); + try headStream(&s); + const tokens = [_]u32{ 11, 12 }; + var plans = [_]win.Plan{.{ .stream = &s, .position = 2, .kind = .copy, .tokens = &tokens }}; + try win.allocate(&r.engine, &plans); + try std.testing.expectEqual(@as(usize, 0), s.draft_chances.items.len); + try std.testing.expectEqual(@as(?usize, null), s.draft_chances_cut); +} + +test "cached draft cuts: a context copy clears both the chances and the marker" { + var r: Round = .{}; + try r.start(shared_model, 5, chainChances); + defer r.finish(); + var s = try Stream.init(a, .{ .id = "context", .prompt = &.{ 7, 13, 29 }, .max_new = 64 }); + defer s.deinit(a); + try headStream(&s); + const tokens = [_]u32{ 11, 12, 13 }; + var plans = [_]win.Plan{.{ .stream = &s, .position = 3, .kind = .head, .tokens = &tokens, .context_copy = true }}; + try win.allocate(&r.engine, &plans); + try std.testing.expectEqual(@as(usize, 0), s.draft_chances.items.len); + try std.testing.expectEqual(@as(?usize, null), s.draft_chances_cut); +} + +test "cached draft cuts: a failing chances hook restores the previous marker" { + var r: Round = .{}; + try r.start(shared_model, 5, markThenFail); + defer r.finish(); + var s = try Stream.init(a, .{ .id = "failed", .prompt = &.{ 7, 13, 29 }, .max_new = 64 }); + defer s.deinit(a); + try headStream(&s); + const tokens = [_]u32{ 11, 12, 13 }; + var plans = [_]win.Plan{.{ .stream = &s, .position = 3, .kind = .head, .tokens = &tokens }}; + try std.testing.expectError(error.NoDraftProbabilities, win.allocate(&r.engine, &plans)); + try std.testing.expectEqualSlices(f64, &earlier, s.draft_chances.items); + try std.testing.expectEqual(@as(?usize, 1), s.draft_chances_cut); +} + +test "cached draft cuts: a head without chances under a floor restores the previous marker" { + var r: Round = .{}; + var m = shared_model; + m.draft_confidence = 0.5; + try r.start(m, 5, noChances); + defer r.finish(); + var s = try Stream.init(a, .{ .id = "refused", .prompt = &.{ 7, 13, 29 }, .max_new = 64 }); + defer s.deinit(a); + try headStream(&s); + const tokens = [_]u32{ 11, 12, 13 }; + var plans = [_]win.Plan{.{ .stream = &s, .position = 3, .kind = .head, .tokens = &tokens }}; + try std.testing.expectError(error.NoDraftProbabilities, win.allocate(&r.engine, &plans)); + try std.testing.expectEqualSlices(f64, &earlier, s.draft_chances.items); + try std.testing.expectEqual(@as(?usize, 1), s.draft_chances_cut); +} diff --git a/zig/src/core/row_projection.zig b/zig/src/core/row_projection.zig index 275477d8deb..9c8162532f9 100644 --- a/zig/src/core/row_projection.zig +++ b/zig/src/core/row_projection.zig @@ -8,7 +8,7 @@ pub const simd = @import("simd_qmm.zig"); /// Groups of 64 at any width with fp32 sums: the same tiles, rows at a stride. pub const simd_bits = @import("simd_qmm_bits.zig"); -/// Rows a weight read (the kernel's MB); a window takes batches of this, then one row at a time. +/// The narrow kernel's rows per weight read; wide windows use 8, 4, 2 and 1. pub const batch = 2; /// Output columns a simdgroup and simdgroups a threadgroup (the kernel's RPS and SG). @@ -73,13 +73,19 @@ pub const Pipelines = struct { indexed: [variants]mtl.Pipeline, indexed_relu2: [variants]mtl.Pipeline, strided: [variants]mtl.Pipeline, + wide_plain: [variants]mtl.Pipeline, + wide_relu2: [variants]mtl.Pipeline, + wide_strided: [variants]mtl.Pipeline, + wide: bool = false, // windows of 4+ rows take the 8-row kernels only on chips with tensor units (the M5 path) pub fn load(device: mtl.Device) !Pipelines { const pool = mtl.objc.Pool.push(); defer pool.pop(); - const lib = try mtl.Library.fromSource(device, sources.core_row_projection, mtl.CompileOptions.mlx()); + const wide = device.tensorUnits(); + const lib = try mtl.Library.fromSource(device, source(wide), mtl.CompileOptions.mlx()); defer lib.deinit(); var p: Pipelines = undefined; + p.wide = wide; inline for (bit_widths, 0..) |bits, b| inline for (.{ "f32", "bf16" }, 0..) |sum, m| { const i = b * 2 + m; p.plain[i] = try mtl.Pipeline.init(device, lib, std.fmt.comptimePrint("tf_row_projection_q{d}_{s}", .{ bits, sum }), false); @@ -87,6 +93,11 @@ pub const Pipelines = struct { p.indexed[i] = try mtl.Pipeline.init(device, lib, std.fmt.comptimePrint("tf_row_projection_indexed_q{d}_{s}", .{ bits, sum }), false); p.indexed_relu2[i] = try mtl.Pipeline.init(device, lib, std.fmt.comptimePrint("tf_row_projection_indexed_relu2_q{d}_{s}", .{ bits, sum }), false); p.strided[i] = try mtl.Pipeline.init(device, lib, std.fmt.comptimePrint("tf_row_projection_strided_q{d}_{s}", .{ bits, sum }), false); + if (wide) { + p.wide_plain[i] = try mtl.Pipeline.init(device, lib, std.fmt.comptimePrint("tf_row_projection_wide_q{d}_{s}", .{ bits, sum }), false); + p.wide_relu2[i] = try mtl.Pipeline.init(device, lib, std.fmt.comptimePrint("tf_row_projection_wide_relu2_q{d}_{s}", .{ bits, sum }), false); + p.wide_strided[i] = try mtl.Pipeline.init(device, lib, std.fmt.comptimePrint("tf_row_projection_wide_strided_q{d}_{s}", .{ bits, sum }), false); + } }; return p; } @@ -97,9 +108,19 @@ pub const Pipelines = struct { for (p.indexed) |x| x.deinit(); for (p.indexed_relu2) |x| x.deinit(); for (p.strided) |x| x.deinit(); + if (p.wide) { + for (p.wide_plain) |x| x.deinit(); + for (p.wide_relu2) |x| x.deinit(); + for (p.wide_strided) |x| x.deinit(); + } } }; +/// Chips without tensor units compile the original narrow source, with no wide definitions or control edits. +pub fn source(wide: bool) []const u8 { + return if (wide) sources.core_row_projection else sources.core_row_projection_legacy; +} + /// Dispatch: pipeline, dims (K, N, group, rows/slots, experts, repeat), grid; buffers x, W, S, B, dims, out 0-5, ids 6. pub const Call = struct { pipeline: mtl.Pipeline, dims: [6]i32, groups: usize, slots: usize = 1, threads: usize = 32 * groups }; @@ -108,7 +129,8 @@ pub fn call(p: *const Pipelines, w: Weights, rows: usize, relu2: bool) !Call { try w.validate(); if (rows == 0) return error.NoRows; const i = w.variant(); - return .{ .pipeline = if (relu2) p.relu2[i] else p.plain[i], .dims = .{ @intCast(w.k), @intCast(w.n), @intCast(w.group), @intCast(rows), 1, 1 }, .groups = w.n / (columns * groups) }; + const pipeline = if (rows >= 4 and p.wide) (if (relu2) p.wide_relu2[i] else p.wide_plain[i]) else if (relu2) p.relu2[i] else p.plain[i]; + return .{ .pipeline = pipeline, .dims = .{ @intCast(w.k), @intCast(w.n), @intCast(w.group), @intCast(rows), 1, 1 }, .groups = w.n / (columns * groups) }; } /// `call` with output row m at y + m * `stride` values: a fused stack member writes its columns of the rows. @@ -116,7 +138,7 @@ pub fn callStrided(p: *const Pipelines, w: Weights, rows: usize, stride: usize) try w.validate(); if (rows == 0) return error.NoRows; if (stride < w.n or stride > std.math.maxInt(i32)) return error.UnsupportedRowStride; - return .{ .pipeline = p.strided[w.variant()], .dims = .{ @intCast(w.k), @intCast(w.n), @intCast(w.group), @intCast(rows), @intCast(stride), 1 }, .groups = w.n / (columns * groups) }; + return .{ .pipeline = if (rows >= 4 and p.wide) p.wide_strided[w.variant()] else p.strided[w.variant()], .dims = .{ @intCast(w.k), @intCast(w.n), @intCast(w.group), @intCast(rows), @intCast(stride), 1 }, .groups = w.n / (columns * groups) }; } /// y[slots, n] = x[slot / repeat] W[ids[slot]]^T; the grid's y is the slot. @@ -181,3 +203,54 @@ test "a strided call writes rows at least a matrix wide" { const c = try callStrided(&p, w, 2, 192); try std.testing.expectEqual([6]i32{ 128, 64, 64, 2, 192, 1 }, c.dims); } + +test "row dispatch selects wide contiguous and strided pipelines from four rows" { + if (comptime @import("builtin").os.tag != .macos) return error.SkipZigTest; // Metal pipelines exist only on macOS + var p: Pipelines = undefined; + p.wide = true; + inline for (.{ "plain", "relu2", "strided", "wide_plain", "wide_relu2", "wide_strided" }, 1..) |field, tag| { + for (&@field(p, field), 0..) |*pipeline, i| pipeline.* = .{ .id = @ptrFromInt(0x1000 + tag * 0x100 + i) }; + } + for (bit_widths) |bits| for ([_]Sum{ .f32, .bf16 }) |sum| { + const w = Weights{ .w = undefined, .scales = undefined, .biases = undefined, .n = 64, .k = 128, .bits = bits, .sum = sum }; + const i = w.variant(); + for (1..33) |rows| { + for ([_]bool{ false, true }) |relu2| { + const expected = if (rows >= 4) (if (relu2) p.wide_relu2[i] else p.wide_plain[i]) else if (relu2) p.relu2[i] else p.plain[i]; + try std.testing.expectEqual(expected.id, (try call(&p, w, rows, relu2)).pipeline.id); + } + const expected = if (rows >= 4) p.wide_strided[i] else p.strided[i]; + try std.testing.expectEqual(expected.id, (try callStrided(&p, w, rows, 128)).pipeline.id); + } + }; +} + +test "row dispatch without tensor units keeps main's pipelines at every row count" { + if (comptime @import("builtin").os.tag != .macos) return error.SkipZigTest; // Metal pipelines exist only on macOS + var p: Pipelines = undefined; + p.wide = false; + inline for (.{ "plain", "relu2", "strided", "wide_plain", "wide_relu2", "wide_strided" }, 1..) |field, tag| { + for (&@field(p, field), 0..) |*pipeline, i| pipeline.* = .{ .id = @ptrFromInt(0x1000 + tag * 0x100 + i) }; + } + for (bit_widths) |bits| for ([_]Sum{ .f32, .bf16 }) |sum| { + const w = Weights{ .w = undefined, .scales = undefined, .biases = undefined, .n = 64, .k = 128, .bits = bits, .sum = sum }; + const i = w.variant(); + for (1..33) |rows| { + for ([_]bool{ false, true }) |relu2| { + const expected = if (relu2) p.relu2[i] else p.plain[i]; + try std.testing.expectEqual(expected.id, (try call(&p, w, rows, relu2)).pipeline.id); + } + try std.testing.expectEqual(p.strided[i].id, (try callStrided(&p, w, rows, 128)).pipeline.id); + } + }; +} + +test "without tensor units the source has no wide grouping, tensor units retain the wide source" { + const narrow = source(false); + try std.testing.expect(std.mem.indexOf(u8, narrow, "tf_row_projection_wide") == null); + try std.testing.expect(std.mem.indexOf(u8, narrow, "tf_row_projection_body") == null); + try std.testing.expect(std.mem.indexOf(u8, narrow, "TF_RP_BAD_ROWS") == null); + try std.testing.expect(std.mem.indexOf(u8, narrow, "tf_row_projection_indexed") != null); + try std.testing.expect(std.mem.indexOf(u8, source(true), "tf_row_projection_wide") != null); + try std.testing.expectEqualStrings(sources.core_row_projection, source(true)); +} diff --git a/zig/src/core/template/filters.zig b/zig/src/core/template/filters.zig index 00e498686c2..d71465a9289 100644 --- a/zig/src/core/template/filters.zig +++ b/zig/src/core/template/filters.zig @@ -12,7 +12,7 @@ const Kw = methods.Kw; const Ctx = eval.Ctx; const bind = methods.bind; -pub const implemented = [_][]const u8{ "default", "d", "length", "count", "string", "trim", "upper", "lower", "capitalize", "safe", "tojson", "fromjson", "items", "dictsort", "join", "list", "map", "first", "last", "unique", "reverse", "sort", "select", "reject", "selectattr", "rejectattr", "indent", "replace", "escape", "e" }; +pub const implemented = [_][]const u8{ "default", "d", "length", "count", "string", "trim", "upper", "lower", "capitalize", "safe", "tojson", "fromjson", "items", "dictsort", "join", "list", "map", "first", "last", "unique", "reverse", "sort", "select", "reject", "selectattr", "rejectattr", "indent", "replace", "escape", "e", "float" }; const jinja_filters = [_][]const u8{ "abs", "attr", "batch", "capitalize", "center", "count", "d", "default", "dictsort", "e", "escape", "filesizeformat", "first", "float", "forceescape", "format", "groupby", "indent", "int", "items", "join", "last", "length", "list", "lower", "map", "max", "min", "pprint", "random", "reject", "rejectattr", "replace", "reverse", "round", "safe", "select", "selectattr", "slice", "sort", "string", "striptags", "sum", "title", "tojson", "trim", "truncate", "unique", "upper", "urlencode", "urlize", "wordcount", "wordwrap", "xmlattr" }; pub const tests = [_][]const u8{ "odd", "even", "divisibleby", "defined", "undefined", "filter", "test", "none", "boolean", "false", "true", "integer", "float", "string", "mapping", "number", "sequence", "iterable", "callable", "sameas", "escaped", "in", "==", "eq", "equalto", "!=", "ne", ">", "gt", "greaterthan", ">=", "ge", "<", "lt", "lessthan", "<=", "le" }; const jinja_tests = tests ++ [_][]const u8{ "lower", "upper" }; @@ -157,6 +157,21 @@ fn indent(c: *Ctx, s: v.Str, width: Value, first: bool, blank: bool) Error!Value return .{ .str = text }; } +/// float(value) for numbers, booleans and ASCII numeric text, as Python reads them; null when it raises. +fn toFloat(x: Value) ?Value { + switch (x) { + .int => |i| return .{ .float = @floatFromInt(i) }, + .float => return x, + .boolean => |b| return .{ .float = if (b) 1 else 0 }, + .str => |s| { + const text = std.mem.trim(u8, s.s, " \t\r\n\x0b\x0c"); + if (text.len == 0 or std.mem.indexOfAny(u8, text, "xXpP") != null) return null; + return .{ .float = std.fmt.parseFloat(f64, text) catch return null }; + }, + else => return null, + } +} + pub fn filter(c: *Ctx, name: []const u8, value: Value, pos: []const Value, kw: []const Kw) Error!Value { const rt = &c.rt; const eq = std.mem.eql; @@ -170,6 +185,11 @@ pub fn filter(c: *Ctx, name: []const u8, value: Value, pos: []const Value, kw: [ return .{ .int = @intCast(v.len(value) orelse return rt.fail("object of type '{s}' has no len()", .{v.typeName(value)})) }; } if (eq(u8, name, "string")) return .{ .str = try softStr(c, value) }; + if (eq(u8, name, "float")) { + const b = try bind(rt, "float", &.{"default"}, 0, pos, kw); + if (v.isUndef(value)) return rt.fail("{s}", .{v.undefMsg(value)}); + return toFloat(value) orelse b[0] orelse Value{ .float = 0 }; + } if (eq(u8, name, "trim")) { const b = try bind(rt, "trim", &.{"chars"}, 0, pos, kw); return methods.strip(rt, try softStr(c, value), b[0]); diff --git a/zig/src/core/template/provenance_test.zig b/zig/src/core/template/provenance_test.zig index 72a71876e76..7be48df6405 100644 --- a/zig/src/core/template/provenance_test.zig +++ b/zig/src/core/template/provenance_test.zig @@ -144,7 +144,7 @@ test "provenance property covers every implemented filter" { if (std.mem.eql(u8, name, "replace")) args = &.{ v.Value.literal("SPECIAL"), req }; try checkValue(&c.rt, try filters.filter(&c, name, input, args, &.{})); } - try t.expectEqual(@as(usize, 30), filters.implemented.len); + try t.expectEqual(@as(usize, 31), filters.implemented.len); } const str_supported = [_][]const u8{ "capitalize", "count", "endswith", "find", "index", "join", "lower", "lstrip", "removeprefix", "removesuffix", "replace", "rfind", "rindex", "rsplit", "rstrip", "split", "startswith", "strip", "upper" }; diff --git a/zig/src/core/template/tests.zig b/zig/src/core/template/tests.zig index baf27a2cee7..46da77e7b0f 100644 --- a/zig/src/core/template/tests.zig +++ b/zig/src/core/template/tests.zig @@ -96,6 +96,12 @@ const probes = [_]struct { []const u8, ?[]const u8, ?[]const u8 }{ .{ "{{ ['b', 'a'] | sort | join }}{{ [{'n': 'b'}, {'n': 'a'}] | sort(attribute='n') | map(attribute='n') | join }}{{ [{'n': 1}] | map(attribute='m', default='d') | join }}", "ababd", null }, .{ "{% for x in 'ab' %}{{ x }}{{ loop.index0 }}{% endfor %}|{% for k in {'p': 1, 'q': 2} %}{{ k }}{% endfor %}|{% for x in none %}{% endfor %}", null, null }, .{ "{%- for m in messages -%}\n {%- set content = m.content | trim -%}\n {{- '<' + m.role + '>' + content -}}\n{%- endfor %}\nx", "HiHelloByex", null }, + .{ "{{ '0.5'|float }}|{{ 3|float }}|{{ 'abc'|float }}|{{ 'abc'|float(2.5) }}|{{ true|float }}|{{ ' 7 '|float }}|{{ none|float }}|{{ 0.9|float }}|{{ '1e3'|float }}|{{ ''|float }}|{{ '0x10'|float }}", "0.5|3.0|0.0|2.5|1.0|7.0|0.0|0.9|1000.0|0.0|0.0", null }, + .{ "{{ '1_0'|float }}|{{ '1__0'|float }}|{{ '_1'|float }}|{{ '1_'|float }}|{{ '1_0.5_5'|float }}|{{ [1]|float }}|{{ {}|float(7) }}|{{ 'x'|float(default=2.5) }}", "10.0|0.0|0.0|0.0|10.55|0.0|7|2.5", null }, + .{ "{{ '1.'|float }}|{{ '.5'|float }}|{{ '+3'|float }}|{{ '-0'|float }}|{{ 'inf'|float }}|{{ 'nan'|float }}|{{ '1e'|float }}|{{ '1e1_0'|float }}|{{ '1_.5'|float }}", "1.0|0.5|3.0|-0.0|inf|nan|0.0|10000000000.0|0.0", null }, + .{ "{{ 1|float(2, 3) }}", null, null }, + .{ "{{ 1|float(boolean=true) }}", null, null }, + .{ "{{ undefined_name|float }}", null, null }, }; test "feature probes match Python jinja2" { diff --git a/zig/src/families/deepseek_v41/forward_prefill.zig b/zig/src/families/deepseek_v41/forward_prefill.zig index 66c5b0a8fac..3d28a144a9b 100644 --- a/zig/src/families/deepseek_v41/forward_prefill.zig +++ b/zig/src/families/deepseek_v41/forward_prefill.zig @@ -150,8 +150,12 @@ pub fn plan(f: *Forward, p: *buffers.Plan, rows: u32) !void { /// The forward's prefill programs at `rows` (`plan` without the workspace). pub fn planPrograms(f: *Forward, p: *buffers.Plan, rows: u32, layers: []const u32) !void { - const sizes = [_]u32{ rows, 17, 16 }; - for (sizes[if (rows > 17) 0 else 1..]) |n| { + // The second streams buffer runs at up to split_rows rows, so plan a program there too. + const sizes = [_]u32{ rows, @intCast(block_prefill.split_rows), 17, 16 }; + const first: usize = if (rows > 17) 0 else 1; + for (sizes[first..], first..) |n, i| { + if (n > rows) continue; // no segment is that long + if (i > first and n == sizes[i - 1]) continue; // rows == split_rows: plan it once const top = try lastStart(f, layers, n, .whole); for ([_]i64{ 0, top }) |start| { var ea = std.heap.ArenaAllocator.init(f.gpa); diff --git a/zig/src/families/deepseek_v41/index_scratch_test.zig b/zig/src/families/deepseek_v41/index_scratch_test.zig index 7a69662e3a4..58f9eb91b85 100644 --- a/zig/src/families/deepseek_v41/index_scratch_test.zig +++ b/zig/src/families/deepseek_v41/index_scratch_test.zig @@ -43,7 +43,7 @@ fn exercise(k4: bool, tbo: bool, budget: i64) !void { try fp.planPrograms(&f, &p, 2048, &layers); if (k4 or tbo) try ws.planWorkspace(&f, &original, 2048, &layers); if (tbo) try t.expectEqual(ws.planBytes(&original), try fp.workspaceBytes(&f, 2048)); - const row_sizes: [4]i64 = if (k4) .{ 2049, 3072, 4095, 4096 } else .{ 17, 1025, 2047, 2048 }; + const row_sizes: []const i64 = if (k4) &.{ 2049, 3072, 4095, 4096 } else &.{ 17, 18, 32, 1025, 2047, 2048 }; for ([_]bool{ false, true }) |shared| { var wp: buffers.Plan = .{ .a = a }; for (original.sizes.keys(), original.sizes.values()) |k, v| try wp.sizes.put(a, k, v); @@ -137,3 +137,33 @@ test "index scratch: TBO-B materialisation missing from full-row endpoints is pl try t.expect(!short.sizes.contains("L.k4~b~ix.stream")); try t.expectEqual(ws.planBytes(&short), try fp.workspaceBytes(&f, 2048)); } + +test "prefill plan: segments of 17..33 rows write the spare streams within the planned roles, full and replay" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const cfg: Config = .{}; + var w: block.Widths = .{}; + try check.parseDense(a, &w, @embedFile("fixtures/dense-k2.txt")); + try check.parseExperts(a, &w, @embedFile("fixtures/expert-k2.txt")); + var layers: [25]u32 = undefined; + for (&layers, 0..) |*l, i| l.* = @intCast(i); + const o: block.Options = .{ .gm_v2 = .one, .limit = 299008, .rope_rows = 301056, .index_budget = 64 << 20, .taps = true }; + for ([_]bool{ false, true }) |replay| { + var f = @import("forward.zig").Forward.init(a, &cfg, &w, o, undefined, undefined); + f.layers = &layers; + var state: fp.State = .{ .mode = if (replay) .replay else .full }; + f.prefill_state = &state; + var p: buffers.Plan = .{ .a = a }; + try fp.planPrograms(&f, &p, 2048, &layers); + // a boundary of at most split_rows rows writes "w.x<1 - cur>": the plan sizes it for those rows + var n: i64 = 17; + while (n <= bp.split_rows + 1) : (n += 1) for ([_]i64{ 0, 2048, 65536 }) |start| { + var tmp = std.heap.ArenaAllocator.init(t.allocator); + defer tmp.deinit(); + const ta = tmp.allocator(); + const cs = if (replay) try bp.emitReplay(ta, &cfg, &w, o, layers[0..21], n, start, .encoder) else try bp.emitPrefill(ta, &cfg, &w, o, &layers, n, start, true); + try covered(ta, cs, &p, &p); + }; + } +} diff --git a/zig/src/families/flashnext/cuda_chunk.zig b/zig/src/families/flashnext/cuda_chunk.zig index c308a8879e7..65577d1f157 100644 --- a/zig/src/families/flashnext/cuda_chunk.zig +++ b/zig/src/families/flashnext/cuda_chunk.zig @@ -3,29 +3,31 @@ const std = @import("std"); const batch = @import("cuda_batch.zig"); const solo_chunk = @import("lanes").solo_chunk; -/// TF_FLASHNEXT_CHUNK's rows a pass: unset, the default; otherwise 1 to batch.max_chunk, anything else refused. +/// TF_FLASHNEXT_CHUNK's rows a pass: unset or blank is the default; 1 to batch.max_chunk, the rest refused. pub fn parseChunk(v: ?[]const u8) !usize { - const s = v orelse return batch.default_chunk; - const n = std.fmt.parseInt(usize, s, 10) catch return error.BadChunk; - if (n == 0 or n > batch.max_chunk) return error.BadChunk; - return n; + return @import("sys").environment.value(usize, "TF_FLASHNEXT_CHUNK", v, batch.default_chunk) catch return error.BadChunk; } pub fn chunkRows() !usize { - return parseChunk(if (std.c.getenv("TF_FLASHNEXT_CHUNK")) |v| std.mem.span(v) else null); + return parseChunk(@import("sys").getenv("TF_FLASHNEXT_CHUNK")); } /// A pass's rows on a server of one stream: no request waits on a pass there, and this takes most of 16,384's gain. pub const lone_rows: usize = 8192; -/// TF_FLASHNEXT_CHUNK_SOLO's rows: unset, `lone_rows` when `lone`, else `busy` (off); below `busy`, refused. +/// TF_FLASHNEXT_CHUNK_SOLO's rows: unset or blank, `lone_rows` when `lone`, else `busy` (off); below `busy`, refused. pub fn parseSolo(v: ?[]const u8, busy: usize, lone: bool) !usize { - if (v == null and lone) return @max(busy, lone_rows); - return solo_chunk.parse(v, .{ .busy = busy, .most = batch.max_chunk }) catch error.BadChunk; + const set = @import("sys").environment.parse("TF_FLASHNEXT_CHUNK_SOLO", v) catch return error.BadChunk; + if (set == null) return if (lone) @max(busy, lone_rows) else busy; + return solo_chunk.parse(v, .{ .busy = busy, .most = batch.max_chunk }) catch { + // a value below the busy chunk is the usual mistake, so it is named before the plain refusal + if (!@import("builtin").is_test and set.? < busy) std.log.err("TF_FLASHNEXT_CHUNK_SOLO=\"{s}\": expected at least TF_FLASHNEXT_CHUNK ({d})", .{ v.?, busy }); + return error.BadChunk; + }; } pub fn soloRows(busy: usize, lone: bool) !usize { - return parseSolo(if (std.c.getenv("TF_FLASHNEXT_CHUNK_SOLO")) |v| std.mem.span(v) else null, busy, lone); + return parseSolo(@import("sys").getenv("TF_FLASHNEXT_CHUNK_SOLO"), busy, lone); } /// The rows the pass of stream `own` takes when it starts: lanes.solo_chunk's rule on the lanes' `filled`. @@ -42,20 +44,23 @@ pub fn readoutTileRows() usize { test "TF_FLASHNEXT_CHUNK takes 1 to the largest measured pass and refuses the rest" { try std.testing.expectEqual(batch.default_chunk, try parseChunk(null)); + try std.testing.expectEqual(@as(usize, 1536), try parseChunk("")); try std.testing.expectEqual(@as(usize, 4096), try parseChunk("4096")); try std.testing.expectEqual(batch.max_chunk, try parseChunk("16384")); - for ([_][]const u8{ "0", "16385", "-1", "4k", "" }) |bad| try std.testing.expectError(error.BadChunk, parseChunk(bad)); + for ([_][]const u8{ "0", "16385", "-1", "4k" }) |bad| try std.testing.expectError(error.BadChunk, parseChunk(bad)); } test "TF_FLASHNEXT_CHUNK_SOLO is off unset, takes the busy chunk to the largest pass and refuses the rest" { try std.testing.expectEqual(@as(usize, 1536), try parseSolo(null, 1536, false)); + try std.testing.expectEqual(@as(usize, 1536), try parseSolo("", 1536, false)); try std.testing.expectEqual(@as(usize, 8192), try parseSolo("8192", 1536, false)); try std.testing.expectEqual(@as(usize, 1536), try parseSolo("1536", 1536, false)); - for ([_][]const u8{ "1024", "0", "16385", "8k", "" }) |bad| try std.testing.expectError(error.BadChunk, parseSolo(bad, 1536, false)); + for ([_][]const u8{ "1024", "0", "16385", "8k" }) |bad| try std.testing.expectError(error.BadChunk, parseSolo(bad, 1536, false)); } test "a server of one stream takes the larger pass unless the variable or a larger busy chunk says otherwise" { try std.testing.expectEqual(lone_rows, try parseSolo(null, 1536, true)); + try std.testing.expectEqual(@as(usize, 8192), try parseSolo("", 1536, true)); try std.testing.expectEqual(@as(usize, 1536), try parseSolo("1536", 1536, true)); try std.testing.expectEqual(@as(usize, 16384), try parseSolo(null, 16384, true)); } diff --git a/zig/src/families/flashnext/cuda_lanes.zig b/zig/src/families/flashnext/cuda_lanes.zig index 1aaf22148e8..6aadd3ada56 100644 --- a/zig/src/families/flashnext/cuda_lanes.zig +++ b/zig/src/families/flashnext/cuda_lanes.zig @@ -587,7 +587,8 @@ pub fn Namespace(comptime Tri: type) type { // every driver entry point undefined: the refusal must come before the first call var driver: cuda.Driver = undefined; const ctx: cuda.Context = .{ .d = &driver, .device = 0, .handle = null }; - for ([_]struct { [*:0]const u8, [*:0]const u8, anyerror }{ .{ "TF_FLASHNEXT_CHUNK", "0", error.BadChunk }, .{ "TF_FLASHNEXT_CHUNK", "16385", error.BadChunk }, .{ "TF_FLASHNEXT_CHUNK", "4k", error.BadChunk }, .{ "TF_FLASHNEXT_CHUNK_SOLO", "1024", error.BadChunk }, .{ "TF_FLASHNEXT_LOAD_THREADS", "0", error.BadLoadThreads }, .{ "TF_FLASHNEXT_LOAD_THREADS", "33", error.BadLoadThreads }, .{ "TF_FLASHNEXT_LOAD_THREADS", "8x", error.BadLoadThreads } }) |bad| { + // a chunk the table refuses is named at startup, so it never reaches the reader's own BadChunk + for ([_]struct { [*:0]const u8, [*:0]const u8, anyerror }{ .{ "TF_FLASHNEXT_CHUNK", "0", error.InvalidEnvironment }, .{ "TF_FLASHNEXT_CHUNK", "16385", error.InvalidEnvironment }, .{ "TF_FLASHNEXT_CHUNK", "4k", error.InvalidEnvironment }, .{ "TF_FLASHNEXT_CHUNK_SOLO", "1024", error.BadChunk }, .{ "TF_FLASHNEXT_LOAD_THREADS", "0", error.BadLoadThreads }, .{ "TF_FLASHNEXT_LOAD_THREADS", "33", error.BadLoadThreads }, .{ "TF_FLASHNEXT_LOAD_THREADS", "8x", error.BadLoadThreads } }) |bad| { _ = env.setenv(bad[0], bad[1], 1); defer _ = env.unsetenv(bad[0]); try std.testing.expectError(bad[2], open(std.testing.allocator, std.testing.io, &ctx, "no-such-checkpoint", null, .{ .context = 4096, .drafts = true })); diff --git a/zig/src/families/flashnext/engine_load.zig b/zig/src/families/flashnext/engine_load.zig index 793859136f6..5cb22e3cc8d 100644 --- a/zig/src/families/flashnext/engine_load.zig +++ b/zig/src/families/flashnext/engine_load.zig @@ -206,7 +206,7 @@ fn finishLoad(context: Construction, r: *Run) !*Engine { } const m = try arena.create(Model); m.* = .{ .r = r, .cap = r.window.capacity, .layers = undefined, .mix = undefined, .head = undefined, .embed = undefined, .ple = undefined, .t = undefined }; - r.sb_index = try platform.environment.read(bool, "TF_FLASHNEXT_SCALE_INDEX", false) and r.fsr == null and r.tp == null and !r.device.tensorUnits(); + r.sb_index = try platform.environment.read(bool, "TF_FLASHNEXT_SCALE_INDEX", true) and r.fsr == null and !r.device.tensorUnits(); for (0..LAYERS) |i| { const linear = i % 4 != 3; var L: Layer = .{ .ahc = try hcOf(r, "L{d}.ahc", .{i}), .mhc = try hcOf(r, "L{d}.mhc", .{i}), .linear = linear, .proj = undefined, .out = undefined, .router = try r.loadf("L{d}.moe.router", .{i}), .ex = undefined }; @@ -235,7 +235,6 @@ fn finishLoad(context: Construction, r: *Run) !*Engine { } } if (r.xpack) try r.repack(&L.ex); - if (r.sb_index) try @import("scale_index.zig").addAll(r, &L.ex); m.layers[i] = L; } m.mix = try hcOf(r, "mix", .{}); @@ -333,7 +332,6 @@ fn finishLoad(context: Construction, r: *Run) !*Engine { } } if (r.xpack) try r.repack(&ex); - if (r.sb_index) try @import("scale_index.zig").addAll(r, &ex); m.mtp = .{ .ahc = try hcOf(r, "mtp.ahc", .{}), .mhc = try hcOf(r, "mtp.mhc", .{}), @@ -386,6 +384,15 @@ fn finishLoad(context: Construction, r: *Run) !*Engine { e.r = r; e.m = m; + if (r.sb_index) { // before the prompt kernels compile: they read the routed experts through the index too + var widths = try @import("widths.zig").Widths.init(arena, &cfg); + defer widths.deinit(); + const ws = try @import("engine_widths.zig").read(&cfg, &widths, r.ngram); + var sets: [LAYERS + 1]@import("scale_index.zig").Set = undefined; + for (&m.layers, 0..) |*L, i| sets[i] = .{ .ex = &L.ex, .xw = ws.layers[i] }; + sets[LAYERS] = .{ .ex = &m.mtp.ex, .xw = ws.mtp }; + try @import("scale_index.zig").build(r, &sets); + } e.pr = try arena.create(Prompt); e.pr.* = try Prompt.init(r, pack_dir, r.xnew_header); const uniform = try @import("engine_widths.zig").apply(arena, &cfg, index.object.get("weight_map").?.object, e.pr, m); diff --git a/zig/src/families/flashnext/experts4.zig b/zig/src/families/flashnext/experts4.zig index 5a79ae2f261..ab6dc064d8d 100644 --- a/zig/src/families/flashnext/experts4.zig +++ b/zig/src/families/flashnext/experts4.zig @@ -117,6 +117,29 @@ pub fn indexed(a: std.mem.Allocator, text: []const u8, consts: []const Const) ![ return out; } +/// The grouped tile kernel's reads (fn_gx.metal): its scale row is the index row, its bias pointer the table. +const tile_reads = [_][2][]const u8{ + .{ "const device bfloat* db = (shared ? SDB : DB) + so;", "const device bfloat* db = shared ? SDB : DB;" }, + .{ "const float sc = float(ds[c / 2]), bi = float(db[c / 2]);", "const uint ti = uint(((const device ushort*)ds)[c / 2]) * 2u; const float sc = float(db[ti]), bi = float(db[ti + 1]);" }, +}; + +/// fn_gx.metal reading each scale and bias through the index and the table, as `indexed` has the recorded kernels. +pub fn indexedGrouped(a: std.mem.Allocator, text: []const u8) ![]const u8 { + var out = text; + var hits: usize = 0; + for (index_reads) |r| { + hits += std.mem.count(u8, out, r[0]); + out = try std.mem.replaceOwned(u8, a, out, r[0], r[1]); + } + for (tile_reads) |r| { + if (std.mem.count(u8, out, r[0]) != 1) return error.KernelPatch; + out = try std.mem.replaceOwned(u8, a, out, r[0], r[1]); + } + if (hits != 4) return error.KernelPatch; + for ([_][]const u8{ "Sp[at])", "float(S[at])", "float(db[c / 2])" }) |direct| if (std.mem.indexOf(u8, out, direct) != null) return error.KernelPatch; + return out; +} + const calls = [2][2][]const u8{ .{ "down_rows(SDW, SDS, SDB, size_t(d0), x, lane, out)", "down_rows_bal(SDW, SDS, SDB, size_t(d0), x, lane, out)" }, .{ "down_rows(DW, DS, DB, size_t(PICK[r * TOPK + k]) * D + d0, x, lane, out)", "down_rows_bal(DW, DS, DB, size_t(PICK[r * TOPK + k]) * D + d0, x, lane, out)" }, @@ -217,3 +240,13 @@ test "the recorded 4/32 expert gate/up takes a row count from buffer 17, once; t } try std.testing.expectEqual(@as(usize, 1), seen); } + +test "the grouped kernels read every scale and bias through the index once patched" { + const ks = @import("kernel_sources"); + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const out = try indexedGrouped(arena.allocator(), ks.flashnext_gx); + const casts = "(const device ushort*)"; // five index reads beside the casts the kernels already have + try std.testing.expectEqual(std.mem.count(u8, ks.flashnext_gx, casts) + 5, std.mem.count(u8, out, casts)); + try std.testing.expectError(error.KernelPatch, indexedGrouped(arena.allocator(), out)); +} diff --git a/zig/src/families/flashnext/grouped_fixture.zig b/zig/src/families/flashnext/grouped_fixture.zig index 7cb745546bb..51e0bee03cc 100644 --- a/zig/src/families/flashnext/grouped_fixture.zig +++ b/zig/src/families/flashnext/grouped_fixture.zig @@ -4,6 +4,8 @@ const mtl = @import("metal"); const variants = @import("variants.zig"); const names = @import("fsr_contract_source.zig"); const gx = @import("gx.zig"); +const pairs = @import("scale_pairs.zig"); +const ks = @import("kernel_sources"); const Buf = @import("replay.zig").Buf; pub const d = 2560; @@ -23,6 +25,11 @@ pub fn text(a: std.mem.Allocator, gate: bool) ![]const u8 { return variants.source(a, try names.recorded(file), &at4, true, false, gate, false); } +/// fn_gx.metal as the loader compiles it; `indexed` with every scale and bias read through the index. +pub fn groupedText(a: std.mem.Allocator, indexed: bool) ![]const u8 { + return if (indexed) @import("experts4.zig").indexedGrouped(a, ks.flashnext_gx) else ks.flashnext_gx; +} + /// Groups of 32 weights in projection j: gate, up, shared gate, shared up, down, shared down. fn groups(j: usize) usize { const routed: usize = if (j == 0 or j == 1 or j == 4) held else 1; @@ -36,9 +43,10 @@ pub const Fixture = struct { queue: mtl.Queue, rows: usize, w: [18]Ref, // each projection's weight, scales and biases + ix: [6][2]Ref, // each projection's index and table io: [7]Ref, // input rows, logits, row count, then act, picks, weights and y direct: [2]mtl.Pipeline, // the recorded gate/up and down - grouped: gx.Gx, + grouped: [2]gx.Gx, // reading scales and biases direct, and through the index libraries: std.ArrayList(mtl.Library) = .empty, pipelines: std.ArrayList(mtl.Pipeline) = .empty, buffers: std.ArrayList(Ref) = .empty, @@ -49,10 +57,12 @@ pub const Fixture = struct { pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, rows: usize, seed: u64, nonfinite: bool) !*Fixture { if (rows == 0 or rows > gx.rmax) return error.GroupedFixtureShape; const p = try a.create(Fixture); - p.* = .{ .memory = .init(a), .a = undefined, .queue = queue, .rows = rows, .w = undefined, .io = undefined, .direct = undefined, .grouped = undefined }; + p.* = .{ .memory = .init(a), .a = undefined, .queue = queue, .rows = rows, .w = undefined, .ix = undefined, .io = undefined, .direct = undefined, .grouped = undefined }; errdefer p.deinit(a); p.a = p.memory.allocator(); var random: std.Random.DefaultPrng = .init(seed); + const table = try p.a.create([pairs.most]u32); + const seen = try p.a.create([pairs.slots]u32); for (0..6) |j| { const n = groups(j); const codes = try p.a.alloc(u8, n * 16); @@ -69,6 +79,9 @@ pub const Fixture = struct { p.w[j * 3] = try p.make(device, codes); p.w[j * 3 + 1] = try p.make(device, std.mem.sliceAsBytes(s)); p.w[j * 3 + 2] = try p.make(device, std.mem.sliceAsBytes(b)); + const index = try p.a.alloc(u16, n); + const count = try pairs.index(s, b, index, table, seen); + p.ix[j] = .{ try p.make(device, std.mem.sliceAsBytes(index)), try p.make(device, std.mem.sliceAsBytes(try p.a.dupe(u32, table[0..count]))) }; } const h = try p.a.alloc(u16, rows * d); for (h, 0..) |*v, i| v.* = bf16(@as(f32, @floatFromInt((i * 7 + seed) % 23)) / 64 - 0.125); @@ -92,15 +105,17 @@ pub const Fixture = struct { p.direct[k] = try mtl.Pipeline.init(device, lib, try std.fmt.allocPrintSentinel(p.a, "{s}", .{if (gate) names.gate else names.down}, 0), false); try p.pipelines.append(p.a, p.direct[k]); } - const lib = try gx.library(device); - try p.libraries.append(p.a, lib); - for (gx.functions, &p.grouped.pipes) |name, *pipe| { - pipe.* = try mtl.Pipeline.init(device, lib, name, false); - try p.pipelines.append(p.a, pipe.*); - } p.list = try device.buffer(gx.list_bytes, mtl.ResourceOptions.shared); - p.grouped.buf = p.list.?; - p.grouped.min_rows = 1; + for ([_]bool{ false, true }, &p.grouped) |indexed, *g| { + const lib = try gx.library(p.a, device, indexed); + try p.libraries.append(p.a, lib); + for (gx.functions, &g.pipes) |name, *pipe| { + pipe.* = try mtl.Pipeline.init(device, lib, name, false); + try p.pipelines.append(p.a, pipe.*); + } + g.buf = p.list.?; + g.min_rows = 1; + } return p; } @@ -142,16 +157,21 @@ pub const Fixture = struct { return .{ .b = ref.buffer, .off = 64 }; } - /// Act, picks, weights and y after the recorded launches, or after gx.zig's when `by_expert`. - pub fn run(p: *Fixture, by_expert: bool) ![]const u8 { + /// Act, picks, weights and y after the recorded launches, or gx.zig's when `by_expert` (`indexed`: on the index). + pub fn run(p: *Fixture, by_expert: bool, indexed: bool) ![]const u8 { for (p.io[3..]) |ref| @memset(p.bytes(ref), 0); const cb = p.queue.commandBuffer(); const e = cb.compute(.serial); if (by_expert) { var w: [18]Buf = undefined; for (p.w, &w) |ref, *out| out.* = buf(ref); - if (p.wrong_scales) std.mem.swap(Buf, &w[1], &w[4]); // the control: gate and up scales change places - p.grouped.launch(e, false, buf(p.io[0]), buf(p.io[1]), w, buf(p.io[3]), buf(p.io[4]), buf(p.io[5]), buf(p.io[2]), buf(p.io[6]), p.rows); + if (indexed) for (p.ix, 0..) |pair, j| { + w[j * 3 + 1] = buf(pair[0]); + w[j * 3 + 2] = buf(pair[1]); + }; + const slot: usize = if (indexed) 2 else 1; // the control: gate and up scales (indexed: their tables) change places + if (p.wrong_scales) std.mem.swap(Buf, &w[slot], &w[slot + 3]); + p.grouped[@intFromBool(indexed)].launch(e, false, buf(p.io[0]), buf(p.io[1]), w, buf(p.io[3]), buf(p.io[4]), buf(p.io[5]), buf(p.io[2]), buf(p.io[6]), p.rows); } else { e.setPipeline(p.direct[0]); bind(e, 0, p.io[0]); diff --git a/zig/src/families/flashnext/gx.zig b/zig/src/families/flashnext/gx.zig index 3def2dc4819..16b63a2a67a 100644 --- a/zig/src/families/flashnext/gx.zig +++ b/zig/src/families/flashnext/gx.zig @@ -24,7 +24,9 @@ pub const Gx = struct { /// The routed and shared experts for `rows` rows (at most rmax; the kernels read the count from `rows_buf`). pub fn encode(g: *const Gx, r: *Run, x: Buf, lg: Buf, e: [18]Buf, act: Buf, pick: Buf, wts: Buf, rows_buf: Buf, y: Buf, rows: usize) void { if (r.skip & (1 << 2) != 0) return; - g.launch(r.enc, !r.serial, x, lg, e, act, pick, wts, rows_buf, y, rows); + var bound = e; + if (r.sb_index) @import("scale_index.zig").bind(r, &bound, true, true) catch return; // init checked each set + g.launch(r.enc, !r.serial, x, lg, bound, act, pick, wts, rows_buf, y, rows); } /// The five launches on `enc`; `barriers` for a concurrent encoder, where each waits for the one it reads. @@ -63,14 +65,15 @@ pub fn applies(w: variants.Experts) bool { return std.mem.eql(usize, &w.gu, &four) and std.mem.eql(usize, &w.down, &four); } -/// fn_gx.metal compiled as the loader compiles it. -pub fn library(device: mtl.Device) !mtl.Library { - return mtl.Library.fromSource(device, ks.flashnext_gx, mtl.CompileOptions.mlx()); +/// fn_gx.metal compiled as the loader compiles it; `indexed` reads scales and biases through scale_index's tables. +pub fn library(a: std.mem.Allocator, device: mtl.Device, indexed: bool) !mtl.Library { + const text = if (indexed) try @import("experts4.zig").indexedGrouped(a, ks.flashnext_gx) else ks.flashnext_gx; + return mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); } /// The grouped kernels for windows of `min_rows` rows or more (at most rmax). pub fn init(r: *Run, min_rows: usize) !*Gx { - const lib = try r.ownResource(try library(r.device)); + const lib = try r.ownResource(try library(r.arena, r.device, r.sb_index)); const g = try r.arena.create(Gx); var pipes: [functions.len]mtl.Pipeline = undefined; for (functions, &pipes) |name, *p| p.* = try r.ownResource(try mtl.Pipeline.init(r.device, lib, name, false)); diff --git a/zig/src/families/flashnext/prompt_index_fixture.zig b/zig/src/families/flashnext/prompt_index_fixture.zig new file mode 100644 index 00000000000..3d3d8b0b78d --- /dev/null +++ b/zig/src/families/flashnext/prompt_index_fixture.zig @@ -0,0 +1,204 @@ +//! The 4/32 prompt gathers reading scales and biases direct and through scale_pairs' index, on the same stored bytes. +const std = @import("std"); +const mtl = @import("metal"); +const ks = @import("kernel_sources"); +const frags = @import("../../core/frags.zig"); +const qmmw_source = @import("../../core/qmmw_source.zig"); +const index_source = @import("prompt_index_source.zig"); +const pairs = @import("scale_pairs.zig"); + +pub const d = 2560; +pub const inner = 640; +pub const experts = 8; +/// The gathers by tile size, then the fused gate/up gathers. +pub const functions = [_][:0]const u8{ "tf_gather_qmmw_nax_32", "tf_gather_qmmw_nax_64", "tf_gather_qmmw_nax_128", "tf_gather_guw_nax_32", "tf_gather_guw_nax_64" }; +const tiles = [_]usize{ 32, 64, 128, 32, 64 }; + +pub const Ref = struct { buffer: mtl.Buffer, size: usize }; + +/// qmmw_nax.metal at 4/32 before nax.h is inlined; `indexed` as the loader patches it for the gathers. +pub fn text(a: std.mem.Allocator, indexed: bool) ![]const u8 { + return qmmw_source.source(a, if (indexed) try index_source.patch(a, ks.flashnext_qmmw) else ks.flashnext_qmmw, 4, 32); +} + +/// Projection j's outputs and inputs: gate and up [inner, d], down [d, inner]. +fn shape(j: usize) [2]usize { + return if (j < 2) .{ inner, d } else .{ d, inner }; +} + +pub const Fixture = struct { + memory: std.heap.ArenaAllocator, + a: std.mem.Allocator, + queue: mtl.Queue, + rows: usize, + w: [9]Ref, // gate, up and down: weight, scales and biases + ix: [3][2]Ref, // each projection's index and table + io: [3]Ref, // input rows [rows, d], activation rows [rows, inner], each expert's first row + out: [8]Ref, // gate by 32, 64 and 128-row tiles, gate/up by 32 and 64, down by 32, 64 and 128 + pipes: [2][functions.len]mtl.Pipeline, // direct, indexed + libraries: std.ArrayList(mtl.Library) = .empty, + pipelines: std.ArrayList(mtl.Pipeline) = .empty, + buffers: std.ArrayList(Ref) = .empty, + stored: std.ArrayList([]const u8) = .empty, + wrong_entry: bool = false, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, rows: usize, seed: u64, nonfinite: bool) !*Fixture { + if (rows < experts or rows > 512) return error.PromptIndexFixtureShape; + const p = try a.create(Fixture); + p.* = .{ .memory = .init(a), .a = undefined, .queue = queue, .rows = rows, .w = undefined, .ix = undefined, .io = undefined, .out = undefined, .pipes = undefined }; + errdefer p.deinit(a); + p.a = p.memory.allocator(); + var random: std.Random.DefaultPrng = .init(seed); + const table = try p.a.create([pairs.most]u32); + const seen = try p.a.create([pairs.slots]u32); + for (0..3) |j| { + const n = experts * shape(j)[0] * (shape(j)[1] / 32); + const codes = try p.a.alloc(u8, n * 16); + random.random().bytes(codes); + const s = try p.a.alloc(u16, n); + const b = try p.a.alloc(u16, n); + for (s, b, 0..) |*sv, *bv, i| { + sv.* = bf16(@as(f32, @floatFromInt(1 + (i * 13 + seed + j) % 97)) / 4096); + bv.* = bf16(-@as(f32, @floatFromInt((i * 5 + seed) % 31)) / 4096); + } + if (nonfinite) for ([_]u16{ 0x7fc0, 0x7f80, 0xff80 }, 0..) |v, i| { + s[i * (n / 3)] = v; + }; + const index = try p.a.alloc(u16, n); + const count = try pairs.index(s, b, index, table, seen); + p.w[j * 3] = try p.make(device, codes); + p.w[j * 3 + 1] = try p.make(device, std.mem.sliceAsBytes(s)); + p.w[j * 3 + 2] = try p.make(device, std.mem.sliceAsBytes(b)); + p.ix[j] = .{ try p.make(device, std.mem.sliceAsBytes(index)), try p.make(device, std.mem.sliceAsBytes(try p.a.dupe(u32, table[0..count]))) }; + } + const x = try p.a.alloc(u16, rows * d); + for (x, 0..) |*v, i| v.* = bf16(@as(f32, @floatFromInt((i * 7 + seed) % 23)) / 64 - 0.125); + const act = try p.a.alloc(u16, rows * inner); + for (act, 0..) |*v, i| v.* = bf16(@as(f32, @floatFromInt((i * 11 + seed) % 19)) / 32 - 0.25); + // every expert's first row: expert 0 always has rows, one expert has none, the last takes what is left + const first = try p.a.alloc(i32, experts); + var at: usize = 0; + for (first, 0..) |*v, e| { + v.* = @intCast(at); + const share = if (e == 3) 0 else 1 + (e * 5 + seed) % (2 * rows / experts); + at = @min(rows, at + share); + } + p.io[0] = try p.make(device, std.mem.sliceAsBytes(x)); + p.io[1] = try p.make(device, std.mem.sliceAsBytes(act)); + p.io[2] = try p.make(device, std.mem.sliceAsBytes(first)); + for (&p.out, 0..) |*o, k| { + const width: usize = if (k < 5) inner else d; + o.* = try p.make(device, try p.a.alloc(u8, rows * width * 2)); + } + for ([_]bool{ false, true }, 0..) |indexed, k| { + const lib = try mtl.Library.fromSource(device, try frags.sourceMode(device, p.a, try text(p.a, indexed), false), mtl.CompileOptions.mlx()); + try p.libraries.append(p.a, lib); + for (functions, &p.pipes[k]) |name, *pipe| { + pipe.* = try mtl.Pipeline.init(device, lib, name, false); + try p.pipelines.append(p.a, pipe.*); + } + } + return p; + } + + fn bf16(x: f32) u16 { + const bits: u32 = @bitCast(x); + return @truncate((bits +% 0x7fff +% ((bits >> 16) & 1)) >> 16); + } + + /// A guarded device buffer holding `data`, which the fixture keeps to prove the kernels left it alone. + fn make(p: *Fixture, device: mtl.Device, data: []const u8) !Ref { + const b = try device.buffer(data.len + 128, mtl.ResourceOptions.shared); + errdefer b.deinit(); + @memset(b.contents()[0 .. data.len + 128], 0xa5); + const ref: Ref = .{ .buffer = b, .size = data.len }; + @memcpy(p.bytes(ref), data); + try p.buffers.append(p.a, ref); + try p.stored.append(p.a, data); + return ref; + } + + pub fn deinit(p: *Fixture, a: std.mem.Allocator) void { + for (p.buffers.items) |b| b.buffer.deinit(); + for (p.pipelines.items) |pipe| pipe.deinit(); + for (p.libraries.items) |lib| lib.deinit(); + p.memory.deinit(); + a.destroy(p); + } + + pub fn bytes(_: *const Fixture, ref: Ref) []u8 { + return ref.buffer.contents()[64..][0..ref.size]; + } + + fn bind(e: mtl.ComputeEncoder, at: usize, ref: Ref) void { + e.setBuffer(ref.buffer, 64, at); + } + + /// Projection j's weight, scales and biases as a launch binds them: the index and table when `indexed`. + fn weights(p: *const Fixture, j: usize, indexed: bool) [3]Ref { + return if (indexed) .{ p.w[j * 3], p.ix[j][0], p.ix[j][1] } else .{ p.w[j * 3], p.w[j * 3 + 1], p.w[j * 3 + 2] }; + } + + /// Every gather's output in `out`'s order, as Prompt.gather and gatherGU launch them. + pub fn run(p: *Fixture, indexed: bool) ![]const u8 { + for (p.out) |ref| @memset(p.bytes(ref), 0); + if (indexed and p.wrong_entry) p.swapPairs(); + defer if (indexed and p.wrong_entry) p.swapPairs(); + const cb = p.queue.commandBuffer(); + const e = cb.compute(.serial); + for (p.out, 0..) |y, k| { + const which = if (k < 5) k else k - 5; // the down gathers reuse the three plain gathers + const fused = k == 3 or k == 4; + const n: usize = if (k < 5) inner else d; + const inputs_k: usize = if (k < 5) d else inner; + const prm = [4]i32{ @intCast(p.rows), @intCast(n), @intCast(inputs_k), experts }; + e.setPipeline(p.pipes[@intFromBool(indexed)][which]); + bind(e, 0, p.io[if (k < 5) 0 else 1]); + var at: usize = 1; + for (p.weights(if (k < 5) 0 else 2, indexed)) |ref| { + bind(e, at, ref); + at += 1; + } + if (fused) for (p.weights(1, indexed)) |ref| { + bind(e, at, ref); + at += 1; + }; + bind(e, at, p.io[2]); + e.setBytes(std.mem.asBytes(&prm), at + 1); + bind(e, at + 2, y); + e.dispatchThreads(mtl.Size.of(((n + 63) / 64) * 128, p.rows / tiles[which] + experts, 1), mtl.Size.of(128, 1, 1)); + } + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure() != null) return error.PromptIndexFixtureGpuFailure; + var all: std.ArrayList(u8) = .empty; + for (p.out) |ref| try all.appendSlice(p.a, p.bytes(ref)); + return all.items; + } + + /// The control: the gate's first two table pairs change places. + fn swapPairs(p: *Fixture) void { + const table = p.bytes(p.ix[0][1]); + var pair: [4]u8 = undefined; + @memcpy(&pair, table[0..4]); + @memcpy(table[0..4], table[4..8]); + @memcpy(table[4..8], &pair); + } + + /// Every input the kernels read, in one slice. + pub fn inputs(p: *Fixture, a: std.mem.Allocator, out: *std.ArrayList(u8)) !void { + for (p.buffers.items[0 .. p.buffers.items.len - p.out.len]) |ref| try out.appendSlice(a, p.bytes(ref)); + } + + /// Guards whole and every input as stored. + pub fn intact(p: *Fixture) bool { + for (p.buffers.items, p.stored.items, 0..) |b, data, i| { + const all = b.buffer.contents()[0 .. b.size + 128]; + for (all[0..64]) |v| if (v != 0xa5) return false; + for (all[64 + b.size ..]) |v| if (v != 0xa5) return false; + if (i + p.out.len < p.buffers.items.len and !std.mem.eql(u8, p.bytes(b), data)) return false; + } + return true; + } +}; diff --git a/zig/src/families/flashnext/prompt_index_source.zig b/zig/src/families/flashnext/prompt_index_source.zig new file mode 100644 index 00000000000..eab8c7cd957 --- /dev/null +++ b/zig/src/families/flashnext/prompt_index_source.zig @@ -0,0 +1,34 @@ +//! qmmw_nax.metal's expert gathers reading scales and biases through scale_index's index and table. +const std = @import("std"); + +/// Each read of the two K loops and each gather's row pointers: the scale row is the index row, the bias the table. +const reads = [_][2][]const u8{ + .{ " T sc = srow[hk / WG], bi = brow[hk / WG];\n", " const device ushort* ixrow = (const device ushort*)srow;\n uint si = uint(ixrow[hk / WG]) * 2u;\n T sc = brow[si], bi = brow[si + 1];\n" }, + .{ " sc = srow[(hk + k + 64) / WG];\n bi = brow[(hk + k + 64) / WG];\n", " si = uint(ixrow[(hk + k + 64) / WG]) * 2u;\n sc = brow[si];\n bi = brow[si + 1];\n" }, + .{ " T gs = sg[hk / WG], gbi = bg[hk / WG], us = su[hk / WG], ubi = bu[hk / WG];\n", " const device ushort* ixg = (const device ushort*)sg;\n const device ushort* ixu = (const device ushort*)su;\n uint gi = uint(ixg[hk / WG]) * 2u, ui = uint(ixu[hk / WG]) * 2u;\n T gs = bg[gi], gbi = bg[gi + 1], us = bu[ui], ubi = bu[ui + 1];\n" }, + .{ " gs = sg[g];\n gbi = bg[g];\n us = su[g];\n ubi = bu[g];\n", " gi = uint(ixg[g]) * 2u;\n ui = uint(ixu[g]) * 2u;\n gs = bg[gi];\n gbi = bg[gi + 1];\n us = bu[ui];\n ubi = bu[ui + 1];\n" }, + .{ "W + wrow * WPR + WB * (t % 2), S + wrow * KG, B + wrow * KG, 0, tile, tn, uint(t),", "W + wrow * WPR + WB * (t % 2), S + wrow * KG, B, 0, tile, tn, uint(t)," }, + .{ "WG_ + wrow * WPR + WB * (t % 2), SG + wrow * KG, BG + wrow * KG,", "WG_ + wrow * WPR + WB * (t % 2), SG + wrow * KG, BG," }, + .{ "WU + wrow * WPR + WB * (t % 2), SU + wrow * KG, BU + wrow * KG, tile_g, tile_u, tn,", "WU + wrow * WPR + WB * (t % 2), SU + wrow * KG, BU, tile_g, tile_u, tn," }, + .{ "[[kernel]] void tf_gather_qmmw_nax_##BM(", "[[max_total_threads_per_threadgroup(128)]] [[kernel]] void tf_gather_qmmw_nax_##BM(" }, + .{ "[[kernel]] void tf_gather_guw_nax_##BM(", "[[max_total_threads_per_threadgroup(128)]] [[kernel]] void tf_gather_guw_nax_##BM(" }, +}; + +/// `text` for the gather kernels alone: the dense kernels share the patched loops, so they keep the unpatched text. +pub fn patch(a: std.mem.Allocator, text: []const u8) ![]const u8 { + var out = text; + for (reads) |r| { + if (std.mem.count(u8, out, r[0]) != 1) return error.KernelPatch; + out = try std.mem.replaceOwned(u8, a, out, r[0], r[1]); + } + return out; +} + +test "every scale and bias read of the prompt gathers goes through the index once patched" { + const ks = @import("kernel_sources"); + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const out = try patch(arena.allocator(), ks.flashnext_qmmw); + for ([_][]const u8{ "srow[", "sg[", "su[", "brow[hk", "bg[hk", "bu[hk", "bg[g]", "bu[g]" }) |direct| try std.testing.expectEqual(@as(usize, 0), std.mem.count(u8, out, direct)); + try std.testing.expectError(error.KernelPatch, patch(arena.allocator(), out)); +} diff --git a/zig/src/families/flashnext/prompt_w.zig b/zig/src/families/flashnext/prompt_w.zig index 0db704c2e49..300fac5be17 100644 --- a/zig/src/families/flashnext/prompt_w.zig +++ b/zig/src/families/flashnext/prompt_w.zig @@ -1,5 +1,6 @@ //! Prompt products at any MLX width: qmmw_nax compiled per (bits, group), and which weights take which width. const std = @import("std"); +const scale_index = @import("scale_index.zig"); const mtl = @import("metal"); pub const ks = @import("kernel_sources"); const frags = @import("../../core/frags.zig"); @@ -11,7 +12,9 @@ const Model = replay.Model; const variants = @import("variants.zig"); /// One width's kernels: dense, split-K, sorted-expert gathers (32, 64, 128 rows) and fused gate/up (32, 64 rows). -pub const Pipes = struct { qmm: mtl.Pipeline, splitk: mtl.Pipeline, gather: [3]mtl.Pipeline, gu: [2]mtl.Pipeline }; +pub const Pipes = struct { qmm: mtl.Pipeline, splitk: mtl.Pipeline, gather: [3]mtl.Pipeline, gu: [2]mtl.Pipeline, ix: ?Gathers = null }; +/// One library's gathers by tile size; `Pipes.ix` holds the ones that read scales and biases through the index. +pub const Gathers = struct { gather: [3]mtl.Pipeline, gu: [2]mtl.Pipeline }; /// A fused member: its rows and width, in member order. pub const Part = struct { rows: usize, bits: u8, group: u16 }; @@ -56,24 +59,31 @@ fn key(b: Buf) Key { return .{ .id = @intFromPtr(b.b.id), .off = b.off }; } -/// qmmw_nax at `bits`/`group` with nax.h inlined for this GPU. -pub fn compile(r: *Run, bits: u8, group: u16) !Pipes { - const body = if (r.window.ssd_experts != null) try @import("fsr_prompt_source.zig").patch(r.arena, ks.flashnext_qmmw, true) else ks.flashnext_qmmw; - const text = try frags.source(r.device, r.arena, try @import("../../core/qmmw_source.zig").source(r.arena, body, bits, group)); - const lib = try r.ownResource(try mtl.Library.fromSource(r.device, text, mtl.CompileOptions.mlx())); - const p = struct { - fn of(rr: *Run, l: mtl.Library, name: [:0]const u8) !mtl.Pipeline { - return rr.ownResource(try mtl.Pipeline.init(rr.device, l, name, false)); - } - }; +fn pipeline(r: *Run, lib: mtl.Library, name: [:0]const u8) !mtl.Pipeline { + return r.ownResource(try mtl.Pipeline.init(r.device, lib, name, false)); +} + +fn gathers(r: *Run, lib: mtl.Library) !Gathers { return .{ - .qmm = try p.of(r, lib, "tf_qmmw_t_nax"), - .splitk = try p.of(r, lib, "tf_qmmw_splitk_nax"), - .gather = .{ try p.of(r, lib, "tf_gather_qmmw_nax_32"), try p.of(r, lib, "tf_gather_qmmw_nax_64"), try p.of(r, lib, "tf_gather_qmmw_nax_128") }, - .gu = .{ try p.of(r, lib, "tf_gather_guw_nax_32"), try p.of(r, lib, "tf_gather_guw_nax_64") }, + .gather = .{ try pipeline(r, lib, "tf_gather_qmmw_nax_32"), try pipeline(r, lib, "tf_gather_qmmw_nax_64"), try pipeline(r, lib, "tf_gather_qmmw_nax_128") }, + .gu = .{ try pipeline(r, lib, "tf_gather_guw_nax_32"), try pipeline(r, lib, "tf_gather_guw_nax_64") }, }; } +fn library(r: *Run, body: []const u8, bits: u8, group: u16) !mtl.Library { + const text = try frags.source(r.device, r.arena, try @import("../../core/qmmw_source.zig").source(r.arena, body, bits, group)); + return r.ownResource(try mtl.Library.fromSource(r.device, text, mtl.CompileOptions.mlx())); +} + +/// qmmw_nax at `bits`/`group` with nax.h inlined for this GPU; with the scale index, 4/32 gathers read through it. +pub fn compile(r: *Run, bits: u8, group: u16) !Pipes { + const body = if (r.window.ssd_experts != null) try @import("fsr_prompt_source.zig").patch(r.arena, ks.flashnext_qmmw, true) else ks.flashnext_qmmw; + const lib = try library(r, body, bits, group); + const g = try gathers(r, lib); + const ix: ?Gathers = if (r.sb_index and bits == 4 and group == 32) try gathers(r, try library(r, try @import("prompt_index_source.zig").patch(r.arena, body), bits, group)) else null; + return .{ .qmm = try pipeline(r, lib, "tf_qmmw_t_nax"), .splitk = try pipeline(r, lib, "tf_qmmw_splitk_nax"), .gather = g.gather, .gu = g.gu, .ix = ix }; +} + fn need(w: *Wide, r: *Run, bits: u8, group: u16) !void { const k = @as(u32, bits) << 16 | group; if (!w.pipes.contains(k)) try w.pipes.put(r.arena, k, try compile(r, bits, group)); @@ -168,7 +178,8 @@ fn launch(p: *Prompt, pipe: mtl.Pipeline, w: [3]Buf, x: Buf, k: usize, n: usize, /// The sorted-expert gather at the weight's width: tiles of 32, 64 or 128 rows as Prompt.gather picks them. pub fn gather(p: *Prompt, pipes: Pipes, bm: usize, x: Buf, w: []const Buf, k: usize, n: usize, pairs: usize, y: Buf) void { - p.bind(pipes.gather[if (bm == 128) 2 else if (bm == 64) 1 else 0], &.{ x, w[0], w[1], w[2], p.b.off }); + const set = if (pipes.ix != null and p.r.sbix.contains(scale_index.keyOf(w[0]))) pipes.ix.?.gather else pipes.gather; + p.bind(set[if (bm == 128) 2 else if (bm == 64) 1 else 0], &.{ x, w[0], w[1], w[2], p.b.off }); const prm = [4]i32{ @intCast(pairs), @intCast(n), @intCast(k), 512 }; p.r.enc.setBytes(std.mem.asBytes(&prm), 5); p.r.enc.setBuffer(y.b, y.off, 6); @@ -178,7 +189,8 @@ pub fn gather(p: *Prompt, pipes: Pipes, bm: usize, x: Buf, w: []const Buf, k: us /// The fused gate/up gather at the weights' width. pub fn gatherGU(p: *Prompt, pipes: Pipes, bm: usize, x: Buf, wg: []const Buf, wu: []const Buf, k: usize, n: usize, pairs: usize, y: Buf) void { - p.bind(pipes.gu[if (bm == 64) 1 else 0], &.{ x, wg[0], wg[1], wg[2], wu[0], wu[1], wu[2], p.b.off }); + const set = if (pipes.ix != null and p.r.sbix.contains(scale_index.keyOf(wg[0]))) pipes.ix.?.gu else pipes.gu; + p.bind(set[if (bm == 64) 1 else 0], &.{ x, wg[0], wg[1], wg[2], wu[0], wu[1], wu[2], p.b.off }); const prm = [4]i32{ @intCast(pairs), @intCast(n), @intCast(k), 512 }; p.r.enc.setBytes(std.mem.asBytes(&prm), 8); p.r.enc.setBuffer(y.b, y.off, 9); diff --git a/zig/src/families/flashnext/replay_run.zig b/zig/src/families/flashnext/replay_run.zig index 41da35de4f6..0b7914b472f 100644 --- a/zig/src/families/flashnext/replay_run.zig +++ b/zig/src/families/flashnext/replay_run.zig @@ -73,7 +73,7 @@ pub const Run = struct { dense: bool = false, dense_target: bool = false, skip: u32 = 0, - sb_index: bool = false, // TF_FLASHNEXT_SCALE_INDEX: the 4/32 expert kernels read scales and biases through scale_index's tables + sb_index: bool = false, // the 4/32 expert kernels read scales and biases through scale_index (TF_FLASHNEXT_SCALE_INDEX=0: off) sbix: std.AutoHashMapUnmanaged(@import("scale_index.zig").Key, [2]Buf) = .empty, sb_pairs: usize = 0, // the most distinct pairs any indexed tensor has hcskip: u32 = 0, // FZ_HCSKIP: hyper-connection knock-outs by kernel (1 norms, 2 downs, 4 ups) diff --git a/zig/src/families/flashnext/scale_index.zig b/zig/src/families/flashnext/scale_index.zig index 58748b28814..988e5d32d4d 100644 --- a/zig/src/families/flashnext/scale_index.zig +++ b/zig/src/families/flashnext/scale_index.zig @@ -1,44 +1,113 @@ -//! TF_FLASHNEXT_SCALE_INDEX: an expert projection's scales and biases as device index and table buffers (scale_pairs). +//! TF_FLASHNEXT_SCALE_INDEX: the 4/32 expert projections' scales and biases as index and table buffers (scale_pairs). const std = @import("std"); const replay = @import("replay.zig"); +const variants = @import("variants.zig"); +const experts4 = @import("experts4.zig"); +const pairs = @import("scale_pairs.zig"); const Run = replay.Run; const Buf = replay.Buf; -const pairs = @import("scale_pairs.zig"); -/// A scales buffer's identity: the map from it to its index and table. +/// A projection's codes buffer: the key of its index and table. pub const Key = struct { id: @FieldType(@FieldType(Buf, "b"), "id"), off: usize }; -pub fn keyOf(b: Buf) Key { - return .{ .id = b.b.id, .off = b.off }; +pub fn keyOf(codes: Buf) Key { + return .{ .id = codes.b.id, .off = codes.off }; } -/// The index and table buffers of the scales `s` and biases `b` (whole buffers of bf16), kept under `s`'s key. -pub fn add(r: *Run, s: Buf, b: Buf) !void { - const groups = (s.b.length() - s.off) / 2; +/// The projections only expert kernels read (routed gate, up, down): their stored scales and biases are released. +pub fn routed(j: usize) bool { + return j == 0 or j == 1 or j == 4; +} + +/// An expert set (weight, scales, biases a projection) and its widths; null widths are the recorded 6/32. +pub const Set = struct { ex: *[18]Buf, xw: ?variants.Experts }; + +const Job = struct { ex: *[18]Buf, j: usize, ix: Buf, table: []u32 = &.{}, state: enum { waiting, done, too_many, failed } = .waiting }; + +const max_workers = 8; + +/// Jobs taken in turn: each projection's pairs indexed into its buffer, its table kept on the host for the caller. +fn work(jobs: []Job, next: *std.atomic.Value(usize)) void { const gpa = std.heap.page_allocator; - const table = try gpa.create([pairs.most]u32); + const table = gpa.create([pairs.most]u32) catch return; defer gpa.destroy(table); - const seen = try gpa.create([pairs.slots]u32); + const seen = gpa.create([pairs.slots]u32) catch return; defer gpa.destroy(seen); - const ix = try r.buffer(groups * 2); - const sp: [*]align(1) const u16 = @ptrCast(s.b.contents() + s.off); - const bp: [*]align(1) const u16 = @ptrCast(b.b.contents() + b.off); - const ip: [*]align(1) u16 = @ptrCast(ix.contents()); - const n = try pairs.index(sp[0..groups], bp[0..groups], ip[0..groups], table, seen); - const t = try r.buffer(n * 4); - @memcpy(t.contents()[0 .. n * 4], std.mem.sliceAsBytes(table[0..n])); - try r.sbix.put(r.arena, keyOf(s), .{ .{ .b = ix }, .{ .b = t } }); - r.sb_pairs = @max(r.sb_pairs, n); + while (true) { + const at = next.fetchAdd(1, .monotonic); + if (at >= jobs.len) return; + const job = &jobs[at]; + const s = job.ex[job.j * 3 + 1]; + const b = job.ex[job.j * 3 + 2]; + const groups = (s.b.length() - s.off) / 2; + const sp: [*]align(1) const u16 = @ptrCast(s.b.contents() + s.off); + const bp: [*]align(1) const u16 = @ptrCast(b.b.contents() + b.off); + const ip: [*]align(1) u16 = @ptrCast(job.ix.b.contents()); + const n = pairs.index(sp[0..groups], bp[0..groups], ip[0..groups], table, seen) catch { + job.state = .too_many; + continue; + }; + job.table = gpa.dupe(u32, table[0..n]) catch { + job.state = .failed; + continue; + }; + job.state = .done; + } } -/// Every projection of an expert set (weight, scales, biases a projection) indexed; a table past 16 bits turns it off. -pub fn addAll(r: *Run, ex: *const [18]Buf) !void { - for (0..6) |j| add(r, ex[j * 3 + 1], ex[j * 3 + 2]) catch |err| switch (err) { - error.TooManyPairs => { - std.log.warn("TF_FLASHNEXT_SCALE_INDEX: a tensor has more than {d} scale and bias pairs; the index is off", .{pairs.most}); - r.sb_index = false; - return; - }, - else => return err, +/// Every 4/32 gate/up and down group of `sets` indexed, routed arrays released and their slots given index and table. +pub fn build(r: *Run, sets: []const Set) !void { + const gpa = std.heap.page_allocator; + var jobs: std.ArrayList(Job) = .empty; + defer jobs.deinit(gpa); + defer for (jobs.items) |job| if (job.table.len != 0) gpa.free(job.table); + for (sets) |set| { + const w = set.xw orelse continue; + var c: [4]variants.Const = undefined; + for ([_][2]usize{ .{ 0, 4 }, .{ 4, 6 } }, [_][4]usize{ w.gu, w.down }) |span, width| { + if (!experts4.q4(variants.four(&c, width))) continue; + for (span[0]..span[1]) |j| { + const s = set.ex[j * 3 + 1]; + try jobs.append(gpa, .{ .ex = set.ex, .j = j, .ix = .{ .b = try r.buffer(s.b.length() - s.off) } }); + } + } + } + if (jobs.items.len == 0) { + r.sb_index = false; + return; + } + var next: std.atomic.Value(usize) = .init(0); + var threads: [max_workers]?std.Thread = @splat(null); + const workers = @min(max_workers, std.Thread.getCpuCount() catch 1, jobs.items.len); + for (threads[1..workers]) |*t| t.* = std.Thread.spawn(.{}, work, .{ jobs.items, &next }) catch null; + work(jobs.items, &next); + for (threads) |t| if (t) |thread| thread.join(); + for (jobs.items) |job| if (job.state != .done) { + for (jobs.items) |made| r.release(made.ix.b); + r.sb_index = false; + if (job.state != .too_many) return error.OutOfMemory; + std.log.warn("TF_FLASHNEXT_SCALE_INDEX: a tensor has more than {d} scale and bias pairs; the index is off", .{pairs.most}); + return; }; + for (jobs.items) |job| { + const table = try r.buffer(job.table.len * 4); + @memcpy(table.contents()[0 .. job.table.len * 4], std.mem.sliceAsBytes(job.table)); + try r.sbix.put(r.arena, keyOf(job.ex[job.j * 3]), .{ job.ix, .{ .b = table } }); + r.sb_pairs = @max(r.sb_pairs, job.table.len); + if (!routed(job.j)) continue; + r.release(job.ex[job.j * 3 + 1].b); + r.release(job.ex[job.j * 3 + 2].b); + job.ex[job.j * 3 + 1] = job.ix; + job.ex[job.j * 3 + 2] = .{ .b = table }; + } +} + +/// `e` as the indexed kernels take it: the shared projections' index and table in their scales' and biases' slots. +pub fn bind(r: *const Run, e: *[18]Buf, gate_up: bool, down: bool) !void { + for (0..6) |j| { + if (routed(j) or !(if (j < 4) gate_up else down)) continue; + const p = r.sbix.get(keyOf(e[j * 3])) orelse return error.NoScaleIndex; + e[j * 3 + 1] = p[0]; + e[j * 3 + 2] = p[1]; + } } diff --git a/zig/src/families/flashnext/variants.zig b/zig/src/families/flashnext/variants.zig index 6b494951315..d01c4a67482 100644 --- a/zig/src/families/flashnext/variants.zig +++ b/zig/src/families/flashnext/variants.zig @@ -93,12 +93,7 @@ pub fn experts(r: *Run, gu_role: []const u8, down_role: []const u8, x: Buf, lg: var e = e_direct; var cg: [4]Const = undefined; var cd: [4]Const = undefined; - if (r.sb_index) for (0..6) |j| { // a 4/32 kernel's projections: index and table in the scales' and biases' slots - if (!experts4.q4(if (j < 4) four(&cg, w.gu) else four(&cd, w.down))) continue; - const p = r.sbix.get(@import("scale_index.zig").keyOf(e[j * 3 + 1])) orelse return error.NoScaleIndex; - e[j * 3 + 1] = p[0]; - e[j * 3 + 2] = p[1]; - }; + if (r.sb_index) try @import("scale_index.zig").bind(r, &e, experts4.q4(four(&cg, w.gu)), experts4.q4(four(&cd, w.down))); if (r.fsr) |stream| if (stream.pool != null) stream.bind(r, 18, 19, 0); r.enc.setBuffer(rows_buf.b, rows_buf.off, 17); // the 4/32 gate/up's row count (experts4.gated) try callAs(r, gu_role, r.rows, &.{ x, lg, e[0], e[1], e[2], e[3], e[4], e[5], e[6], e[7], e[8], e[9], e[10], e[11] }, &.{ act, pick, wts }, four(&cg, w.gu)); diff --git a/zig/src/families/glm/checks.zig b/zig/src/families/glm/checks.zig index 00df4b8925b..98fa944e277 100644 --- a/zig/src/families/glm/checks.zig +++ b/zig/src/families/glm/checks.zig @@ -226,3 +226,49 @@ pub fn profilePrompt(e: *Engine, prompt: []const u32, reps: usize, only: bool, p if (mask != 0 and !only and mask != all) std.debug.print(" class {d:8.2} ms {d:5.1}%\n", .{ full - med, 100 * (full - med) / full }); } } + +/// Per-token loss via the prompt path in `rows`-row chunks: the head over every row, -log p(ids[i + 1]) into out[i]. +pub fn promptNll(e: *Engine, ids: []const u32, rows: u32, out: []f32) !void { + const c = &e.c; + const V: usize = c.vocab; + const pr = &(e.pr orelse return error.NoPromptChunks); + const P: u32 = @intCast(ids.len); + if (P < 2 or out.len < P - 1) return error.BadArguments; + if (P + 1 > e.s.cap) return error.ContextFull; + const R: u32 = @min(rows, e.chunk_rows); + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const logits = try e.device.buffer(@as(usize, R) * V * 2, mtl.ResourceOptions.shared); + defer logits.deinit(); + e.sync(); + e.s.reset(); + @memcpy(Engine.u32s(e.prompt_ids, P), ids); + var x = e.ctx(); + var at: u32 = 0; + while (at < P - 1) { + const n: u32 = @min(R, P - at); + const b = e.begin(); + var px = x; + px.sc = &pr.streams; + prompt_mod.backbone(pr, &px, b.enc, e.prompt_ids.at(@as(usize, at) * 4), n, at); + fwd.flipKda(&x); + fwd.qmv(&x, b.enc, x.k.qmv_head, pr.streams.hidden, x.w.head, .{ .buf = logits }, n); + try e.finish(b.cb, b.enc); + const l = logits.slice(u16, @as(usize, n) * V); + for (0..n) |r| { + const i = at + @as(u32, @intCast(r)); // row i predicts ids[i + 1] + if (i + 1 >= P) break; + const row = l[r * V ..][0..V]; + var m: f32 = -std.math.inf(f32); + for (row) |v| m = @max(m, bf16f(v)); + var s: f64 = 0; + for (row) |v| s += @exp(@as(f64, bf16f(v) - m)); + out[i] = @floatCast(@as(f64, m) + @log(s) - @as(f64, bf16f(row[ids[i + 1]]))); + } + at += n; + } +} + +fn bf16f(v: u16) f32 { + return @bitCast(@as(u32, v) << 16); +} diff --git a/zig/src/families/glm/engine.zig b/zig/src/families/glm/engine.zig index 9e437852224..fc60204cf0d 100644 --- a/zig/src/families/glm/engine.zig +++ b/zig/src/families/glm/engine.zig @@ -370,6 +370,7 @@ pub const Engine = struct { pub const profile = checks.profile; pub const checkMatmul = checks.checkMatmul; pub const profilePrompt = checks.profilePrompt; + pub const promptNll = checks.promptNll; /// One reply, greedy or sampled by `e.sampling`; `depth` drafts a round (drafted equals plain, depth 0). pub fn generate(e: *Engine, prompt: []const u32, max_tokens: usize, eos: []const u32, depth: usize, out: Out) !Result { diff --git a/zig/src/families/glm/forward.zig b/zig/src/families/glm/forward.zig index 289daff8ee6..82c5db3158b 100644 --- a/zig/src/families/glm/forward.zig +++ b/zig/src/families/glm/forward.zig @@ -519,11 +519,16 @@ pub fn head(x: *const Ctx, e: mtl.ComputeEncoder, in: Ref, logits: Ref, picks: R /// `head` over the first `vocab` tokens; `greedy` forces the MTP draft head's argmax draws. pub fn headOver(x: *const Ctx, e: mtl.ComputeEncoder, in: Ref, logits: Ref, picks: Ref, rows: u32, vocab: u32, greedy: bool) void { + headWith(x, e, x.w.head, in, logits, picks, rows, vocab, greedy); +} + +/// headOver through the LM head `hw` (the MTP drafts' own when one is loaded). +pub fn headWith(x: *const Ctx, e: mtl.ComputeEncoder, hw: wts.Affine, in: Ref, logits: Ref, picks: Ref, rows: u32, vocab: u32, greedy: bool) void { if (x.skip & Class.head != 0) return; const part = x.c.vocabPart(); // TP2: this Mac's half, its picks merged with the peer's const n: u32 = if (vocab > part[0]) @min(vocab, part[1]) - part[0] else 0; if (n > 0) { - var q = x.w.head; + var q = hw; q.n = n; qmv(x, e, if (x.c.tp > 1) x.k.qmv_head_tp else x.k.qmv_head, in, q, logits, rows); const payload = @import("draw_rule.zig").Payload.init(if (greedy) null else x.draws, rows, vocab); diff --git a/zig/src/families/glm/moe.zig b/zig/src/families/glm/moe.zig index 04c074864c4..43af19a28fd 100644 --- a/zig/src/families/glm/moe.zig +++ b/zig/src/families/glm/moe.zig @@ -15,6 +15,10 @@ const bind = fwd.bind; const shape = fwd.shape; const size = fwd.size; +comptime { + std.debug.assert(st.max_rows == wide.max_members); // the route's member lists, read by wide.moe's unique launches +} + /// MoE block (shared expert, route, routed experts, combine); expert parallel: our experts, sent, the peer's received. pub fn moe(x: *const Ctx, e: mtl.ComputeEncoder, w: *const wts.Moe, x_in: Ref, rows: u32) void { std.debug.assert(rows <= st.max_rows); @@ -63,6 +67,7 @@ pub fn moe(x: *const Ctx, e: mtl.ComputeEncoder, w: *const wts.Moe, x_in: Ref, r c.swiglu_limit, .{ .x = x_in, .ids = sc.pick, .act = sc.act, .acts = sc.acts, .ye = sc.ye, .ys = sc.ys }, rows, + .{ .ids = sc.uids, .members = sc.umem, .count = sc.ucount }, // the route's unique experts, every window ); } else { if (s & Class.shared == 0) experts(x, e, w, x_in, rows, 1, .{ sc.none, sc.none, sc.none }); diff --git a/zig/src/families/glm/mtp.zig b/zig/src/families/glm/mtp.zig index f7b9fbe3f50..53c35fda955 100644 --- a/zig/src/families/glm/mtp.zig +++ b/zig/src/families/glm/mtp.zig @@ -65,12 +65,12 @@ pub fn finish(x: *fwd.Ctx, e: mtl.ComputeEncoder, res: Ref, normed: Ref, rows: u add(x, e, sc.m_out, sc.branch, sc.m_x, rows * D); } -/// Drafts for `rows` pre-norm head outputs at `out`: the head's norm, then the LM head over the draft vocabulary. +/// Drafts for `rows` head outputs at `out`: the norm, then shared_head.head when stored, else lm_head (drafts only). pub fn drafts(x: *const fwd.Ctx, e: mtl.ComputeEncoder, out: Ref, rows: u32, picks: Ref) void { const c = x.c; const D = c.hidden; fwd.rms(x, e, out, x.w.mtp.?.norm, x.sc.m_hn, rows, D, D, D, c.eps); - fwd.headOver(x, e, x.sc.m_hn, x.sc.m_logits.at(@as(usize, x.m_row) * c.vocab * 2), picks, rows, x.draft_vocab, true); + fwd.headWith(x, e, x.w.draft_head orelse x.w.head, x.sc.m_hn, x.sc.m_logits.at(@as(usize, x.m_row) * c.vocab * 2), picks, rows, x.draft_vocab, true); } /// One chained draft from `h` (a row of the head's previous output, m_x) and the draft before it (`token`, u32). diff --git a/zig/src/families/glm/weights.zig b/zig/src/families/glm/weights.zig index 97987e3f425..a2c7fdd0e8a 100644 --- a/zig/src/families/glm/weights.zig +++ b/zig/src/families/glm/weights.zig @@ -57,6 +57,7 @@ pub const Weights = struct { mtp: ?Mtp = null, embed: Affine = undefined, head: Affine = undefined, + draft_head: ?Affine = null, // layers.45.shared_head.head when stored (one Mac): the MTP drafts' own LM head norm: Ref = undefined, buffers: std.ArrayList(mtl.Buffer) = .empty, bytes: usize = 0, @@ -524,10 +525,14 @@ pub fn load(gpa: std.mem.Allocator, device: mtl.Device, dir: []const u8, c: *con l.widths = try readWidths(l.arena, dir, c); const D: usize = c.hidden; const V: usize = c.vocab; - try l.begin(affine.bytes(V, D, try l.widths.of(prefix ++ "embed_tokens")) + affine.bytes(V, D, try l.widths.of("lm_head")) + D * 2 + 8 * 256); + const dh_name = prefix ++ "layers.45.shared_head.head"; // a lighter LM head for the MTP drafts (verification keeps lm_head) + const dh = c.tp == 1 and c.mtp > 0 and l.names.contains(dh_name ++ ".weight"); + const dh_bytes = if (dh) affine.bytes(V, D, try l.widths.of(dh_name)) else 0; + try l.begin(affine.bytes(V, D, try l.widths.of(prefix ++ "embed_tokens")) + affine.bytes(V, D, try l.widths.of("lm_head")) + dh_bytes + D * 2 + 8 * 256); w.embed = try l.mat(.embed, D, prefix ++ "embed_tokens", &.{""}, &.{V}, .{}); const vp = c.vocabPart(); // TP2: this Mac's half of the head's rows w.head = try l.stack(.head, D, "lm_head", &.{""}, &.{vp[0]}, &.{vp[1] - vp[0]}, &.{V}, 1, .{}); + if (dh) w.draft_head = try l.stack(.head, D, dh_name, &.{""}, &.{0}, &.{V}, &.{V}, 1, .{}); w.norm = try l.plain(prefix ++ "norm.weight", .{}, .bf16, &.{D}); for (0..c.run) |i| w.layers[i] = try l.layer(i); const has_mtp = c.mtp > 0 and l.names.contains(prefix ++ "layers.45.eh_proj.weight"); diff --git a/zig/src/families/glm/wide.zig b/zig/src/families/glm/wide.zig index 67e391e8b4b..3305fe15e67 100644 --- a/zig/src/families/glm/wide.zig +++ b/zig/src/families/glm/wide.zig @@ -29,6 +29,8 @@ pub const Pipes = struct { glu_sorted: [nw]mtl.Pipeline, moe: [nw]mtl.Pipeline, // routed experts by pick at each width and the 8-bit shared expert, one launch moe_glu: [nw]mtl.Pipeline, // the same through gate and up, SwiGLU'd + moe_u: [nw]mtl.Pipeline, // `moe` by unique expert (2+ rows): an expert's weights read once for the rows that picked it + moe_glu_u: [nw]mtl.Pipeline, gather: [2]mtl.Pipeline, // four gathered rows sharing the sorted row arithmetic bf16: mtl.Pipeline, // an unquantized matrix (the MTP head's eh_proj, scalar path; decode-side path keeps this) bf16_nax: ?mtl.Pipeline, // bf16 GEMM on tensor units: prefill-side eh_proj replacement for `bf16` (null: `bf16` serves) @@ -53,6 +55,8 @@ pub const Pipes = struct { &p.glu_sorted, &p.moe, &p.moe_glu, + &p.moe_u, + &p.moe_glu_u, &p.embed, &p.kda_fg, }) |set| for (set) |x| x.deinit(); @@ -108,7 +112,7 @@ pub const gather_source = sources.core_row_projection ++ glue_math ++ sources.gl /// The pipelines built so far: a failed compile releases them all. const Made = struct { - list: [nw * 9 + 7 + 4 * affine_mm.names.len]mtl.Pipeline = undefined, + list: [nw * 11 + 7 + 4 * affine_mm.names.len]mtl.Pipeline = undefined, // 11 a width (rows .. moe_glu_u, kda_fg) n: usize = 0, released: usize = 0, @@ -159,6 +163,8 @@ fn build(gpa: std.mem.Allocator, device: mtl.Device, kda: []const u8, made: *Mad p.glu_sorted[i] = try made.add(device, l, "glm_rows_glu_sorted" ++ q); p.moe[i] = try made.add(device, l, "glm_moe_rows" ++ q ++ "_s8"); p.moe_glu[i] = try made.add(device, l, "glm_moe_rows_glu" ++ q ++ "_s8"); + p.moe_u[i] = try made.add(device, l, "glm_moe_rows_u" ++ q ++ "_s8"); + p.moe_glu_u[i] = try made.add(device, l, "glm_moe_rows_glu_u" ++ q ++ "_s8"); } p.bf16 = try made.add(device, l, "glm_rows_bf16"); for (gather.names, &p.gather) |name, *pipe| pipe.* = try made.add(device, l, name); @@ -328,7 +334,13 @@ pub fn moeOne(m: Moe) bool { return m.up.bits == m.gate.bits and m.down.bits == m.gate.bits and m.sh_gate_up.bits == 8 and m.sh_down.bits == 8; } -/// byIds's GLU and down for the slots, glu and dense for the shared expert's rows: a launch each step, the same bits. +/// The route's unique experts (ids, their picks GLM_MAXR a list, their count): `moe` by expert, not by pick. +pub const Unique = struct { ids: Ref, members: Ref, count: Ref }; + +/// The member lists' length in glm_rows.metal (GLM_MAXR): a window's most rows. +pub const max_members = 16; + +/// byIds's GLU and down, glu and dense for the shared expert, a launch a step; with `u` at 2+ rows, by unique expert. pub fn moe( p: *const Pipes, e: mtl.ComputeEncoder, @@ -338,8 +350,11 @@ pub fn moe( lim: f32, io: MoeIo, rows: u32, + u: ?Unique, ) void { + std.debug.assert(rows <= max_members); const slots = rows * topk; + const by_expert = u != null and rows >= 2; const g = m.sh_gate_up; const steps = [2]struct { pipe: mtl.Pipeline, @@ -375,9 +390,10 @@ pub fn moe( .repeat = 1, }, }; - for (steps) |s| { - const u = s.up orelse s.w; - e.setPipeline(s.pipe); + for (steps, 0..) |s, si| { + const uw = s.up orelse s.w; + const pipe = if (!by_expert) s.pipe else if (si == 0) p.moe_glu_u[at(m.gate.bits)] else p.moe_u[at(m.down.bits)]; + e.setPipeline(pipe); bind(e, 0, .{ s.x, s.w.w, s.w.s, s.w.b }); e.setValue(PickDims{ .k = @intCast(s.w.k), @@ -389,7 +405,13 @@ pub fn moe( .ldo = @intCast(s.w.n), .lim = lim, }, 4); - bind(e, 5, .{ s.out, io.ids, u.w, u.s, u.b, s.x2, s.sh.w, s.sh.s, s.sh.b, s.out2 }); + if (by_expert) { + const q = u.?; + bind(e, 5, .{ s.out, q.ids, uw.w, uw.s, uw.b, s.x2, s.sh.w, s.sh.s, s.sh.b, s.out2, q.members, q.count }); + e.dispatchGroups(mtl.Size.of((s.w.n + 3) / 4, slots + 1, 1), mtl.Size.of(32 * rows, 1, 1)); + continue; + } + bind(e, 5, .{ s.out, io.ids, uw.w, uw.s, uw.b, s.x2, s.sh.w, s.sh.s, s.sh.b, s.out2 }); e.dispatchGroups(mtl.Size.of((s.w.n + 7) / 8, slots + rows, 1), mtl.Size.of(64, 1, 1)); } } @@ -499,7 +521,7 @@ test "a failed compile releases every pipeline built before it; a load counts ea defer device.deinit(); var made: Made = .{}; try std.testing.expectError(error.KernelCompile, build(gpa, device, "", &made)); // after the row kernels - try std.testing.expectEqual(@as(usize, nw * 8 + 4), made.released); + try std.testing.expectEqual(@as(usize, nw * 10 + 4), made.released); try std.testing.expectEqual(@as(usize, 0), made.n); var all: Made = .{}; var p = try build(gpa, device, comptime kernels.generatedSource("kda_rows"), &all); diff --git a/zig/src/families/h3/checkpoint.zig b/zig/src/families/h3/checkpoint.zig index db1689c75ec..ebbf3f1164d 100644 --- a/zig/src/families/h3/checkpoint.zig +++ b/zig/src/families/h3/checkpoint.zig @@ -1,7 +1,7 @@ //! One safetensors file mapped read-only, its tensors found by name in core's index of the header. const std = @import("std"); const report = @import("report.zig"); -const st = @import("safetensors"); +const st = @import("core").safetensors; const c = struct { extern "c" fn open(path: [*:0]const u8, flags: c_int, ...) c_int; diff --git a/zig/src/families/h3/geometry.zig b/zig/src/families/h3/geometry.zig index ae8c66f276e..ee1c4fb299c 100644 --- a/zig/src/families/h3/geometry.zig +++ b/zig/src/families/h3/geometry.zig @@ -1,6 +1,6 @@ //! H3's host admission, before shader compilation, buffer allocation or indexing caller data. const std = @import("std"); -const st = @import("safetensors"); +const st = @import("core").safetensors; pub const scalar_max = std.math.maxInt(i32); pub const tile_rows = 64; diff --git a/zig/src/families/h3/geometry_test.zig b/zig/src/families/h3/geometry_test.zig index 8343ba9f5fd..fceb35447b4 100644 --- a/zig/src/families/h3/geometry_test.zig +++ b/zig/src/families/h3/geometry_test.zig @@ -1,6 +1,6 @@ //! Serialized H3 case fixtures run through the reader used by Model.load, without a Metal device. const std = @import("std"); -const st = @import("safetensors"); +const st = @import("core").safetensors; const g = @import("geometry.zig"); const schedule = @import("schedule.zig"); const testing = std.testing; diff --git a/zig/src/families/h3/h3.zig b/zig/src/families/h3/h3.zig index b768d978923..729bfe5aaa6 100644 --- a/zig/src/families/h3/h3.zig +++ b/zig/src/families/h3/h3.zig @@ -1,7 +1,7 @@ //! MiniMax H3 / FastH3's transformer on Metal in the checkpoint's bf16: one denoising forward over the packed rows. const std = @import("std"); const mtl = @import("metal"); -const st = @import("safetensors"); +const st = @import("core").safetensors; const tensors = @import("tensors.zig"); const kernels = @import("h3_kernels"); const block = @import("block.zig"); @@ -137,16 +137,16 @@ pub const Model = struct { } /// `checkpoint_dir`: the FastH3 transformer folder of `shards` files. `case`: tools/zig/h3_case.py's output. - pub fn load(gpa: std.mem.Allocator, checkpoint_dir: []const u8, shards: usize, case: *Tensors, options: Options) !*Model { - return bind(gpa, try open(gpa, checkpoint_dir, shards), case, options); + pub fn load(gpa: std.mem.Allocator, io: std.Io, checkpoint_dir: []const u8, shards: usize, case: *Tensors, options: Options) !*Model { + return bind(gpa, try open(gpa, io, checkpoint_dir, shards), case, options); } /// The checkpoint's shards mapped and read into the page cache: the weights every `bind` reads in place. - pub fn open(gpa: std.mem.Allocator, checkpoint_dir: []const u8, shards: usize) !Checkpoint { + pub fn open(gpa: std.mem.Allocator, io: std.Io, checkpoint_dir: []const u8, shards: usize) !Checkpoint { const device = try mtl.Device.init(); if (!@import("source.zig").available(device)) return error.NeedsTensorUnits; const ck = try Checkpoint.open(gpa, device, checkpoint_dir, shards); - try ck.readAhead(gpa); + try ck.readAhead(gpa, io); return ck; } diff --git a/zig/src/families/h3/image_decoder.zig b/zig/src/families/h3/image_decoder.zig index 5706bba6ada..c3bc38b1ebc 100644 --- a/zig/src/families/h3/image_decoder.zig +++ b/zig/src/families/h3/image_decoder.zig @@ -1,6 +1,6 @@ //! MiniMax-H3-Image's image decoder on the host: the tensors it reads, a tile's sequence and rotary table, unpatchify. const std = @import("std"); -const st = @import("safetensors"); +const st = @import("core").safetensors; const rounding = @import("bf16_round"); const vae = @import("picture_vae.zig"); const geometry = @import("geometry.zig"); diff --git a/zig/src/families/h3/image_decoder_metal.zig b/zig/src/families/h3/image_decoder_metal.zig index 40071080c9b..0f78a35807a 100644 --- a/zig/src/families/h3/image_decoder_metal.zig +++ b/zig/src/families/h3/image_decoder_metal.zig @@ -104,7 +104,7 @@ pub const Decoder = struct { } /// The decoder's tensors of `vae/diffusion_pytorch_model.safetensors`, checked, each F32 value rounded to bf16. - pub fn load(d: *Decoder, path: [*:0]const u8) !void { + pub fn load(d: *Decoder, io: std.Io, path: [*:0]const u8) !void { const map = try mtl.MappedFile.open(path); defer map.deinit(); var arena = std.heap.ArenaAllocator.init(d.gpa); @@ -116,7 +116,7 @@ pub const Decoder = struct { const e = w.header.get(it.name).?; s.* = .{ .path = path, .lo = w.start + e.begin, .hi = w.start + e.end }; } - _ = try read_ahead.read(spans); + _ = try read_ahead.read(a, io, spans); host.read(w, d.params()); } diff --git a/zig/src/families/h3/image_decoder_test.zig b/zig/src/families/h3/image_decoder_test.zig index f2604c52141..cf88073d958 100644 --- a/zig/src/families/h3/image_decoder_test.zig +++ b/zig/src/families/h3/image_decoder_test.zig @@ -1,6 +1,6 @@ //! MiniMax-H3-Image's image decoder host rules (image_decoder.zig): ids, angles, the suffix, unpatchify, tensors. const std = @import("std"); -const st = @import("safetensors"); +const st = @import("core").safetensors; const rounding = @import("bf16_round"); const h = @import("image_decoder.zig"); const vae = @import("picture_vae.zig"); diff --git a/zig/src/families/h3/image_encoder.zig b/zig/src/families/h3/image_encoder.zig index 658a14cd545..252194f571c 100644 --- a/zig/src/families/h3/image_encoder.zig +++ b/zig/src/families/h3/image_encoder.zig @@ -1,7 +1,7 @@ //! MiniMax-H3-Image's edit encoder on Metal in fp32: a reference's tiles through the VAE's CNN to blended moments. const std = @import("std"); const mtl = @import("metal"); -const st = @import("safetensors"); +const st = @import("core").safetensors; const kernels = @import("h3_image_encoder_kernels"); pub const reference = @import("picture_reference.zig"); pub const vae = @import("picture_vae.zig"); diff --git a/zig/src/families/h3/modulation_shape.zig b/zig/src/families/h3/modulation_shape.zig index 1fbb0b12eaf..b7a6d323034 100644 --- a/zig/src/families/h3/modulation_shape.zig +++ b/zig/src/families/h3/modulation_shape.zig @@ -1,6 +1,6 @@ //! H3 modulation dimensions checked on the host before division, indexing or GPU allocation. const std = @import("std"); -const st = @import("safetensors"); +const st = @import("core").safetensors; const geometry = @import("geometry.zig"); pub fn linear(x: usize, w: usize, n: usize, rows: usize, k: usize) !usize { diff --git a/zig/src/families/h3/picture_prompt_test.zig b/zig/src/families/h3/picture_prompt_test.zig index 62e4f459cb3..68fd68341e5 100644 --- a/zig/src/families/h3/picture_prompt_test.zig +++ b/zig/src/families/h3/picture_prompt_test.zig @@ -4,10 +4,6 @@ const pp = @import("picture_prompt.zig"); const picture = @import("picture"); const testing = std.testing; -test { - _ = @import("read_ahead.zig"); -} - const marks: pp.Marks = .{ .start = 151652, .image = 151655, .end = 151653 }; /// One id per segment: the hash of the whole text, so a segment merged with its neighbour would show. diff --git a/zig/src/families/h3/picture_reference.zig b/zig/src/families/h3/picture_reference.zig index bbedf23c4a0..c22a32a36ca 100644 --- a/zig/src/families/h3/picture_reference.zig +++ b/zig/src/families/h3/picture_reference.zig @@ -1,6 +1,6 @@ //! MiniMax-H3-Image's edit references on the host: sizes, the encoder's input and layers, clean and anchor rows. const std = @import("std"); -const st = @import("safetensors"); +const st = @import("core").safetensors; const geometry = @import("geometry.zig"); const picture = @import("picture.zig"); const vae = @import("picture_vae.zig"); diff --git a/zig/src/families/h3/picture_reference_test.zig b/zig/src/families/h3/picture_reference_test.zig index 32639f94d1d..9a4810a9b7b 100644 --- a/zig/src/families/h3/picture_reference_test.zig +++ b/zig/src/families/h3/picture_reference_test.zig @@ -1,6 +1,6 @@ //! MiniMax-H3-Image's edit reference rules (picture_reference.zig): sizes, crops, grids, layers, weights, rows. const std = @import("std"); -const st = @import("safetensors"); +const st = @import("core").safetensors; const r = @import("picture_reference.zig"); const vae = @import("picture_vae.zig"); const testing = std.testing; diff --git a/zig/src/families/h3/prompt_weights.zig b/zig/src/families/h3/prompt_weights.zig index 537f41be575..da344e5a659 100644 --- a/zig/src/families/h3/prompt_weights.zig +++ b/zig/src/families/h3/prompt_weights.zig @@ -73,7 +73,7 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, device: mtl.Device, dir: []const var it = out[made - 1].names.iterator(); while (it.next()) |e| if (wanted.accepts(e.key_ptr.*)) try spans.append(arena, out[made - 1].span(e.value_ptr.*)); } - _ = try read_ahead.read(spans.items); + _ = try read_ahead.read(arena, io, spans.items); return .{ .files = out }; } diff --git a/zig/src/families/h3/read_ahead.zig b/zig/src/families/h3/read_ahead.zig index 5cff8e57e2c..d1fdc71e112 100644 --- a/zig/src/families/h3/read_ahead.zig +++ b/zig/src/families/h3/read_ahead.zig @@ -1,93 +1,53 @@ -//! Weight bytes read into the page cache before the GPU or a loader touches their mapping. +//! Weight bytes read into the page cache before the GPU or a loader touches their mapping, through core's checked reader. const std = @import("std"); - -/// A byte range of one file. -pub const Span = struct { path: [*:0]const u8, lo: usize, hi: usize }; - -/// The bytes of one pread. -const piece = 8 << 20; -/// Readers at once, the calling thread among them. -const readers = 16; - -const Work = struct { - spans: []const Span, - /// The next piece to read. - next: std.atomic.Value(usize) = .init(0), - read: std.atomic.Value(usize) = .init(0), - failed: std.atomic.Value(bool) = .init(false), - - /// Piece `n`, counted across every span in order, or null past the last. - fn take(w: *Work, n: usize) ?Span { - var left = n; - for (w.spans) |s| { - const count = std.math.divCeil(usize, s.hi - s.lo, piece) catch unreachable; - if (left < count) { - const lo = s.lo + left * piece; - return .{ .path = s.path, .lo = lo, .hi = @min(lo + piece, s.hi) }; - } - left -= count; +const core = @import("core"); +const ahead = core.checkpoint_read_ahead; + +/// A byte range of one file; its path outlives the read. +pub const Span = ahead.Span; + +/// Every span's bytes, cut into `chunk` pieces, with `TF_LOAD_PREFETCH` readers; missing or short files fail. +pub fn read(gpa: std.mem.Allocator, io: std.Io, spans: []const Span) !u64 { + const readers = try ahead.readers(); + if (readers == 0) return 0; + var pieces: std.ArrayList(Span) = .empty; + errdefer pieces.deinit(gpa); + for (spans) |s| { + var lo = s.lo; + while (lo < s.hi) { + const hi = lo + @min(ahead.chunk, s.hi - lo); + try pieces.append(gpa, .{ .path = s.path, .lo = lo, .hi = hi }); + lo = hi; } - return null; } - - fn run(w: *Work) void { - const buf = std.heap.page_allocator.alloc(u8, piece) catch return w.failed.store(true, .monotonic); - defer std.heap.page_allocator.free(buf); - var path: [*:0]const u8 = ""; - var fd: std.c.fd_t = -1; - defer if (fd >= 0) close(fd); - while (!w.failed.load(.monotonic)) { - const s = w.take(w.next.fetchAdd(1, .monotonic)) orelse return; - if (s.path != path) { - if (fd >= 0) close(fd); - fd = std.c.open(s.path, .{ .ACCMODE = .RDONLY, .CLOEXEC = true }); - if (fd < 0) return w.failed.store(true, .monotonic); - path = s.path; - } - var at = s.lo; - while (at < s.hi) { - const n = std.c.pread(fd, buf.ptr, s.hi - at, @intCast(at)); - if (n <= 0) return w.failed.store(true, .monotonic); - at += @intCast(n); - } - _ = w.read.fetchAdd(s.hi - s.lo, .monotonic); - } - } -}; - -fn close(fd: std.c.fd_t) void { - _ = std.c.close(fd); + var reader = try ahead.start(gpa, io, try pieces.toOwnedSlice(gpa), readers); + defer reader.deinit(); + return reader.check(); } -/// Read every span with up to 16 readers; missing or short files fail. -pub fn read(spans: []const Span) !usize { - if (spans.len == 0) return 0; - var w: Work = .{ .spans = spans }; - var threads: [readers - 1]?std.Thread = @splat(null); - for (&threads) |*t| t.* = std.Thread.spawn(.{}, Work.run, .{&w}) catch null; - w.run(); - for (threads) |t| if (t) |thread| thread.join(); - if (w.failed.load(.monotonic)) return error.H3ReadAheadFailed; - return w.read.load(.monotonic); -} - -test "h3 read ahead: every span's bytes once across pieces and files, a short or missing file refused" { +test "h3 read ahead: every span's bytes across pieces and files, short or missing files refused, disabled reads skipped" { const gpa = std.testing.allocator; + const io = std.testing.io; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); - const big = try gpa.alloc(u8, piece + 5); + const big = try gpa.alloc(u8, ahead.chunk + 5); defer gpa.free(big); @memset(big, 1); - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "a", .data = big }); - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "b", .data = big[0..100] }); + try tmp.dir.writeFile(io, .{ .sub_path = "a", .data = big }); + try tmp.dir.writeFile(io, .{ .sub_path = "b", .data = big[0..100] }); const a = try std.fmt.allocPrintSentinel(gpa, ".zig-cache/tmp/{s}/a", .{tmp.sub_path}, 0); defer gpa.free(a); const b = try std.fmt.allocPrintSentinel(gpa, ".zig-cache/tmp/{s}/b", .{tmp.sub_path}, 0); defer gpa.free(b); + if (try ahead.readers() == 0) { + try std.testing.expectEqual(0, try read(gpa, io, &.{.{ .path = b, .lo = 0, .hi = 101 }})); + return; + } // a's span crosses a piece boundary: two pieces; b's is one; an empty span reads nothing - const spans = [_]Span{ .{ .path = a, .lo = 3, .hi = piece + 5 }, .{ .path = b, .lo = 0, .hi = 100 }, .{ .path = b, .lo = 7, .hi = 7 } }; - try std.testing.expectEqual(@as(usize, piece + 2 + 100), try read(&spans)); - try std.testing.expectEqual(@as(usize, 0), try read(&.{})); - try std.testing.expectError(error.H3ReadAheadFailed, read(&.{.{ .path = b, .lo = 0, .hi = 101 }})); - try std.testing.expectError(error.H3ReadAheadFailed, read(&.{.{ .path = ".zig-cache/tmp/none", .lo = 0, .hi = 1 }})); + const spans = [_]Span{ .{ .path = a, .lo = 3, .hi = ahead.chunk + 5 }, .{ .path = b, .lo = 0, .hi = 100 }, .{ .path = b, .lo = 7, .hi = 7 } }; + try std.testing.expectEqual(ahead.chunk + 2 + 100, try read(gpa, io, &spans)); + try std.testing.expectEqual(0, try read(gpa, io, &.{})); + try std.testing.expectError(error.LoadPrefetchRead, read(gpa, io, &.{.{ .path = b, .lo = 0, .hi = 101 }})); + try tmp.dir.deleteFile(io, "b"); + try std.testing.expectError(error.LoadPrefetchRead, read(gpa, io, &.{.{ .path = b, .lo = 0, .hi = 1 }})); } diff --git a/zig/src/families/h3/schedule_geometry_test.zig b/zig/src/families/h3/schedule_geometry_test.zig index 6629cf4ec41..93b785196e0 100644 --- a/zig/src/families/h3/schedule_geometry_test.zig +++ b/zig/src/families/h3/schedule_geometry_test.zig @@ -2,7 +2,7 @@ const std = @import("std"); const s = @import("schedule.zig"); const m = @import("modulation_shape.zig"); -const st = @import("safetensors"); +const st = @import("core").safetensors; const t = std.testing; fn entry(shape: []const usize) st.Entry { diff --git a/zig/src/families/h3/tensors.zig b/zig/src/families/h3/tensors.zig index fa157f33b1e..ec4d2be7d86 100644 --- a/zig/src/families/h3/tensors.zig +++ b/zig/src/families/h3/tensors.zig @@ -1,7 +1,7 @@ //! Safetensors files mapped once and handed to Metal whole, and a checkpoint's shards searched by tensor name. const std = @import("std"); const mtl = @import("metal"); -const st = @import("safetensors"); +const st = @import("core").safetensors; const read_ahead = @import("read_ahead.zig"); /// A safetensors file mapped once and handed to Metal whole; a tensor is an offset into that one buffer. @@ -101,11 +101,11 @@ pub const Checkpoint = struct { } /// Every shard's whole file into the page cache, ahead of the first forward's faults. - pub fn readAhead(self: *const Checkpoint, gpa: std.mem.Allocator) !void { + pub fn readAhead(self: *const Checkpoint, gpa: std.mem.Allocator, io: std.Io) !void { const whole = try gpa.alloc(read_ahead.Span, self.shards.len); defer gpa.free(whole); for (whole, self.shards) |*s, *shard| s.* = .{ .path = shard.path, .lo = 0, .hi = shard.map.size }; - _ = try read_ahead.read(whole); + _ = try read_ahead.read(gpa, io, whole); } pub fn entry(self: *const Checkpoint, name: []const u8) ?st.Entry { diff --git a/zig/src/families/kolibri1/forward.zig b/zig/src/families/kolibri1/forward.zig index 28b504135cc..49674391867 100644 --- a/zig/src/families/kolibri1/forward.zig +++ b/zig/src/families/kolibri1/forward.zig @@ -12,6 +12,11 @@ const grouped = cuda.grouped; const experts = cuda.experts; const TreeAttention = cuda.tree_attention.TreeAttention; +/// bf16 elements from `origin` to `at`, signed: a cache made after `origin` (attach's rings) may sit below it. +pub fn elementsFrom(origin: u64, at: u64) i64 { + return @divExact(@as(i64, @bitCast(at -% origin)), 2); +} + /// Prompt rows a forward takes: the chunk grid, from position 0. pub const prompt_rows = 8192; /// Decode rows a forward takes over every stream's window. @@ -405,8 +410,8 @@ pub const Model = struct { defer m.gpa.free(offs); for (0..c.layers) |i| for (chains, 0..) |ch, j| { const at = if (m.paged and c.full[i]) 0 else ch.slot * per; // paged: the layer's region, the table's rows - offs[(i * chains.len + j) * 2] = @intCast((m.k[i] + at - m.origin) / 2); - offs[(i * chains.len + j) * 2 + 1] = @intCast((m.v[i] + at - m.origin) / 2); + offs[(i * chains.len + j) * 2] = elementsFrom(m.origin, m.k[i] + at); + offs[(i * chains.len + j) * 2 + 1] = elementsFrom(m.origin, m.v[i] + at); }; try m.upload(s, dst, std.mem.sliceAsBytes(offs)); } @@ -590,3 +595,6 @@ test "a page's bytes: the pool's layout and the kernels' stride agree" { try std.testing.expectEqual(m.pageBytes(), m.layout().pageBytes()); try std.testing.expectEqual(@as(u32, 10), m.layout().group().layers); } +test { + _ = @import("forward_offsets_test.zig"); +} diff --git a/zig/src/families/kolibri1/forward_offsets_test.zig b/zig/src/families/kolibri1/forward_offsets_test.zig new file mode 100644 index 00000000000..8eead33babf --- /dev/null +++ b/zig/src/families/kolibri1/forward_offsets_test.zig @@ -0,0 +1,8 @@ +const std = @import("std"); +const fwd = @import("forward.zig"); + +test "cache offsets from the tree origin are signed: a ring made below the origin counts back" { + try std.testing.expectEqual(@as(i64, 128), fwd.elementsFrom(0x1000, 0x1100)); + try std.testing.expectEqual(@as(i64, -128), fwd.elementsFrom(0x1100, 0x1000)); + try std.testing.expectEqual(@as(i64, 0), fwd.elementsFrom(0x7f00_0000_0000, 0x7f00_0000_0000)); +} diff --git a/zig/src/families/nemotron/hip/prompt_test.zig b/zig/src/families/nemotron/hip/prompt_test.zig index cc24fabf74c..2606e9b3cc3 100644 --- a/zig/src/families/nemotron/hip/prompt_test.zig +++ b/zig/src/families/nemotron/hip/prompt_test.zig @@ -247,3 +247,20 @@ test "Nemotron layer traces keep non-cancel failures as BadShape" { var ctx: u8 = 0; try T.expectError(error.BadShape, forward.traceLayer(.{ .ctx = &ctx, .layer = Fail.layer }, 0, undefined, 512)); } + +test "chunk cuts leaving 1, 8, 15, 16, 17 or 65 trailing rows partition every token in order" { + const prompt_len: usize = 193; + for ([_]usize{ 1, 8, 15, 16, 17, 65 }) |tail| { + const cut = prompt_len - tail; + var at: usize = 0; + var last_rows: usize = 0; + while (at < prompt_len) { + const n = @min(cut, prompt_len - at); + try T.expect(n > 0); + last_rows = n; + at += n; + } + try T.expectEqual(prompt_len, at); + try T.expectEqual(tail, last_rows); + } +} diff --git a/zig/src/families/nemotron/kernels.zig b/zig/src/families/nemotron/kernels.zig index 33f9b06f536..bd7294f979e 100644 --- a/zig/src/families/nemotron/kernels.zig +++ b/zig/src/families/nemotron/kernels.zig @@ -88,7 +88,7 @@ pub fn keyOf(i: usize) []const u8 { pub fn sourceHash() u64 { var h = std.hash.Wyhash.init(0x6e); inline for (sources.nemotron.all) |k| h.update(k.source); - for ([_][]const u8{ sources.nemotron_glue, sources.nemotron_experts, sources.nemotron_tree, sources.nemotron_round, sources.nemotron_head, sources.nemotron_sample, sources.nax, sources.core_row_projection, sources.packed_metallib }) |s| h.update(s); + for ([_][]const u8{ sources.nemotron_glue, sources.nemotron_experts, sources.nemotron_tree, sources.nemotron_round, sources.nemotron_head, sources.nemotron_sample, sources.nax, sources.core_row_projection, sources.core_row_projection_legacy, sources.packed_metallib }) |s| h.update(s); for (sources.prefill) |f| h.update(f.text); return h.final(); } diff --git a/zig/src/families/qwen3_5/cuda.zig b/zig/src/families/qwen3_5/cuda.zig index 6c74c7e2616..2b6b8c30e04 100644 --- a/zig/src/families/qwen3_5/cuda.zig +++ b/zig/src/families/qwen3_5/cuda.zig @@ -54,6 +54,7 @@ test { _ = @import("cuda_prefix_fault_test.zig"); _ = @import("cuda_pend_test.zig"); _ = @import("cuda_reuse_pages_test.zig"); + _ = @import("cuda_warm_turns_test.zig"); } pub const slide = @import("cuda_slide.zig"); diff --git a/zig/src/families/qwen3_5/cuda_admit_test.zig b/zig/src/families/qwen3_5/cuda_admit_test.zig index 8fff7322d70..f0193616a40 100644 --- a/zig/src/families/qwen3_5/cuda_admit_test.zig +++ b/zig/src/families/qwen3_5/cuda_admit_test.zig @@ -112,3 +112,11 @@ pub fn refusals() !void { try t.expectError(error.QwenShareNeedsPages, refused(false, null, "16")); try t.expectError(error.QwenShareNeedsPages, refused(false, "100", "16")); } + +test "Qwen share faults: --parallel N admits N streams at once with every stream on pages" { + try admits(native.Lanes); +} + +test "Qwen pages default: --parallel a cap with TF_QWEN_KV_PAGES set, a request waits for pages; unset, a window each" { + try caps(native.Lanes); +} diff --git a/zig/src/families/qwen3_5/cuda_cache.zig b/zig/src/families/qwen3_5/cuda_cache.zig index 8f43d5bdd42..7c3c98e1762 100644 --- a/zig/src/families/qwen3_5/cuda_cache.zig +++ b/zig/src/families/qwen3_5/cuda_cache.zig @@ -40,6 +40,17 @@ pub fn pendBytes(g: anytype) usize { pub const Seg = extern struct { rec: u64, conv: u64, kv: u64, tap: u64, log: u64, before: u64, cap: c_int, len: c_int, row0: c_int, rows: c_int, tap_rows: c_int, taps: c_int, delta: c_int, pt: u64 = 0, ps: u64 = 0, ptok: c_int = 0, pn: c_int = 0, plog: u64 = 0 }; pub const Path = extern struct { n: c_int, rows: [engine.most_window]c_int }; +/// Whether two of the forward's parts' paged caches start on one KV page (the shared store's prefix): the join kernels. +pub fn anyShares(parts: anytype) bool { + for (parts, 0..) |p, i| if (firstPage(p.cache)) |f| for (parts[0..i]) |q| if (firstPage(q.cache)) |g| if (f == g) return true; + return false; +} + +fn firstPage(c: *const Cache) ?u32 { + const p = c.paged orelse return null; + return if (p.ids.len > 0) p.ids[0] else null; +} + /// A cache's keys and values as pages (qwen35.cuh kv_row): page i of the stream's positions at `base` + ids[i] pages. pub const Paged = struct { /// Where page 0 of the arena starts: the core pool's, or the cache's own buffer under TF_QWEN_KV_PAGE_TEST. @@ -416,3 +427,15 @@ test "KV page dimensions: diagnostic admission includes its padded rows and devi try std.testing.expectError(error.BadQwenPageTest, cacheRows(2147483647, 48)); try std.testing.expectError(error.BadQwenPageTest, cacheRows(std.math.maxInt(usize), 48)); } + +test "Qwen share faults: a forward joins only when two parts' paged caches start on one page" { + var ids = [_][2]u32{ .{ 4, 5 }, .{ 4, 9 }, .{ 7, 5 } }; + var cs: [4]Cache = undefined; + for (cs[0..3], &ids) |*c, *i| c.paged = .{ .base = 0, .table = undefined, .ids = i, .tokens = 16, .own_ids = false }; + cs[3].paged = null; + const P = struct { cache: *const Cache }; + const all = [_]P{ .{ .cache = &cs[0] }, .{ .cache = &cs[1] }, .{ .cache = &cs[2] }, .{ .cache = &cs[3] } }; + try std.testing.expect(anyShares(all[0..]) and anyShares(all[0..2])); + // a later page in common, no table, or the first page's holder alone in the forward: no join + try std.testing.expect(!anyShares(all[1..]) and !anyShares(all[0..1]) and !anyShares(&[_]P{ all[0], all[2], all[3] })); +} diff --git a/zig/src/families/qwen3_5/cuda_engine.zig b/zig/src/families/qwen3_5/cuda_engine.zig index 8d05e284540..ba4702143eb 100644 --- a/zig/src/families/qwen3_5/cuda_engine.zig +++ b/zig/src/families/qwen3_5/cuda_engine.zig @@ -159,7 +159,7 @@ pub const Engine = struct { /// presence and frequency penalties the next forward takes from its kept rows' logits (staged by the caller). penalties: @import("cuda_penalties.zig").Rows = .{}, /// The captured forwards by shape (`Shape.key`): the launches from the embedding to the head. - graphs: std.AutoHashMapUnmanaged(u32, cuda.graph.Exec) = .empty, + graphs: std.AutoHashMapUnmanaged(u64, cuda.graph.Exec) = .empty, /// A drafter's tapped layers (`setTaps`): each row's residual after them lands in its stream's tap ring. taps: [8]u32 = undefined, n_taps: usize = 0, @@ -265,14 +265,12 @@ pub const Engine = struct { e.plan = try cuda.grouped.Router.resolve(e.mods[10]); e.moe = try cuda.moe.Fns.resolve(e.mods[13]); inline for (@typeInfo(Fns).@"struct".field_names) |name| @field(e.fns, name) = try e.mods[4].function("tf_q35_" ++ name); - try e.fns.attn_partial.allowDynamicShared(@import("cuda_forward.zig").attn_tiles); // bf16 tiles' two buffers - try e.fns.attn_rows.allowDynamicShared(@import("cuda_forward.zig").attn_tiles); - try e.fns.attn_partial_whole.allowDynamicShared(@import("cuda_forward.zig").attn_tiles); - try e.fns.attn_rows_whole.allowDynamicShared(@import("cuda_forward.zig").attn_tiles); + // bf16 tiles' two buffers + for ([_]cuda.Function{ e.fns.attn_partial, e.fns.attn_rows, e.fns.attn_rows_join, e.fns.attn_partial_whole, e.fns.attn_rows_whole }) |f| try f.allowDynamicShared(@import("cuda_forward.zig").attn_tiles); inline for (@typeInfo(Keeps).@"struct".field_names) |name| @field(e.keeps, name) = try e.mods[6].function("tf_q35k_" ++ name); e.prompt_attn = try @import("cuda_prompt.zig").resolve(e.mods[16], e.mods[17]); try e.int8.resolve(e.mods[18]); - e.fp8 = .{ .rope = try e.mods[9].function("tf_q35_rope8"), .attn_partial = try e.mods[9].function("tf_q35_attn_partial8"), .attn_rows = try e.mods[9].function("tf_q35_attn_rows8"), .attn_partial8_whole = try e.mods[9].function("tf_q35_attn_partial8_whole"), .attn_rows8_whole = try e.mods[9].function("tf_q35_attn_rows8_whole"), .compact = try e.mods[9].function("tf_q35k_compact8") }; + e.fp8 = .{ .rope = try e.mods[9].function("tf_q35_rope8"), .attn_partial = try e.mods[9].function("tf_q35_attn_partial8"), .attn_rows = try e.mods[9].function("tf_q35_attn_rows8"), .attn_rows_join = try e.mods[9].function("tf_q35_attn_rows8_join"), .attn_partial8_whole = try e.mods[9].function("tf_q35_attn_partial8_whole"), .attn_rows8_whole = try e.mods[9].function("tf_q35_attn_rows8_whole"), .compact = try e.mods[9].function("tf_q35k_compact8") }; e.mo = if (g.kinds.modelopt) try modelopt.Kernels.load(d, @intCast(10 * major + minor), sms, g.moe()) else null; errdefer if (e.mo) |*m| m.unload(); e.layers = try gpa.alloc(Layer, g.layers); @@ -490,8 +488,7 @@ pub const Engine = struct { } // words 0 and 1 are reserved (each row's attention chunks follow its own keys: qwen35.cu's chunk_keys) const params = std.mem.bytesAsSlice(c_int, st[params_at..][0..32]); - params[0] = 0; - params[1] = 0; + params[0..2].* = .{ 0, 0 }; params[2] = @intCast(total); params[3] = @intCast(parts.len); params[4] = @intFromBool(record); @@ -514,6 +511,7 @@ pub const Engine = struct { shape.hidden = keep == .hidden; shape.rows = keep == .rows; shape.paged = @import("cuda_attention.zig").hasPages(segs); + shape.join = shape.paged and caches.anyShares(parts); shape.mt2 = @import("cuda_shapes.zig").useMt2(e.mt2.enabled, e.kv8, !record, total, parts.len, parts[0].cache.len); if (e.learning != null or e.pockets.any()) { shape.total = @intCast(total); diff --git a/zig/src/families/qwen3_5/cuda_engine_test.zig b/zig/src/families/qwen3_5/cuda_engine_test.zig index 19d6c285f32..eb532a4c69b 100644 --- a/zig/src/families/qwen3_5/cuda_engine_test.zig +++ b/zig/src/families/qwen3_5/cuda_engine_test.zig @@ -3,7 +3,7 @@ const std = @import("std"); const Shape = @import("cuda_shapes.zig").Shape; test "dense read cost: hidden and slot variants have distinct graph keys" { - var seen: [32]u32 = undefined; + var seen: [32]u64 = undefined; var n: usize = 0; for ([_]u8{ 1, 2, 4, 8, 16 }) |slots| { for ([_]bool{ false, true }) |hidden| { diff --git a/zig/src/families/qwen3_5/cuda_forward.zig b/zig/src/families/qwen3_5/cuda_forward.zig index 5e34e6f8cc8..21742b846a0 100644 --- a/zig/src/families/qwen3_5/cuda_forward.zig +++ b/zig/src/families/qwen3_5/cuda_forward.zig @@ -92,11 +92,11 @@ pub fn body(e: *E.Engine, shape: anytype) !void { const rows_args = .{ geo, e.qn, t_segs, t_rows, t_anc, @as(c_int, ai), t_params, @as(f32, 1.0 / 16.0), @as(c_int, @intCast(total)), e.pm, e.pl, e.po }; if (e.kv8) { try launch(e, if (shape.paged) e.fp8.attn_partial else e.fp8.attn_partial8_whole, sig.attn_partial8, .{ total, max_chunks, g.kv_heads }, .{ 128, 1, 1 }, args); - const rows_fn = if (shape.mt2) (if (shape.paged) e.mt2.paged else e.mt2.whole) else (if (shape.paged) e.fp8.attn_rows else e.fp8.attn_rows8_whole); + const rows_fn = if (shape.mt2) (if (shape.paged) e.mt2.paged else e.mt2.whole) else (if (shape.join) e.fp8.attn_rows_join else if (shape.paged) e.fp8.attn_rows else e.fp8.attn_rows8_whole); try launch(e, rows_fn, sig.attn_rows8, .{ groups, max_chunks, g.kv_heads }, .{ if (shape.mt2) @as(usize, 128) else 256, 1, 1 }, rows_args); } else { try shared(e, if (shape.paged) e.fns.attn_partial else e.fns.attn_partial_whole, sig.attn_partial, .{ total, max_chunks, g.kv_heads }, 128, args); - try shared(e, if (shape.paged) e.fns.attn_rows else e.fns.attn_rows_whole, sig.attn_rows, .{ groups, max_chunks, g.kv_heads }, 256, rows_args); + try shared(e, if (shape.join) e.fns.attn_rows_join else if (shape.paged) e.fns.attn_rows else e.fns.attn_rows_whole, sig.attn_rows, .{ groups, max_chunks, g.kv_heads }, 256, rows_args); } try launch(e, e.fns.attn_merge, sig.attn_merge, .{ g.q_heads, total, 1 }, .{ 32, 1, 1 }, .{ geo, e.pm, e.pl, e.po, t_segs, t_rows, t_anc, t_params, e.y }); } diff --git a/zig/src/families/qwen3_5/cuda_layers.zig b/zig/src/families/qwen3_5/cuda_layers.zig index e6cf8e57231..58495475913 100644 --- a/zig/src/families/qwen3_5/cuda_layers.zig +++ b/zig/src/families/qwen3_5/cuda_layers.zig @@ -63,6 +63,7 @@ pub const Fns = struct { rope: cuda.Function, attn_partial: cuda.Function, attn_rows: cuda.Function, + attn_rows_join: cuda.Function, attn_partial_whole: cuda.Function, attn_rows_whole: cuda.Function, attn_merge: cuda.Function, @@ -79,4 +80,4 @@ pub const Fns = struct { pub const Keeps = struct { apply: cuda.Function, apply_pend: cuda.Function, conv: cuda.Function, compact: cuda.Function }; /// qwen35_kv8.cu's kernels: the cache writes, attention reads and keep's moves over e4m3 rows (--kv-cache fp8). -pub const Kv8 = struct { rope: cuda.Function, attn_partial: cuda.Function, attn_rows: cuda.Function, attn_partial8_whole: cuda.Function, attn_rows8_whole: cuda.Function, compact: cuda.Function }; +pub const Kv8 = struct { rope: cuda.Function, attn_partial: cuda.Function, attn_rows: cuda.Function, attn_rows_join: cuda.Function, attn_partial8_whole: cuda.Function, attn_rows8_whole: cuda.Function, compact: cuda.Function }; diff --git a/zig/src/families/qwen3_5/cuda_native.zig b/zig/src/families/qwen3_5/cuda_native.zig index 20ab6df6250..b8c0b84dd31 100644 --- a/zig/src/families/qwen3_5/cuda_native.zig +++ b/zig/src/families/qwen3_5/cuda_native.zig @@ -53,6 +53,10 @@ pub const snap_drop = reuse.drop; pub const snap_host = true; pub const snap_lookahead: u32 = 0; pub const snap_grid: u32 = E.max_rows; +/// Nanoseconds a reply's background warm pass waits for the next request before its first chunk. +pub const warm_quiet: u64 = 150 * std.time.ns_per_ms; +/// Keep a warm pass's end only where a resume can use it. +pub const warm_usable = true; /// --learn-conversations: the kept states' disk image, the probe their identity hashes, the facts they depend on. pub const kept_disk = @import("cuda_disk.zig"); @@ -579,14 +583,6 @@ pub const Lanes = struct { } }; -test "Qwen share faults: --parallel N admits N streams at once with every stream on pages" { - try @import("cuda_admit_test.zig").admits(Lanes); -} - -test "Qwen pages default: --parallel a cap with TF_QWEN_KV_PAGES set, a request waits for pages; unset, a window each" { - try @import("cuda_admit_test.zig").caps(Lanes); -} - test "Qwen stepped prefill: cancel between host iterations retains only the last completed cut" { try @import("cuda_prefill_test.zig").cancelled(Lanes, Lanes.backend); } @@ -596,5 +592,6 @@ test "Qwen stepped prefill: a cap (the flag's or fcfs's) cuts on the 128 grid in } test { + _ = @import("cuda_admit_test.zig"); _ = @import("cuda_mtp_budget.zig"); } diff --git a/zig/src/families/qwen3_5/cuda_native_moe.zig b/zig/src/families/qwen3_5/cuda_native_moe.zig index a67ab344581..7cda3556745 100644 --- a/zig/src/families/qwen3_5/cuda_native_moe.zig +++ b/zig/src/families/qwen3_5/cuda_native_moe.zig @@ -27,6 +27,9 @@ pub const snap_host = native.snap_host; pub const snap_lookahead = native.snap_lookahead; pub const snap_grid = native.snap_grid; pub const kept_disk = native.kept_disk; +/// The dense family's warm pass: its wait for the next request and the ends a resume can use. +pub const warm_quiet = native.warm_quiet; +pub const warm_usable = native.warm_usable; pub const request_starts = native.request_starts; pub const request_starts_switch = native.request_starts_switch; diff --git a/zig/src/families/qwen3_5/cuda_shapes.zig b/zig/src/families/qwen3_5/cuda_shapes.zig index 06893b55365..108de66427e 100644 --- a/zig/src/families/qwen3_5/cuda_shapes.zig +++ b/zig/src/families/qwen3_5/cuda_shapes.zig @@ -14,6 +14,7 @@ pub const Shape = struct { rows: bool = false, // a readout piece: every row through the last layer and the final norm, no head paged: bool = false, mt2: bool = false, + join: bool = false, // a paged forward whose streams share pages (Seg.share): the rows kernels' join variants /// A pipeline stage's piece of the forward (cuda_stage_forward.zig); one engine runs the whole. part: @import("cuda_stage_forward.zig").Part = .whole, @@ -24,9 +25,9 @@ pub const Shape = struct { return .{ .total = @intCast(if (record) bucket else rows), .nseg = @intCast(if (record) windows else segments), .record = record, .prompt = !record, .taps = taps, .slots = slots }; } - pub fn key(s: Shape) u32 { + pub fn key(s: Shape) u64 { // captured shapes only: a window bucket's rows fit the low byte - return @as(u32, @as(u8, @intCast(s.total))) | @as(u32, s.nseg) << 8 | @as(u32, @intFromBool(s.record)) << 16 | @as(u32, @intFromBool(s.prompt)) << 17 | @as(u32, @intFromBool(s.taps)) << 18 | @as(u32, s.slots) << 19 | @as(u32, @intFromBool(s.hidden)) << 27 | @as(u32, @intFromBool(s.paged)) << 28 | @as(u32, @intFromBool(s.mt2)) << 29 | @as(u32, @intFromBool(s.rows)) << 30 | @as(u32, @intFromBool(s.part == .head)) << 31; + return @as(u32, @as(u8, @intCast(s.total))) | @as(u32, s.nseg) << 8 | @as(u32, @intFromBool(s.record)) << 16 | @as(u32, @intFromBool(s.prompt)) << 17 | @as(u32, @intFromBool(s.taps)) << 18 | @as(u32, s.slots) << 19 | @as(u32, @intFromBool(s.hidden)) << 27 | @as(u32, @intFromBool(s.paged)) << 28 | @as(u32, @intFromBool(s.mt2)) << 29 | @as(u32, @intFromBool(s.rows)) << 30 | @as(u32, @intFromBool(s.part == .head)) << 31 | @as(u64, @intFromBool(s.join)) << 32; } }; @@ -40,7 +41,7 @@ test "MT2 dispatch keeps context boundaries and graph identities separate" { const before = Shape.init(16, 1, true, false, 1); var after = before; after.mt2 = true; - try std.testing.expectEqual(@as(u32, 1) << 29, before.key() ^ after.key()); + try std.testing.expectEqual(@as(u64, 1) << 29, before.key() ^ after.key()); for ([_]usize{ 8192, 32768, 65535 }) |n| try std.testing.expect(useMt2(true, true, false, 16, 1, n)); for ([_]usize{ 0, 8191, 65536, 131071 }) |n| try std.testing.expect(!useMt2(true, true, false, 16, 1, n)); for ([_]usize{ 0, 1, 512, 8191 }) |n| try std.testing.expect(!useMt2(true, true, false, 1, 1, n)); @@ -61,8 +62,8 @@ test "Qwen stage: the head piece keys its own graph, apart from the layers' and layers.part = .layers; var head = whole; head.part = .head; - try std.testing.expectEqual(@as(u32, 1) << 31, head.key() ^ whole.key()); - try std.testing.expectEqual(@as(u32, 1) << 31, head.key() ^ layers.key()); + try std.testing.expectEqual(@as(u64, 1) << 31, head.key() ^ whole.key()); + try std.testing.expectEqual(@as(u64, 1) << 31, head.key() ^ layers.key()); }; } @@ -79,18 +80,19 @@ test "one-row and 2-8-row windows take the smaller buckets" { test "every captured verify shape keys its own graph: a shape after another never replays the other's (#2138)" { const gpa = std.testing.allocator; - var keys: std.AutoHashMapUnmanaged(u32, Shape) = .empty; + var keys: std.AutoHashMapUnmanaged(u64, Shape) = .empty; defer keys.deinit(gpa); var distinct: std.AutoHashMapUnmanaged(Shape, void) = .empty; defer distinct.deinit(gpa); const variants = [_]u8{ 1, 2, 4, 8, 16 }; // every slot count a window's register peak gives for (1..Round.most_window + 1) |peak| try std.testing.expect(std.mem.indexOfScalar(u8, &variants, @intCast(Round.variant(peak))) != null); for (1..Round.most_verify + 1) |rows| for (1..@min(rows, Round.max_segs) + 1) |segments| for ([_]bool{ false, true }) |taps| { - for (variants) |slots| for (0..8) |bits| { + for (variants) |slots| for (0..16) |bits| { var s = Shape.init(rows, segments, true, taps, slots); s.hidden = bits & 1 != 0; s.paged = bits & 2 != 0; s.mt2 = bits & 4 != 0; + s.join = bits & 8 != 0; try distinct.put(gpa, s, {}); const got = try keys.getOrPut(gpa, s.key()); if (got.found_existing) try std.testing.expectEqual(got.value_ptr.*, s) else got.value_ptr.* = s; diff --git a/zig/src/families/qwen3_5/cuda_signatures.zig b/zig/src/families/qwen3_5/cuda_signatures.zig index 2e08d01ae4a..66087358d20 100644 --- a/zig/src/families/qwen3_5/cuda_signatures.zig +++ b/zig/src/families/qwen3_5/cuda_signatures.zig @@ -28,6 +28,10 @@ pub const attn_rows = Sig{ .name = "attn_rows", .handle = "e.fns.attn_rows", .sy /// The e4m3 decode attention over a long stream's rows. pub const attn_rows8 = Sig{ .name = "attn_rows8", .handle = "e.fp8.attn_rows", .symbol = "tf_q35_attn_rows8", .params = &.{ .geo, .ptr, .ptr, .ptr, .ptr, .i32, .ptr, .f32, .i32, .ptr, .ptr, .ptr } }; +/// The rows kernels for a forward whose streams share pages (Seg.share), the same ABI. +pub const attn_rows_join = Sig{ .name = "attn_rows_join", .handle = "e.fns.attn_rows_join", .symbol = "tf_q35_attn_rows_join", .params = attn_rows.params }; +pub const attn_rows8_join = Sig{ .name = "attn_rows8_join", .handle = "e.fp8.attn_rows_join", .symbol = "tf_q35_attn_rows8_join", .params = attn_rows8.params }; + /// Whole-window instances use the same ABI without consulting Seg.pt. pub const attn_partial_whole = Sig{ .name = "attn_partial_whole", .handle = "e.fns.attn_partial_whole", .symbol = "tf_q35_attn_partial_whole", .params = &.{ .geo, .ptr, .ptr, .ptr, .ptr, .i32, .ptr, .f32, .ptr, .ptr, .ptr } }; pub const attn_partial8_whole = Sig{ .name = "attn_partial8_whole", .handle = "e.fp8.attn_partial8_whole", .symbol = "tf_q35_attn_partial8_whole", .params = &.{ .geo, .ptr, .ptr, .ptr, .ptr, .i32, .ptr, .f32, .ptr, .ptr, .ptr } }; @@ -56,7 +60,7 @@ pub const draft_merge = Sig{ .name = "draft_merge", .handle = "d.fns.attn_merge" pub const attn_rows8_mt2 = Sig{ .name = "attn_rows8_mt2", .handle = "e.mt2.paged", .symbol = "tf_q35_attn_rows8_mt2", .params = attn_rows8.params }; pub const attn_rows8_mt2_whole = Sig{ .name = "attn_rows8_mt2_whole", .handle = "e.mt2.whole", .symbol = "tf_q35_attn_rows8_mt2_whole", .params = attn_rows8.params }; -pub const all = [_]Sig{ attn_rows8_mt2, attn_rows8_mt2_whole, attn_partial, attn_partial8, attn_rows, attn_rows8, attn_merge, attn_gate, rope, rope8, draft_partial, draft_merge, attn_partial_whole, attn_partial8_whole, attn_rows_whole, attn_rows8_whole }; +pub const all = [_]Sig{ attn_rows8_mt2, attn_rows8_mt2_whole, attn_partial, attn_partial8, attn_rows, attn_rows8, attn_merge, attn_gate, rope, rope8, draft_partial, draft_merge, attn_partial_whole, attn_partial8_whole, attn_rows_whole, attn_rows8_whole, attn_rows_join, attn_rows8_join }; /// The list a launch site's handle names, if the table holds one. pub fn byHandle(handle: []const u8) ?Sig { diff --git a/zig/src/families/qwen3_5/cuda_warm.zig b/zig/src/families/qwen3_5/cuda_warm.zig index 274aa174799..2cc67913e89 100644 --- a/zig/src/families/qwen3_5/cuda_warm.zig +++ b/zig/src/families/qwen3_5/cuda_warm.zig @@ -5,12 +5,12 @@ const E = @import("cuda_engine.zig"); pub const profile = @import("cuda_startup_profile.zig"); pub const Seen = struct { - keys: [E.most_verify + E.most_window]u32 = undefined, + keys: [E.most_verify + E.most_window]u64 = undefined, len: usize = 0, counts: [E.most_verify + E.most_window]u8 = @splat(0), pub fn contains(self: *const Seen, shape: E.Engine.Shape) bool { - return std.mem.indexOfScalar(u32, self.keys[0..self.len], shape.key()) != null; + return std.mem.indexOfScalar(u64, self.keys[0..self.len], shape.key()) != null; } pub fn passes(self: *const Seen, shape: E.Engine.Shape) u8 { diff --git a/zig/src/families/qwen3_5/cuda_warm_turns_test.zig b/zig/src/families/qwen3_5/cuda_warm_turns_test.zig new file mode 100644 index 00000000000..4e977a0e52d --- /dev/null +++ b/zig/src/families/qwen3_5/cuda_warm_turns_test.zig @@ -0,0 +1,11 @@ +//! Qwen3.5 CUDA's warm turns: the dense family and its MoE wrapper declare the wait and a usable end. +const std = @import("std"); +const native = @import("cuda_native.zig"); +const moe = @import("cuda_native_moe.zig"); + +test "Qwen warm turns: the dense family and its MoE wrapper share the wait and keep only usable ends" { + try std.testing.expectEqual(@as(u64, 150 * std.time.ns_per_ms), native.warm_quiet); + try std.testing.expect(native.warm_usable); + try std.testing.expectEqual(@as(u64, 150 * std.time.ns_per_ms), moe.warm_quiet); + try std.testing.expect(moe.warm_usable); +} diff --git a/zig/src/families/qwen3_5/prefill.zig b/zig/src/families/qwen3_5/prefill.zig index 0be0f2127e4..f5b7c9b61da 100644 --- a/zig/src/families/qwen3_5/prefill.zig +++ b/zig/src/families/qwen3_5/prefill.zig @@ -25,6 +25,12 @@ pub fn run(cache: *st.Cache, stream: *lanes.Stream, chunk: usize, ctx: anytype, stream.keepInterruptedPrefill(@intCast(at)); return error.Cancelled; } + + // A background pass steps aside when real work waits: the kept prefix is what the next pass resumes. + if (stream.yields()) { + stream.keepInterruptedPrefill(@intCast(at)); + return error.Yielded; + } var end = @min(ids.len, at + chunk); for (stream.chunks) |boundary| if (boundary > at) { end = @min(end, boundary); diff --git a/zig/src/hip/kernel_tests/flashnext_attn.zig b/zig/src/hip/kernel_tests/flashnext_attn.zig index 9523dd1d6ec..d7352dd8d04 100644 --- a/zig/src/hip/kernel_tests/flashnext_attn.zig +++ b/zig/src/hip/kernel_tests/flashnext_attn.zig @@ -177,7 +177,12 @@ test "block scores and selection: relu-summed heads, the best blocks with ties t const ratio = 4; const top = 32; const blocks = 3000; - const ends = [_]i32{ 100, 4 * 3000 + 3, 4 * 1500, 4 * 33 + 1, 4 * 2999 + 2 }; + // thirteen rows span two 8-row blockIdx.y tiles so staged indexing across tiles is exercised + const ends = [_]i32{ + 100, 4 * 3000 + 3, 4 * 1500, 4 * 33 + 1, 4 * 2999 + 2, + 4 * 200, 4 * 500 + 3, 4 * 12 + 2, 4 * 1024, 4 * 64 + 1, + 4 * 1800, 4 * 2500 + 3, 4 * 77 + 1, + }; const rows = ends.len; var complete: [rows]i32 = undefined; for (&complete, ends) |*c, e| c.* = @divFloor(e, ratio); @@ -230,6 +235,28 @@ test "block scores and selection: relu-summed heads, the best blocks with ties t .{ r, b }, ); }; + // the kernel's own fp32 order, bit for bit: a lane's dims 32 apart, the 32-lane xor tree, then the heads in order + for (0..rows) |r| for (0..blocks) |b| { + if (!(complete[r] > top and b < complete[r])) continue; + var total: f32 = 0; + for (0..heads) |h| { + var lanes: [32]f32 = @splat(0); + for (&lanes, 0..) |*x, l| for (0..dims / 32) |i| { + const d = l + 32 * i; + x.* += hq[(r * heads + h) * dims + d] * @as(f32, @floatCast(t.value(hp[b * dims + d]))); + }; + var mask: usize = 16; + while (mask > 0) : (mask >>= 1) { + var next: [32]f32 = undefined; + for (&next, 0..) |*x, l| x.* = lanes[l] + lanes[l ^ mask]; + lanes = next; + } + total += @max(lanes[0], 0); + } + const want = total / @sqrt(@as(f32, dims)); + const got = gs[r * blocks + b]; + try rig.expect(got == want, "score row {d} block {d}: {e} != {e}", .{ r, b, got, want }); + }; // the selection runs on scores with ties written in: the GPU's, then a few equal to the cut for (0..rows) |r| for (0..blocks) |b| if (b % 50 == 5) { gs[r * blocks + b] = 3.0; diff --git a/zig/src/native/cuda.zig b/zig/src/native/cuda.zig index f7349cfb7f5..8fcfa239f3d 100644 --- a/zig/src/native/cuda.zig +++ b/zig/src/native/cuda.zig @@ -105,8 +105,8 @@ pub const Host = struct { } } /// The round loop and the lane host over the family's backend, its thread started. - pub fn serve(h: *Host, io: std.Io, facts: lanes.Model, rows: u32, info: api.Info, explain: ?api.Explain) !void { - return @import("cuda_startup_phase.zig").serve(h, io, facts, rows, info, explain, .{ + pub fn serve(h: *Host, io: std.Io, facts: lanes.Model, rows: u32, info: api.Info, explain: ?api.Explain, warm_quiet: u64) !void { + return @import("cuda_startup_phase.zig").serve(h, io, facts, rows, info, explain, warm_quiet, .{ .bound = &bound, .backend = backend, .initThread = initThread, @@ -473,7 +473,7 @@ fn openWith(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, o: api.O .slide_conversations = conversations, .readouts = readouts, .text_generation = readouts == null, // a readout engine answers its readouts only (Clef's /v1/systemone) - }), .{ .ctx = loaded.ctx, .text = F.explain }); + }), .{ .ctx = loaded.ctx, .text = F.explain }, snaps.warmQuiet(F)); opened = true; kv_pages.warnCapacity(cache_capacity, o.keep == 0 or o.prompt_cache_gib == 0 or share, if (paged) |p| p.taken else 0, std.log); // TF_KV_SHARE: no copied rows if (@hasField(@TypeOf(loaded), "follow")) if (loaded.follow) |f| { diff --git a/zig/src/native/cuda_health_test.zig b/zig/src/native/cuda_health_test.zig index c61ecf80248..e9483ec703f 100644 --- a/zig/src/native/cuda_health_test.zig +++ b/zig/src/native/cuda_health_test.zig @@ -34,7 +34,7 @@ pub fn check(comptime Host: type, comptime readiness: anytype, comptime serve: a try std.testing.expect(h.health == null); try std.testing.expect(h.startup_phase == null); readiness(h, Family); - try serve(h, std.testing.io, .{ .exact_width = 8 }, 8, .{ .lanes = 2 }, null); + try serve(h, std.testing.io, .{ .exact_width = 8 }, 8, .{ .lanes = 2 }, null, 0); try std.testing.expectEqual(@as(usize, 2), family.notes); try std.testing.expectEqual(Phase.calibration, family.phases[0]); try std.testing.expectEqual(Phase.ready, family.phases[1]); @@ -86,7 +86,7 @@ fn eager(comptime Host: type, comptime serve: anytype) !void { h.* = .{ .gpa = gpa, .gpu = null, .family = &probe, .release = Probe.release, .inner = backend.backend(), .vtable = undefined, .cfg = undefined, .clock = undefined, .core = undefined, .host = undefined, .served = .{ .backend = backend.backend(), .facts = facts, .stream_bytes = 0, .prepare = .{ .ctx = &probe, .run = Probe.run } } }; Probe.opening = true; defer Probe.opening = false; - try serve(h, std.testing.io, facts, 64, .{ .lanes = 1 }, null); + try serve(h, std.testing.io, facts, 64, .{ .lanes = 1 }, null, 0); defer { h.host.stop(); h.core.deinit(); @@ -142,7 +142,7 @@ pub fn context(comptime H: type, comptime serve: anytype) !void { defer backend.deinit(); var dummy: u8 = 0; var h: H = .{ .gpa = a, .gpu = &gpu, .family = &dummy, .release = undefined, .inner = backend.backend(), .vtable = undefined, .cfg = undefined, .clock = undefined, .core = undefined, .host = undefined }; - try serve(&h, std.testing.io, .{}, 1, .{ .lanes = 1 }, null); + try serve(&h, std.testing.io, .{}, 1, .{ .lanes = 1 }, null, 0); defer { h.host.stop(); h.core.deinit(); @@ -189,7 +189,7 @@ fn failedStartup(comptime Host: type, comptime readiness: anytype, comptime serv const facts: lanes.Model = .{ .exact_width = 8 }; h.* = .{ .gpa = a, .gpu = null, .family = &family, .release = Family.release, .inner = backend.backend(), .vtable = undefined, .cfg = undefined, .clock = undefined, .core = undefined, .host = undefined, .served = .{ .backend = backend.backend(), .facts = facts, .stream_bytes = 0, .prepare = .{ .ctx = &family, .run = Family.prepare } } }; readiness(h, Family); - try std.testing.expectError(error.InjectedCalibration, serve(h, std.testing.io, facts, 8, .{ .lanes = 2 }, null)); + try std.testing.expectError(error.InjectedCalibration, serve(h, std.testing.io, facts, 8, .{ .lanes = 2 }, null, 0)); try std.testing.expectEqual(@as(usize, 2), family.count); try std.testing.expectEqualSlices(Phase, &.{ .calibration, .failed }, &family.phases); } diff --git a/zig/src/native/cuda_ledger.zig b/zig/src/native/cuda_ledger.zig index 8bafd878cde..b19eae6ddb1 100644 --- a/zig/src/native/cuda_ledger.zig +++ b/zig/src/native/cuda_ledger.zig @@ -40,7 +40,7 @@ pub fn declared(loaded: anytype) ?PerRequest { /// Whether this load serves from the ledger: the family allocates per request and nothing it loaded escapes the cost. pub fn wanted(comptime F: type, loaded: anytype, served_stream_bytes: u64) bool { if (declared(loaded) == null) return false; - // no path yet routes a warm pass's or a lone driver's LaneMemory back to the queue + // a family that declares warm turns serves off the ledger: its warm pass's LaneMemory ends the job, no requeue if (comptime @hasDecl(F, "warm_quiet")) return false; const L = @TypeOf(loaded); if (comptime @hasField(L, "lone")) if (loaded.lone != null) return false; diff --git a/zig/src/native/cuda_prompt_cancel_test.zig b/zig/src/native/cuda_prompt_cancel_test.zig index f7ec3234543..a4db1b697fb 100644 --- a/zig/src/native/cuda_prompt_cancel_test.zig +++ b/zig/src/native/cuda_prompt_cancel_test.zig @@ -13,7 +13,7 @@ pub fn check(comptime Host: type, comptime serve: anytype) !void { const h = try gpa.create(Host); defer gpa.destroy(h); h.* = .{ .gpa = gpa, .gpu = null, .family = &target, .release = Nothing.release, .inner = target.backend(), .vtable = undefined, .cfg = undefined, .clock = undefined, .core = undefined, .host = undefined }; - try serve(h, std.testing.io, .{ .exact_width = 8, .mtp = true, .speculate = true, .drafts = 7, .hidden_rows = true }, 8, .{ .lanes = 2 }, null); + try serve(h, std.testing.io, .{ .exact_width = 8, .mtp = true, .speculate = true, .drafts = 7, .hidden_rows = true }, 8, .{ .lanes = 2 }, null, 0); defer { h.host.stop(); h.core.deinit(); diff --git a/zig/src/native/cuda_snaps.zig b/zig/src/native/cuda_snaps.zig index df4527771b9..e915e1e91c3 100644 --- a/zig/src/native/cuda_snaps.zig +++ b/zig/src/native/cuda_snaps.zig @@ -7,6 +7,7 @@ pub fn cacheRules(comptime F: type) api.prompt_cache.Rules { var rules: api.prompt_cache.Rules = .{ .lookahead = 1, .min_prompt = 0 }; if (@hasDecl(F, "snap_lookahead")) rules.lookahead = F.snap_lookahead; if (@hasDecl(F, "warm_quiet")) rules.warm = .waits; + if (@hasDecl(F, "warm_usable")) rules.warm_usable = F.warm_usable; if (@hasDecl(F, "snap_fork")) rules.fork = F.snap_fork; // opt-in, a family at a time after its device check if (@hasDecl(F, "snap_tail")) rules.tail = if (@import("core").profile.lookup(F.snap_tail)) |v| std.mem.eql(u8, v, "1") else false; if (@hasDecl(F, "snap_intermediate")) { // a chunk-invariant family's opt-in ladder of intermediate checkpoints @@ -20,6 +21,11 @@ pub fn cacheRules(comptime F: type) api.prompt_cache.Rules { return rules; } +/// The family's own wait before a warm pass's first chunk (0: it declares none). +pub fn warmQuiet(comptime F: type) u64 { + return if (@hasDecl(F, "warm_quiet")) F.warm_quiet else 0; +} + /// Native CUDA families own their grid, independently of the server's template chunk starts. pub fn passRules(comptime F: type, prompt_rows: u32) api.prompt_cache.Rules { var rules = cacheRules(F); diff --git a/zig/src/native/cuda_snaps_test.zig b/zig/src/native/cuda_snaps_test.zig index f167c7c9ac0..b5c2f649de4 100644 --- a/zig/src/native/cuda_snaps_test.zig +++ b/zig/src/native/cuda_snaps_test.zig @@ -2,6 +2,7 @@ const std = @import("std"); const api = @import("engine_api"); const cacheRules = @import("cuda_snaps.zig").cacheRules; +const warmQuiet = @import("cuda_snaps.zig").warmQuiet; /// Copies that hold nothing: a store keys its states by tokens and position, all that its plans read. const Held = struct { @@ -85,3 +86,22 @@ test "snap fork: a family that opts in keeps where the questions part, and the n try std.testing.expectEqualSlices(u32, &.{ 16, 20 }, planned.marks[1]); try std.testing.expectEqual(@as(u32, 16), planned.from[2]); } + +test "CUDA warm rules: a warm end stays usable only where a family declares it, and its own wait comes through" { + const Both = struct { + pub const warm_quiet: u64 = 7; + pub const warm_usable = true; + }; + const Ends = struct { + pub const warm_quiet: u64 = 7; + }; + try std.testing.expectEqual(@as(u64, 7), warmQuiet(Both)); + try std.testing.expectEqual(@as(u64, 7), warmQuiet(Ends)); + try std.testing.expectEqual(@as(u64, 0), warmQuiet(struct {})); + // A family's wait and the rule that follows it come from one declaration: a nonzero wait is a waiting family. + inline for (@import("cuda.zig").registry) |F| { + try std.testing.expectEqual(warmQuiet(F) > 0, cacheRules(F).warm == .waits); + } + try std.testing.expect(cacheRules(Both).warm_usable); + try std.testing.expect(!cacheRules(Ends).warm_usable); +} diff --git a/zig/src/native/cuda_startup_phase.zig b/zig/src/native/cuda_startup_phase.zig index 42b3626d882..6a680b3efb5 100644 --- a/zig/src/native/cuda_startup_phase.zig +++ b/zig/src/native/cuda_startup_phase.zig @@ -16,7 +16,7 @@ fn note(h: anytype, phase: cuda.startup_watch.Phase) void { if (h.startup_phase) |callback| callback(h.family, phase); } -pub fn serve(h: anytype, io: std.Io, facts: lanes.Model, rows: u32, info: api.Info, explain: ?api.Explain, callbacks: anytype) !void { +pub fn serve(h: anytype, io: std.Io, facts: lanes.Model, rows: u32, info: api.Info, explain: ?api.Explain, warm_quiet: u64, callbacks: anytype) !void { note(h, .calibration); errdefer note(h, .failed); h.cfg = try lanes.Config.init(h.gpa, facts, rows, rows - 1); @@ -34,7 +34,7 @@ pub fn serve(h: anytype, io: std.Io, facts: lanes.Model, rows: u32, info: api.In h.host.explain = explain; h.host.health = @import("cuda_readiness.zig").source(h); h.host.cache = h.store; - h.host.warm_quiet = if (info.warm_turns) nemotron.native.warm_quiet else 0; + h.host.warm_quiet = if (info.warm_turns) warm_quiet else 0; if (h.lone != null) h.host.lone = .{ .ctx = h, .run = callbacks.loneRun, .sampled = true, .logprobs = h.inner.vtable.first_row != null, .structures = h.inner.vtable.first_masked != null, .min_budget = nemotron.native.lone_min_budget, .resumes = true }; if (h.learn != null) h.host.learner = callbacks.learner(h); kv_pages.install(&h.kv, &h.host); // the pool's first census, before the engine thread owns the pool diff --git a/zig/src/native/dense_trainer_close_test.zig b/zig/src/native/dense_trainer_close_test.zig index aa2dd9261bd..7aa56ca3b6c 100644 --- a/zig/src/native/dense_trainer_close_test.zig +++ b/zig/src/native/dense_trainer_close_test.zig @@ -147,7 +147,7 @@ pub fn close(comptime Host: type, comptime serve: anytype, comptime closeHost: a defer backend.deinit(); const h = try a.create(Host); h.* = .{ .gpa = a, .gpu = null, .family = e, .release = F.family, .inner = backend.backend(), .vtable = undefined, .cfg = undefined, .clock = undefined, .core = undefined, .host = undefined }; - try serve(h, std.testing.io, .{ .exact_width = 8 }, 8, .{ .lanes = 1 }, null); + try serve(h, std.testing.io, .{ .exact_width = 8 }, 8, .{ .lanes = 1 }, null, 0); h.served = .{ .backend = backend.backend(), .facts = .{ .exact_width = 8 }, .stream_bytes = 0 }; adapter.learner.pockets.save_pending = true; const hook = adapter.hook(); diff --git a/zig/src/native/nemotron_trainer_test.zig b/zig/src/native/nemotron_trainer_test.zig index 9ce405c8a92..16dac6299bd 100644 --- a/zig/src/native/nemotron_trainer_test.zig +++ b/zig/src/native/nemotron_trainer_test.zig @@ -168,7 +168,7 @@ pub fn close(comptime Host: type, comptime serve: anytype, comptime closeHost: a defer backend.deinit(); const h = try a.create(Host); h.* = .{ .gpa = a, .gpu = null, .family = e, .release = F.family, .inner = backend.backend(), .vtable = undefined, .cfg = undefined, .clock = undefined, .core = undefined, .host = undefined }; - try serve(h, std.testing.io, .{ .exact_width = 8 }, 8, .{ .lanes = 1 }, null); + try serve(h, std.testing.io, .{ .exact_width = 8 }, 8, .{ .lanes = 1 }, null, 0); h.served = .{ .backend = backend.backend(), .facts = .{ .exact_width = 8 }, .stream_bytes = 0 }; h.slide = adapter; h.slide_free = struct { diff --git a/zig/src/native/qwen35.zig b/zig/src/native/qwen35.zig index d896988e90c..f2aaa8f1044 100644 --- a/zig/src/native/qwen35.zig +++ b/zig/src/native/qwen35.zig @@ -134,11 +134,11 @@ pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Ope h.cache = api.prompt_cache.Store.init(gpa, .{ .ptr = h.metal, .vtable = &.{ .bytes = S.bytes, .save = S.save, .restore = S.restore, .drop = S.drop }, - }, .{ .planned = true, .grid = chunk, .chunk = chunk }, plan.budget_bytes); + }, .{ .planned = true, .grid = chunk, .chunk = chunk, .warm_usable = true }, plan.budget_bytes); h.host.cache = &h.cache.?; - h.host.info_.prompt_cache = true; } } + h.host.advertiseCache(if (h.cache) |*store| store else null); errdefer if (h.cache) |*store| store.deinit(); try mtl.resident.streams.hold(h, io, "qwen3.5"); errdefer mtl.resident.streams.drop(h); diff --git a/zig/src/native/trainer_close_test.zig b/zig/src/native/trainer_close_test.zig index 1669e2cea12..bef242c14e9 100644 --- a/zig/src/native/trainer_close_test.zig +++ b/zig/src/native/trainer_close_test.zig @@ -145,7 +145,7 @@ pub fn close(comptime Host: type, comptime serve: anytype, comptime closeHost: a defer backend.deinit(); const h = try a.create(Host); h.* = .{ .gpa = a, .gpu = null, .family = e, .release = F.family, .inner = backend.backend(), .vtable = undefined, .cfg = undefined, .clock = undefined, .core = undefined, .host = undefined, .served = .{ .backend = backend.backend(), .facts = .{ .exact_width = 8 }, .stream_bytes = 0 } }; - try serve(h, std.testing.io, .{ .exact_width = 8 }, 8, .{ .lanes = 1 }, null); + try serve(h, std.testing.io, .{ .exact_width = 8 }, 8, .{ .lanes = 1 }, null, 0); adapter.learner.pockets.save_pending = true; const hook = adapter.hook(); try std.testing.expect(hook.step(hook.ctx).stale); diff --git a/zig/src/platform/environment.zig b/zig/src/platform/environment.zig index 0a2e84b7423..952a13ef47f 100644 --- a/zig/src/platform/environment.zig +++ b/zig/src/platform/environment.zig @@ -64,7 +64,7 @@ pub const rules = [_]Rule{ .{ .name = "TF_HEAD_GEOMETRY", .scope = .metal, .kind = .size, .forms = "a whole nonnegative native-size geometry count" }, .{ .name = "TF_PROMPT_ROWS", .scope = .metal, .kind = .prompt, .forms = "a multiple of 16 from 128 to 2048 for native serving" }, .{ .name = "TF_ANE_COLUMNS", .scope = .metal, .kind = .u32, .forms = "a whole column count from 0 to 4294967295 (0 disables the share)" }, - .{ .name = "TF_FLASHNEXT_SCALE_INDEX", .scope = .metal, .kind = .flag, .forms = "0 or 1 (1: Flash Next's 4-bit expert kernels read scales and biases through a 16-bit index)" }, + .{ .name = "TF_FLASHNEXT_SCALE_INDEX", .scope = .metal, .kind = .flag, .forms = "0 or 1 (0: Flash Next's 4-bit expert kernels read the stored scales and biases, not their 16-bit index)" }, .{ .name = "GLM_EHPROJ_NAX", .scope = .metal, .kind = .flag, .forms = "0 or 1 (0 serves GLM's MTP eh_proj on the scalar kernel)" }, .{ .name = "TF_FLASHNEXT_GROUPED_ROWS", .scope = .metal, .kind = .size, .forms = "0 (never) or the rows, 1 to 32, from which a window's experts run grouped", .max = 32 }, .{ .name = "TF_QWEN27_SLOT_RESUME", .scope = .metal, .kind = .flag, .forms = "0 or 1 (0 stops slot 0 resuming a later prompt; unset or blank keeps it on)" }, @@ -201,6 +201,8 @@ pub const rules = [_]Rule{ .{ .name = "TF_FLASHNEXT_GREEDY_WIDE", .scope = .flashnext, .kind = .size, .forms = "a whole round width from 0 to the native size maximum (default 4)" }, .{ .name = "TF_FLASHNEXT_WINDOW_ROWS", .scope = .flashnext, .kind = .size, .forms = "a whole row count from 0 to the native size maximum (default the shared round's rows; capped by them)" }, .{ .name = "TF_FLASHNEXT_READOUT_ROWS", .scope = .flashnext, .kind = .size, .forms = "a whole row count from 0 to the native size maximum (default 64; 0 never takes the tiles)" }, + .{ .name = "TF_FLASHNEXT_CHUNK", .scope = .flashnext, .kind = .size, .min = 1, .max = 16384, .forms = "whole prompt rows a pass, 1 to 16384 (default 1536)" }, + .{ .name = "TF_FLASHNEXT_CHUNK_SOLO", .scope = .flashnext, .kind = .size, .max = 16384, .forms = "whole prompt rows a pass with no stream decoding, TF_FLASHNEXT_CHUNK to 16384 (unset: 8192 alone at --parallel 1, else off)" }, .{ .name = "TF_FLASHNEXT_FACT_ROWS", .scope = .flashnext, .kind = .size, .forms = "a whole row count from 0 to the native size maximum (default 64; 0 never takes the tiles)" }, .{ .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)" }, diff --git a/zig/src/platform/environment_flashnext_test.zig b/zig/src/platform/environment_flashnext_test.zig index 1bfb646a3af..6df4cdca58d 100644 --- a/zig/src/platform/environment_flashnext_test.zig +++ b/zig/src/platform/environment_flashnext_test.zig @@ -33,13 +33,13 @@ fn check(name: []const u8, raw: []const u8, valid: bool) !void { try t.expect(std.mem.endsWith(u8, why.?, e.rule(name).forms)); } -test "Flash Next strict env: the table holds all 29 settings: 20 switches, 7 integers, 1 real, 1 structured" { +test "Flash Next strict env: the table holds all 31 settings: 20 switches, 9 integers, 1 real, 1 structured" { var counts: [4]usize = @splat(0); for (e.rules) |r| if (r.scope == .flashnext) { try t.expect(std.mem.startsWith(u8, r.name, "TF_FLASHNEXT_")); counts[@backingInt(group(r))] += 1; }; - try t.expectEqual([4]usize{ 20, 7, 1, 1 }, counts); + try t.expectEqual([4]usize{ 20, 9, 1, 1 }, counts); } test "Flash Next strict env: unset and blank settings both read as the caller's default" { @@ -64,12 +64,22 @@ test "Flash Next strict env: every switch keeps exactly 0 and 1 and refuses the test "Flash Next strict env: every count keeps its whole numbers and refuses junk, negatives, overflow" { for (e.rules) |r| if (r.scope == .flashnext and group(r) == .integers) { - for ([_][]const u8{ "0", "7", "007" }) |raw| try check(r.name, raw, true); + try check(r.name, "0", r.min == 0); + for ([_][]const u8{ "7", "007" }) |raw| try check(r.name, raw, true); try t.expectEqual(@as(u64, 7), try e.value(u64, r.name, "007", 0)); for ([_][]const u8{ "-1", "1.5", "abc", "18446744073709551616" }) |raw| try check(r.name, raw, false); }; } +test "Flash Next strict env: chunk rows take 1 to 16384 and refuse the rest by name" { + const chunk = "TF_FLASHNEXT_CHUNK"; + const solo = "TF_FLASHNEXT_CHUNK_SOLO"; + for ([_][]const u8{ "1", "1536", "16384" }) |raw| try check(chunk, raw, true); + for ([_][]const u8{ "1", "8192", "16384" }) |raw| try check(solo, raw, true); + for ([_][]const u8{ "0", "16385", "4k", "-1" }) |raw| try check(chunk, raw, false); + for ([_][]const u8{ "16385", "4k", "-1" }) |raw| try check(solo, raw, false); +} + test "Flash Next strict env: the page test keeps 0 in the table while its reader refuses it, blank reads unset" { const name = "TF_FLASHNEXT_KV_PAGE_TEST"; try check(name, "0", true); diff --git a/zig/src/qwen35_cache_test.zig b/zig/src/qwen35_cache_test.zig index 2918c37fc06..2a23ab2ab4b 100644 --- a/zig/src/qwen35_cache_test.zig +++ b/zig/src/qwen35_cache_test.zig @@ -186,6 +186,7 @@ const Harness = struct { store: pc.Store = undefined, active: ?*st.Cache = null, cancel_at: ?usize = null, + yield_at: ?usize = null, fail_at: ?usize = null, fn init(h: *Harness) void { @@ -206,6 +207,10 @@ const Harness = struct { const h: *Harness = @ptrCast(@alignCast(ptr)); return if (h.cancel_at) |at| h.active.?.len >= at else false; } + fn waits(ptr: *anyopaque) bool { + const h: *Harness = @ptrCast(@alignCast(ptr)); + return if (h.yield_at) |at| h.active.?.len >= at else false; + } fn advance(h: *Harness, cache: *st.Cache, ids: []const u32) !void { if (h.fail_at) |at| if (cache.len >= at) return error.FakeForward; try step({}, cache, ids); @@ -213,7 +218,7 @@ const Harness = struct { fn pass(h: *Harness, cache: *st.Cache, ids: []const u32, cuts: []const u32) !u32 { const lookup = try h.store.lookup(a, ids, 128, &.{}, cuts, &.{}); defer a.free(lookup.marks); - var stream = try lanes.Stream.init(a, .{ .id = "fixture", .prompt = ids, .max_new = 8, .chunks = cuts, .cancel_check = .{ .ptr = h, .check = cancelled }, .reuse = .{ + var stream = try lanes.Stream.init(a, .{ .id = "fixture", .prompt = ids, .max_new = 8, .chunks = cuts, .cancel_check = .{ .ptr = h, .check = cancelled }, .yield_check = .{ .ptr = h, .check = waits }, .reuse = .{ .saved = if (lookup.entry) |entry| entry.saved else null, .at = if (lookup.entry) |entry| entry.at else 0, .marks = lookup.marks, @@ -289,6 +294,28 @@ test "Qwen retained: cancellation after restore preserves the valid prefix and a try t.expect(h.store.counts.failed > 0); } +test "Qwen retained: foreground work arriving after a chunk yields at the boundary and keeps the prefix" { + var allocations: mtl.Allocations = .{}; + const device: mtl.Device = .{ .allocations = &allocations }; + const ids = tokens(); + var h: Harness = .{}; + h.init(); + defer h.deinit(); + h.yield_at = 128; + var yielded = try st.Cache.init(a, device, 400); + defer yielded.deinit(); + seed(&yielded); + try t.expectError(error.Yielded, h.pass(&yielded, ids[0..300], &.{})); + try t.expectEqual(@as(usize, 128), yielded.len); // one chunk ran, not the whole prompt + + // The completed prefix is kept before the pass steps aside, so the next pass resumes at it. + h.yield_at = null; + var resumed = try st.Cache.init(a, device, 410); + defer resumed.deinit(); + seed(&resumed); + try t.expectEqual(@as(u32, 128), try h.pass(&resumed, &ids, &.{})); +} + test "Qwen retained: a failed chunk never captures its incomplete state" { var allocations: mtl.Allocations = .{}; const device: mtl.Device = .{ .allocations = &allocations }; diff --git a/zig/src/server/chat.zig b/zig/src/server/chat.zig index 1c0076d1845..b02f226fc13 100644 --- a/zig/src/server/chat.zig +++ b/zig/src/server/chat.zig @@ -16,7 +16,6 @@ const wait = @import("wait_reason.zig"); const refusals = @import("refusals.zig"); const server_mod = @import("server.zig"); const Server = server_mod.Server; -const chunk_plan = @import("chunk_plan.zig"); const Mailbox = @import("mailbox.zig").Mailbox; const StopHook = @import("stop_hook.zig").StopHook; const engine_refusal = @import("engine_refusal.zig"); @@ -200,7 +199,7 @@ pub fn prepare(srv: *Server, cx: *Cx, input: Input, gone: anytype) Failure!Prepa .user_end = @intCast(rendered.user_end), .shared_prefixes = shared.items, // a cut before the conversation's own text: fresh sessions resume their whole harness - .chunks = try chunk_plan.withCut(a, try srv.chunks.starts(a, rendered.ids), if (srv.chunks.step > 0) @intCast(@max(system_len, 1) - 1) else 0, rendered.ids.len, srv.chunks.min_chunk), + .chunks = try srv.chunks.request(a, rendered.ids, system_len), // from the tokens alone, for every request: cached states are keyed by tokens .decode_spans = try prompt_mod.replySpans(srv, cx, rendered.ids), .tools_json = if (input.tools.len > 0) try json.stringify(a, .{ .array = @constCast(input.tools) }, .{ .ascii = false }) else "", diff --git a/zig/src/server/chat_generation.zig b/zig/src/server/chat_generation.zig index 137db952be5..0671a613b62 100644 --- a/zig/src/server/chat_generation.zig +++ b/zig/src/server/chat_generation.zig @@ -279,8 +279,13 @@ pub const Generation = struct { const native = if (g.srv.text.vtable.format == .kimi) try @import("chat_kimi.zig").read(g, content_tokens, true) else null; const raw_visible = g.stops.visible(raw, false); const visible = if (native) |n| n.content else try @import("tool_minimax.zig").dsml(a, raw_visible, g.tools); + const close_at: ?reply_text.Close = if (native == null and g.thinking) + try @import("tool_minimax.zig").closeAfterRewrite(a, raw_visible, g.tools, try reply_text.closeWhere(a, reply_text.decodeText, g.srv.text, content_tokens, g.srv.close_id)) + else + null; + const call_tail = answerTail(visible, g.srv.markers, close_at); // closed before the think split, so a call ending an unclosed think block is the answer - const close = if (native != null) "" else try g.closeCall(visible); + const close = if (native != null) "" else try g.closeCall(call_tail); 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; @@ -288,9 +293,7 @@ pub const Generation = struct { const r = reply_text.pyStrip(n.reasoning); reasoning = if (r.len > 0) r else null; } else if (g.thinking) { - const original_close = try reply_text.closeWhere(a, reply_text.decodeText, g.srv.text, content_tokens, g.srv.close_id); - const close_at = try @import("tool_minimax.zig").closeAfterRewrite(a, raw_visible, g.tools, original_close); - const split = try reply_text.splitThinkingAt(a, text, true, g.srv.markers, close_at); + const split = 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; @@ -308,12 +311,17 @@ pub const Generation = struct { 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| if (close.len > 0 or std.mem.eql(u8, reason, "length")) { + 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; - try c.finishCut(if (g.thinking) content else text, &out); // a cut value sends its held bytes + const final_text = if (g.thinking) content else text; + if (std.mem.eql(u8, reason, "length")) { + try c.finishCut(final_text, &out); + } else if (close.len > 0 or c.streamed) { + try c.finish(final_text, &out); + } for (out.items) |d| try g.emit(sink, d); - }; + } } const prefilled = m.prefilled_ns; const decode_s: f64 = if (prefilled) |p| @max(0, seconds(finished_ns - p)) else 0; @@ -401,3 +409,21 @@ pub const Generation = struct { return reply; } }; + +/// Answer suffix after a confirmed thinking close, so unclosed fences inside thinking do not block closeCall. +fn answerTail(visible: []const u8, m: reply_text.Markers, close_at: ?reply_text.Close) []const u8 { + const close = close_at orelse return visible; + if (m.open.len > 0 and reply_text.findTag(visible, 0, m.open) == null) return visible; + const at = switch (close) { + .token => |v| v, + .pending => return visible, + .spelled => blk: { + const start = if (m.open.len > 0) reply_text.findTag(visible, 0, m.open).? else 0; + break :blk reply_text.findTag(visible, start, m.close) orelse return visible; + }, + }; + if (at + m.close.len <= visible.len and std.mem.startsWith(u8, visible[at..], m.close)) { + return visible[at + m.close.len ..]; + } + return visible; +} diff --git a/zig/src/server/chunk_plan.zig b/zig/src/server/chunk_plan.zig index bf3fdf0672f..930fbb62db7 100644 --- a/zig/src/server/chunk_plan.zig +++ b/zig/src/server/chunk_plan.zig @@ -52,6 +52,11 @@ pub const Plan = struct { last = next; } } + + /// The starts of a request over `ids`: `starts` with the system prompt's cut, so a warm pass and a turn agree. + pub fn request(p: Plan, a: Allocator, ids: []const u32, system_len: usize) ![]const u32 { + return withCut(a, try p.starts(a, ids), if (p.step > 0) @intCast(@max(system_len, 1) - 1) else 0, ids.len, p.min_chunk); + } }; /// `starts` with `cut` too: a state kept just before a conversation's own text reads only shared tokens. @@ -154,6 +159,24 @@ test "a harness cut joins the starts, nearer ones go" { try std.testing.expectEqualSlices(u32, &.{ 600, 4096 }, try withCut(a, &.{4096}, 600, 4680, 256)); } +test "a warm pass and the next request cut the same starts below the warm end" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const p: Plan = .{ .step = 4096, .min_chunk = 1 }; + const next = try a.alloc(u32, 4700); // the next turn's prompt; a warm pass covered its first 4680 tokens + @memset(next, 0); + const warm = next[0..4680]; + const system_len: usize = 600; + const w = try p.request(a, warm, system_len); + const n = try p.request(a, next, system_len); + try std.testing.expect(std.mem.indexOfScalar(u32, w, 599) != null); // the warm pass cuts before the conversation's own text + var shared: usize = 0; + while (shared < n.len and n[shared] < warm.len) shared += 1; // the next turn's starts the warm pass could serve + try std.testing.expectEqualSlices(u32, w, n[0..shared]); + try std.testing.expect(std.mem.indexOfScalar(u32, try p.starts(a, warm), 599) == null); // starts alone keep no such cut +} + test "chunk starts match PrefillPlan.chunks" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); diff --git a/zig/src/server/grammar.zig b/zig/src/server/grammar.zig index 8799e14aa36..9a542827e0b 100644 --- a/zig/src/server/grammar.zig +++ b/zig/src/server/grammar.zig @@ -10,6 +10,9 @@ const Cx = errors.Cx; pub const fields = [_][]const u8{ "response_format", "guided_json", "guided_regex", "guided_choice", "guided_grammar", "structured_outputs" }; +/// The most bytes a grammar's text may be: xgrammar compiles it under one lock, in time that grows with its square. +pub const max_text = 512 * 1024; + pub const Kind = @FieldType(api.Structure, "kind"); pub const Spec = struct { kind: Kind, text: []const u8 = "", field: []const u8 = "response_format" }; diff --git a/zig/src/server/logprob_parts.zig b/zig/src/server/logprob_parts.zig index 4aa8feaa3b7..3863113d9a8 100644 --- a/zig/src/server/logprob_parts.zig +++ b/zig/src/server/logprob_parts.zig @@ -256,10 +256,16 @@ fn toolRanges(a: A, answer: []const u8, tools: []const V, count: usize, offset_a try envelopes.appendSlice(a, try tp.envelopes(a, answer)); const lfm = rt.calls[3]; var pos: usize = 0; + var code: @import("reply_code.zig").Scanner = .{}; while (std.mem.indexOfPos(u8, answer, pos, lfm[0])) |at| { + if (code.check(answer, at, true) == .skip) { + pos = code.skip_end; + continue; + } const end = if (std.mem.indexOfPos(u8, answer, at + lfm[0].len, lfm[1])) |e| e + lfm[1].len else answer.len; try envelopes.append(a, .{ .start = at, .end = end, .payload = answer[at..end] }); pos = end; + code.jumpTo(pos); } if (tp.openCall(answer)) |at| try envelopes.append(a, .{ .start = at, .end = answer.len, .payload = answer[at..] }); std.mem.sort(tp.Envelope, envelopes.items, {}, struct { diff --git a/zig/src/server/reply_code.zig b/zig/src/server/reply_code.zig new file mode 100644 index 00000000000..8eb600921ea --- /dev/null +++ b/zig/src/server/reply_code.zig @@ -0,0 +1,315 @@ +//! Linear-time Markdown inline code-span and fenced code-block scanner so quoted call markup stays prose. +const std = @import("std"); + +pub const Status = union(enum) { + outside, + skip: usize, + pending, +}; + +const LineEnd = enum { yes, no, wait }; + +pub const Scanner = struct { + pos: usize = 0, + skip_end: usize = 0, + open_kind: enum { none, fence_line, fence_body, inline_span } = .none, + open_at: usize = 0, + open_ch: u8 = 0, + open_len: usize = 0, + open_scan: usize = 0, + once: u128 = 0, + twice: u128 = 0, + long_runs: usize = 0, + dead_until: usize = 0, + dead_runs: u128 = 0, + dead_long: bool = false, + + /// Advances past an already consumed envelope so markup inside tool arguments is not scanned as Markdown. + pub fn jumpTo(c: *Scanner, pos: usize) void { + if (c.pos < pos or c.open_kind != .none) c.* = .{ .pos = pos, .skip_end = pos }; + } + + /// Classifies `at` in `text` against preceding Markdown code spans and fences; monotone `at` stays O(N). + pub fn check(c: *Scanner, text: []const u8, at: usize, finished: bool) Status { + if (at >= text.len) return .outside; + if (at < c.skip_end) c.* = .{}; + if (c.open_kind == .none and at < c.pos) return .outside; + if (c.open_kind != .none and at < c.open_at) return .outside; + if (c.open_kind != .none) if (c.resumeOpen(text, at, finished)) |st| return st; + while (c.pos <= at) { + const i = std.mem.indexOfAnyPos(u8, text[0 .. at + 1], c.pos, "`~") orelse { + c.pos = at + 1; + return .outside; + }; + c.pos = i; + const ch = text[i]; + const e = runEnd(text, i, ch); + const n = e - i; + if (ch == '~') { + if (!atFenceStart(text, i)) { + c.pos = e; + continue; + } + if (e == text.len and !finished and n < 3) return .pending; + if (n < 3) { + c.pos = e; + continue; + } + c.open_kind = .fence_line; + } else { + if (e == text.len and !finished) return .pending; + if (e == text.len) { + c.pos = e; + continue; + } + if (n >= 3 and atFenceStart(text, i)) { + c.open_kind = .fence_line; + } else { + if (i < c.dead_until and c.isDead(n)) { + c.pos = e; + continue; + } + c.open_kind = .inline_span; + c.once = 0; + c.twice = 0; + c.long_runs = 0; + } + } + c.open_at = i; + c.open_ch = ch; + c.open_len = n; + c.open_scan = e; + if (c.resumeOpen(text, at, finished)) |st| return st; + } + return .outside; + } + + fn resumeOpen(c: *Scanner, text: []const u8, at: usize, finished: bool) ?Status { + if (c.open_kind == .fence_line) { + const needles: []const u8 = if (c.open_ch == '`') "\n`" else "\n"; + if (std.mem.indexOfAnyPos(u8, text, c.open_scan, needles)) |hit| { + if (text[hit] == '`') { + c.open_kind = .inline_span; + c.open_scan = hit; + c.once = 0; + c.twice = 0; + c.long_runs = 0; + } else { + c.open_kind = .fence_body; + c.open_scan = hit + 1; + } + } else { + if (finished) { + c.open_kind = .none; + c.pos = c.open_at + c.open_len; + return null; + } + c.open_scan = text.len; + return .pending; + } + } + if (c.open_kind == .fence_body) return c.resumeFenceBody(text, at, finished); + return c.resumeInline(text, at, finished); + } + + fn resumeFenceBody(c: *Scanner, text: []const u8, at: usize, finished: bool) ?Status { + var line = c.open_scan; + while (true) { + c.open_scan = line; + if (line == text.len) { + if (!finished) return .{ .skip = text.len }; + c.open_kind = .none; + c.pos = text.len; + c.skip_end = text.len; + return .{ .skip = text.len }; + } + var q = line; + var sp: usize = 0; + while (sp < 4 and q < text.len and text[q] == ' ') : ({ + q += 1; + sp += 1; + }) {} + if (sp <= 3 and q < text.len and text[q] == c.open_ch) { + const r = runEnd(text, q, c.open_ch); + if (r - q >= c.open_len) { + var k = r; + while (k < text.len and (text[k] == ' ' or text[k] == '\t' or text[k] == '\r')) k += 1; + if (k < text.len and text[k] == '\n') { + const end = k + 1; + c.open_kind = .none; + c.pos = end; + c.skip_end = end; + return if (at < end) .{ .skip = end } else null; + } + if (k == text.len) { + if (!finished) return .{ .skip = text.len }; + c.open_kind = .none; + c.pos = text.len; + c.skip_end = text.len; + return .{ .skip = text.len }; + } + } + } + if (std.mem.indexOfScalarPos(u8, text, line, '\n')) |nl| { + line = nl + 1; + continue; + } + if (!finished) return .{ .skip = text.len }; + c.open_kind = .none; + c.pos = text.len; + c.skip_end = text.len; + return .{ .skip = text.len }; + } + } + + fn resumeInline(c: *Scanner, text: []const u8, at: usize, finished: bool) ?Status { + var p = c.open_scan; + while (std.mem.indexOfAnyPos(u8, text, p, "\n`")) |hit| { + if (text[hit] == '\n') { + switch (nlEndsParagraph(text, hit, finished)) { + .yes => { + c.markDead(hit); + c.open_kind = .none; + c.pos = c.open_at + c.open_len; + return null; + }, + .wait => { + c.open_scan = hit; + return .pending; + }, + .no => { + p = hit + 1; + continue; + }, + } + } + const je = runEnd(text, hit, '`'); + if (!finished and je == text.len) { + c.open_scan = hit; + return .pending; + } + const m = je - hit; + if (m == c.open_len) { + c.open_kind = .none; + c.pos = je; + c.skip_end = je; + return if (at < je) .{ .skip = je } else null; + } + c.recordRun(m); + p = je; + } + if (finished) { + c.markDead(text.len); + c.open_kind = .none; + c.pos = c.open_at + c.open_len; + return null; + } + c.open_scan = text.len; + return .pending; + } + + fn recordRun(c: *Scanner, n: usize) void { + if (n < 128) { + const bit = @as(u128, 1) << @intCast(n); + if ((c.once & bit) != 0) c.twice |= bit; + c.once |= bit; + } else c.long_runs +|= 1; + } + + fn markDead(c: *Scanner, until: usize) void { + c.dead_until = until; + c.dead_runs = ~c.twice; + c.dead_long = c.long_runs < 2; + } + + fn isDead(c: *const Scanner, n: usize) bool { + if (n < 128) return (c.dead_runs & (@as(u128, 1) << @intCast(n))) != 0; + return c.dead_long; + } +}; + +fn runEnd(text: []const u8, from: usize, ch: u8) usize { + var i = from + 1; + while (i < text.len and text[i] == ch) i += 1; + return i; +} + +fn atFenceStart(text: []const u8, i: usize) bool { + var s: usize = 0; + while (s < 4 and i > s and text[i - 1 - s] == ' ') s += 1; + return s <= 3 and (i == s or text[i - 1 - s] == '\n'); +} + +fn nlEndsParagraph(text: []const u8, nl: usize, finished: bool) LineEnd { + var q = nl + 1; + while (q < text.len and (text[q] == ' ' or text[q] == '\t' or text[q] == '\r')) q += 1; + if (q == text.len) return if (finished) .no else .wait; + if (text[q] == '\n') return .yes; + var s = nl + 1; + var sp: usize = 0; + while (sp < 4 and s < text.len and text[s] == ' ') : ({ + s += 1; + sp += 1; + }) {} + if (sp <= 3 and s < text.len and (text[s] == '`' or text[s] == '~')) { + const ch = text[s]; + const e = runEnd(text, s, ch); + if (!finished and e == text.len and e - s < 3) return .wait; + if (e - s >= 3) { + var u = e; + while (u < text.len) : (u += 1) { + if (ch == '`' and text[u] == '`') return .no; + if (text[u] == '\n') return .yes; + } + return if (finished) .no else .wait; + } + } + return .no; +} + +test "reply code scanner agrees between one-pass finished and incremental streaming queries" { + var prng: std.Random.DefaultPrng = .init(0x5eedc0de); + const r = prng.random(); + const parts = [_][]const u8{ "`", "``", "```", "~~~", "<", "x", " ", "\n", "\n\n", "a buf.len) break; + @memcpy(buf[len..][0..p.len], p); + len += p.len; + } + const text = buf[0..len]; + var whole_sc: Scanner = .{}; + var stream_sc: Scanner = .{}; + for (0..text.len) |i| { + const ch = text[i]; + if (ch == '`' or ch == '~') continue; + var resolved = false; + var n = i + 1; + while (n <= text.len) : (n += 1) { + const st = stream_sc.check(text[0..n], i, false); + if (st != .pending) { + const whole = whole_sc.check(text, i, true); + switch (st) { + .outside => try std.testing.expectEqual(Status.outside, whole), + .skip => |s| switch (whole) { + .skip => |w| try std.testing.expect(s <= w), + else => return error.TestUnexpectedResult, + }, + .pending => unreachable, + } + resolved = true; + break; + } + } + if (!resolved) { + const st = stream_sc.check(text, i, true); + const whole = whole_sc.check(text, i, true); + try std.testing.expectEqual(whole, st); + } + } + } +} diff --git a/zig/src/server/reply_text.zig b/zig/src/server/reply_text.zig index 6f942d1e4a3..bba2c60a13e 100644 --- a/zig/src/server/reply_text.zig +++ b/zig/src/server/reply_text.zig @@ -201,14 +201,16 @@ pub fn hideToolCalls(a: Allocator, text: []const u8, finished: bool) Allocator.E pub fn hideInto(a: Allocator, out: *std.ArrayList(u8), text: []const u8, finished: bool, defer_closed: bool, o: Openers) Allocator.Error![]const u8 { out.clearRetainingCapacity(); var pos: usize = 0; - var next_buf: [mm_calls.len]?usize = undefined; // each opener at or after `pos`, searched again only once `pos` passes it + var search: usize = 0; + var code: @import("reply_code.zig").Scanner = .{}; + var next_buf: [mm_calls.len]?usize = undefined; // each opener at or after `search`, re-searched when passed const next = next_buf[0..o.calls.len]; for (o.calls, next) |c, *n| n.* = findTag(text, 0, c[0]); while (true) { var start: ?usize = null; var which: usize = 0; for (o.calls, next, 0..) |c, *n, i| { - if (n.* != null and n.*.? < pos) n.* = findTag(text, pos, c[0]); + if (n.* != null and n.*.? < search) n.* = findTag(text, search, c[0]); if (n.*) |at| if (start == null or at < start.?) { start = at; which = i; @@ -217,24 +219,33 @@ pub fn hideInto(a: Allocator, out: *std.ArrayList(u8), text: []const u8, finishe if (start == null) { const tail = text[pos..]; var held: usize = 0; - if (!finished) for (o.calls) |c| { - held = @max(held, partialTag(tail, c[0])); - }; + if (!finished) { + const scan = text[@min(text.len, @max(pos, search))..]; + for (o.calls) |c| held = @max(held, partialTag(scan, c[0])); + } if (pos == 0) return text[0 .. text.len - held]; try out.appendSlice(a, tail[0 .. tail.len - held]); return out.items; } - try out.appendSlice(a, text[pos..start.?]); + const st = code.check(text, start.?, finished); + if (st == .skip) { + search = st.skip; + continue; + } const after = start.? + o.calls[which][0].len; - switch (payloadOf(text[after..], o, which, finished)) { + switch (if (st == .pending) .wait else payloadOf(text[after..], o, which, finished)) { .call => {}, - .wait => return out.items, + .wait => { + if (pos == 0) return text[0..start.?]; + try out.appendSlice(a, text[pos..start.?]); + return out.items; + }, .prose => { - try out.appendSlice(a, text[start.?..after]); - pos = after; + search = after; continue; }, } + try out.appendSlice(a, text[pos..start.?]); const end = findTag(text, after, o.calls[which][1]) orelse { // a finished reply's envelope that never closed is text, as tool_parse.parse keeps it in the content if (finished) try out.appendSlice(a, text[start.?..]); @@ -243,6 +254,8 @@ pub fn hideInto(a: Allocator, out: *std.ArrayList(u8), text: []const u8, finishe // Final parsing may retain this envelope, so later prose must not overtake it. if (defer_closed) return out.items; pos = end + o.calls[which][1].len; + search = pos; + code.jumpTo(pos); } } diff --git a/zig/src/server/reply_tool_tail.zig b/zig/src/server/reply_tool_tail.zig index 8e36a9ee95d..6151e9230ab 100644 --- a/zig/src/server/reply_tool_tail.zig +++ b/zig/src/server/reply_tool_tail.zig @@ -1,9 +1,11 @@ //! The first byte of a suffix made only of whole call envelopes and whitespace. const reply = @import("reply_text.zig"); +const reply_code = @import("reply_code.zig"); pub fn start(text: []const u8, openers: reply.Openers) ?usize { var pos: usize = 0; var tail: ?usize = null; + var code: reply_code.Scanner = .{}; while (true) { var next: ?usize = null; var which: usize = 0; @@ -14,6 +16,11 @@ pub fn start(text: []const u8, openers: reply.Openers) ?usize { } }; const at = next orelse return if (reply.pyStrip(text[pos..]).len == 0) tail else null; + if (code.check(text, at, true) == .skip) { + tail = null; + pos = code.skip_end; + continue; + } const tags = openers.calls[which]; const payload = at + tags[0].len; if (reply.payloadOf(text[payload..], openers, which, true) != .call) { @@ -24,5 +31,6 @@ pub fn start(text: []const u8, openers: reply.Openers) ?usize { const end = reply.findTag(text, payload, tags[1]) orelse return null; if (tail == null or reply.pyStrip(text[pos..at]).len > 0) tail = at; pos = end + tags[1].len; + code.jumpTo(pos); } } diff --git a/zig/src/server/root.zig b/zig/src/server/root.zig index ad27c644f0f..63b39204bbf 100644 --- a/zig/src/server/root.zig +++ b/zig/src/server/root.zig @@ -58,6 +58,7 @@ test { _ = @import("json"); _ = @import("std_options.zig"); _ = @import("fields.zig"); + _ = @import("reply_code.zig"); _ = @import("reply_text.zig"); _ = @import("reply_incremental_test.zig"); _ = @import("tool_parse.zig"); @@ -160,6 +161,7 @@ test { _ = @import("thinking_reserve_test.zig"); _ = @import("loop_stop_test.zig"); _ = @import("late_system_test.zig"); + _ = @import("tool_prose_code_http_test.zig"); _ = @import("compact.zig"); _ = @import("compact_test.zig"); _ = @import("private_files_test.zig"); diff --git a/zig/src/server/server.zig b/zig/src/server/server.zig index 6b7559685f8..7de73011657 100644 --- a/zig/src/server/server.zig +++ b/zig/src/server/server.zig @@ -29,7 +29,6 @@ const idle_unload = @import("idle_unload.zig"); const Value = json.Value; 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 }; @@ -363,6 +362,7 @@ pub const Server = struct { } if (try grammar.spec(cx, f)) |s| { if (!srv.info.capability(.structures)) return cx.refuse("structured output (response_format and the guided_* fields) is not supported by this engine yet"); + if (s.text.len > grammar.max_text) return cx.fail(.request, "{s}: the grammar is {d} bytes, more than the {d} KiB a grammar may be", .{ s.field, s.text.len, grammar.max_text / 1024 }); const st = try srv.compiledStructure(cx, s.kind, s.text, s.field, thinking); if (request.structure) |tool| tool.free(); request.structure = st; diff --git a/zig/src/server/tool_grammar.zig b/zig/src/server/tool_grammar.zig index c2320b86938..2a458e17425 100644 --- a/zig/src/server/tool_grammar.zig +++ b/zig/src/server/tool_grammar.zig @@ -7,6 +7,7 @@ const prompt = @import("prompt.zig"); const tool_specs = @import("tool_specs.zig"); const lfm2 = @import("tool_grammar_lfm2.zig"); const deepseek = @import("tool_grammar_deepseek.zig"); +const max_text = @import("grammar.zig").max_text; const Server = @import("server.zig").Server; const Value = json.Value; const Cx = errors.Cx; @@ -44,7 +45,11 @@ const mm = "]<]minimax[>["; pub fn structure(srv: *Server, cx: *Cx, tools: []const Value, parallel: bool, thinking: bool) errors.Refused!api.Structure { const rendered = try probed(srv, cx); const s = style(rendered) orelse .json; // unrecognized markup uses the canonical call form the parser accepts - const text = if (lfm2.isStyle(rendered, probe, key)) try lfm2.build(cx.a, tools, parallel) else try build(cx.a, s, tools, parallel); + const markup = lfm2.isStyle(rendered, probe, key); + // measured for one call: parallel calls repeat that call's rule, and the limit counts each tool once + const once = if (markup) try lfm2.build(cx.a, tools, false) else try build(cx.a, s, tools, false); + try fits(cx, once); + const text = if (!parallel) once else if (markup) try lfm2.build(cx.a, tools, true) else try build(cx.a, s, tools, true); const reason = try std.fmt.allocPrint(cx.a, "tool_choice \"required\" or a named function on backend '{s}'", .{srv.backendName()}); var st = try srv.compiledStructure(cx, .structural_tag, text, reason, thinking); // The structure names the request's field; the sentence above words the 400. @@ -56,7 +61,10 @@ pub fn structure(srv: *Server, cx: *Cx, tools: []const Value, parallel: bool, th pub fn optionalStructure(srv: *Server, cx: *Cx, tools: []const Value, all: bool, parallel: bool, thinking: bool) errors.Refused!?api.Structure { const rendered = try probed(srv, cx); if (lfm2.isStyle(rendered, probe, key)) return null; // its call list is one grammar rule, not a tag a trigger opens - const text = try optional(cx.a, style(rendered) orelse .json, tools, all, parallel); + const s = style(rendered) orelse .json; + const once = try optional(cx.a, s, tools, all, false); + try fits(cx, once); + const text = if (parallel) try optional(cx.a, s, tools, all, true) else once; const reason = try std.fmt.allocPrint(cx.a, "strict tools under tool_choice \"auto\" on backend '{s}'", .{srv.backendName()}); var st = try srv.compiledStructure(cx, .structural_tag, text, reason, thinking); // The structure names the request's field; the sentence above words the 400. @@ -74,6 +82,11 @@ fn probed(srv: *Server, cx: *Cx) errors.Refused![]const u8 { }; } +/// A 400 before compiling when one call's grammar (each tool's name and schema once) passes grammar.zig's limit. +fn fits(cx: *Cx, once: []const u8) errors.Refused!void { + if (once.len > max_text) return cx.fail(.request, "tools: the tools' names and schemas make a {d}-byte grammar, more than the {d} KiB a grammar may be", .{ once.len, max_text / 1024 }); +} + /// TENSORFOLD_TOOL_GRAMMAR=1 (legacy TF_DSV41_TOOL_GRAMMAR): every auto tools request is held as strict tools are. pub fn autoAllEnv() !bool { if (std.c.getenv("TENSORFOLD_TOOL_GRAMMAR")) |v| return std.mem.eql(u8, std.mem.trim(u8, std.mem.span(v), " "), "1"); diff --git a/zig/src/server/tool_lfm2.zig b/zig/src/server/tool_lfm2.zig index 9ca68a902af..7e99ff068ea 100644 --- a/zig/src/server/tool_lfm2.zig +++ b/zig/src/server/tool_lfm2.zig @@ -21,7 +21,19 @@ pub fn dsml(a: Allocator, text: []const u8, tools: []const Value, finished: bool var pos: usize = 0; var end = text.len; var rewrote = false; + var code: @import("reply_code.zig").Scanner = .{}; while (true) { + switch (code.check(text, at, finished)) { + .skip => |to| { + at = reply_text.findTag(text, to, open) orelse break; + continue; + }, + .pending => { + end = at; + break; + }, + .outside => {}, + } const e = reply_text.findTag(text, at + open.len, close) orelse { if (!finished) { // the stream's parser resumes where it stopped: it must meet the calls so far as DSML end = at; @@ -42,6 +54,7 @@ pub fn dsml(a: Allocator, text: []const u8, tools: []const Value, finished: bool pos = e + close.len; rewrote = true; } + code.jumpTo(e + close.len); at = reply_text.findTag(text, e + close.len, open) orelse break; } if (!rewrote) return text[0..end]; diff --git a/zig/src/server/tool_parse.zig b/zig/src/server/tool_parse.zig index 6d1252dc61f..0ec7795e7fb 100644 --- a/zig/src/server/tool_parse.zig +++ b/zig/src/server/tool_parse.zig @@ -2,6 +2,7 @@ const std = @import("std"); const json = @import("json"); const ids = @import("ids.zig"); +const reply_code = @import("reply_code.zig"); const reply_text = @import("reply_text.zig"); const tool_closers = @import("tool_closers.zig"); const tool_dsml = @import("tool_dsml.zig"); @@ -53,55 +54,49 @@ fn allSpace(s: []const u8) bool { /// (start, end, payload) of each tool-call block in order; a block inside an earlier one is part of it. pub fn envelopes(a: Allocator, text: []const u8) Allocator.Error![]Envelope { - var found: std.ArrayList(Envelope) = .empty; + var kept: std.ArrayList(Envelope) = .empty; var pos: usize = 0; - var dsml = tool_dsml.findOpen(text, 0); // the DSML opener at or after `pos`, searched again only once `pos` passes it - while (findCI(text, "", pos)) |s| { - if (dsml != null and dsml.?.at < pos) dsml = tool_dsml.findOpen(text, pos); - if (dsml) |outer| if (outer.at < s) { - pos = tool_dsml.blockEnd(text, outer) orelse break; - continue; - }; - const e = findCI(text, "", s + 11) orelse break; - try found.append(a, .{ .start = s, .end = e + 12, .payload = strip(text[s + 11 .. e]) }); - pos = e + 12; - } - pos = 0; + var code: reply_code.Scanner = .{}; var closers: tool_closers.Closers = .{ .text = text }; + var no_tc = false; + var no_gemma = false; while (std.mem.indexOfScalarPos(u8, text, pos, '<')) |s| { - pos = s + 1; - var j = s + 1; - if (j >= text.len or !(std.ascii.isAlphabetic(text[j]) or text[j] == '_')) continue; - j += 1; - while (j < text.len and tool_closers.nameByte(text[j])) j += 1; - if (!std.ascii.startsWithIgnoreCase(text[j..], ":tool_call>")) continue; - const e = (try closers.next(a, text[s + 1 .. j], j + 11)) orelse continue; - const end = e + j - s + 12; // ```` - try found.append(a, .{ .start = s, .end = end, .payload = strip(text[j + 11 .. e]) }); - pos = end; - } - pos = 0; - while (find(text, "<|tool_call>", pos)) |s| { - const e = find(text, "", s + 12) orelse break; - try found.append(a, .{ .start = s, .end = e + 12, .payload = strip(text[s + 12 .. e]) }); - pos = e + 12; - } - pos = 0; - while (tool_dsml.findOpen(text, pos)) |o| { - const e = tool_dsml.blockEnd(text, o); - const end = e orelse text.len; - try found.append(a, .{ .start = o.at, .end = end, .payload = text[o.at..end], .complete = e != null }); - pos = end; - } - std.mem.sort(Envelope, found.items, {}, struct { - fn less(_: void, x: Envelope, y: Envelope) bool { - if (x.start != y.start) return x.start < y.start; - if (x.end != y.end) return x.end < y.end; - return std.mem.order(u8, x.payload, y.payload) == .lt; + if (code.check(text, s, true) == .skip) { + pos = code.skip_end; + continue; } - }.less); - var kept: std.ArrayList(Envelope) = .empty; - for (found.items) |env| if (kept.items.len == 0 or env.start >= kept.items[kept.items.len - 1].end) try kept.append(a, env); + const env: ?Envelope = blk: { + if (tool_dsml.openedBy(text[s..])) |sp| { + const e = tool_dsml.blockEnd(text, .{ .at = s, .spelling = sp }); + const end = e orelse text.len; + break :blk .{ .start = s, .end = end, .payload = text[s..end], .complete = e != null }; + } + if (!no_tc and std.ascii.startsWithIgnoreCase(text[s..], "")) { + if (findCI(text, "", s + 11)) |e| { + break :blk .{ .start = s, .end = e + 12, .payload = strip(text[s + 11 .. e]) }; + } + no_tc = true; + } + if (!no_gemma and std.mem.startsWith(u8, text[s..], "<|tool_call>")) { + if (find(text, "", s + 12)) |e| { + break :blk .{ .start = s, .end = e + 12, .payload = strip(text[s + 12 .. e]) }; + } + no_gemma = true; + } + var j = s + 1; + if (j >= text.len or !(std.ascii.isAlphabetic(text[j]) or text[j] == '_')) break :blk null; + j += 1; + while (j < text.len and tool_closers.nameByte(text[j])) j += 1; + if (!std.ascii.startsWithIgnoreCase(text[j..], ":tool_call>")) break :blk null; + const e = (try closers.next(a, text[s + 1 .. j], j + 11)) orelse break :blk null; + break :blk .{ .start = s, .end = e + j - s + 12, .payload = strip(text[j + 11 .. e]) }; + }; + if (env) |item| { + try kept.append(a, item); + pos = item.end; + code.jumpTo(pos); + } else pos = s + 1; + } return kept.items; } @@ -205,14 +200,25 @@ pub fn closeCall(a: Allocator, text: []const u8, tools: []const Value) Allocator /// Where the reply's open call starts: the opener ``envelopes`` leaves without a closer, so one appended pairs with it. pub fn openCall(text: []const u8) ?usize { var pos: usize = 0; + var code: reply_code.Scanner = .{}; var dsml = tool_dsml.findOpen(text, 0); // as in ``envelopes`` return while (findCI(text, "", pos)) |s| { if (dsml != null and dsml.?.at < pos) dsml = tool_dsml.findOpen(text, pos); if (dsml) |outer| if (outer.at < s) { + if (code.check(text, outer.at, true) == .skip) { + pos = code.skip_end; + continue; + } pos = tool_dsml.blockEnd(text, outer) orelse return null; + code.jumpTo(pos); continue; }; + if (code.check(text, s, true) == .skip) { + pos = code.skip_end; + continue; + } pos = (findCI(text, "", s + 11) orelse break s) + 12; + code.jumpTo(pos); } else null; } diff --git a/zig/src/server/tool_parse_visibility_test.zig b/zig/src/server/tool_parse_visibility_test.zig index 40e8da2c90e..b54fe08c275 100644 --- a/zig/src/server/tool_parse_visibility_test.zig +++ b/zig/src/server/tool_parse_visibility_test.zig @@ -1,7 +1,35 @@ //! Rejected tool envelopes stay visible without consuming the accepted-call limit. const std = @import("std"); const json = @import("json"); -const parse = @import("tool_parse.zig").parse; +const tp = @import("tool_parse.zig"); +const rc = @import("reply_code.zig"); +const rt = @import("reply_text.zig"); + +test { + _ = rc; +} +const tail_mod = @import("reply_tool_tail.zig"); +const lfm2 = @import("tool_lfm2.zig"); +const stream = @import("tool_stream.zig"); +const parse = tp.parse; + +fn testTools(a: std.mem.Allocator) ![]const json.Value { + return (try json.parse(a, "[{\"type\":\"function\",\"function\":{\"name\":\"lookup\"}}]")).ok.array; +} + +fn streamedArgs(a: std.mem.Allocator, tools: []const json.Value, text: []const u8, split: usize) !struct { headers: usize, args: []const u8 } { + var s = try stream.Streamer.init(a, tools); + var out: std.ArrayList(json.Value) = .empty; + try s.feed(text[0..split], &out); + try s.finishCut(text, &out); + var headers: usize = 0; + var args: std.ArrayList(u8) = .empty; + for (out.items) |delta| for (delta.get("tool_calls").?.array) |one| { + if (one.get("id") != null) headers += 1; + if (one.get("function").?.strField("arguments")) |part| try args.appendSlice(a, part); + }; + return .{ .headers = headers, .args = args.items }; +} test "tool visibility: a first unoffered call remains content in single-call mode" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); @@ -34,3 +62,122 @@ test "tool visibility: rejected text does not consume a valid call and the secon try std.testing.expectEqual(@as(usize, 1), result.calls.?.len); try std.testing.expectEqualStrings("execute", result.calls.?[0].get("function").?.get("name").?.string); } + +test "quoted openers in inline code or fenced blocks do not swallow a following call" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const tools = try testTools(a); + const call = "lookupqok"; + const cases = [_]struct { reply: []const u8, content: []const u8 }{ + .{ .reply = "Raw `` markup before call.\n" ++ call, .content = "Raw `` markup before call." }, + .{ .reply = "Doubled `` `` `` markup.\n" ++ call, .content = "Doubled `` `` `` markup." }, + .{ .reply = "Fenced:\n```xml\n\n```\n" ++ call, .content = "Fenced:\n```xml\n\n```" }, + .{ .reply = "Tilde:\n~~~\n<|tool_call>call:lookup{}\n~~~\n" ++ call, .content = "Tilde:\n~~~\n<|tool_call>call:lookup{}\n~~~" }, + .{ .reply = "Note `<|DSML|tool_calls><|DSML|invoke name=\"lookup\">` first.\n" ++ call, .content = "Note `<|DSML|tool_calls><|DSML|invoke name=\"lookup\">` first." }, + }; + for (cases) |c| { + const res = try parse(a, c.reply, tools, null); + try std.testing.expectEqual(@as(usize, 0), res.rejected_envelopes); + try std.testing.expectEqualStrings(c.content, res.content); + try std.testing.expectEqual(@as(usize, 1), res.calls.?.len); + try std.testing.expectEqualStrings("{\"q\":\"ok\"}", res.calls.?[0].get("function").?.get("arguments").?.string); + } + // An unclosed fence inside a real call's value stays part of that call and must not suppress the next call. + const nested = "lookupq```md\n\n\n" ++ call; + const nested_res = try parse(a, nested, tools, null); + try std.testing.expectEqual(@as(usize, 2), nested_res.calls.?.len); + try std.testing.expectEqualStrings("{\"q\":\"```md\\n\\n\"}", nested_res.calls.?[0].get("function").?.get("arguments").?.string); + try std.testing.expectEqualStrings("{\"q\":\"ok\"}", nested_res.calls.?[1].get("function").?.get("arguments").?.string); + const cut = "Raw `` and `<|DSML|tool_calls>` before:\nlookupqok"; + try std.testing.expectEqualStrings("", try tp.closeCall(a, cut, tools)); + const quoted_lfm = "Note `<|tool_call_start|>[lookup(q=\"x\")]<|tool_call_end|>` prose."; + try std.testing.expectEqualStrings(quoted_lfm, try lfm2.dsml(a, quoted_lfm, tools, true)); +} + +test "streamed quoted GLM opener naming an offered tool stays prose at every byte boundary" { + const text = "The tag `lookupbad` broke; running:\n" ++ + "lookupqok"; + const want_prose = "The tag `lookupbad` broke; running:\n"; + var outer = std.heap.ArenaAllocator.init(std.testing.allocator); + defer outer.deinit(); + const whole = try rt.hideToolCalls(outer.allocator(), text, true); + try std.testing.expectEqualStrings(want_prose, whole); + for (0..text.len + 1) |b| { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const tools = try testTools(a); + const partial = try rt.hideToolCalls(a, text[0..b], false); + try std.testing.expect(std.mem.startsWith(u8, whole, partial)); + const got = try streamedArgs(a, tools, text, b); + try std.testing.expectEqual(@as(usize, 1), got.headers); + try std.testing.expectEqualStrings("{\"q\":\"ok\"}", got.args); + } +} + +test "complete calls inside inline code or fenced blocks stay prose whole and streamed" { + const cases = [_][]const u8{ + "Use `lookupqx` here.", + "Example:\n```xml\nlookupqx\n```\nDone.", + "Example:\n~~~\n{\"name\":\"lookup\",\"arguments\":{\"q\":\"x\"}}\n~~~", + "Gemma form: `<|tool_call>call:lookup{q:<|\"|>x<|\"|>}`.", + "LFM form: `<|tool_call_start|>[lookup(q=\"x\")]<|tool_call_end|>`.", + }; + const single: stream.Policy = .{ .single = true }; + for (cases) |text| { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const tools = try testTools(a); + const res = try parse(a, text, tools, null); + try std.testing.expect(res.calls == null); + try std.testing.expectEqual(@as(usize, 0), res.rejected_envelopes); + try std.testing.expectEqualStrings(text, res.content); + try std.testing.expectEqualStrings(text, try rt.hideToolCalls(a, text, true)); + try std.testing.expectEqualStrings(text, try rt.finishedProse(a, text)); + try std.testing.expectEqualStrings(text, try single.parsedContent(a, text)); + for (0..text.len + 1) |b| { + const partial = try rt.hideToolCalls(a, text[0..b], false); + try std.testing.expect(std.mem.startsWith(u8, text, partial)); + } + } + const tail = "Thought.\n```xml\nlookupqx\n```"; + try std.testing.expect(tail_mod.start(tail, rt.shared_openers) == null); +} + +test "single-call TextFilter keeps unclosed quoted openers and stray backtick does not block later call" { + const prose = "Prose quotes `` and `` and `` and keeps going."; + var outer = std.heap.ArenaAllocator.init(std.testing.allocator); + defer outer.deinit(); + const oa = outer.allocator(); + var f: stream.TextFilter = .{}; + var joined: std.ArrayList(u8) = .empty; + for (0..prose.len) |i| try joined.appendSlice(oa, try f.feed(oa, prose[i .. i + 1])); + try joined.appendSlice(oa, f.finish()); + try std.testing.expectEqualStrings(prose, joined.items); + const single: stream.Policy = .{ .single = true }; + try std.testing.expectEqualStrings(prose, try single.parsedContent(oa, prose)); + const stray_cases = [_]struct { reply: []const u8, prose: []const u8 }{ + .{ .reply = "Format is `lookupqok", .prose = "Format is `" }, + .{ .reply = "Format is `\n\nlookupqok", .prose = "Format is `\n\n" }, + }; + for (stray_cases) |c| { + const tools = try testTools(oa); + const res = try parse(oa, c.reply, tools, null); + try std.testing.expectEqual(@as(usize, 1), res.calls.?.len); + try std.testing.expectEqualStrings(std.mem.trimEnd(u8, c.prose, "\n"), res.content); + try std.testing.expectEqualStrings(c.prose, try rt.hideToolCalls(oa, c.reply, true)); + for (0..c.reply.len + 1) |b| { + var run = std.heap.ArenaAllocator.init(std.testing.allocator); + defer run.deinit(); + const ra = run.allocator(); + const rtools = try testTools(ra); + const partial = try rt.hideToolCalls(ra, c.reply[0..b], false); + try std.testing.expect(std.mem.startsWith(u8, c.prose, partial)); + const got = try streamedArgs(ra, rtools, c.reply, b); + try std.testing.expectEqual(@as(usize, 1), got.headers); + try std.testing.expectEqualStrings("{\"q\":\"ok\"}", got.args); + } + } +} diff --git a/zig/src/server/tool_policy.zig b/zig/src/server/tool_policy.zig new file mode 100644 index 00000000000..774cbc2569a --- /dev/null +++ b/zig/src/server/tool_policy.zig @@ -0,0 +1,181 @@ +//! Single-call tool policy and streamed prose tag filter (parallel_tool_calls: false). +const std = @import("std"); +const reply_code = @import("reply_code.zig"); +const reply_text = @import("reply_text.zig"); +const Allocator = std.mem.Allocator; + +fn nameLike(s: []const u8) bool { + if (s.len == 0 or !(std.ascii.isAlphabetic(s[0]) or s[0] == '_')) return false; + for (s[1..]) |ch| if (!(std.ascii.isAlphanumeric(ch) or ch == '_' or ch == '.' or ch == '-' or ch >= 0x80)) return false; + return true; +} + +/// ``(?:NAME:)?tool_call``, any case. +pub fn callTag(name: []const u8) bool { + if (std.ascii.eqlIgnoreCase(name, "tool_call")) return true; + const colon = std.mem.indexOfScalar(u8, name, ':') orelse return false; + return nameLike(name[0..colon]) and std.ascii.eqlIgnoreCase(name[colon + 1 ..], "tool_call"); +} + +/// Hides tool envelopes from streamed prose, holding only a partial tag or open code span between deltas. +pub const TextFilter = struct { + buf: std.ArrayList(u8) = .empty, + sent: usize = 0, + scan: usize = 0, + hidden: ?[2]usize = null, + hidden_from: usize = 0, + deferred: bool = false, // a closed envelope was hidden: later prose waits for the reply's final content + code: reply_code.Scanner = .{}, + + pub fn feed(f: *TextFilter, a: Allocator, text: []const u8) Allocator.Error![]const u8 { + if (f.deferred) return ""; + try f.buf.appendSlice(a, text); + return f.step(false); + } + + pub fn finish(f: *TextFilter) []const u8 { + const tail = if (f.hidden != null or f.deferred) "" else f.step(true); + f.buf = .empty; + return tail; + } + + fn step(f: *TextFilter, finished: bool) []const u8 { + const b = f.buf.items; + const emit_start = f.sent; + if (f.hidden) |tag| { + f.matchCloser(b, tag); + return b[emit_start..f.sent]; + } + while (std.mem.indexOfScalarPos(u8, b, f.scan, '<')) |start| { + switch (f.code.check(b, start, finished)) { + .skip => |to| { + f.sent = @min(to, b.len); + f.scan = f.sent; + continue; + }, + .pending => { + f.sent = start; + f.scan = start; + return b[emit_start..f.sent]; + }, + .outside => {}, + } + const rest = b[start..]; + const end = std.mem.indexOfScalar(u8, rest, '>') orelse { + if (!finished) { + const name = rest[1..]; + const colon = std.mem.indexOfScalar(u8, name, ':'); + const possible = name.len == 0 or nameLike(name) or (colon != null and nameLike(name[0..colon.?]) and + std.ascii.startsWithIgnoreCase("tool_call", name[colon.? + 1 ..])); + if (possible) { + f.sent = start; + f.scan = start; + return b[emit_start..f.sent]; + } + } + f.sent = start + 1; + f.scan = start + 1; + continue; + }; + if (callTag(rest[1..end])) { + f.sent = start; + f.hidden = .{ start + 1, start + end }; + f.hidden_from = start + end + 1; + f.matchCloser(b, f.hidden.?); + return b[emit_start..f.sent]; + } + f.sent = start + 1; + f.scan = start + 1; + } + f.sent = b.len; + f.scan = b.len; + return b[emit_start..f.sent]; + } + + fn matchCloser(f: *TextFilter, b: []const u8, tag: [2]usize) void { + const name = b[tag[0]..tag[1]]; + var at = f.hidden_from; + while (std.mem.indexOfScalarPos(u8, b, at, '<')) |i| { + if (i + 3 + name.len > b.len) { + f.hidden_from = i; + return; + } + if (b[i + 1] == '/' and std.ascii.eqlIgnoreCase(b[i + 2 .. i + 2 + name.len], name) and b[i + 2 + name.len] == '>') { + f.hidden = null; + f.deferred = true; + return; + } + at = i + 1; + } + f.hidden_from = b.len; + } +}; + +/// ``parallel_tool_calls: false`` keeps one call and hides call markup from streamed prose. +pub const Policy = struct { + single: bool = false, + filter: TextFilter = .{}, + + pub fn maxCalls(p: *const Policy) ?usize { + return if (p.single) 1 else null; + } + + /// Filters a str delta's text (dict deltas lose tool_calls and filter content), or passes it through. + pub fn text(p: *Policy, a: Allocator, s: []const u8) Allocator.Error![]const u8 { + return if (p.single) p.filter.feed(a, s) else s; + } + + pub fn flush(p: *Policy) []const u8 { + return if (p.single) p.filter.finish() else ""; + } + + pub fn content(p: *const Policy, a: Allocator, s: []const u8) Allocator.Error![]const u8 { + if (!p.single) return s; + var f: TextFilter = .{}; + const head = try f.feed(a, s); + return std.mem.concat(a, u8, &.{ head, f.finish() }); + } + + /// parsed_content: parsed reply content; whole envelopes left as text kept, rest filtered; unclosed stays hidden. + pub fn parsedContent(p: *const Policy, a: Allocator, s: []const u8) Allocator.Error![]const u8 { + if (!p.single) return s; + var out: std.ArrayList(u8) = .empty; + var cursor: usize = 0; + var code: reply_code.Scanner = .{}; + while (try wholeEnvelope(a, s, cursor, &code)) |e| : (cursor = e.end) { + try out.appendSlice(a, try p.content(a, s[cursor..e.start])); + try out.appendSlice(a, s[e.start..e.end]); + } + try out.appendSlice(a, try p.content(a, s[cursor..])); + return out.items; + } + + /// Held-back malformed or unoffered call envelopes kept as reply text: ``final`` past the prose ``sent``. + pub fn kept(p: *const Policy, final: []const u8, sent: []const u8) ?[]const u8 { + // Replies without parsed calls retain their leading whitespace; parsed content may be stripped. + const shown = if (std.mem.startsWith(u8, final, sent)) sent else reply_text.pyLstrip(sent); + if (!std.mem.startsWith(u8, final, shown)) return null; + const rest = final[shown.len..]; + if (p.single) return if (rest.len > 0) rest else null; + return if (reply_text.pyStrip(rest).len > 0) rest else null; + } +}; + +/// The first whole envelope from ``from`` (``<((?:NAME:)?tool_call)>.*?``, any case). +fn wholeEnvelope(a: Allocator, s: []const u8, from: usize, code: *reply_code.Scanner) Allocator.Error!?struct { start: usize, end: usize } { + var at = from; + while (std.mem.indexOfScalarPos(u8, s, at, '<')) |start| { + if (code.check(s, start, true) == .skip) { + at = code.skip_end; + continue; + } + at = start + 1; + const close = std.mem.indexOfScalarPos(u8, s, start, '>') orelse return null; + if (!callTag(s[start + 1 .. close])) continue; + const closer = try std.mem.concat(a, u8, &.{ "" }); + const end = std.ascii.findIgnoreCasePos(s, close + 1, closer) orelse continue; + code.jumpTo(end + closer.len); + return .{ .start = start, .end = end + closer.len }; + } + return null; +} diff --git a/zig/src/server/tool_prose_code_http_test.zig b/zig/src/server/tool_prose_code_http_test.zig new file mode 100644 index 00000000000..d5331b29e17 --- /dev/null +++ b/zig/src/server/tool_prose_code_http_test.zig @@ -0,0 +1,233 @@ +//! Quoted tool markup in Markdown inline code spans and fenced code blocks stays prose over HTTP and SSE. +const std = @import("std"); +const api = @import("engine_api"); +const server = @import("root.zig"); +const json = server.json; +const openai = @import("openai.zig"); +const pre = @import("stream_preflight_test.zig"); +const Conn = @import("http_conn.zig").Conn; +const Allocator = std.mem.Allocator; + +const Got = struct { + opened: bool = false, + status: ?u16 = null, + calls: usize = 0, + has_kept: bool = false, + content: std.ArrayList(u8) = .empty, + arguments: std.ArrayList(u8) = .empty, + finish: [16]u8 = undefined, + finish_len: usize = 0, + + fn deinit(g: *Got) void { + g.content.deinit(std.testing.allocator); + g.arguments.deinit(std.testing.allocator); + } + + fn reason(g: *const Got) []const u8 { + return g.finish[0..g.finish_len]; + } + + fn keepFinish(g: *Got, choice: json.Value) void { + const f = choice.strField("finish_reason") orelse return; + g.finish_len = @min(f.len, g.finish.len); + @memcpy(g.finish[0..g.finish_len], f[0..g.finish_len]); + } + + fn keepCall(g: *Got, call: json.Value) error{Closed}!void { + const f = call.get("function") orelse return; + const args = f.strField("arguments") orelse return; + g.arguments.appendSlice(std.testing.allocator, args) catch return error.Closed; + } + + fn out(g: *Got) openai.Out { + return .{ .ctx = g, .vt = &.{ .open = open, .event = event, .reply = reply } }; + } + + fn open(ctx: *anyopaque, _: usize) error{Closed}!void { + const g: *Got = @ptrCast(@alignCast(ctx)); + g.opened = true; + } + + fn event(ctx: *anyopaque, payload: ?json.Value) error{Closed}!void { + const g: *Got = @ptrCast(@alignCast(ctx)); + const p = payload orelse return; + if (p.get("tensorfold")) |tf| if (tf.get("kept_tool_calls") != null) { + g.has_kept = true; + }; + const choices = p.get("choices") orelse return; + if (choices != .array or choices.array.len == 0) return; + const choice = choices.array[0]; + g.keepFinish(choice); + const delta = choice.get("delta") orelse return; + if (delta.get("content")) |t| if (t == .string) { + g.content.appendSlice(std.testing.allocator, t.string) catch return error.Closed; + }; + if (delta.get("tool_calls")) |t| if (t == .array) for (t.array) |call| { + if (call.get("id") != null) g.calls += 1; + try g.keepCall(call); + }; + } + + fn reply(ctx: *anyopaque, status: u16, payload: json.Value) void { + const g: *Got = @ptrCast(@alignCast(ctx)); + g.status = status; + if (payload.get("tensorfold")) |tf| if (tf.get("kept_tool_calls") != null) { + g.has_kept = true; + }; + const choices = payload.get("choices") orelse return; + if (choices != .array or choices.array.len == 0) return; + const choice = choices.array[0]; + g.keepFinish(choice); + const message = choice.get("message") orelse return; + if (message.get("content")) |t| if (t == .string) g.content.appendSlice(std.testing.allocator, t.string) catch {}; + if (message.get("tool_calls")) |t| if (t == .array) { + g.calls += t.array.len; + for (t.array) |call| g.keepCall(call) catch {}; + }; + } +}; + +fn send(engine: api.Engine, body: []const u8) !Got { + var text: pre.TestText = .{}; + var srv = try server.Server.init(std.testing.allocator, std.testing.io, engine, text.text(), .{ + .served_name = "test-model", + .model_ids = &.{"test-model"}, + .enable_thinking = false, + .use_drafts = false, + }, null); + defer srv.deinit(); + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const raw = (try json.parse(a, body)).ok; + var conn: Conn = .{ .fd = -1, .peer = "", .buf = &.{}, .gpa = a }; + var got: Got = .{}; + errdefer got.deinit(); + openai.run(srv, a, got.out(), .{ .conn = &conn }, true, raw); + return got; +} + +const head = "{\"model\":\"test-model\",\"messages\":[{\"role\":\"user\",\"content\":\"x\"}]," ++ + "\"tools\":[{\"type\":\"function\",\"function\":{\"name\":\"lookup\",\"parameters\":{\"type\":\"object\"," ++ + "\"properties\":{\"q\":{\"type\":\"string\"}}}}}]"; + +const Case = struct { + reply: []const u8, + cut: ?usize = null, + content: []const u8, + calls: usize = 0, + arguments: []const u8 = "", + finish: []const u8 = "stop", +}; + +fn expectAgreesSingle(a: Allocator, single: bool, c: Case) !void { + const tokens = try pre.TestText.encode(undefined, a, c.reply, false); + const body = try std.fmt.allocPrint(a, "{s}{s},\"max_tokens\":{d}", .{ head, if (single) ",\"parallel_tool_calls\":false" else "", c.cut orelse 2000 }); + for ([_]bool{ false, true }) |batched| { + var backend: pre.CallEngine = .{ .tokens = tokens, .batched = batched }; + var whole = try send(backend.engine(), try std.mem.concat(a, u8, &.{ body, ",\"stream\":false}" })); + defer whole.deinit(); + var streamed = try send(backend.engine(), try std.mem.concat(a, u8, &.{ body, ",\"stream\":true}" })); + defer streamed.deinit(); + try std.testing.expectEqual(@as(?u16, 200), whole.status); + try std.testing.expect(streamed.opened and streamed.status == null); + try std.testing.expect(!whole.has_kept); + try std.testing.expect(!streamed.has_kept); + try std.testing.expectEqualStrings(c.content, whole.content.items); + try std.testing.expectEqual(c.calls, whole.calls); + try std.testing.expectEqualStrings(c.arguments, whole.arguments.items); + try std.testing.expectEqualStrings(c.finish, whole.reason()); + try std.testing.expectEqualStrings(whole.content.items, streamed.content.items); + try std.testing.expectEqual(whole.calls, streamed.calls); + try std.testing.expectEqualStrings(whole.arguments.items, streamed.arguments.items); + try std.testing.expectEqualStrings(whole.reason(), streamed.reason()); + } +} + +fn expectAgrees(a: Allocator, c: Case) !void { + try expectAgreesSingle(a, false, c); + try expectAgreesSingle(a, true, c); +} + +test "tool visibility HTTP: backticked tool openers before a real GLM or XML call stream prose and emit only the real call" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const glm = "lookupqok"; + const xml = "\n\n\nok\n\n\n"; + try expectAgrees(a, .{ + .reply = "Raw `` XML leaking into output.\n" ++ glm, + .content = "Raw `` XML leaking into output.", + .calls = 1, + .arguments = "{\"q\":\"ok\"}", + .finish = "tool_calls", + }); + try expectAgrees(a, .{ + .reply = "The tag `lookupx` broke args.\n" ++ glm, + .content = "The tag `lookupx` broke args.", + .calls = 1, + .arguments = "{\"q\":\"ok\"}", + .finish = "tool_calls", + }); + try expectAgrees(a, .{ + .reply = "Quoting `` before:\n" ++ xml, + .content = "Quoting `` before:", + .calls = 1, + .arguments = "{\"q\":\"ok\"}", + .finish = "tool_calls", + }); +} + +test "tool visibility HTTP: complete tool calls inside inline code or fenced blocks stay prose with stop finish" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const quoted = "Use `lookupqx` here."; + try expectAgrees(a, .{ .reply = quoted, .content = quoted }); + const fenced = "Example:\n```xml\nlookupqx\n```\nDone."; + try expectAgrees(a, .{ .reply = fenced, .content = fenced }); + const real = "lookupqreal"; + try expectAgrees(a, .{ + .reply = fenced ++ "\n" ++ real, + .content = fenced, + .calls = 1, + .arguments = "{\"q\":\"real\"}", + .finish = "tool_calls", + }); +} + +test "tool visibility HTTP: an unmatched backtick before a real call agrees whole and streamed" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const glm = "lookupqok"; + try expectAgrees(a, .{ + .reply = "DeepSeek's format is `" ++ glm, + .content = "DeepSeek's format is `", + .calls = 1, + .arguments = "{\"q\":\"ok\"}", + .finish = "tool_calls", + }); + try expectAgrees(a, .{ + .reply = "DeepSeek's format is `\n\n" ++ glm, + .content = "DeepSeek's format is `", + .calls = 1, + .arguments = "{\"q\":\"ok\"}", + .finish = "tool_calls", + }); + const cut_reply = "Prose with `` then\nlookupqok"; + try expectAgreesSingle(a, false, .{ + .reply = cut_reply ++ " more", + .cut = cut_reply.len, + .content = "Prose with `` then", + .calls = 1, + .arguments = "{\"q\":\"ok", + .finish = "length", + }); + try expectAgreesSingle(a, true, .{ + .reply = cut_reply ++ " more", + .cut = cut_reply.len, + .content = "Prose with `` then\n", + .finish = "length", + }); +} diff --git a/zig/src/server/tool_required_test.zig b/zig/src/server/tool_required_test.zig index 3e3f22d9cba..e073e61639f 100644 --- a/zig/src/server/tool_required_test.zig +++ b/zig/src/server/tool_required_test.zig @@ -363,6 +363,41 @@ test "a request's compiled grammar is kept for the engine, freed once at release try std.testing.expectEqual(@as(usize, 4), fake.frees); } +test "security: a grammar over the size limit is refused before the compiler sees it, and one at the limit compiles" { + var arena = std.heap.ArenaAllocator.init(a); + defer arena.deinit(); + const g = arena.allocator(); + const fake = lanes.grammar_fake; + const old = fake.install(); + defer _ = lanes.grammar.swapLibrary(old); + var compiler = fake.compiler(); + var text: Text = .{}; + var stub: Stub = .{}; + const srv = try Server.init(a, std.testing.io, stub.engine(), text.text(), .{ .served_name = "m", .model_ids = &.{"m"} }, null); + defer srv.deinit(); + srv.info.structures = true; + srv.grammars = &compiler; + const most = @import("grammar.zig").max_text; + const letters = try g.alloc(u8, most + 1); + @memset(letters, 'x'); + for ([_]usize{ most, most + 1 }) |len| { + var cx: errors.Cx = .{ .a = g }; + var request: api.Request = .{ .prompt = &.{1}, .max_tokens = 64 }; + const fields = try value(g, try std.fmt.allocPrint(g, "{{\"guided_regex\":\"{s}\"}}", .{letters[0..len]})); + const result = srv.checkFeatures(&cx, fields, false, false, &.{1}, &.{}, &request); + if (len <= most) { + try result; + srv.release(false, request); + continue; + } + try std.testing.expectError(error.Refused, result); + try std.testing.expectEqual(@as(u16, 400), cx.status()); + try std.testing.expect(std.mem.indexOf(u8, cx.message, "guided_regex: the grammar is 524289 bytes, more than the 512 KiB") != null); + } + try std.testing.expectEqual(@as(usize, 1), fake.compiles); // the grammar over the limit never reached the compiler + try std.testing.expectEqual(@as(usize, 1), fake.frees); +} + fn never(_: *anyopaque) callconv(.c) c_int { return 0; } @@ -371,6 +406,52 @@ fn overWork(_: *anyopaque) callconv(.c) c_int { return 2; } +test "security: tools count once against the grammar size limit: 300 KiB of required tools is served, 600 KiB refused" { + var arena = std.heap.ArenaAllocator.init(a); + defer arena.deinit(); + const g = arena.allocator(); + const fake = lanes.grammar_fake; + const old = fake.install(); + defer _ = lanes.grammar.swapLibrary(old); + var compiler = fake.compiler(); + var text: Text = .{}; + var stub: Stub = .{}; + const srv = try Server.init(a, std.testing.io, stub.engine(), text.text(), .{ .served_name = "m", .model_ids = &.{"m"} }, null); + defer srv.deinit(); + srv.info.structures = true; + srv.grammars = &compiler; + const filler = try g.alloc(u8, 600 * 1024); + @memset(filler, 'x'); + const schema = "[{{\"type\":\"function\",\"function\":{{\"name\":\"lookup\",\"parameters\":{{\"type\":\"object\",\"properties\":{{\"q\":{{\"type\":\"string\",\"description\":\"{s}\"}}}},\"required\":[\"q\"]}}}}}}]"; + const named = "[{{\"type\":\"function\",\"function\":{{\"name\":\"{s}\",\"parameters\":{{\"type\":\"object\",\"properties\":{{}}}}}}}}]"; + // a long description, then a long name: the grammar holds both, so both count + const cases = [_]struct { kib: usize, list: []const u8 }{ + .{ .kib = 300, .list = try std.fmt.allocPrint(g, schema, .{filler[0 .. 300 * 1024]}) }, + .{ .kib = 600, .list = try std.fmt.allocPrint(g, schema, .{filler[0 .. 600 * 1024]}) }, + .{ .kib = 600, .list = try std.fmt.allocPrint(g, named, .{filler[0 .. 600 * 1024]}) }, + }; + for (cases) |case| { + const offered = (try value(g, case.list)).array; + const before = fake.compiles; + var cx: errors.Cx = .{ .a = g }; + var request: api.Request = .{ .prompt = &.{1}, .max_tokens = 64 }; + // parallel calls: the structural tag holds the call twice, for the first call and the further ones + const result = srv.checkFeatures(&cx, try value(g, "{\"tool_call_required\":true}"), true, false, &.{1}, offered, &request); + if (case.kib == 300) { + try result; + try std.testing.expect(request.structure.?.text.len > 2 * 300 * 1024); // over 512 KiB, and served + try std.testing.expectEqual(before + 1, fake.compiles); + srv.release(false, request); + continue; + } + try std.testing.expectError(error.Refused, result); + try std.testing.expectEqual(@as(u16, 400), cx.status()); + try std.testing.expect(std.mem.startsWith(u8, cx.message, "tools: the tools' names and schemas make a ")); + try std.testing.expect(std.mem.endsWith(u8, cx.message, "-byte grammar, more than the 512 KiB a grammar may be")); + try std.testing.expectEqual(before, fake.compiles); // refused before the compiler saw it + } +} + test "grammar_budget: a boolean that marks a covered grammar, refused when malformed, unbuilt or not covered" { var arena = std.heap.ArenaAllocator.init(a); defer arena.deinit(); diff --git a/zig/src/server/tool_stream.zig b/zig/src/server/tool_stream.zig index 76bad230b94..47b118c4dc2 100644 --- a/zig/src/server/tool_stream.zig +++ b/zig/src/server/tool_stream.zig @@ -1,7 +1,8 @@ -//! Tool calls while they are written: XML calls as argument deltas, and the one-call policy's text filter. +//! Tool calls while they are written: XML, GLM and DSML calls as argument deltas. const std = @import("std"); const json = @import("json"); const ids = @import("ids.zig"); +const reply_code = @import("reply_code.zig"); const reply_text = @import("reply_text.zig"); const tool_dsml = @import("tool_dsml.zig"); const tool_dsml_stream = @import("tool_dsml_stream.zig"); @@ -9,11 +10,15 @@ const tool_glm_cut = @import("tool_glm_cut.zig"); const tool_json_cut = @import("tool_json_cut.zig"); const tool_glm_stream = @import("tool_glm_stream.zig"); const tool_params = @import("tool_params.zig"); +const tool_policy = @import("tool_policy.zig"); const tool_specs = @import("tool_specs.zig"); const tool_parse = @import("tool_parse.zig"); const Value = json.Value; const Allocator = std.mem.Allocator; +pub const TextFilter = tool_policy.TextFilter; +pub const Policy = tool_policy.Policy; + const space = reply_text.isSpaceByte; /// ``\s*\n]+)>\n?`` at the start of ``rest``: the name and the bytes matched. @@ -64,6 +69,8 @@ pub const Streamer = struct { buffered_close: []const u8 = "", glm: tool_glm_stream.Glm = .{}, dsml: tool_dsml_stream.Dsml = .{}, + code: reply_code.Scanner = .{}, + finished: bool = false, pub fn init(a: Allocator, tools: []const Value) Allocator.Error!Streamer { var s: Streamer = .{ .a = a, .schemas = try tool_params.schemas(a, tools), .tools = tools }; @@ -148,10 +155,22 @@ pub const Streamer = struct { const parsed = try tool_parse.parse(s.a, text[start..s.pos], s.tools, null); if (parsed.calls) |calls| try s.emitCalls(calls, out); } + s.code.jumpTo(s.pos); if (text.len < s.searched) s.searched = s.pos; - const from = @min(text.len, @max(s.pos, s.searched -| (tool_dsml.open_max - 1))); + const from = @min(text.len, @max(@max(s.pos, s.code.skip_end), s.searched -| (tool_dsml.open_max - 1))); var at = from; while (std.mem.indexOfScalarPos(u8, text, at, '<')) |start| { + switch (s.code.check(text, start, s.finished)) { + .skip => |to| { + at = to; + continue; + }, + .pending => { + s.searched = start; + return; + }, + .outside => {}, + } if (tool_dsml.openedBy(text[start..])) |sp| { s.dsml_seen = true; s.pos = start + sp.open.len; @@ -182,7 +201,7 @@ pub const Streamer = struct { at = end; continue; } - if (callTag(text[start + 1 .. end])) { + if (tool_policy.callTag(text[start + 1 .. end])) { s.buffered_start = start; s.buffered_close = try std.mem.concat(s.a, u8, &.{ "" }); s.pos = end + 1; @@ -356,9 +375,15 @@ pub const Streamer = struct { } } + /// ``feed`` at the reply's end: resolves any open backtick ambiguity without cutting open values. + pub fn finish(s: *Streamer, text: []const u8, out: *std.ArrayList(Value)) Allocator.Error!void { + s.finished = true; + return s.feed(text, out); + } + /// ``feed`` of the reply's final text; a value it cuts sends the bytes held back for a closer that never came. pub fn finishCut(s: *Streamer, text: []const u8, out: *std.ArrayList(Value)) Allocator.Error!void { - try s.feed(text, out); + try s.finish(text, out); if (s.state == .glm) return tool_glm_stream.cut(s, text, out); // a GLM value's held bytes if (s.state == .dsml) return tool_dsml_stream.cut(s, text, out); // a DSML value's held bytes if (s.state != .value) return; @@ -424,150 +449,6 @@ fn typedSchema(a: Allocator, schema: tool_params.Schema) Allocator.Error!bool { const wrap = @import("tool_parse.zig").wrapCalls; -fn nameLike(s: []const u8) bool { - if (s.len == 0 or !(std.ascii.isAlphabetic(s[0]) or s[0] == '_')) return false; - for (s[1..]) |ch| if (!(std.ascii.isAlphanumeric(ch) or ch == '_' or ch == '.' or ch == '-' or ch >= 0x80)) return false; - return true; -} - -/// Hides tool envelopes from streamed prose, holding only a partial tag between deltas. -pub const TextFilter = struct { - pending: std.ArrayList(u8) = .empty, - hidden: ?[]const u8 = null, - deferred: bool = false, // a closed envelope was hidden: later prose waits for the reply's final content - - pub fn feed(f: *TextFilter, a: Allocator, text: []const u8) Allocator.Error![]const u8 { - if (f.deferred) return ""; - try f.pending.appendSlice(a, text); - var out: std.ArrayList(u8) = .empty; - while (f.pending.items.len > 0) { - const p = f.pending.items; - if (f.hidden) |name| { - const close = try std.mem.concat(a, u8, &.{ "" }); - if (std.ascii.findIgnoreCase(p, close) == null) { - const keep = reply_text.charCount(close) - 1; - const chars = reply_text.charCount(p); - const tail = if (chars > keep) reply_text.afterChars(p, chars - keep) else p; - try f.reset(a, tail); - break; - } - // The whole reply may keep this envelope as text, so what follows cannot overtake it. - f.hidden = null; - f.deferred = true; - f.pending.clearRetainingCapacity(); - break; - } - const start = std.mem.indexOfScalar(u8, p, '<') orelse { - try out.appendSlice(a, p); - f.pending.clearRetainingCapacity(); - break; - }; - try out.appendSlice(a, p[0..start]); - const rest = p[start..]; - const end = std.mem.indexOfScalar(u8, rest, '>') orelse { - const name = rest[1..]; - const colon = std.mem.indexOfScalar(u8, name, ':'); - const possible = name.len == 0 or nameLike(name) or (colon != null and nameLike(name[0..colon.?]) and - std.ascii.startsWithIgnoreCase("tool_call", name[colon.? + 1 ..])); - if (possible) { - try f.reset(a, rest); - break; - } - try out.append(a, '<'); - try f.reset(a, rest[1..]); - continue; - }; - const name = rest[1..end]; - if (callTag(name)) { - f.hidden = try std.ascii.allocLowerString(a, name); - } else try out.appendSlice(a, rest[0 .. end + 1]); - try f.reset(a, rest[end + 1 ..]); - } - return out.items; - } - - fn reset(f: *TextFilter, a: Allocator, rest: []const u8) Allocator.Error!void { - const copy = try a.dupe(u8, rest); - f.pending.clearRetainingCapacity(); - try f.pending.appendSlice(a, copy); - } - - pub fn finish(f: *TextFilter) []const u8 { - const tail = if (f.hidden != null or f.deferred) "" else f.pending.items; - f.pending = .empty; - return tail; - } -}; - -/// ``(?:NAME:)?tool_call``, any case. -fn callTag(name: []const u8) bool { - if (std.ascii.eqlIgnoreCase(name, "tool_call")) return true; - const colon = std.mem.indexOfScalar(u8, name, ':') orelse return false; - return nameLike(name[0..colon]) and std.ascii.eqlIgnoreCase(name[colon + 1 ..], "tool_call"); -} - -/// ``parallel_tool_calls: false`` keeps one call and hides call markup from streamed prose. -pub const Policy = struct { - single: bool = false, - filter: TextFilter = .{}, - - pub fn maxCalls(p: *const Policy) ?usize { - return if (p.single) 1 else null; - } - - /// Filters a str delta's text (dict deltas lose tool_calls and filter content), or passes it through. - pub fn text(p: *Policy, a: Allocator, s: []const u8) Allocator.Error![]const u8 { - return if (p.single) p.filter.feed(a, s) else s; - } - - pub fn flush(p: *Policy) []const u8 { - return if (p.single) p.filter.finish() else ""; - } - - pub fn content(p: *const Policy, a: Allocator, s: []const u8) Allocator.Error![]const u8 { - if (!p.single) return s; - var f: TextFilter = .{}; - const head = try f.feed(a, s); - return std.mem.concat(a, u8, &.{ head, f.finish() }); - } - - /// parsed_content: parsed reply content; whole envelopes left as text kept, rest filtered; unclosed stays hidden. - pub fn parsedContent(p: *const Policy, a: Allocator, s: []const u8) Allocator.Error![]const u8 { - if (!p.single) return s; - var out: std.ArrayList(u8) = .empty; - var cursor: usize = 0; - while (try wholeEnvelope(a, s, cursor)) |e| : (cursor = e.end) { - try out.appendSlice(a, try p.content(a, s[cursor..e.start])); - try out.appendSlice(a, s[e.start..e.end]); - } - try out.appendSlice(a, try p.content(a, s[cursor..])); - return out.items; - } - - /// Held-back malformed or unoffered call envelopes kept as reply text: ``final`` past the prose ``sent``. - pub fn kept(p: *const Policy, final: []const u8, sent: []const u8) ?[]const u8 { - // Replies without parsed calls retain their leading whitespace; parsed content may be stripped. - const shown = if (std.mem.startsWith(u8, final, sent)) sent else reply_text.pyLstrip(sent); - if (!std.mem.startsWith(u8, final, shown)) return null; - const rest = final[shown.len..]; - if (p.single) return if (rest.len > 0) rest else null; - return if (reply_text.pyStrip(rest).len > 0) rest else null; - } -}; - -/// The first whole envelope from ``from`` (``<((?:NAME:)?tool_call)>.*?``, any case). -fn wholeEnvelope(a: Allocator, s: []const u8, from: usize) Allocator.Error!?struct { start: usize, end: usize } { - var at = from; - while (std.mem.indexOfScalarPos(u8, s, at, '<')) |start| : (at = start + 1) { - const close = std.mem.indexOfScalarPos(u8, s, start, '>') orelse return null; - if (!callTag(s[start + 1 .. close])) continue; - const closer = try std.mem.concat(a, u8, &.{ "" }); - const end = std.ascii.findIgnoreCasePos(s, close + 1, closer) orelse continue; - return .{ .start = start, .end = end + closer.len }; - } - return null; -} - test { _ = @import("tool_stream_test.zig"); } diff --git a/zig/src/server/warm.zig b/zig/src/server/warm.zig index 6f63b9ae365..5b4629993e8 100644 --- a/zig/src/server/warm.zig +++ b/zig/src/server/warm.zig @@ -50,8 +50,9 @@ fn start(srv: *Server, input: chat.Input, message: Value, thinking: bool, effort const pictures = try images.expand(srv.info.vision, null, srv.text, &cx, .{ .array = warm_prompt.messages }, prompt, prompt.len); if (pictures) |x| prompt = x.ids; if (prompt.len == 0 or (srv.info.context_window > 0 and prompt.len >= srv.info.context_window)) return; + const system_len = prompt_mod.systemPrefixLen(srv, &cx, .{ .array = warm_prompt.messages }, input.tools, prompt, thinking, effort); // its states count as the reply's request's: they supersede none of that turn's own until a later turn does - p.request = .{ .prompt = prompt, .max_tokens = 0, .background = true, .born = @intCast(prompt_len), .history_len = @intCast(prompt.len), .rewind_len = if (pictures != null) 0 else @intCast(prompt_mod.rewindLen(srv, &cx, .{ .array = warm_prompt.messages }, input.messages.array.len, input.tools, prompt, thinking, effort)), .chunks = try srv.chunks.starts(a, prompt), .decode_spans = try prompt_mod.replySpans(srv, &cx, prompt) }; + p.request = .{ .prompt = prompt, .max_tokens = 0, .background = true, .born = @intCast(prompt_len), .history_len = @intCast(prompt.len), .rewind_len = if (pictures != null) 0 else @intCast(prompt_mod.rewindLen(srv, &cx, .{ .array = warm_prompt.messages }, input.messages.array.len, input.tools, prompt, thinking, effort)), .chunks = try srv.chunks.request(a, prompt, system_len), .decode_spans = try prompt_mod.replySpans(srv, &cx, prompt) }; if (pictures) |x| { p.request.images = x.images; p.request.cache_key = x.cache_key; diff --git a/zig/src/tensorfold.zig b/zig/src/tensorfold.zig index dd94cd026f7..210d6b07c50 100644 --- a/zig/src/tensorfold.zig +++ b/zig/src/tensorfold.zig @@ -49,6 +49,7 @@ pub const flashnext_fsr_fixture = @import("families/flashnext/fsr_gpu_fixture.zi pub const flashnext_fsr_contract = @import("families/flashnext/fsr_contract_source.zig"); pub const flashnext_scale_index_fixture = @import("families/flashnext/scale_index_fixture.zig"); pub const flashnext_grouped_fixture = @import("families/flashnext/grouped_fixture.zig"); +pub const flashnext_prompt_index_fixture = @import("families/flashnext/prompt_index_fixture.zig"); pub const flashnext_replay = @import("families/flashnext/replay.zig"); pub const flashnext_rows = @import("families/flashnext/rows_load.zig"); pub const flashnext_sample = @import("families/flashnext/host_sample.zig"); diff --git a/zig/src/xpu/drafter.zig b/zig/src/xpu/drafter.zig index de97d6e33d7..fbd6a8c1acd 100644 --- a/zig/src/xpu/drafter.zig +++ b/zig/src/xpu/drafter.zig @@ -4,6 +4,7 @@ const ze = @import("ze"); const kb = @import("xpu_qwen27_kernels"); const q = @import("qwen27.zig"); const dtree = @import("drafter_tree.zig"); +const rope_table = @import("rope_table.zig"); const alloc = q.alloc; const D = q.D; @@ -299,8 +300,7 @@ pub const Drafter = struct { dr.head = try pack(d, &parts, kk, true); } dr.logits = try d.alloc_(MAXB * @as(usize, dr.head.n) * 2); - var invf: [64]f32 = undefined; - for (&invf, 0..) |*f, i| f.* = @floatCast(1.0 / std.math.pow(f64, 1e7, @as(f64, @floatFromInt(2 * i)) / 128.0)); + const invf = rope_table.drafter(); dr.invf = try d.upload(std.mem.sliceAsBytes(&invf)); try dr.use(0); return dr; diff --git a/zig/src/xpu/load.zig b/zig/src/xpu/load.zig index 300d1f7fb63..e5d60b9b68d 100644 --- a/zig/src/xpu/load.zig +++ b/zig/src/xpu/load.zig @@ -3,6 +3,7 @@ const std = @import("std"); const q = @import("qwen27.zig"); const dev = @import("dev.zig"); const fwd = @import("forward.zig"); +const rope_table = @import("rope_table.zig"); const Checkpoint = dev.Checkpoint; const D = q.D; const Dev = dev.Dev; @@ -203,8 +204,7 @@ pub fn loadGptq(d: *Dev, c: *const Checkpoint) !Model { m.embed_b = null; m.norm = try vecTensor(d, c, "model.norm.weight", true); m.head = try projectionQuantized(d, c, "lm_head.weight", true, stage); - var invf: [32]f32 = undefined; - for (&invf, 0..) |*f, i| f.* = @floatCast(std.math.pow(f64, 1e7, -@as(f64, @floatFromInt(i)) / 32.0)); + const invf = rope_table.target(); m.invf = try d.upload(std.mem.sliceAsBytes(&invf)); for (&m.layers, 0..) |*l, i| { const p = try std.fmt.allocPrint(alloc, "model.layers.{d}.", .{i}); @@ -269,8 +269,7 @@ pub fn load(d: *Dev, c: *const Checkpoint) !Model { m.embed_b = try bf16Tensor(d, c, "model.embed_tokens.biases"); m.norm = try bf16Tensor(d, c, "model.norm.weight"); m.head = try projection(d, c, "lm_head", &.{""}, true, false, stage); - var invf: [32]f32 = undefined; - for (&invf, 0..) |*f, i| f.* = @floatCast(std.math.pow(f64, 1e7, -@as(f64, @floatFromInt(i)) / 32.0)); + const invf = rope_table.target(); m.invf = try d.upload(std.mem.sliceAsBytes(&invf)); for (&m.layers, 0..) |*l, i| { const p = try std.fmt.allocPrint(alloc, "model.layers.{d}.", .{i}); diff --git a/zig/src/xpu/rope_table.zig b/zig/src/xpu/rope_table.zig new file mode 100644 index 00000000000..3d36e342e8e --- /dev/null +++ b/zig/src/xpu/rope_table.zig @@ -0,0 +1,97 @@ +//! The Qwen3.8-27B XPU runner's RoPE inverse frequencies (theta 1e7): core's rope_freq, transformers' words. +const std = @import("std"); +const rope_freq = @import("core").rope_freq; + +/// The target's attention rotates 64 of each 256-wide head's dims: 32 words, as attn_prep reads them. +pub fn target() [32]f32 { + var out: [32]f32 = undefined; + rope_freq.inverseFrequencies(1e7, 64, &out); + return out; +} + +/// The DFlash2 drafter rotates all 128 dims of its heads: 64 words, as dprep reads them. +pub fn drafter() [64]f32 { + var out: [64]f32 = undefined; + rope_freq.inverseFrequencies(1e7, 128, &out); + return out; +} + +/// Prints old and new side by side with the largest absolute and relative difference; returns the differing indices. +fn receipt(name: []const u8, old: []const f32, new: []const f32, differ: []usize) []usize { + std.debug.print("\n{s}\n", .{name}); + std.debug.print(" i old word new word old new |old - new| old - new\n", .{}); + var n: usize = 0; + var abs: f64 = 0; + var rel: f64 = 0; + for (old, new, 0..) |o, w, i| { + const a: u32 = @bitCast(o); + const b: u32 = @bitCast(w); + const d = @abs(@as(f64, o) - @as(f64, w)); + abs = @max(abs, d); + rel = @max(rel, d / @abs(@as(f64, w))); + const ulp: i64 = @as(i64, a) - @as(i64, b); + if (ulp != 0) { + differ[n] = i; + n += 1; + } + const row = " {d:>3} 0x{x:0>8} 0x{x:0>8} {e:.8} {e:.8} {e:.3} {d} ulp\n"; + std.debug.print(row, .{ i, a, b, o, w, d, ulp }); + } + const summary = " {d} of {d} words differ; largest absolute difference {e:.3}, largest relative {e:.3}\n"; + std.debug.print(summary, .{ n, old.len, abs, rel }); + return differ[0..n]; +} + +fn expectWords(want: []const u32, got: []const f32) !void { + for (want, got) |w, g| try std.testing.expectEqual(w, @as(u32, @bitCast(g))); +} + +fn expectUlps(old: []const f32, new: []const f32, most: u32) !void { + for (old, new) |o, w| { + const a: u32 = @bitCast(o); + const b: u32 = @bitCast(w); + try std.testing.expect((if (a > b) a - b else b - a) <= most); + } +} + +test "Qwen3.8-27B XPU RoPE: the target's 32 words are transformers', 15 of them 1 ulp from the loaders' old ones" { + // the replaced expression (load.zig, both loaders): f32(1e7^(-i / 32)), a negative f64 exponent, no reciprocal + var old: [32]f32 = undefined; + for (&old, 0..) |*f, i| f.* = @floatCast(std.math.pow(f64, 1e7, -@as(f64, @floatFromInt(i)) / 32.0)); + const new = target(); + // transformers 5.22.1, torch 2.15.0 CPU: the words core's rope_freq test pins for theta 1e7 over 64 + try expectWords(&.{ + 0x3f800000, 0x3f1ab32b, 0x3ebaf81b, 0x3e61f835, 0x3e088d77, 0x3da50956, 0x3d47763f, 0x3cf11177, + 0x3c91ad39, 0x3c301052, 0x3bd4ca15, 0x3b80967d, 0x3b1b690d, 0x3abbd3ed, 0x3a6301e2, 0x3a092e02, + 0x39a5cb60, 0x394860c1, 0x38f22ce2, 0x3892587e, 0x3830df52, 0x37d5c441, 0x37812dab, 0x371c1fc4, + 0x36bcb0c1, 0x36640cc6, 0x3609cf4a, 0x35a68e4c, 0x35494c57, 0x34f3499d, 0x3493048e, 0x3431af44, + }, &new); + var differ: [32]usize = undefined; + const at = receipt("Qwen3.8-27B target, theta 1e7 over 64 rotated dims (load.zig)", &old, &new, &differ); + try std.testing.expectEqualSlices(usize, &.{ 2, 3, 5, 7, 10, 13, 16, 18, 19, 20, 21, 22, 26, 28, 29 }, at); + try expectUlps(&old, &new, 1); +} + +test "Qwen3.8-27B XPU RoPE: the drafter's 64 words, 18 of them 1 ulp from its old ones" { + // the replaced expression (drafter.zig): f32(1 / 1e7^(2i / 128)), power and reciprocal in f64, rounded once + var old: [64]f32 = undefined; + for (&old, 0..) |*f, i| f.* = @floatCast(1.0 / std.math.pow(f64, 1e7, @as(f64, @floatFromInt(2 * i)) / 128.0)); + const new = drafter(); + // each step correctly rounded (60-digit decimal); the even words are transformers' theta 1e7 over 64 above + try expectWords(&.{ + 0x3f800000, 0x3f470165, 0x3f1ab32b, 0x3ef0843c, 0x3ebaf81b, 0x3e9157e1, 0x3e61f835, 0x3e2fa92d, + 0x3e088d77, 0x3dd44d6c, 0x3da50956, 0x3d804b29, 0x3d47763f, 0x3d1b0e01, 0x3cf11177, 0x3cbb65e3, + 0x3c91ad39, 0x3c627ce5, 0x3c301052, 0x3c08dda5, 0x3bd4ca15, 0x3ba56a3f, 0x3b80967d, 0x3b47eb5e, + 0x3b1b690d, 0x3af19f02, 0x3abbd3ed, 0x3a9202c3, 0x3a6301e2, 0x3a3077b3, 0x3a092e02, 0x39d54706, + 0x39a5cb60, 0x3980e1fe, 0x394860c1, 0x391bc44e, 0x38f22ce2, 0x38bc4236, 0x3892587e, 0x3863872c, + 0x3830df52, 0x38097e8f, 0x37d5c441, 0x37a62cb9, 0x37812dab, 0x3748d669, 0x371c1fc4, 0x36f2bb16, + 0x36bcb0c1, 0x3692ae6d, 0x36640cc6, 0x3631472c, 0x3609cf4a, 0x35d641c6, 0x35a68e4c, 0x35817985, + 0x35494c57, 0x351c7b70, 0x34f3499d, 0x34bd1f8c, 0x3493048e, 0x346492ae, 0x3431af44, 0x340a2036, + }, &new); + for (0..32) |i| try std.testing.expectEqual(@as(u32, @bitCast(target()[i])), @as(u32, @bitCast(new[2 * i]))); + var differ: [64]usize = undefined; + const at = receipt("Qwen3.8-27B DFlash2 drafter, theta 1e7 over 128 (drafter.zig)", &old, &new, &differ); + const want = [_]usize{ 4, 6, 10, 14, 20, 25, 26, 32, 35, 36, 38, 39, 40, 42, 44, 52, 56, 58 }; + try std.testing.expectEqualSlices(usize, &want, at); + try expectUlps(&old, &new, 1); +} diff --git a/zig/tests/contract/metal_flashnext_grouped.zig b/zig/tests/contract/metal_flashnext_grouped.zig index 0bf34fb48d6..54b32d6e4ff 100644 --- a/zig/tests/contract/metal_flashnext_grouped.zig +++ b/zig/tests/contract/metal_flashnext_grouped.zig @@ -13,6 +13,7 @@ pub const Probe = struct { device: mtl.Device, queue: mtl.Queue, control: bool = false, + indexed: bool = false, fixture: ?*Fixture = null, actual: []const u8 = &.{}, baseline: []const u8 = &.{}, @@ -22,7 +23,8 @@ pub const Probe = struct { if (p.fixture) |fixture| fixture.deinit(p.a); p.inputs_.deinit(p.a); } - pub fn name(control: bool) []const u8 { + pub fn name(control: bool, indexed: bool) []const u8 { + if (indexed) return if (control) "control: Flash Next grouped experts through the scale index, gate and up tables swapped" else "Flash Next q4 experts grouped by expert through the scale index"; return if (control) "control: Flash Next grouped experts, gate and up scales swapped" else "Flash Next q4 experts grouped by expert"; } fn depth(_: c.Shape) usize { @@ -30,7 +32,7 @@ pub const Probe = struct { } pub fn kernel(p: *Probe) g.Kernel { return .{ .ctx = p, .control = if (p.control) .shapes else null, .spec = .{ - .name = name(p.control), + .name = name(p.control, p.indexed), .accum = .none, .depth = depth, .out = .raw, @@ -59,9 +61,9 @@ pub const Probe = struct { const p = of(ctx); const fixture = p.fixture.?; fixture.wrong_scales = false; - p.baseline = try fixture.run(false); + p.baseline = try fixture.run(false, false); fixture.wrong_scales = p.control; - p.actual = try fixture.run(true); + p.actual = try fixture.run(true, p.indexed); } fn output(ctx: *anyopaque) ![]const u8 { return of(ctx).actual; diff --git a/zig/tests/contract/metal_flashnext_prompt_index.zig b/zig/tests/contract/metal_flashnext_prompt_index.zig new file mode 100644 index 00000000000..e6e11820eef --- /dev/null +++ b/zig/tests/contract/metal_flashnext_prompt_index.zig @@ -0,0 +1,97 @@ +//! Bit-preserving read contract: the indexed 4/32 prompt gathers against the same gathers reading scales direct. +const std = @import("std"); +const mtl = @import("metal"); +const tf = @import("tensorfold"); +const contract = @import("contract"); +const c = contract.spec; +const g = contract.gates; +const fx = tf.flashnext_prompt_index_fixture; +const Fixture = fx.Fixture; + +pub const Probe = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + control: bool = false, + fixture: ?*Fixture = null, + actual: []const u8 = &.{}, + baseline: []const u8 = &.{}, + inputs_: std.ArrayList(u8) = .empty, + + pub fn deinit(p: *Probe) void { + if (p.fixture) |fixture| fixture.deinit(p.a); + p.inputs_.deinit(p.a); + } + pub fn name(control: bool) []const u8 { + return if (control) "control: Flash Next q4 prompt gather index, two table pairs swapped" else "Flash Next q4 prompt gathers through the scale index"; + } + fn depth(_: c.Shape) usize { + return 0; + } + pub fn kernel(p: *Probe) g.Kernel { + return .{ .ctx = p, .control = if (p.control) .shapes else null, .spec = .{ + .name = name(p.control), + .accum = .none, + .depth = depth, + .out = .raw, + .replaces = "the 4/32 prompt gathers (32, 64 and 128-row tiles, fused gate/up) reading each group's scale and bias direct, on the same stored bytes and rows", + .nan = .{ .stated = "every output bit of the direct kernels, non-finite scales included, is retained" }, + .served = &.{ .{ .rows = 40, .n = fx.inner, .k = fx.d }, .{ .rows = 97, .n = fx.inner, .k = fx.d }, .{ .rows = 200, .n = fx.inner, .k = fx.d } }, + .sums = .{ .why = "the index changes where two operands are read, not a sum; the direct kernels' sums are not requalified here" }, + }, .vt = &vt }; + } + fn of(ctx: *anyopaque) *Probe { + return @ptrCast(@alignCast(ctx)); + } + fn prepare(ctx: *anyopaque, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + const p = of(ctx); + if (shape.rows < fx.experts or shape.rows > 512 or shape.n != fx.inner or shape.k != fx.d) return false; + if (p.fixture) |fixture| { + fixture.deinit(p.a); + p.fixture = null; + } + p.fixture = try Fixture.init(p.a, p.device, p.queue, shape.rows, seed, fill == .nonfinite); + p.actual = &.{}; + p.baseline = &.{}; + return true; + } + fn run(ctx: *anyopaque) !void { + const p = of(ctx); + const fixture = p.fixture.?; + fixture.wrong_entry = false; + p.baseline = try fixture.run(false); + fixture.wrong_entry = p.control; + p.actual = try fixture.run(true); + } + fn output(ctx: *anyopaque) ![]const u8 { + return of(ctx).actual; + } + fn inputs(ctx: *anyopaque) ![]const u8 { + const p = of(ctx); + p.inputs_.clearRetainingCapacity(); + try p.fixture.?.inputs(p.a, &p.inputs_); + return p.inputs_.items; + } + fn intact(ctx: *anyopaque) !bool { + return of(ctx).fixture.?.intact(); + } + fn overlap(_: *anyopaque) bool { + return false; + } + fn count(ctx: *anyopaque) usize { + return of(ctx).actual.len; + } + fn reference(_: *anyopaque, want: []f64, mag: []f64) !void { + @memset(want, 0); + @memset(mag, 0); + } + fn check(ctx: *anyopaque, _: g.Gate) !?[]const u8 { + const p = of(ctx); + if (!std.mem.eql(u8, p.actual, p.baseline)) return "the indexed read changed the direct gathers' output bits"; + return null; + } + fn replaced(ctx: *anyopaque) ![]const u8 { + return of(ctx).baseline; + } + const vt: g.VTable = .{ .prepare = prepare, .run = run, .output = output, .inputs = inputs, .intact = intact, .overlap = overlap, .count = count, .reference = reference, .check = check, .replaced = replaced }; +}; diff --git a/zig/tests/contract/metal_limits.zig b/zig/tests/contract/metal_limits.zig index 39fd689fb78..bef7353bb86 100644 --- a/zig/tests/contract/metal_limits.zig +++ b/zig/tests/contract/metal_limits.zig @@ -141,7 +141,15 @@ fn resolve(a: std.mem.Allocator, device: mtl.Device, d: limits.MetalLaunch, comp } if (std.mem.startsWith(u8, d.name, "flashnext grouped ")) { if (!assemble) return undefined; - return .{ .decl = d, .function = fun, .here = sources.flashnext_gx, .pre_m5 = sources.flashnext_gx }; + const body = try tf.flashnext_grouped_fixture.groupedText(a, std.mem.startsWith(u8, d.name, "flashnext grouped index ")); + return .{ .decl = d, .function = fun, .here = body, .pre_m5 = body }; + } + if (std.mem.startsWith(u8, d.name, "flashnext prompt index ")) { + if (!assemble) return undefined; + const body = try tf.flashnext_prompt_index_fixture.text(a, true); + const pre = try preM5(a, "", body); + const here = if (device.tensorUnits()) try std.mem.replaceOwned(u8, a, body, "#include \"../nax.h\"", sources.nax) else pre; + return .{ .decl = d, .function = fun, .here = here, .pre_m5 = pre }; } if (std.mem.startsWith(u8, d.name, "flashnext FSR ")) { if (!assemble) return undefined; diff --git a/zig/tests/contract/metal_main.zig b/zig/tests/contract/metal_main.zig index d8730be05bb..26d7e2f6c26 100644 --- a/zig/tests/contract/metal_main.zig +++ b/zig/tests/contract/metal_main.zig @@ -418,6 +418,9 @@ pub fn main(init: std.process.Init) !u8 { var moe: Moe = .{}; defer moe.deinit(a); try moe.collect(a, device, queue, o, &kernels); + var row_wide: @import("metal_row_wide.zig").Suite = .{ .a = a, .device = device, .queue = queue, .kernels = &kernels }; + defer row_wide.deinit(); + try row_wide.collect(o.only); var glm_windows: @import("metal_glm_rows.zig").Suite = .{ .a = a, .device = device, .queue = queue, .kernels = &kernels }; defer glm_windows.deinit(); try glm_windows.collect(o.only); @@ -470,14 +473,24 @@ pub fn main(init: std.process.Init) !u8 { defer attention_pv.deinit(); try attention_pv.collect(a, device, queue, &kernels, o.only); const flash_grouped = @import("metal_flashnext_grouped.zig"); - var grouped_probes: [2]flash_grouped.Probe = undefined; + var grouped_probes: [4]flash_grouped.Probe = undefined; var grouped_made: usize = 0; defer for (grouped_probes[0..grouped_made]) |*probe| probe.deinit(); - for ([_]bool{ false, true }) |control| { - if (!wanted(o, flash_grouped.Probe.name(control))) continue; - grouped_probes[grouped_made] = .{ .a = a, .device = device, .queue = queue, .control = control }; + for ([_]bool{ false, true }) |indexed| for ([_]bool{ false, true }) |control| { + if (!wanted(o, flash_grouped.Probe.name(control, indexed))) continue; + grouped_probes[grouped_made] = .{ .a = a, .device = device, .queue = queue, .control = control, .indexed = indexed }; grouped_made += 1; try kernels.append(a, grouped_probes[grouped_made - 1].kernel()); + }; + const flash_prompt_index = @import("metal_flashnext_prompt_index.zig"); + var prompt_index_probes: [2]flash_prompt_index.Probe = undefined; + var prompt_index_made: usize = 0; + defer for (prompt_index_probes[0..prompt_index_made]) |*probe| probe.deinit(); + for ([_]bool{ false, true }) |control| { + if (!wanted(o, flash_prompt_index.Probe.name(control))) continue; + prompt_index_probes[prompt_index_made] = .{ .a = a, .device = device, .queue = queue, .control = control }; + prompt_index_made += 1; + try kernels.append(a, prompt_index_probes[prompt_index_made - 1].kernel()); } const weight_only = @import("metal_weight_only.zig"); const weight_source = try weight_only.text(a); diff --git a/zig/tests/contract/metal_q27_attn_rows.zig b/zig/tests/contract/metal_q27_attn_rows.zig index a752aec6fbd..cf4e62089bb 100644 --- a/zig/tests/contract/metal_q27_attn_rows.zig +++ b/zig/tests/contract/metal_q27_attn_rows.zig @@ -356,6 +356,16 @@ pub const Suite = struct { attns: std.ArrayList(*Attn) = .empty, pub fn collect(s: *Suite, only: ?[]const u8) !void { + // each chip's control edit must match its source once, checked on every chip, so an M4 run sees a stale M5 edit + for ([_]bool{ false, true }) |units| for (std.enums.values(Which)) |w| if (controlEdit(w, units)) |e| { + const gm = at_.geometry(.q27b, units); + const body = try q.simd_attention.grouped(s.a, units, true, gm.group(), gm.kv_heads, false); + defer s.a.free(body); + if (std.mem.count(u8, body, e.from) != 1) { + std.debug.print("control edit for {s} rows (tensor units {}) matches {d} times, not once: {s}\n", .{ @tagName(w), units, std.mem.count(u8, body, e.from), e.from }); + return error.ControlEdit; + } + }; const tensor = s.device.tensorUnits(); var regs: std.ArrayList(Reg) = .empty; defer regs.deinit(s.a); diff --git a/zig/tests/contract/metal_row_wide.zig b/zig/tests/contract/metal_row_wide.zig new file mode 100644 index 00000000000..3c56f846b90 --- /dev/null +++ b/zig/tests/contract/metal_row_wide.zig @@ -0,0 +1,223 @@ +//! Wide row projections against one-row bytes, independent FP64 dots and a dispatched row-coupling control. +const std = @import("std"); +const mtl = @import("metal"); +const tf = @import("tensorfold"); +const sources = @import("kernel_sources"); +const ct = @import("contract"); +const affine = @import("metal_affine.zig"); +const rig = @import("rig.zig"); +const row = tf.row_projection; +const c = ct.spec; +const g = ct.gates; +const Style = enum { plain, relu2, strided }; +const Proof = enum { bytes, fp64, control }; + +fn shapes() [34]c.Shape { + var out: [34]c.Shape = undefined; + for (out[0..32], 1..) |*s, n| s.* = .{ .rows = n, .n = 16, .k = 576 }; + out[32] = .{ .rows = 8, .n = 2688, .k = 4096 }; + out[33] = .{ .rows = 16, .n = 4608, .k = 2688 }; + return out; +} + +fn symbol(a: std.mem.Allocator, bits: u8, sum: row.Sum, style: Style) ![]u8 { + return std.fmt.allocPrint(a, "tf_row_projection_wide{s}_q{d}_{t}", .{ switch (style) { + .plain => "", + .relu2 => "_relu2", + .strided => "_strided", + }, bits, sum }); +} + +const Probe = struct { + inner: affine.Proj, + pipes: *const row.Pipelines, + pipe: mtl.Pipeline, + sum: row.Sum, + style: Style, + proof: Proof, + previous: rig.Ref = undefined, + served: [34]c.Shape = shapes(), + + const vt = blk: { + var v = g.hooks(affine.Proj); + v.prepare = prepare; + v.run = run; + v.replaced = replaced; + v.reference = reference; + v.simulate = simulate; + v.check = nonfinite; + break :blk v; + }; + const oracle_vt = blk: { + var v = vt; + v.check = null; + break :blk v; + }; + fn of(ctx: *anyopaque) *Probe { + const inner: *affine.Proj = @ptrCast(@alignCast(ctx)); + return @fieldParentPtr("inner", inner); + } + fn kernel(p: *Probe) g.Kernel { + var s = affine.spec(p.inner.v, p.inner.name); + s.served = &p.served; + s.tiles[0].size = 8; + s.replaces = if (p.proof == .fp64) null else "the narrow projection applied to each row alone"; + if (p.proof != .fp64) s.nan = .{ .stated = "the same nonfinite output bytes as each row alone" }; + return .{ .spec = s, .ctx = &p.inner, .vt = if (p.proof == .fp64) &oracle_vt else &vt, .control = if (p.proof == .control) .shapes else null }; + } + fn prepare(ctx: *anyopaque, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + const p = of(ctx); + if (!try p.inner.prepare(shape, fill, seed)) return false; + if (fill == .stress and p.style == .relu2) { + const f = p.inner.f.?; + for (f.x) |*x| x.* ^= 0x8000; + @memcpy(p.inner.rig.bytes(p.inner.x, f.x.len * 2), std.mem.sliceAsBytes(f.x)); + } + p.previous = try p.inner.rig.scratch(p.inner.f.?.outputs() * 2); + return true; + } + fn weights(p: *Probe) row.Weights { + const b = &p.inner; + const s = b.f.?.shape; + return .{ .w = b.w.buf, .w_off = b.w.off, .scales = b.s.buf, .s_off = b.s.off, .biases = b.b.buf, .b_off = b.b.off, .n = s.n, .k = s.k, .group = b.v.group, .bits = b.v.bits, .sum = p.sum }; + } + fn encode(p: *Probe, call: row.Call, target: rig.Ref, first: usize) !void { + const b = &p.inner; + const pass = b.rig.begin(); + pass.e.setPipeline(call.pipeline); + pass.e.setBuffer(b.x.buf, b.x.off + first * b.f.?.shape.k * 2, 0); + for ([_]rig.Ref{ b.w, b.s, b.b }, 1..) |r, i| pass.e.setBuffer(r.buf, r.off, i); + pass.e.setValue(call.dims, 4); + pass.e.setBuffer(target.buf, target.off + first * b.f.?.shape.n * 2, 5); + pass.e.dispatchGroups(mtl.Size.of(call.groups, 1, 1), mtl.Size.of(call.threads, 1, 1)); + try b.rig.finish(pass); + } + fn run(ctx: *anyopaque) !void { + const p = of(ctx); + const w = p.weights(); + const n = p.inner.f.?.shape.rows; + var call = if (p.style == .strided) try row.callStrided(p.pipes, w, n, w.n) else try row.call(p.pipes, w, n, p.style == .relu2); + call.pipeline = p.pipe; + try p.encode(call, p.inner.out, 0); + } + fn replaced(ctx: *anyopaque) ![]const u8 { + const p = of(ctx); + const call = try row.call(p.pipes, p.weights(), 1, p.style == .relu2); + for (0..p.inner.f.?.shape.rows) |r| try p.encode(call, p.previous, r); + return p.inner.rig.bytes(p.previous, p.inner.f.?.outputs() * 2); + } + fn nonfinite(ctx: *anyopaque, at: g.Gate) !?[]const u8 { + if (at != .nonfinite) return null; + const p = of(ctx); + const want = try replaced(ctx); + const got = p.inner.rig.bytes(p.inner.out, want.len); + return if (std.mem.eql(u8, want, got)) null else "wide nonfinite bytes differ from the one-row path"; + } + fn rounded(x: f64) f64 { + return c.fromBf16(c.toBf16(@floatCast(x))); + } + fn epilogue(p: *Probe, x: f64) f64 { + if (p.style != .relu2) return x; + const h = @max(rounded(x), 0); + return rounded(h * h); + } + fn reference(ctx: *anyopaque, want: []f64, mag: []f64) !void { + const p = of(ctx); + const f = p.inner.f.?; + const kg = f.shape.k / f.group; + for (want, mag, 0..) |*out, *magnitude, index| { + const r = index / f.shape.n; + const col = index % f.shape.n; + var total: f64 = 0; + var terms: f64 = 0; + var k: usize = 0; + while (k < f.shape.k) : (k += 16) { + var dot: f64 = 0; + var xs: f64 = 0; + for (0..16) |i| dot += c.fromBf16(f.x[r * f.shape.k + k + i]) * @as(f64, @floatFromInt(f.codes[col * f.shape.k + k + i])); + for (0..4) |part| { + const x = f.x[r * f.shape.k + k + 4 * part ..][0..4]; + var sum: f64 = @as(f64, c.fromBf16(x[0])) + c.fromBf16(x[1]); + if (p.sum == .bf16) sum = rounded(sum); + sum += c.fromBf16(x[2]); + if (p.sum == .bf16) sum = rounded(sum); + sum += c.fromBf16(x[3]); + xs += if (p.sum == .bf16) rounded(sum) else sum; + } + const scale = c.fromBf16(f.scales[col * kg + k / f.group]); + const bias = c.fromBf16(f.biases[col * kg + k / f.group]); + total += scale * dot + bias * xs; + for (0..16) |i| terms += @abs(scale * c.fromBf16(f.x[r * f.shape.k + k + i]) * @as(f64, @floatFromInt(f.codes[col * f.shape.k + k + i]))); + terms += @abs(bias * xs); + } + out.* = p.epilogue(total); + magnitude.* = terms; + } + } + fn simulate(ctx: *anyopaque, acc: c.Accum, order: g.Order, out: []f64) !void { + const p = of(ctx); + try p.inner.simulate(acc, order, out); + for (out) |*v| v.* = p.epilogue(v.*); + } +}; + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + pipes: ?row.Pipelines = null, + control: ?mtl.Library = null, + probes: std.ArrayList(*Probe) = .empty, + + pub fn collect(s: *Suite, only: ?[]const u8) !void { + if (!s.device.tensorUnits()) return; // the served wide pipelines exist only on tensor-unit chips + for (row.bit_widths) |bits| for ([_]row.Sum{ .f32, .bf16 }) |sum| for (std.enums.values(Style)) |style| { + for (std.enums.values(Proof)) |proof| { + if (proof == .fp64 and (sum != .f32 or style != .plain)) continue; + const fun = try symbol(s.a, bits, sum, style); + defer s.a.free(fun); + const name = try std.fmt.allocPrint(s.a, "{s}row projection wide q{d} {t} {t} {s}", .{ if (proof == .control) "control: metal " else "metal ", bits, sum, proof, fun }); + defer s.a.free(name); + if (only) |q| if (std.mem.indexOf(u8, name, q) == null) continue; + if (s.pipes == null) s.pipes = try row.Pipelines.load(s.device); + const i = std.mem.indexOfScalar(u8, &row.bit_widths, bits).? * 2 + @backingInt(sum); + var pipeline = switch (style) { + .plain => s.pipes.?.wide_plain[i], + .relu2 => s.pipes.?.wide_relu2[i], + .strided => s.pipes.?.wide_strided[i], + }; + if (proof == .control) { + if (s.control == null) { + const text = try std.mem.concat(s.a, u8, &.{ "#define TF_RP_BAD_ROWS 1\n", sources.core_row_projection }); + defer s.a.free(text); + s.control = try mtl.Library.fromSource(s.device, text, mtl.CompileOptions.mlx()); + } + pipeline = try mtl.Pipeline.init(s.device, s.control.?, fun, false); + } + const p = blk: { + errdefer if (proof == .control) pipeline.deinit(); + const probe = try s.a.create(Probe); + errdefer s.a.destroy(probe); + const owned_name = try s.a.dupe(u8, name); + errdefer s.a.free(owned_name); + probe.* = .{ .inner = .{ .a = s.a, .rig = .{ .a = s.a, .device = s.device, .queue = s.queue }, .v = .{ .kind = .row, .bits = bits, .group = 64 }, .name = owned_name }, .pipes = &s.pipes.?, .pipe = pipeline, .sum = sum, .style = style, .proof = proof }; + try s.probes.append(s.a, probe); + break :blk probe; + }; + try s.kernels.append(s.a, p.kernel()); + } + }; + } + pub fn deinit(s: *Suite) void { + for (s.probes.items) |p| { + if (p.proof == .control) p.pipe.deinit(); + p.inner.deinit(); + s.a.free(p.inner.name); + s.a.destroy(p); + } + s.probes.deinit(s.a); + if (s.control) |lib| lib.deinit(); + if (s.pipes) |*pipes| pipes.deinit(); + } +}; diff --git a/zig/tests/cuda/contract_after.zig b/zig/tests/cuda/contract_after.zig index ebddc1a4a76..03a557ee3a3 100644 --- a/zig/tests/cuda/contract_after.zig +++ b/zig/tests/cuda/contract_after.zig @@ -19,6 +19,7 @@ pub fn keep(kernels: *std.ArrayList(g.Kernel), only: []const []const u8) void { pub fn suites(gpu: check.Gpu) !void { try @import("contract_qwen_served.zig").run(gpu); try @import("contract_qwen_pages.zig").run(gpu); + try @import("contract_qwen_shared_prefix.zig").run(gpu, &.{}); try @import("contract_qwen_pending.zig").run(gpu); try @import("contract_qwen_learning.zig").numerical(gpu); try @import("contract_fn_lanes.zig").run(gpu); diff --git a/zig/tests/cuda/contract_qwen_pages.zig b/zig/tests/cuda/contract_qwen_pages.zig index 12e26137a4e..ce296ef5aad 100644 --- a/zig/tests/cuda/contract_qwen_pages.zig +++ b/zig/tests/cuda/contract_qwen_pages.zig @@ -7,12 +7,12 @@ const rig_ = @import("contract_rig.zig"); const numerical = @import("contract_qwen_pages_numerical.zig"); pub const hd = 256; -const max_chunks = 64; -const attentions = 2; // the fixture's attention layers: the kernels run layer 1, so a page's layer offset counts +pub const max_chunks = 64; +pub const attentions = 2; // the fixture's attention layers: the kernels run layer 1, so a page's layer offset counts pub const q_heads = 24; // the 27B's heads pub const kv_heads = 4; const group = q_heads / kv_heads; -const attn_tiles = 4 * 32 * hd * 2; // cuda_forward.zig's dynamic shared bytes for the bf16 tensor-core tiles +pub const attn_tiles = 4 * 32 * hd * 2; // cuda_forward.zig's dynamic shared bytes for the bf16 tensor-core tiles const prompt_shared = 98304; // cuda_prompt.zig's smem /// cuda_prompt.zig's symbols: hpattn_kernel<256, 8, 2, 2> and hpattn8_kernel<256, 8, 2, 2> const prompt_symbols = .{ @@ -24,9 +24,9 @@ const prompt_symbols = .{ const e4m3 = core.quant.fp8.e4m3; // qwen35.cuh's Geo, Seg, Ancestor and Path (src/families/qwen3_5/cuda_cache.zig mirrors them for the engine) -const Geo = extern struct { hid: c_int, nk: c_int, nv: c_int, qh: c_int, kvh: c_int, nl: c_int }; -const Seg = extern struct { rec: u64 = 0, conv: u64 = 0, kv: u64, tap: u64 = 0, log: u64 = 0, before: u64 = 0, cap: c_int, len: c_int, row0: c_int, rows: c_int, tap_rows: c_int = 0, taps: c_int = 0, delta: c_int = 0, pt: u64 = 0, ps: u64 = 0, ptok: c_int = 0, pn: c_int = 0, plog: u64 = 0 }; -const Ancestor = extern struct { bits: u64, depth: u32, chain: u32 }; +pub const Geo = extern struct { hid: c_int, nk: c_int, nv: c_int, qh: c_int, kvh: c_int, nl: c_int }; +pub const Seg = extern struct { rec: u64 = 0, conv: u64 = 0, kv: u64, tap: u64 = 0, log: u64 = 0, before: u64 = 0, cap: c_int, len: c_int, row0: c_int, rows: c_int, tap_rows: c_int = 0, taps: c_int = 0, delta: c_int = 0, pt: u64 = 0, ps: u64 = 0, ptok: c_int = 0, pn: c_int = 0, plog: u64 = 0 }; +pub const Ancestor = extern struct { bits: u64, depth: u32, chain: u32 }; const Path = extern struct { n: c_int, rows: [64]c_int }; /// bf16 rows (qwen35.cu), or e4m3 rows with an fp32 scale each (qwen35_kv8.cu, --kv-cache fp8). @@ -52,12 +52,12 @@ const cases = [_]Case{ const Span = struct { off: usize, len: usize }; /// Bytes of a layer's (or a whole block's, `layers`) rows, `n` positions a head. -fn blockBytes(f: Format, n: usize, layers: usize) usize { +pub fn blockBytes(f: Format, n: usize, layers: usize) usize { return layers * 2 * kv_heads * n * @as(usize, if (f == .fp8) hd + 4 else hd * 2); } /// Layer a's key (s 0) or value (s 1) at pos, head h, in a block of n positions a head: its row, and fp8's scale. -fn spans(f: Format, n: usize, a: usize, s: usize, h: usize, pos: usize) [2]Span { +pub fn spans(f: Format, n: usize, a: usize, s: usize, h: usize, pos: usize) [2]Span { const blk = s * kv_heads + h; const layer = blockBytes(f, n, a); return switch (f) { @@ -105,7 +105,7 @@ pub const Fixture = struct { var f: Fixture = .{ .c = c, .format = format, .cap = cap, .kv = undefined, .q = undefined, .k = undefined, .v = undefined, .ids = undefined, .pages = 2 * (cap / c.ptok) + 2 }; for (&f.kv) |*x| { x.* = try a.alloc(u8, f.streamBytes()); - for (0..attentions) |at| for (0..2) |s| for (0..kv_heads) |h| for (0..cap) |pos| fill(f, rng, x.*, f.logical(at, s, h, pos)); + for (0..attentions) |at| for (0..2) |s| for (0..kv_heads) |h| for (0..cap) |pos| fill(f.format, rng, x.*, f.logical(at, s, h, pos)); } f.q = try randoms(a, rng, c.rows * 2 * q_heads * hd); f.k = try randoms(a, rng, c.rows * 2 * kv_heads * hd); @@ -119,8 +119,8 @@ pub const Fixture = struct { } /// A row's bytes: bf16 in [-1, 1); e4m3 codes but NaN's, a scale in [1/1792, 1/448) (values within 1). - fn fill(f: Fixture, rng: std.Random, out: []u8, sp: [2]Span) void { - switch (f.format) { + pub fn fill(format: Format, rng: std.Random, out: []u8, sp: [2]Span) void { + switch (format) { .bf16 => for (std.mem.bytesAsSlice(u16, out[sp[0].off..][0..sp[0].len])) |*x| { x.* = @truncate(@as(u32, @bitCast(rng.float(f32) * 2 - 1)) >> 16); }, @@ -169,7 +169,7 @@ pub const Fixture = struct { }; /// bf16 in [-1, 1): finite, so a sum's bytes are its order's alone. -fn randoms(a: std.mem.Allocator, rng: std.Random, n: usize) ![]u16 { +pub fn randoms(a: std.mem.Allocator, rng: std.Random, n: usize) ![]u16 { const out = try a.alloc(u16, n); for (out) |*x| x.* = @truncate(@as(u32, @bitCast(rng.float(f32) * 2 - 1)) >> 16); return out; diff --git a/zig/tests/cuda/contract_qwen_shared_prefix.zig b/zig/tests/cuda/contract_qwen_shared_prefix.zig new file mode 100644 index 00000000000..de52f91cf00 --- /dev/null +++ b/zig/tests/cuda/contract_qwen_shared_prefix.zig @@ -0,0 +1,449 @@ +//! attn_rows's join variants on shared pages: every row's partials and merge == main's kernel alone, bit for bit. +const std = @import("std"); +const cuda = @import("cuda"); +const check = @import("check.zig"); +const rig_ = @import("contract_rig.zig"); +const qp = @import("contract_qwen_pages.zig"); + +const hd = qp.hd; +const q_heads = qp.q_heads; +const kv_heads = qp.kv_heads; +const group = q_heads / kv_heads; +const max_chunks = qp.max_chunks; +const Format = qp.Format; +const Seg = qp.Seg; +const Ancestor = qp.Ancestor; +const ptok = 256; // TF_QWEN_KV_PAGES=256's positions a page +const scale: f32 = 1.0 / 16.0; +const layer: c_int = 1; // the second of a page's two attention layers, as qwen-pages runs +const geo: qp.Geo = .{ .hid = 0, .nk = 0, .nv = 0, .qh = q_heads, .kvh = kv_heads, .nl = 0 }; + +/// A rows kernel and its join: cache, threads, rows a block (cuda_forward.zig's tile_rows), dynamic shared bytes. +const Kernel = struct { name: [:0]const u8, join: [:0]const u8, format: Format, threads: u32, tile_rows: usize, shared: u32 = 0 }; +const kernels = [_]Kernel{ + .{ .name = "tf_q35_attn_rows", .join = "tf_q35_attn_rows_join", .format = .bf16, .threads = 256, .tile_rows = 64 / group, .shared = qp.attn_tiles }, + .{ .name = "tf_q35_attn_rows8", .join = "tf_q35_attn_rows8_join", .format = .fp8, .threads = 256, .tile_rows = 64 / group }, +}; +/// main's rows kernel, its join (a launch whose streams share takes it: cuda_cache.anyShares) and the merge. +const Fns = struct { rows: cuda.Function, join: cuda.Function, merge: cuda.Function }; + +/// Paged streams' lengths, all in 640-key chunks (keys in (32768, 40960]); a case takes the first `streams`. +const lens = [_]usize{ 34000, 33000, 35000, 33500, 34700, 33100, 34900, 33900 }; +const band_len = 17000; // 384-key chunks: the same page ids as the common prefix, but it must not join +const flat_len = 34200; // pt = 0 (its own contiguous cache) in the 640-key band: it must not join either +const Case = struct { streams: usize, rows: usize }; +const cases = [_]Case{ .{ .streams = 2, .rows = 1 }, .{ .streams = 2, .rows = 4 }, .{ .streams = 4, .rows = 1 }, .{ .streams = 4, .rows = 4 }, .{ .streams = 8, .rows = 1 }, .{ .streams = 8, .rows = 4 } }; + +// The pool's page ids: a prefix all paged streams share, two groups' prefixes, then each stream's own pages. +const common = 60; +const prefix = 121; // 30,976 keys a group shares: no 640-key chunk ends there, so chunk 48 straddles it +const tail = 17; // a stream's own pages past the prefix +const group_base = common; +const own_base = group_base + 2 * (prefix - common); +const band_base = own_base + lens.len * tail; +const band_pages = 7; +const planted_id = band_base + band_pages; // control (a): a copy of page `planted_page` with one value changed +const planted_page = 30; +const pool_pages = planted_id + 1; + +fn pageBytes(f: Format) usize { + return qp.blockBytes(f, ptok, qp.attentions); +} + +/// Every row of a block of n positions a head as qwen-pages fills its caches: bf16 in [-1, 1), e4m3 and scales. +fn fillBlock(f: Format, rng: std.Random, out: []u8, n: usize) void { + for (0..qp.attentions) |at| for (0..2) |s| for (0..kv_heads) |h| for (0..n) |pos| { + qp.Fixture.fill(f, rng, out, qp.spans(f, n, at, s, h, pos)); + }; +} + +/// Pages in one device arena, the host copy kept; the first `random` filled, the rest zero until a caller copies. +const Pool = struct { + format: Format, + host: []u8, + dev: cuda.DeviceBuffer, + + fn make(gpu: check.Gpu, a: std.mem.Allocator, f: Format, pages: usize, random: usize, seed: u64) !Pool { + var prng = std.Random.DefaultPrng.init(seed); + const host = try a.alloc(u8, pages * pageBytes(f)); + @memset(host, 0); + for (0..random) |p| fillBlock(f, prng.random(), host[p * pageBytes(f) ..][0..pageBytes(f)], ptok); + return .{ .format = f, .host = host, .dev = try cuda.DeviceBuffer.fromHost(gpu.d, host) }; + } + + fn page(p: Pool, id: usize) []u8 { + return p.host[id * pageBytes(p.format) ..][0..pageBytes(p.format)]; + } +}; + +/// Layer 1's value at (head 0, position 7, dim 3) of a page set to another value: 0.75 or 0.25, e4m3's exponent bit. +fn plant(f: Format, page: []u8) void { + const sp = qp.spans(f, ptok, 1, 1, 0, 7); + switch (f) { + .bf16 => { + const at = page[sp[0].off + 2 * 3 ..][0..2]; + std.mem.writeInt(u16, at, if (std.mem.readInt(u16, at, .little) == 0x3f40) 0x3e80 else 0x3f40, .little); + }, + .fp8 => { + const at = &page[sp[0].off + 3]; + at.* ^= 0x40; + if (at.* & 0x7f == 0x7f) at.* ^= 1; + }, + } +} + +/// A launch's stream: length, page table (null: its own contiguous cache at `flat`), rows' ancestors and queries. +const Stream = struct { len: usize, table: ?[]const u32 = null, anc: []const Ancestor, q: []const u16, row0: usize = 0, flat: u64 = 0, cap: usize = 0 }; + +fn chain(a: std.mem.Allocator, n: usize) ![]Ancestor { + const out = try a.alloc(Ancestor, n); + for (out, 0..) |*x, r| x.* = .{ .bits = 0, .depth = @intCast(r), .chain = 1 }; + return out; +} + +/// Paged stream i's table for `keys` positions: the common pages, its group's ((i / 2) % 2), then its own. +fn streamTable(a: std.mem.Allocator, i: usize, keys: usize) ![]u32 { + const t = try a.alloc(u32, (keys + ptok - 1) / ptok); + std.debug.assert(t.len <= prefix + tail); + const g = i / 2 % 2; + for (t, 0..) |*x, p| x.* = @intCast(if (p < common) p else if (p < prefix) group_base + g * (prefix - common) + p - common else own_base + i * tail + p - prefix); + return t; +} + +fn bandTable(a: std.mem.Allocator, keys: usize) ![]u32 { + const t = try a.alloc(u32, (keys + ptok - 1) / ptok); + std.debug.assert(t.len <= common + band_pages); + for (t, 0..) |*x, p| x.* = @intCast(if (p < common) p else band_base + p - common); + return t; +} + +/// cuda_cache.anyShares: two streams with rows in the launch start on one page, so it takes the join kernel. +fn joins(st: []const Stream, order: []const usize) bool { + for (order, 0..) |i, n| if (st[i].table) |t| for (order[0..n]) |j| if (st[j].table) |u| if (t.len > 0 and u.len > 0 and t[0] == u[0]) return true; + return false; +} + +/// A launch's device buffers: segments, rows (`order`'s streams, each's rows in turn), partials and merged rows. +const Staged = struct { m: usize, q: u64, segs: u64, rowseg: u64, rowanc: u64, pm: u64, pl: u64, po: u64, out: u64, join: bool }; + +fn stage(rig: *rig_.Rig, a: std.mem.Allocator, pool: Pool, st: []const Stream, order: []const usize) !Staged { + var m: usize = 0; + for (order) |i| m += st[i].anc.len; + const segs = try a.alloc(Seg, st.len); + for (st, segs) |x, *sg| { + sg.* = .{ .kv = if (x.table == null) x.flat else pool.dev.ptr, .cap = @intCast(x.cap), .len = @intCast(x.len), .row0 = @intCast(x.row0), .rows = @intCast(x.anc.len) }; + if (x.table) |t| { + sg.pt = try rig.input(std.mem.sliceAsBytes(t)); + sg.ps = if (pool.format == .fp8) pageBytes(.fp8) else pageBytes(.bf16) / 2; + sg.ptok = ptok; + } + } + const row = q_heads * hd; + const rowseg = try a.alloc(i32, m); + const rowanc = try a.alloc(Ancestor, m); + const q = try a.alloc(u16, m * row); + var r: usize = 0; + for (order) |i| for (st[i].anc, 0..) |anc, j| { + rowseg[r] = @intCast(i); + rowanc[r] = anc; + @memcpy(q[r * row ..][0..row], st[i].q[j * row ..][0..row]); + r += 1; + }; + var x: Staged = undefined; + x.m = m; + x.join = joins(st, order); + x.q = try rig.input(std.mem.sliceAsBytes(q)); + x.segs = try rig.input(std.mem.sliceAsBytes(segs)); + x.rowseg = try rig.input(std.mem.sliceAsBytes(rowseg)); + x.rowanc = try rig.input(std.mem.sliceAsBytes(rowanc)); + const slots = m * q_heads * max_chunks; + x.pm = try rig.output(slots * 4); + x.pl = try rig.output(slots * 4); + x.po = try rig.output(slots * hd * 4); + x.out = try rig.output(m * row * 2); + return x; +} + +/// cuda_forward.zig's rows launch: groups of tile_rows rows by MAXCH chunks by key heads. +fn rows(k: Kernel, f: cuda.Function, s: cuda.Stream, x: Staged) !void { + const none: u64 = 0; + var args: cuda.Args = .{}; + inline for (.{ geo, x.q, x.segs, x.rowseg, x.rowanc, layer, none, scale, @as(c_int, @intCast(x.m)), x.pm, x.pl, x.po }) |v| args.add(v); + const groups = (x.m + k.tile_rows - 1) / k.tile_rows; + try cuda.launch.launch(f, .{ .grid = .{ .x = @intCast(groups), .y = max_chunks, .z = kv_heads }, .block = .{ .x = k.threads }, .shared = k.shared }, s, &args); +} + +const Out = struct { pm: []u8, pl: []u8, po: []u8, out: []u8 }; +const Part = enum { pm, pl, po, out }; + +fn part(o: Out, p: Part) []const u8 { + return switch (p) { + .pm => o.pm, + .pl => o.pl, + .po => o.po, + .out => o.out, + }; +} + +/// A row's bytes in each part: (query head, chunk) floats, their HD values, its merged bf16 row. +fn rowBytes(p: Part) usize { + return switch (p) { + .pm, .pl => q_heads * max_chunks * 4, + .po => q_heads * max_chunks * hd * 4, + .out => q_heads * hd * 2, + }; +} + +/// The rows kernel then tf_q35_attn_merge over `order`'s rows; inputs and guards checked unchanged. +fn launch(gpu: check.Gpu, s: cuda.Stream, k: Kernel, fns: Fns, pool: Pool, st: []const Stream, order: []const usize, a: std.mem.Allocator) !Out { + var rig = rig_.Rig{ .gpu = gpu, .s = s }; + defer rig.deinit(); + const x = try stage(&rig, a, pool, st, order); + const before = try a.dupe(u8, try rig.inputBytes()); + try rows(k, if (x.join) fns.join else fns.rows, s, x); + const none: u64 = 0; + var args: cuda.Args = .{}; + inline for (.{ geo, x.pm, x.pl, x.po, x.segs, x.rowseg, x.rowanc, none, x.out }) |v| args.add(v); + try cuda.launch.launch(fns.merge, .{ .grid = .{ .x = q_heads, .y = @intCast(x.m) }, .block = .{ .x = 32 } }, s, &args); + var o: Out = undefined; + o.pm = try a.dupe(u8, try rig.bytes(x.pm, x.m * rowBytes(.pm))); + o.pl = try a.dupe(u8, try rig.bytes(x.pl, x.m * rowBytes(.pl))); + o.po = try a.dupe(u8, try rig.bytes(x.po, x.m * rowBytes(.po))); + o.out = try a.dupe(u8, try rig.bytes(x.out, x.m * rowBytes(.out))); + try check.expect(try rig.intact() and !rig.overlap() and std.mem.eql(u8, before, try rig.inputBytes()), "qwen shared prefix: a launch changed an input or guard", .{}); + return o; +} + +/// Rows [at, at + n) of x and [bt, bt + n) of y hold the same bytes in every part. +fn same(x: Out, at: usize, y: Out, bt: usize, n: usize) bool { + for (std.enums.values(Part)) |p| { + const w = rowBytes(p); + if (!std.mem.eql(u8, part(x, p)[at * w ..][0 .. n * w], part(y, p)[bt * w ..][0 .. n * w])) return false; + } + return true; +} + +/// As `same`, failing with the first difference by part, row, query head, chunk and dim, and the count differing. +fn agree(what: []const u8, x: Out, at: usize, y: Out, bt: usize, n: usize) !void { + for (std.enums.values(Part)) |p| { + const w = rowBytes(p); + const gx = part(x, p)[at * w ..][0 .. n * w]; + const gy = part(y, p)[bt * w ..][0 .. n * w]; + const first = std.mem.indexOfDiff(u8, gx, gy) orelse continue; + const e: usize = if (p == .out) 2 else 4; + var count: usize = 0; + var i: usize = 0; + while (i < gx.len) : (i += e) count += @intFromBool(!std.mem.eql(u8, gx[i..][0..e], gy[i..][0..e])); + const k = first / e; + const per_head: usize = switch (p) { + .pm, .pl => max_chunks, + .po => max_chunks * hd, + .out => hd, + }; + const row = k / (q_heads * per_head); + const head = k / per_head % q_heads; + const chunk = switch (p) { + .pm, .pl => k % max_chunks, + .po => k / hd % max_chunks, + .out => 0, + }; + const dim = if (p == .po or p == .out) k % hd else 0; + const got = if (e == 4) std.mem.readInt(u32, gx[k * 4 ..][0..4], .little) else std.mem.readInt(u16, gx[k * 2 ..][0..2], .little); + const want = if (e == 4) std.mem.readInt(u32, gy[k * 4 ..][0..4], .little) else std.mem.readInt(u16, gy[k * 2 ..][0..2], .little); + std.debug.print("FAIL qwen shared prefix {s}: {t} first differs at the stream's row {d}, query head {d}, chunk {d}, dim {d}: {x} for {x}; {d} of {d} differ\n", .{ what, p, row, head, chunk, dim, got, want, count, gx.len / e }); + return error.TestFailed; + } +} + +/// Every case on one rows kernel, then control (b); `flat` is the contiguous stream's cache (cap rows a head). +fn kernelCases(gpu: check.Gpu, s: cuda.Stream, k: Kernel, fns: Fns, pool: Pool, flat: u64, flat_cap: usize) !void { + var red_planted = false; + for (cases, 0..) |c, ci| { + var arena = std.heap.ArenaAllocator.init(gpu.gpa); + defer arena.deinit(); + const a = arena.allocator(); + var prng = std.Random.DefaultPrng.init(0x5eed + ci); + const st = try a.alloc(Stream, c.streams + 2); + for (st, 0..) |*x, i| { + const len: usize = if (i < c.streams) lens[i] else if (i == c.streams) band_len else flat_len; + x.* = .{ .len = len, .anc = try chain(a, c.rows), .q = try qp.randoms(a, prng.random(), c.rows * q_heads * hd) }; + if (i < c.streams) x.table = try streamTable(a, i, len + c.rows); + if (i == c.streams) x.table = try bandTable(a, len + c.rows); + if (x.table) |t| x.cap = t.len * ptok else { + x.flat = flat; + x.cap = flat_cap; + } + } + // rows of stream 0, the band stream, stream 1, the contiguous stream, then the rest: blocks mix every kind + const order = try a.alloc(usize, st.len); + order[0..4].* = .{ 0, c.streams, 1, c.streams + 1 }; + for (2..c.streams) |i| order[i + 2] = i; + var at: usize = 0; + for (order) |i| { + st[i].row0 = at; + at += c.rows; + } + const label = try std.fmt.allocPrint(a, "{s} {d} streams x {d} rows", .{ k.name, c.streams, c.rows }); + const joint = try launch(gpu, s, k, fns, pool, st, order, a); + const again = try launch(gpu, s, k, fns, pool, st, order, a); + try agree(try std.fmt.allocPrint(a, "{s}: joint repeat", .{label}), again, 0, joint, 0, at); + for (st, 0..) |x, i| { + const solo = try launch(gpu, s, k, fns, pool, st, &[_]usize{i}, a); + try agree(try std.fmt.allocPrint(a, "{s}: stream {d} (len {d}) joint against alone", .{ label, i, x.len }), joint, x.row0, solo, 0, c.rows); + } + // control (a): stream 1 reads one common page from a copy with one value changed; it must show + const planted = try a.dupe(Stream, st); + const t1 = try a.dupe(u32, st[1].table.?); + t1[planted_page] = planted_id; + planted[1].table = t1; + const bad = try launch(gpu, s, k, fns, pool, planted, order, a); + const moved = !same(bad, st[1].row0, joint, st[1].row0, c.rows); + red_planted = red_planted or moved; + try check.expect(moved, "qwen shared prefix {s}: a one-value change in stream 1's page left its rows (control missed)", .{label}); + const bad_solo = try launch(gpu, s, k, fns, pool, planted, &[_]usize{1}, a); + try agree(try std.fmt.allocPrint(a, "{s}: planted stream 1 joint against alone", .{label}), bad, st[1].row0, bad_solo, 0, c.rows); + for (st, 0..) |x, i| if (i != 1) try agree(try std.fmt.allocPrint(a, "{s}: stream {d} beside the planted page", .{ label, i }), bad, x.row0, joint, x.row0, c.rows); + std.debug.print("PASS qwen shared prefix {s} (+ a 384-key-chunk stream, a contiguous one): each stream's PM, PL, PO and merge == alone, repeat, planted page seen\n", .{label}); + } + const red_len = try lenControl(gpu, s, k, fns, pool); + try check.expect(red_planted and red_len, "qwen shared prefix {s}: a control never fired", .{k.name}); + std.debug.print("PASS qwen shared prefix {s}: controls RED as planted (a changed copy of a shared page, a tree row past its length)\n", .{k.name}); +} + +/// Control (b): B's table is A's, its length one short of chunk 51's end; its tree row's window key must not join. +fn lenControl(gpu: check.Gpu, s: cuda.Stream, k: Kernel, fns: Fns, pool: Pool) !bool { + var arena = std.heap.ArenaAllocator.init(gpu.gpa); + defer arena.deinit(); + const a = arena.allocator(); + var prng = std.Random.DefaultPrng.init(0xb1); + const table = try streamTable(a, 0, 34000 + 1); + const tree = [_]Ancestor{.{ .bits = 0b100, .depth = 0, .chain = 0 }}; // its window key is row 2's, at len + 2 + var st = [2]Stream{ + .{ .len = 34000, .table = table, .anc = try chain(a, 1), .q = try qp.randoms(a, prng.random(), q_heads * hd), .cap = table.len * ptok }, + .{ .len = 51 * 640 + 640 - 1, .table = table, .anc = &tree, .q = try qp.randoms(a, prng.random(), q_heads * hd), .cap = table.len * ptok }, + }; + for ([_][2]usize{ .{ 0, 1 }, .{ 1, 0 } }) |order| { + st[order[0]].row0 = 0; + st[order[1]].row0 = 1; + const joint = try launch(gpu, s, k, fns, pool, &st, &order, a); + for (st, 0..) |x, i| { + const solo = try launch(gpu, s, k, fns, pool, &st, &[_]usize{i}, a); + try agree(try std.fmt.allocPrint(a, "{s} control (b), rows {any}: stream {d} joint against alone", .{ k.name, order, i }), joint, x.row0, solo, 0, 1); + } + } + // what a join would have read: B's window key at its logical position (a chain row), not its tree row's + var chained = st; + chained[1].anc = try chain(a, 1); + const right = try launch(gpu, s, k, fns, pool, &st, &[_]usize{1}, a); + const wrong = try launch(gpu, s, k, fns, pool, &chained, &[_]usize{1}, a); + const red = !same(right, 0, wrong, 0, 1); + try check.expect(red, "qwen shared prefix {s}: a tree row's own window key read alike at its logical position (control missed)", .{k.name}); + std.debug.print("PASS qwen shared prefix {s}: control (b) B len {d} (chunk 51 ends at {d}) on A's pages: joint == alone both row orders\n", .{ k.name, st[1].len, 51 * 640 + 640 }); + return red; +} + +pub fn run(gpu: check.Gpu, rest: []const [:0]const u8) !void { + var s = try cuda.Stream.init(gpu.d, false); + defer s.deinit(); + var mod = try cuda.Module.load(gpu.d, cuda.kernels.qwen35); + defer mod.unload(); + var kv8 = try cuda.Module.load(gpu.d, cuda.kernels.qwen35_kv8); + defer kv8.unload(); + const merge = try mod.function("tf_q35_attn_merge"); + const bf16: Fns = .{ .rows = try mod.function(kernels[0].name), .join = try mod.function(kernels[0].join), .merge = merge }; + for ([_]cuda.Function{ bf16.rows, bf16.join }) |f| try f.allowDynamicShared(kernels[0].shared); + if (rest.len == 1 and std.mem.eql(u8, rest[0], "time")) return time(gpu, s, bf16); + if (rest.len != 0) return error.UnknownCommand; + for (std.enums.values(Format)) |f| { + var arena = std.heap.ArenaAllocator.init(gpu.gpa); + defer arena.deinit(); + const a = arena.allocator(); + var pool = try Pool.make(gpu, a, f, pool_pages, planted_id, 0x9001 + @as(u64, @backingInt(f))); + defer pool.dev.free(); + @memcpy(pool.page(planted_id), pool.page(planted_page)); + plant(f, pool.page(planted_id)); + try pool.dev.upload(planted_id * pageBytes(f), pool.page(planted_id)); + const flat_cap = (flat_len + 4 + ptok - 1) / ptok * ptok; + const flat_host = try a.alloc(u8, qp.blockBytes(f, flat_cap, qp.attentions)); + var prng = std.Random.DefaultPrng.init(0xf1a7 + @as(u64, @backingInt(f))); + fillBlock(f, prng.random(), flat_host, flat_cap); + var flat = try cuda.DeviceBuffer.fromHost(gpu.d, flat_host); + defer flat.free(); + for (kernels) |k| { + if (k.format != f) continue; + const fns: Fns = if (f == .bf16) bf16 else .{ .rows = try kv8.function(k.name), .join = try kv8.function(k.join), .merge = merge }; + try kernelCases(gpu, s, k, fns, pool, flat.ptr, flat_cap); + } + } +} + +/// tf_q35_attn_rows and its join at 34,817+ keys (8 x 1, 8 x 4, 4 x 1): one prefix's pages, and copies on distinct ids. +fn time(gpu: check.Gpu, s: cuda.Stream, fns: Fns) !void { + var arena = std.heap.ArenaAllocator.init(gpu.gpa); + defer arena.deinit(); + const a = arena.allocator(); + const n = 8; // streams at most + const shared_pages = 136; // 34,816 keys: the prefix ends on a page, each stream's rows on a page of its own + const len = shared_pages * ptok; + const copies = shared_pages + n; // the distinct streams' pages start here + var pool = try Pool.make(gpu, a, .bf16, copies + n * shared_pages, copies, 0x71e); + defer pool.dev.free(); + for (0..n) |i| for (0..shared_pages) |p| @memcpy(pool.page(copies + i * shared_pages + p), pool.page(p)); + try pool.dev.upload(0, pool.host); + const k = kernels[0]; + const reps = 30; + const dropped = 2; + for ([_][2]usize{ .{ 8, 1 }, .{ 8, 4 }, .{ 4, 1 } }) |shape| { + const ns = shape[0]; + const rows_n = shape[1]; + var rig = rig_.Rig{ .gpu = gpu, .s = s }; + defer rig.deinit(); + var prng = std.Random.DefaultPrng.init(0x71e + 16 * ns + rows_n); + var shared: [n]Stream = undefined; + var distinct: [n]Stream = undefined; + var order: [n]usize = undefined; + for (0..ns) |i| { + const ts = try a.alloc(u32, shared_pages + 1); + const td = try a.alloc(u32, shared_pages + 1); + for (0..shared_pages) |p| { + ts[p] = @intCast(p); + td[p] = @intCast(copies + i * shared_pages + p); + } + ts[shared_pages] = @intCast(shared_pages + i); + td[shared_pages] = @intCast(shared_pages + i); + shared[i] = .{ .len = len, .table = ts, .anc = try chain(a, rows_n), .q = try qp.randoms(a, prng.random(), rows_n * q_heads * hd), .row0 = i * rows_n, .cap = ts.len * ptok }; + distinct[i] = shared[i]; + distinct[i].table = td; + order[i] = i; + } + const xs = try stage(&rig, a, pool, shared[0..ns], order[0..ns]); + const xd = try stage(&rig, a, pool, distinct[0..ns], order[0..ns]); + // shared through main's kernel and the join, then distinct (no Seg.share) through both + const runs = [4]struct { x: Staged, f: cuda.Function }{ .{ .x = xs, .f = fns.rows }, .{ .x = xs, .f = fns.join }, .{ .x = xd, .f = fns.rows }, .{ .x = xd, .f = fns.join } }; + var ev: [8]cuda.Event = undefined; + for (&ev) |*e| e.* = try cuda.Event.init(gpu.d, true); + defer for (&ev) |*e| e.deinit(); + var ms: [4][reps - dropped]f64 = undefined; + var got: [4][3][]u8 = undefined; + for (0..reps) |rep| { + // the four in turn, each rep starting one later; every run's partials kept from its last rep + for (0..4) |w| { + const v = (w + rep) % 4; + try ev[2 * w].record(s); + try rows(k, runs[v].f, s, runs[v].x); + try ev[2 * w + 1].record(s); + if (rep == reps - 1) inline for (.{ Part.pm, Part.pl, Part.po }, 0..) |p, i| { + got[v][i] = try a.dupe(u8, try rig.bytes(@field(runs[v].x, @tagName(p)), runs[v].x.m * rowBytes(p))); + }; + } + try s.synchronize(); + if (rep < dropped) continue; + for (0..4) |w| ms[(w + rep) % 4][rep - dropped] = try cuda.Event.elapsedMs(ev[2 * w], ev[2 * w + 1]); + } + const keys = len + rows_n; + const label = try std.fmt.allocPrint(a, "{s} {d} streams x {d} rows, {d}-{d} keys", .{ k.name, ns, rows_n, keys - rows_n + 1, keys }); + // one prefix's pages and their copies hold the same bytes, so every run gives the one-stream bytes + for (1..4) |v| for (0..3) |i| try check.sameBytes(try std.fmt.allocPrint(a, "qwen shared prefix time {s}: run {d} part {d} against main's kernel on distinct pages", .{ label, v, i }), got[v][i], got[2][i]); + std.debug.print("RESULT qwen shared prefix time {s}: shared pages {d:.4} ms a launch through main's kernel, {d:.4} ms joined; distinct pages {d:.4} ms, {d:.4} ms joined; {d} reps after {d} dropped, bytes equal\n", .{ label, check.median(&ms[0]), check.median(&ms[1]), check.median(&ms[2]), check.median(&ms[3]), reps - dropped, dropped }); + } +} diff --git a/zig/tests/cuda/main.zig b/zig/tests/cuda/main.zig index 3a389316397..ab3615179dc 100644 --- a/zig/tests/cuda/main.zig +++ b/zig/tests/cuda/main.zig @@ -15,8 +15,6 @@ const roce_gather_tests = @import("roce_gather_tests.zig"); const sample_tests = @import("sample_tests.zig"); const nemotron_draw_tests = @import("nemotron_draw_tests.zig"); const glue_tests = @import("glue_tests.zig"); -const window_profile = @import("window_profile.zig"); -const tree_accept = @import("tree_accept.zig"); const resume_tests = @import("resume_tests.zig"); const prompt_cuts = @import("prompt_cuts.zig"); const shared_fork = @import("shared_fork.zig"); @@ -263,6 +261,7 @@ const usage = \\ qmm-prefill-many-bench same-process A-B-A screening for the GB10 launch fusion \\ mtp-rows tf_q36m_attn_rows: gates 1-4 (byte-equal to tf_q36m_attn a segment) and float64 alone \\ qwen-pages qwen35.cu's attention cache through a page table: paged == contiguous, float64, red controls + \\ qwen-shared-prefix [time] attn_rows's classes across streams on shared pages == each stream alone, red controls; time: A/B \\ qwen-norm-shift qwen35.cu's _shift norms (BF16 checkpoints): 1 + w in FP32 within a BF16 ulp of float64, red controls \\ clef tiny DIR | head MODEL CASES OUT [--piece N] Clef's joint schema head: the tiny fixture, gate 3's logits \\ qwen-pending qwen35's pending kept rows: the slot scans and tf_q35k_apply_pend == tf_q35k_apply, red controls @@ -506,8 +505,8 @@ fn run(gpu: check.Gpu, cmd: []const u8, rest: []const [:0]const u8) !void { if (std.mem.eql(u8, cmd, "radio-processor")) return radio_tests.processor(gpu, try arg(rest, 0), try arg(rest, 1), try arg(rest, 2)); if (std.mem.eql(u8, cmd, "radio-kernels")) return radio_tests.kernels(gpu); if (std.mem.eql(u8, cmd, "radio-attention")) return radio_tests.attention(gpu); - if (std.mem.eql(u8, cmd, "window-profile")) return window_profile.run(gpu, try arg(rest, 0), try arg(rest, 1), try arg(rest, 2)); - if (std.mem.eql(u8, cmd, "tree-accept")) return tree_accept.run(gpu, try arg(rest, 0), try arg(rest, 1), try arg(rest, 2), try arg(rest, 3)); + if (std.mem.eql(u8, cmd, "window-profile")) return @import("window_profile.zig").run(gpu, try arg(rest, 0), try arg(rest, 1), try arg(rest, 2)); + if (std.mem.eql(u8, cmd, "tree-accept")) return @import("tree_accept.zig").run(gpu, try arg(rest, 0), try arg(rest, 1), try arg(rest, 2), try arg(rest, 3)); if (std.mem.eql(u8, cmd, "chunk-costs")) return chunk_costs.run(gpu, try arg(rest, 0), try arg(rest, 1), try arg(rest, 2)); if (std.mem.eql(u8, cmd, "resume")) return resume_tests.run(gpu, try arg(rest, 0), try arg(rest, 1)); if (std.mem.eql(u8, cmd, "marks")) return resume_tests.insideChunks(gpu, try arg(rest, 0), try arg(rest, 1), try arg(rest, 2), try arg(rest, 3)); @@ -532,6 +531,7 @@ fn run(gpu: check.Gpu, cmd: []const u8, rest: []const [:0]const u8) !void { if (std.mem.eql(u8, cmd, "qmm-prefill-many-bench")) return qmm_prefill_many_contract.bench(gpu); if (std.mem.eql(u8, cmd, "mtp-rows")) return @import("contract_qwen_mtp_rows.zig").alone(gpu); if (std.mem.eql(u8, cmd, "qwen-pages")) return @import("contract_qwen_pages.zig").run(gpu); + if (std.mem.eql(u8, cmd, "qwen-shared-prefix")) return @import("contract_qwen_shared_prefix.zig").run(gpu, rest); if (std.mem.eql(u8, cmd, "qwen-norm-shift")) return @import("qwen_norm_shift_tests.zig").run(gpu); if (std.mem.eql(u8, cmd, "clef")) return @import("clef_tests.zig").run(gpu, rest); if (std.mem.eql(u8, cmd, "qwen-pending")) return @import("contract_qwen_pending.zig").run(gpu); diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index 33dce205b14..a60d94d6c22 100644 --- a/zig/tests/fixtures/gradient-serving.tsv +++ b/zig/tests/fixtures/gradient-serving.tsv @@ -129,7 +129,7 @@ zig/src/families/flashnext/cuda_hc.zig 01f897ac65d6edd2cd6ac76d97cb4d96619c25ffa zig/src/families/flashnext/cuda_head.zig fc6410e8b17d559a12d81fd4bee9ab4e65f6f8b0999796c68baba58efb8fe818 raw zig/src/families/flashnext/cuda_images.zig 5bd8a6c06cb69440522f4392794d9ef52b3760195b97d96f2316b1acac271bd4 raw zig/src/families/flashnext/cuda_images_test.zig df984d54d9de1bb732544785cddf82a124de2a7019041ed1f7483b2a4a2d7c99 raw -zig/src/families/flashnext/cuda_lanes.zig 1ebf522d252b795b15d58a15eb38d9d3227c341df80522ad8a89d5ff3cfbdac4 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 +zig/src/families/flashnext/cuda_lanes.zig b17a890be34945e506970c577909896b52fa6e13b1024d326520ca6ab7583ab0 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) 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_restore_test.zig f9947521a6d9c7d7380ca1b784a93a43b364c6fa5861cad15efd3538d2b8ceff raw diff --git a/zig/tests/glm_rows_check.zig b/zig/tests/glm_rows_check.zig index fba33c56059..d73948083b9 100644 --- a/zig/tests/glm_rows_check.zig +++ b/zig/tests/glm_rows_check.zig @@ -546,6 +546,7 @@ pub fn main() !void { all.pairs += try @import("glm_rows_kda.zig").fusedCheck(&g.p, device, queue); all.pairs += try batch.sharedGluCheck(&g); all.pairs += try @import("glm_rows_moe.zig").check(&g); + all.pairs += try @import("glm_rows_moe.zig").checkUnique(&g); all.values += try @import("glm_rows_kda.zig").bf16Check(&g.p, device, queue, &all.worst); all.values += try @import("glm_rows_kda.zig").embedCheck(&g.p, device, queue, &all.worst); const cl = try @import("glm_rows_classes.zig").check(&g.p, device, queue); diff --git a/zig/tests/glm_rows_moe.zig b/zig/tests/glm_rows_moe.zig index f4e286f8394..62b24fd11af 100644 --- a/zig/tests/glm_rows_moe.zig +++ b/zig/tests/glm_rows_moe.zig @@ -7,7 +7,11 @@ const affine = tf.glm.affine; const rc = @import("glm_rows_check.zig"); fn moeLaunch(e: mtl.ComputeEncoder, p: *const wide.Pipes, m: wide.Moe, io: wide.MoeIo, n_rows: u32) void { - wide.moe(p, e, m, 4, 8, 0.75, io, n_rows); + wide.moe(p, e, m, 4, 8, 0.75, io, n_rows, null); +} + +fn moeLaunchBy(e: mtl.ComputeEncoder, p: *const wide.Pipes, m: wide.Moe, experts: u32, io: wide.MoeIo, n_rows: u32, u: ?wide.Unique) void { + wide.moe(p, e, m, experts, 8, 0.75, io, n_rows, u); } /// wide.moe (routed at q2..q8, shared at 8, two launches) == byIds GLU/down + glu/dense bit for bit; id 5 of 4: zeros. @@ -97,3 +101,82 @@ pub fn check(g: *const rc.Gpu) !usize { ); return pairs; } + +/// wide.moe by unique expert == by pick, bit for bit: 2, 4 and 16 rows of 8 distinct picks of 16 experts, q8, q4, q2. +pub fn checkUnique(g: *const rc.Gpu) !usize { + const n = 256; + const k = 512; + const E = 16; + const top = 8; + var pairs: usize = 0; + const sh = [2]rc.Mat{ + try rc.Mat.init(g.device, 2 * n, k, 8, 64, 7310), + try rc.Mat.init(g.device, k, n, 8, 64, 7311), + }; + defer for (sh) |mm| mm.deinit(); + var prng = std.Random.DefaultPrng.init(7320); + const r = prng.random(); + for ([_]u8{ 8, 4, 2 }) |bits| { + const ms = [3]rc.Mat{ + try rc.Mat.init(g.device, E * n, k, bits, 64, 7410 + @as(u64, bits)), + try rc.Mat.init(g.device, E * n, k, bits, 64, 7510 + @as(u64, bits)), + try rc.Mat.init(g.device, E * k, n, bits, 64, 7610 + @as(u64, bits)), + }; + defer for (ms) |mm| mm.deinit(); + var q: [3]affine.Affine = undefined; + for (&q, ms, [_]u32{ n, n, k }) |*x, mm, rr| { + x.* = mm.q; + x.n = rr; + } + const m: wide.Moe = .{ .gate = q[0], .up = q[1], .down = q[2], .sh_gate_up = sh[0].q, .sh_down = sh[1].q }; + for ([_]u32{ 2, 4, 16 }) |n_rows| { + const slots = top * n_rows; + const bs = [_]mtl.Buffer{ + try rc.buf(g.device, slots * 4), // picks + try rc.buf(g.device, 2 * slots * n * 2), // act: by expert, then by pick + try rc.buf(g.device, 2 * n_rows * n * 2), // acts + try rc.buf(g.device, 2 * slots * k * 2), // ye + try rc.buf(g.device, 2 * n_rows * k * 2), // ys + try rc.buf(g.device, slots * 4), // unique ids + try rc.buf(g.device, slots * wide.max_members * 4), // their picks + try rc.buf(g.device, 4), // their count + }; + defer for (bs) |b| b.deinit(); + const picks = bs[0].slice(i32, slots); + for (0..n_rows) |row| { // a row's 8 distinct experts, as the route picks them + var order: [E]i32 = undefined; + for (&order, 0..) |*o, i| o.* = @intCast(i); + r.shuffle(i32, &order); + @memcpy(picks[row * top ..][0..top], order[0..top]); + } + const uids = bs[5].slice(i32, slots); + const umem = bs[6].slice(i32, slots * wide.max_members); + @memset(umem, -1); + var count: usize = 0; + for (0..E) |ex| { // moe_route's order: experts ascending, each one's picks ascending + var j: usize = 0; + for (picks, 0..) |pk, pi| if (pk == @as(i32, @intCast(ex))) { + umem[count * wide.max_members + j] = @intCast(pi); + j += 1; + }; + if (j == 0) continue; + uids[count] = @intCast(ex); + count += 1; + } + bs[7].slice(i32, 1)[0] = @intCast(count); + const half = [5]usize{ 0, slots * n, n_rows * n, slots * k, n_rows * k }; + const io: wide.MoeIo = .{ .x = rc.ref(ms[0].x()), .ids = rc.ref(bs[0]), .act = rc.ref(bs[1]), .acts = rc.ref(bs[2]), .ye = rc.ref(bs[3]), .ys = rc.ref(bs[4]) }; + const by_pick: wide.MoeIo = .{ .x = io.x, .ids = io.ids, .act = io.act.at(half[1] * 2), .acts = io.acts.at(half[2] * 2), .ye = io.ye.at(half[3] * 2), .ys = io.ys.at(half[4] * 2) }; + const u: wide.Unique = .{ .ids = rc.ref(bs[5]), .members = rc.ref(bs[6]), .count = rc.ref(bs[7]) }; + try g.run(moeLaunchBy, .{ &g.p, m, @as(u32, E), io, n_rows, u }); + try g.run(moeLaunchBy, .{ &g.p, m, @as(u32, E), by_pick, n_rows, null }); + for (bs[1..5], half[1..]) |b, h| { + const v = b.slice(u16, 2 * h); + try rc.eql(v[0..h], v[h..]); + pairs += h; + } + } + } + std.debug.print("routed experts by unique expert == by pick at q8, q4 and q2, 2, 4 and 16 rows: {d} bit-equal values\n", .{pairs}); + return pairs; +} diff --git a/zig/tests/glm_rows_speed.zig b/zig/tests/glm_rows_speed.zig index 05488e5d451..7369e0dbd8b 100644 --- a/zig/tests/glm_rows_speed.zig +++ b/zig/tests/glm_rows_speed.zig @@ -350,7 +350,7 @@ pub fn moeTwo( .acts = z.at(TOPK * N * 2), .ye = rf(io.y), .ys = rf(io.y).at(TOPK * D * 2), - }, 1); + }, 1, null); } fn routedRows(e: mtl.ComputeEncoder, i: usize, p: *const wide.Pipes, gu: [2]Pool, down: Pool, io: Io) void { diff --git a/zig/tests/glm_run.zig b/zig/tests/glm_run.zig index bf6d9cde7b4..6fee086b346 100644 --- a/zig/tests/glm_run.zig +++ b/zig/tests/glm_run.zig @@ -17,6 +17,8 @@ const usage = \\GLM_PROFILE=D,D (after the replies: a knock-out profile of a round at each depth, GLM_PROFILE_REPS times; GLM_PROFILE_ROWS=N: N rows at depth 0), \\GLM_LOGITS=PREFIX (write each prompt's last-row logits, bf16, to PREFIX.NAME.bf16 at its first depth's first run), \\GLM_LOGITS_VS=PREFIX (compare them with such a file: the largest difference against the bf16 step at the top logit), + \\GLM_PROMPT_NLL=ROWS (each prompt's per-token loss through the prompt path, ROWS a chunk; GLM_PROMPT_NLL_OUT=PREFIX writes + \\PREFIX.NAME.f32; GLM_PROMPT_NLL_ONLY stops before the replies), \\GLM_PROMPT_PROFILE=REPS (after the replies: each prompt's first chunk by class, each left out or alone), \\GLM_MARGINS=PREFIX (each emitted token's top-two logit margin, f32, to PREFIX.NAME.margins), GLM_MARGINS_VS=PREFIX \\(at the first token that differs from GLM_VS's reply, both runs' margins there), @@ -149,6 +151,26 @@ pub fn main(init: std.process.Init) !void { std.debug.print("{s} forced: {d} of {d} picks equal the reference's", .{ p.object.get("name").?.string, r.same, want.len }); if (r.first) |i| std.debug.print(", first differs at {d}\n", .{i}) else std.debug.print("\n", .{}); }; + if (platform.c.getenv("GLM_PROMPT_NLL")) |v| { // each prompt's per-token loss through the prompt path, ROWS a chunk + const rows = try std.fmt.parseInt(u32, std.mem.span(v), 10); + for (doc.object.get("prompts").?.array.items) |p| { + const name = p.object.get("name").?.string; + const ids = try ints(arena, p.object.get("ids").?); + const out = try arena.alloc(f32, ids.len - 1); + try e.promptNll(ids, rows, out); + var s: f64 = 0; + for (out) |o| s += o; + std.debug.print("{s} prompt nll: mean {d:.6} over {d} tokens ({d}-row chunks)\n", .{ name, s / @as(f64, @floatFromInt(out.len)), out.len, rows }); + if (platform.c.getenv("GLM_PROMPT_NLL_OUT")) |pre| { + const path = try std.fmt.allocPrintSentinel(arena, "{s}.{s}.f32", .{ std.mem.span(pre), name }, 0); + const f = platform.c.fopen(path, "wb") orelse return error.OpenFailed; + defer _ = platform.c.fclose(f); + const bytes = std.mem.sliceAsBytes(out); + if (platform.c.fwrite(bytes.ptr, 1, bytes.len, f) != bytes.len) return error.WriteFailed; + } + } + if (platform.c.getenv("GLM_PROMPT_NLL_ONLY") != null) return; + } var failures: usize = 0; const vs: ?std.json.Value = if (platform.c.getenv("GLM_VS")) |path| blk: { const f = try mtl.MappedFile.open(path); diff --git a/zig/tests/h3_dit.zig b/zig/tests/h3_dit.zig index ac205af486c..efa89a69dca 100644 --- a/zig/tests/h3_dit.zig +++ b/zig/tests/h3_dit.zig @@ -87,7 +87,7 @@ pub fn main(init: std.process.Init) !void { } } options.defines = defines[0..used]; - const model = try h3.Model.load(gpa, args[1], try std.fmt.parseInt(usize, args[2], 10), &case, options); + const model = try h3.Model.load(gpa, init.io, args[1], try std.fmt.parseInt(usize, args[2], 10), &case, options); model.dense = dense or model.base; var steps = (case.names.get("video_step") orelse return error.MissingTensor).shape[0]; const nv = model.video * model.video_in; diff --git a/zig/tests/h3_image.zig b/zig/tests/h3_image.zig index 5dd49ff1861..69bf764e824 100644 --- a/zig/tests/h3_image.zig +++ b/zig/tests/h3_image.zig @@ -1,7 +1,7 @@ //! MiniMax-H3-Image's transformer on Metal from a picture case: six steps teacher-forced and gated, then free. const std = @import("std"); const mtl = @import("metal"); -const st = @import("safetensors"); +const st = @import("core").safetensors; const h3 = @import("h3"); const fixture = @import("checkpoint_fixture"); @@ -100,7 +100,7 @@ pub const Folder = struct { try picture.checkTransformer(a, try read(init, a, transformer_dir, "config.json")); const shards = try picture.shardCount(a, try read(init, a, transformer_dir, "model.safetensors.index.json")); const pdd = try picture.pdd(a, try read(init, a, std.fs.path.dirname(try std.fs.path.join(a, &.{ dir, heads_name })) orelse dir, "pdd_config.json")); - const ck = try h3.Model.open(init.gpa, transformer_dir, shards); + const ck = try h3.Model.open(init.gpa, init.io, transformer_dir, shards); const heads = try h3.Tensors.open(init.gpa, try mtl.Device.init(), try std.fmt.allocPrintSentinel(a, "{s}/{s}", .{ dir, heads_name }, 0)); const hidden = (ck.entry("final_layer.norm.weight") orelse return error.MissingTensor).shape[0]; var name: [32]u8 = undefined; diff --git a/zig/tests/h3_image_decoder.zig b/zig/tests/h3_image_decoder.zig index cc42fd7017b..aab4463ab5e 100644 --- a/zig/tests/h3_image_decoder.zig +++ b/zig/tests/h3_image_decoder.zig @@ -33,7 +33,7 @@ pub const Vae = struct { const d = try dec.Decoder.init(init.gpa, device, vae.layers, config.rope_theta); errdefer d.deinit(); const weights = try std.fmt.allocPrintSentinel(a, "{s}/diffusion_pytorch_model.safetensors", .{vae_dir}, 0); - try d.load(weights); + try d.load(init.io, weights); d.give_way = .{ .io = init.io }; std.debug.print("{s}: decoder weights in bf16 in {d:.1} s\n", .{ device.name(), mtl.clock.seconds() - loading }); return .{ .config = config, .d = d }; diff --git a/zig/tests/h3_image_prompt_cuda.zig b/zig/tests/h3_image_prompt_cuda.zig index cd5b9d116f7..b51ec2a4abb 100644 --- a/zig/tests/h3_image_prompt_cuda.zig +++ b/zig/tests/h3_image_prompt_cuda.zig @@ -78,7 +78,7 @@ pub fn main(init: std.process.Init) !u8 { const prefix = try rules.textPrefix(shards.where.keys()); const embed = try shards.tensorBytes(try std.fmt.allocPrint(a, "{s}embed_tokens.weight", .{prefix}), .{ enc.text.vocab, enc.text.hidden }); // the mapped bytes into the page cache before the uploads fault them in mid-copy - try shards.readAhead(a, TextNames{ .prefix = prefix, .layers = enc.text.layers }); + try shards.readAhead(io, a, TextNames{ .prefix = prefix, .layers = enc.text.layers }); const enc_rows = try a.alloc(u16, T * enc.text.hidden); var gpu_started = seconds(); var layer_ctx: LayerCtx = .{ .shards = &shards, .g = enc.text, .prefix = prefix }; @@ -89,7 +89,7 @@ pub fn main(init: std.process.Init) !u8 { var front_shards = try Shards.open(io, a, gpa, transformer); defer front_shards.deinit(gpa); const front_w = try frontTensors(&front_shards, front); - try front_shards.readAhead(a, struct { + try front_shards.readAhead(io, a, struct { fn accepts(_: @This(), name: []const u8) bool { return std.mem.startsWith(u8, name, "condition_proj.") or std.mem.startsWith(u8, name, "token_refiner."); } @@ -155,7 +155,7 @@ const Shards = struct { /// The mapped bytes of every tensor `accepts` into the page cache before the GPU's uploads fault /// them in one at a time, as the Metal prompt paths do (`h3/read_ahead.zig`); each shard mapped /// once, its accepted tensors one span. - fn readAhead(s: *Shards, a: std.mem.Allocator, accepts: anytype) !void { + fn readAhead(s: *Shards, io: std.Io, a: std.mem.Allocator, accepts: anytype) !void { var spans: std.ArrayList(hp.read_ahead.Span) = .empty; defer spans.deinit(a); var done: std.StringHashMapUnmanaged(void) = .empty; @@ -173,7 +173,7 @@ const Shards = struct { try spans.append(a, .{ .path = path, .lo = file.data + entry.begin, .hi = file.data + entry.end }); }; } - _ = try hp.read_ahead.read(spans.items); + _ = try hp.read_ahead.read(a, io, spans.items); } /// The bf16 tensor `name` at `shape` as stored bytes (columns 0: a vector of `rows` values). diff --git a/zig/tests/hip/contract_idx_scores.zig b/zig/tests/hip/contract_idx_scores.zig new file mode 100644 index 00000000000..1c3dc02aa39 --- /dev/null +++ b/zig/tests/hip/contract_idx_scores.zig @@ -0,0 +1,171 @@ +//! Flash Next's indexer block scores under the contract on HIP: relu-summed heads against an fp64 reference. +const std = @import("std"); +const hip = @import("hip"); +const core = @import("core"); +const rig_ = @import("contract_rig.zig"); +const kit = @import("contract_kit.zig"); + +const contract = core.contract; +const c = contract.spec; +const g = contract.gates; + +const heads = 4; +const dims = 128; +const top = 4; + +/// Fp32 sums over a head's dims, then over the heads. +fn depth(_: c.Shape) usize { + return dims + heads; +} + +const why = "a lane's dims 32 apart, the 32-lane xor tree, then the heads"; +const rule = "a dot that is NaN adds 0 (relu by fmaxf); an infinite q reaches the blocks whose key carries its sign"; + +pub fn spec(k: kit.Kind) c.Spec { + return .{ + .name = if (k == .bf16) "hip tf_fn_idx_scores (bf16 keys)" else "hip tf_fn_idx_scores (fp16 keys)", + .accum = .f32, + .depth = depth, + .ops = 2, // the relu and the divide by sqrt(dims) + .out = .f32, + .nan = .{ .stated = rule }, + .tiles = .{ .{ .size = 8, .min = 1 }, .{ .size = 8, .min = 1 }, .{} }, + // a 64-row slice over a 32K prompt's blocks, a tail of rows past one tile, and a deep cache + .served = &.{ + .{ .rows = 64, .n = 8192, .k = dims }, + .{ .rows = 13, .n = 2051, .k = dims }, + .{ .rows = 8, .n = 32768, .k = dims }, + }, + .sums = .{ .f16 = 0, .bf16 = 0, .why = why, .exact = false }, + }; +} + +/// Either the real launch or a control that drops the last head so gate 3 catches the missing sum. +pub const Fault = enum { + none, + one_head_short, + + fn name(f: Fault) ?[]const u8 { + return switch (f) { + .none => null, + .one_head_short => "control: tf_fn_idx_scores leaves out each row's last head", + }; + } +}; + +/// Rows of q against a cache of pooled block keys of the kind; every row scores every block. +pub const IdxScores = struct { + rig: rig_.Rig, + l: *const hip.Launcher, + k: kit.Kind, + fault: Fault, + arena: std.heap.ArenaAllocator, + shape: c.Shape = undefined, + q: []f32 = &.{}, + keys: []f64 = &.{}, + dev: [3]u64 = @splat(0), + out: u64 = 0, + + pub fn init(a: std.mem.Allocator, rt: *const hip.Runtime, s: hip.Stream, l: *const hip.Launcher, f: Fault) IdxScores { + return .{ .rig = .{ .a = a, .r = rt, .s = s }, .l = l, .k = kit.act(), .fault = f, .arena = .init(a) }; + } + + pub fn deinit(self: *IdxScores) void { + self.arena.deinit(); + self.rig.deinit(); + } + + /// The control keeps the spec under its own name and must go red at gate 3 (shapes). + pub fn kernel(self: *IdxScores) g.Kernel { + var s = spec(self.k); + const control = self.fault.name(); + if (control) |name| s.name = name; + return .{ .spec = s, .ctx = self, .vt = &vt, .control = if (control != null) .shapes else null }; + } + + const vt = g.hooks(IdxScores); + + /// Random: values in [-1, 1) exact in the kind. Stress: small integers, so every sum is exact. + pub fn prepare(self: *IdxScores, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.k != dims or shape.rows < 1 or shape.n <= top or shape.n > 40000) return false; + self.rig.reset(); + _ = self.arena.reset(.retain_capacity); + const a = self.arena.allocator(); + self.shape = shape; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const stress = fill == .stress; + self.q = try a.alloc(f32, shape.rows * heads * dims); + for (self.q) |*x| { + x.* = if (stress) @floatFromInt(rng.intRangeAtMost(i32, -3, 3)) else @floatCast(rng.float(f64) * 2 - 1); + } + self.keys, const kb = try kit.values(a, rng, self.k, shape.n * dims, -1, 1); + if (stress) for (self.keys, 0..) |*x, i| { + x.* = @floatFromInt(rng.intRangeAtMost(i32, -3, 3)); + kit.put(self.k, kb, i, x.*); + }; + if (fill == .nonfinite) self.q[heads * dims] = std.math.inf(f32); // row 1, head 0, dim 0 + const complete = try a.alloc(i32, shape.rows); + @memset(complete, @intCast(shape.n)); + self.dev = .{ + try self.rig.input(std.mem.sliceAsBytes(self.q)), + try self.rig.input(kb), + try self.rig.input(std.mem.sliceAsBytes(complete)), + }; + self.out = try self.rig.output(shape.rows * shape.n * 4); + return true; + } + + pub fn run(self: *IdxScores) !void { + const s = self.shape; + const d = self.dev; + const run_heads: c_int = if (self.fault == .one_head_short) heads - 1 else heads; + try self.l.fn_idx_scores( + @ptrFromInt(d[0]), + @ptrFromInt(d[1]), + @ptrFromInt(d[2]), + @ptrFromInt(self.out), + @backingInt(self.k), + @intCast(s.rows), + run_heads, + dims, + @intCast(s.n), + @intCast(s.n), + top, + self.rig.s.handle, + ); + try self.rig.s.synchronize(); + } + + pub fn count(self: *IdxScores) usize { + return self.shape.rows * self.shape.n; + } + + /// fp64 scores: each head's dot over the dims, a NaN dot as 0, the rest relu'd, summed over heads, / sqrt(dims). + pub fn reference(self: *IdxScores, want: []f64, mag: []f64) !void { + const n = self.shape.n; + for (0..self.shape.rows) |r| for (0..n) |b| { + var total: f64 = 0; + var size: f64 = 0; + for (0..heads) |h| { + var dot: f64 = 0; + var m: f64 = 0; + for (0..dims) |d| { + const p = @as(f64, self.q[(r * heads + h) * dims + d]) * self.keys[b * dims + d]; + dot += p; + m += @abs(p); + } + if (!std.math.isNan(dot) and dot > 0) total += dot; + size += m; + } + want[r * n + b] = total / @sqrt(@as(f64, dims)); + mag[r * n + b] = size / @sqrt(@as(f64, dims)); + }; + } + + /// Every sum is exact on the stress fill's integers, in any order. + pub fn simulate(self: *IdxScores, _: c.Accum, _: g.Order, out: []f64) !void { + const mag = try self.arena.allocator().alloc(f64, out.len); + try self.reference(out, mag); + } +}; diff --git a/zig/tests/hip/contract_main.zig b/zig/tests/hip/contract_main.zig index 59416a7b740..5c3f785c606 100644 --- a/zig/tests/hip/contract_main.zig +++ b/zig/tests/hip/contract_main.zig @@ -40,6 +40,7 @@ const vl_k = @import("contract_vl.zig"); const pos_k = @import("contract_vl_position.zig"); const sparse_k = @import("contract_sparse_lanes.zig"); const skew_k = @import("contract_wmma_skew.zig"); +const idx_k = @import("contract_idx_scores.zig"); const g = core.contract.gates; @@ -345,6 +346,10 @@ fn run(a: std.mem.Allocator, io: std.Io) !usize { var sparse = sparse_k.SparseLanes.init(a, &r, s, &l); defer sparse.deinit(); try kernels.append(a, sparse.kernel()); + var idx_scores: [2]idx_k.IdxScores = undefined; + for (&idx_scores, std.enums.values(idx_k.Fault)) |*x, fault| x.* = .init(a, &r, s, &l, fault); + defer for (&idx_scores) |*x| x.deinit(); + for (&idx_scores) |*x| try kernels.append(a, x.kernel()); var skews: [skew_k.cases.len]skew_k.Skew = undefined; for (&skews, 0..) |*x, i| x.* = .init(a, &r, s, &l, i); defer for (&skews) |*x| x.deinit(); diff --git a/zig/tests/nemotron_hip/invariance.zig b/zig/tests/nemotron_hip/invariance.zig new file mode 100644 index 00000000000..49a05b212ec --- /dev/null +++ b/zig/tests/nemotron_hip/invariance.zig @@ -0,0 +1,290 @@ +//! Within-path HIP invariance checks: prompt cuts + 1-row head, decode window/grouping, and prompt-cache resume. +const std = @import("std"); +const hip = @import("hip"); +const nem = @import("nemotron"); +const gen = @import("gen.zig"); +const replay = @import("replay.zig"); + +pub const usage = " tf-nemotron-hip-test invariance [ids.bin] [--no-mtp]\n"; + +const Snap = struct { + state: []u8, + hidden: []u8, + logits: []f32, + + fn alloc(gpa: std.mem.Allocator, state_bytes: usize, hidden_bytes: usize, logits_len: usize) !Snap { + return .{ + .state = try gpa.alloc(u8, state_bytes), + .hidden = try gpa.alloc(u8, hidden_bytes), + .logits = try gpa.alloc(f32, logits_len), + }; + } + + fn deinit(s: Snap, gpa: std.mem.Allocator) void { + gpa.free(s.state); + gpa.free(s.hidden); + gpa.free(s.logits); + } +}; + +fn buildPrompt(gpa: std.mem.Allocator, io: std.Io, path: ?[]const u8, vocab: usize) ![]u32 { + if (path) |p| return gen.readIds(gpa, io, p); + const ids = try gpa.alloc(u32, 193); + const mod: usize = @min(vocab, 50000); + for (ids, 0..) |*t, i| t.* = @intCast((1000 + i * 37) % mod); + return ids; +} + +fn checkKv(e: *nem.engine.Engine, gpa: std.mem.Allocator, a: *nem.pages.Stream, b: *nem.pages.Stream, len: usize, label: []const u8) !void { + if (try replay.kvDiffers(e, gpa, a, b, len)) |w| { + std.debug.print("invariance ({s}): K/V differ at slot {d} pos {d} ({s})\n", .{ label, w.slot, w.pos, if (w.key) "keys" else "values" }); + return error.KvMismatch; + } +} + +fn captureHidden(e: *nem.engine.Engine, t: hip.ops.Tensor, dst: []u8) !void { + try e.stream.synchronize(); + try hip.runtime.check(e.driver.api.hipMemcpyDtoH(dst.ptr, @ptrFromInt(t.ptr), dst.len)); +} + +/// Synchronizes `e.stream` (hipStreamNonBlocking) before synchronous null-stream Mamba state downloads. +fn downloadState(e: *nem.engine.Engine, s: *nem.pages.Stream, dst: []u8) !void { + try e.stream.synchronize(); + try s.mem.download(0, dst); +} + +fn compareLogits(a: []const f32, b: []const f32, what: []const u8) !void { + const ba = std.mem.sliceAsBytes(a); + const bb = std.mem.sliceAsBytes(b); + if (!std.mem.eql(u8, ba, bb)) { + var worst: f32 = 0; + for (a, b) |x, y| worst = @max(worst, @abs(x - y)); + std.debug.print("invariance ({s}): logits bits differ (max diff {e})\n", .{ what, worst }); + return error.LogitsMismatch; + } +} + +/// Checks prompt chunk-cut invariance (trunk + 1-row head) across trailing chunks {1, 8, 15, 16, 17} and multi-chunk. +fn checkPromptCuts(gpa: std.mem.Allocator, e: *nem.engine.Engine, prompt: []const u32) !void { + const m = e.model_(); + const d = m.dims; + const width = d.hidden * e.act.size(); + const state_bytes = nem.pages.Stream.stateBytes(d, e.act, e.cfg.count(.mamba)); + const saved_chunk = e.o.chunk; + defer e.o.chunk = saved_chunk; + + var base_s = try e.openStream(); + defer e.closeStream(&base_s); + e.o.chunk = prompt.len; + const base_last = try e.prompt(&base_s, prompt); + const ref = try Snap.alloc(gpa, state_bytes, prompt.len * width, d.vocab); + defer ref.deinit(gpa); + try downloadState(e, &base_s, ref.state); + try captureHidden(e, base_last, ref.hidden); + const o0 = e.ops(&e.arena); + try gen.readBack(e, gpa, try e.logits(o0, nem.forward.at(base_last, (prompt.len - 1) * d.hidden), 1), ref.logits); + + const tails = [_]usize{ 1, 8, 15, 16, 17, 65 }; + const got = try Snap.alloc(gpa, state_bytes, prompt.len * width, d.vocab); + defer got.deinit(gpa); + for (tails) |tail| { + if (tail >= prompt.len) continue; + const cut = prompt.len - tail; + e.o.chunk = cut; + var s = try e.openStream(); + defer e.closeStream(&s); + const last = try e.prompt(&s, prompt); + const rem = prompt.len - ((prompt.len - 1) / cut) * cut; + try downloadState(e, &s, got.state); + if (!std.mem.eql(u8, ref.state, got.state)) { + std.debug.print("invariance (prompt cut {d}, tail {d}): Mamba state differs\n", .{ cut, rem }); + return error.StateMismatch; + } + const chunk_bytes = rem * width; + try captureHidden(e, last, got.hidden[0..chunk_bytes]); + if (!std.mem.eql(u8, ref.hidden[(prompt.len - rem) * width ..][0..chunk_bytes], got.hidden[0..chunk_bytes])) { + std.debug.print("invariance (prompt cut {d}, tail {d}): hidden chunk differs\n", .{ cut, rem }); + return error.HiddenMismatch; + } + try checkKv(e, gpa, &base_s, &s, prompt.len, "prompt cut"); + const o = e.ops(&e.arena); + try gen.readBack(e, gpa, try e.logits(o, nem.forward.at(last, (rem - 1) * d.hidden), 1), got.logits); + try compareLogits(ref.logits, got.logits, "prompt cut 1-row head"); + } + std.debug.print("invariance: prompt cuts ({d} cuts) + 1-row head: 0 bits differ\n", .{tails.len}); +} + +/// Checks decode window width (1 vs 2/3/4) and multi-stream grouping invariance on identical input rows. +fn checkDecodeGrouping(gpa: std.mem.Allocator, e: *nem.engine.Engine, base_prompt: []const u32, tail: []const u32) !void { + const m = e.model_(); + const d = m.dims; + const v = d.vocab; + const k = tail.len; + const state_bytes = nem.pages.Stream.stateBytes(d, e.act, e.cfg.count(.mamba)); + + var ref_s = try e.openStream(); + defer e.closeStream(&ref_s); + _ = try e.prompt(&ref_s, base_prompt); + const serial_logits = try gpa.alloc(f32, k * v); + defer gpa.free(serial_logits); + for (tail, 0..) |t, step| { + try ref_s.cover(&e.pool, ref_s.len + 1); + const h = try e.round(&.{.{ .s = &ref_s, .tokens = &.{t} }}, null); + const o = e.ops(&e.arena); + ref_s.len += 1; + try gen.readBack(e, gpa, try e.roundLogits(o, h, 1), serial_logits[step * v ..][0..v]); + } + const ref_state = try gpa.alloc(u8, state_bytes); + defer gpa.free(ref_state); + try downloadState(e, &ref_s, ref_state); + + // 2-row and 4-row windows across the same 8 tokens, then a grouped 2-stream round + const win_logits = try gpa.alloc(f32, k * v); + defer gpa.free(win_logits); + const win_state = try gpa.alloc(u8, state_bytes); + defer gpa.free(win_state); + for ([_]usize{ 2, 4 }) |w| { + var s = try e.openStream(); + defer e.closeStream(&s); + _ = try e.prompt(&s, base_prompt); + var at: usize = 0; + while (at < k) : (at += w) { + try s.cover(&e.pool, s.len + w); + const h = try e.round(&.{.{ .s = &s, .tokens = tail[at..][0..w] }}, null); + const o = e.ops(&e.arena); + s.len += w; + try gen.readBack(e, gpa, try e.roundLogits(o, h, w), win_logits[at * v ..][0 .. w * v]); + } + try compareLogits(serial_logits, win_logits, "decode window"); + try downloadState(e, &s, win_state); + if (!std.mem.eql(u8, ref_state, win_state)) return error.StateMismatch; + try checkKv(e, gpa, &ref_s, &s, ref_s.len, "decode window"); + } + + // Grouped multi-stream round: stream 0 takes tail[0..4], stream 1 takes a shorter prompt + 3 rows alongside it + var s0 = try e.openStream(); + defer e.closeStream(&s0); + _ = try e.prompt(&s0, base_prompt); + var s1 = try e.openStream(); + defer e.closeStream(&s1); + _ = try e.prompt(&s1, base_prompt[0 .. base_prompt.len - 13]); + try s0.cover(&e.pool, s0.len + 4); + try s1.cover(&e.pool, s1.len + 3); + const h_grp = try e.round(&.{ + .{ .s = &s0, .tokens = tail[0..4] }, + .{ .s = &s1, .tokens = base_prompt[base_prompt.len - 13 ..][0..3] }, + }, null); + const grp_logits = try gpa.alloc(f32, 4 * v); + defer gpa.free(grp_logits); + const o_grp = e.ops(&e.arena); + try gen.readBack(e, gpa, try e.roundLogits(o_grp, h_grp, 4), grp_logits); + try compareLogits(serial_logits[0 .. 4 * v], grp_logits, "grouped 2-stream round"); + std.debug.print("invariance: decode windows (1 vs 2 vs 4) and 2-stream grouping: 0 bits differ\n", .{}); +} + +/// Checks served prompt-cache resume-equals-fresh at a prompt state (state, KV pages, logits and 4 decode steps). +fn checkResumePrefix(gpa: std.mem.Allocator, e: *nem.engine.Engine, prompt: []const u32, decode_tail: []const u32) !void { + const m = e.model_(); + const d = m.dims; + const width = d.hidden * e.act.size(); + const h = try nem.lanes.Hip.init(gpa, e); + defer h.deinit(); + + // Fresh reference lane without prefix cache + const l_fresh = try h.make(); + defer h.free(l_fresh); + try l_fresh.s.cover(&e.pool, prompt.len); + const y_fresh_t = try h.chunk(l_fresh, prompt, 0, prompt.len, null); + const ref = try Snap.alloc(gpa, h.state_bytes, width, d.vocab); + defer ref.deinit(gpa); + try downloadState(e, &l_fresh.s, ref.state); + try captureHidden(e, .{ .ptr = l_fresh.hidden.base(), .kind = e.act }, ref.hidden); + try gen.readBack(e, gpa, y_fresh_t.?, ref.logits); + + // Seed the prefix cache at mark 128 on lane 1, free it so only the cached prefix stays, then resume on lane 2 + h.prefix.keepPages(16, 4); + { + const l_seed = try h.make(); + defer h.free(l_seed); + var adopt_seed: std.ArrayList(u32) = .empty; + defer adopt_seed.deinit(gpa); + const plan_seed = try h.prefix.begin(prompt, 128, &.{}, l_seed, &adopt_seed); + defer gpa.free(plan_seed.marks); + if (plan_seed.marks.len == 0) return error.NoPrefixMark; + var at: usize = 0; + for (plan_seed.marks) |mark| { + try l_seed.s.cover(&e.pool, mark); + _ = try h.chunk(l_seed, prompt, at, mark, null); + try h.keepCut(l_seed, prompt, mark); + at = mark; + } + try l_seed.s.cover(&e.pool, prompt.len); + _ = try h.chunk(l_seed, prompt, at, prompt.len, null); + } + + const l_res = try h.make(); + defer h.free(l_res); + var adopt_res: std.ArrayList(u32) = .empty; + defer adopt_res.deinit(gpa); + const plan_res = try h.prefix.begin(prompt, 0, &.{}, l_res, &adopt_res); + defer gpa.free(plan_res.marks); + if (plan_res.from == 0) return error.PrefixNotReused; + if (adopt_res.items.len > 0) try l_res.s.adopt(&e.pool, adopt_res.items, false); + l_res.s.len = plan_res.from; + l_res.s.mtp_len = plan_res.from - 1; + l_res.resumed = true; + try l_res.s.cover(&e.pool, prompt.len); + const y_res_t = try h.chunk(l_res, prompt, plan_res.from, prompt.len, null); + + const got = try Snap.alloc(gpa, h.state_bytes, width, d.vocab); + defer got.deinit(gpa); + try downloadState(e, &l_res.s, got.state); + if (!std.mem.eql(u8, ref.state, got.state)) return error.StateMismatch; + try captureHidden(e, .{ .ptr = l_res.hidden.base(), .kind = e.act }, got.hidden); + if (!std.mem.eql(u8, ref.hidden, got.hidden)) return error.HiddenMismatch; + try checkKv(e, gpa, &l_fresh.s, &l_res.s, prompt.len, "resume prompt"); + try gen.readBack(e, gpa, y_res_t.?, got.logits); + try compareLogits(ref.logits, got.logits, "resume prompt head"); + + // Step 4 decode tokens on both lanes through Hip.windows + keepRows + try l_fresh.s.cover(&e.pool, prompt.len + decode_tail.len); + try l_res.s.cover(&e.pool, prompt.len + decode_tail.len); + const dec_fresh = try gpa.alloc(f32, decode_tail.len * d.vocab); + defer gpa.free(dec_fresh); + const dec_res = try gpa.alloc(f32, decode_tail.len * d.vocab); + defer gpa.free(dec_res); + try gen.readBack(e, gpa, try h.windows(&.{l_fresh}, &.{decode_tail}), dec_fresh); + try h.keepRows(l_fresh, decode_tail.len); + try gen.readBack(e, gpa, try h.windows(&.{l_res}, &.{decode_tail}), dec_res); + try h.keepRows(l_res, decode_tail.len); + try compareLogits(dec_fresh, dec_res, "resume decode"); + try checkKv(e, gpa, &l_fresh.s, &l_res.s, l_fresh.s.len, "resume decode"); + std.debug.print( + "invariance: served prompt-cache resume at {d}/{d} (+{d} decode steps): 0 bits differ\n", + .{ plan_res.from, prompt.len, decode_tail.len }, + ); +} + +pub fn run(gpa: std.mem.Allocator, io: std.Io, args: []const [:0]const u8) !void { + if (args.len < 1) return error.MissingArgument; + const dir = args[0]; + var ids_path: ?[]const u8 = null; + var mtp = true; + for (args[1..]) |arg| { + if (std.mem.eql(u8, arg, "--no-mtp")) { + mtp = false; + } else if (ids_path == null) { + ids_path = arg; + } else return error.UnknownOption; + } + const e = try nem.engine.Engine.open(gpa, io, dir, .{ .capacity = 4096, .streams = 2, .extra_pages = 32, .mtp = mtp }); + defer e.deinit(); + const prompt = try buildPrompt(gpa, io, ids_path, e.model_().dims.vocab); + defer gpa.free(prompt); + if (prompt.len < 193) return error.PromptTooShort; + try checkPromptCuts(gpa, e, prompt); + const tail = [_]u32{ 1001, 2003, 3005, 4007, 5009, 6011, 7013, 8015 }; + try checkDecodeGrouping(gpa, e, prompt[0 .. prompt.len - 8], &tail); + try checkResumePrefix(gpa, e, prompt, tail[0..4]); + std.debug.print("invariance: PASS\n", .{}); +} diff --git a/zig/tests/nemotron_hip/main.zig b/zig/tests/nemotron_hip/main.zig index 41cd64928a5..3d49e7a02ea 100644 --- a/zig/tests/nemotron_hip/main.zig +++ b/zig/tests/nemotron_hip/main.zig @@ -5,6 +5,7 @@ const nem = @import("nemotron"); const gen = @import("gen.zig"); const replay = @import("replay.zig"); +const invariance = @import("invariance.zig"); const Tensor = hip.ops.Tensor; @@ -12,7 +13,7 @@ const Tensor = hip.ops.Tensor; pub const std_options: std.Options = .{ .signal_stack_size = null }; const usage = "usage: tf-nemotron-hip-test load [--capacity N] [--rows N] [--no-mtp] [--tp W " ++ - "--rank R]\n" ++ gen.usage ++ replay.usage; + "--rank R]\n" ++ gen.usage ++ replay.usage ++ invariance.usage; const Args = struct { dir: []const u8 = "", @@ -283,6 +284,7 @@ pub fn main(init: std.process.Init) !u8 { if (args.len >= 3 and std.mem.eql(u8, args[1], "rounds")) return run(gen.rounds, init, args[2..]); if (args.len >= 3 and std.mem.eql(u8, args[1], "trace")) return run(gen.trace, init, args[2..]); if (args.len >= 3 and std.mem.eql(u8, args[1], "replay")) return run(replay.replay, init, args[2..]); + if (args.len >= 3 and std.mem.eql(u8, args[1], "invariance")) return run(invariance.run, init, args[2..]); if (args.len < 3 or !std.mem.eql(u8, args[1], "load")) { std.debug.print(usage, .{}); return 2; diff --git a/zig/tests/nemotron_hip/replay.zig b/zig/tests/nemotron_hip/replay.zig index c56df1e31d8..5baf1becfe9 100644 --- a/zig/tests/nemotron_hip/replay.zig +++ b/zig/tests/nemotron_hip/replay.zig @@ -283,16 +283,17 @@ const Probe = struct { } }; -const KvWhere = struct { slot: usize, pos: usize, key: bool }; +pub const KvWhere = struct { slot: usize, pos: usize, key: bool }; /// The first attention slot and position below `len` whose keys or values differ between the two streams. -fn kvDiffers( +pub fn kvDiffers( e: *nem.engine.Engine, gpa: std.mem.Allocator, a: *nem.pages.Stream, b: *nem.pages.Stream, len: usize, ) !?KvWhere { + try e.stream.synchronize(); const pool = &e.pool; const d = e.model_().dims; const row = d.head_dim * e.act.size(); diff --git a/zig/tests/row_widths_check.zig b/zig/tests/row_widths_check.zig index 327f7bc3d1e..1878b0488ab 100644 --- a/zig/tests/row_widths_check.zig +++ b/zig/tests/row_widths_check.zig @@ -12,7 +12,7 @@ const groups_tested = [_]usize{ 32, 64, 128 }; const Shape = struct { n: usize, k: usize }; // all tail (K < 512), full passes and a tail, full passes only const shapes = [_]Shape{ .{ .n = 64, .k = 384 }, .{ .n = 128, .k = 2688 }, .{ .n = 32, .k = 1536 } }; -const rows = 16; +const rows = 32; // a fused stack's windows reach this many rows const x_rows = 48; const sentinel: u16 = 0xffff; @@ -217,8 +217,8 @@ fn check(device: mtl.Device, queue: mtl.Queue, p: *const row.Pipelines, stock: ? if (alone[i * n + c] == toBf(@floatCast(ref[0]))) t.exact += 1; t.values += 1; }; - // windows of 2, 3, 8 and 16 rows (ending at the last row): each row as it was alone - for ([_]usize{ 2, 3, 8, 16 }) |w| { + // Every width through 32, ending at the last row, equals those rows alone. + for (1..rows + 1) |w| { const start = rows - w; try run(queue, launchAt(try row.call(p, m.w, w, false), start * k * 2, 0), m, out); for (0..w) |i| {