From 6b9de695104b6b8b30c20458da87ac06c9480289 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 14 Nov 2026 22:35:57 +0000 Subject: [PATCH 01/14] flash next cuda: a lone stream draws on its own path, not the group's whole-buffer download On the 1.2.9 release commit, one sampled stream of Flash Next (MLX 4-bit checkpoint, chat, temperature 1.0) decoded about 10% slower than 1.2.8 on a GB10: 48.7, 46.1 and 48.8 tok/s against 43.9, 44.3 and 42.2, alternating runs; the other sweep cells were level or faster. #2927's group path runs a top-k launch and a synchronous download of the whole batch buffer every draw step, which one stream cannot amortise. A lone stream now takes the per-stream draw it had before #2927; two or more streams keep the group draw. Tokens are unchanged either way: both paths draw the same rows, and the batch tests compare them. --- CHANGELOG.md | 2 ++ zig/src/families/flashnext/cuda_draw_batch.zig | 6 ++++-- zig/src/families/flashnext/cuda_draw_batch_test.zig | 12 ++++++++++++ 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a6c4c732909..107cb50010f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## 1.2.9 +- Flash Next on CUDA: a lone stream draws on its own path again; the batched draws #2927 added now run only when two or more streams share a step, so one sampled stream no longer pays the group's whole-buffer download each step. Tokens are unchanged (#3391, after #2927). + - Tests: the sessions writes test on real files does the same coverage with 40 requests at half the token sizes, so it no longer times out on busy CI runners (#3347). - Tests: two CI flakes fixed: the security check accepts the server closing an over-cap request first, and check-release-paths waits for its install before running (#3349). diff --git a/zig/src/families/flashnext/cuda_draw_batch.zig b/zig/src/families/flashnext/cuda_draw_batch.zig index 85c5fa75f18..7b7a778c4be 100644 --- a/zig/src/families/flashnext/cuda_draw_batch.zig +++ b/zig/src/families/flashnext/cuda_draw_batch.zig @@ -63,7 +63,9 @@ pub fn drawsMany(h: *const mtp.Head, st: cuda.Stream, a: std.mem.Allocator, scor if (!mtp.isSampled(sm)) greedy = true else if (k == 0 and draw.usable(sm.?)) k = sm.?.top_k; } if (rows > rows_max) return error.ProposalScoreShape; - if (b.on and (greedy or k != 0)) { + // a lone stream has nothing to share: its own draw skips the group's whole-buffer download + const group = b.on and ds.len > 1; + if (group and (greedy or k != 0)) { if (greedy) try h.best(st, scores, vocab, vocab, rows, b.device.ptr); if (k != 0) try h.topk(st, scores, vocab, vocab, rows, k, b.device.ptr + vals_at, b.device.ptr + cols_at); try st.synchronize(); @@ -72,7 +74,7 @@ pub fn drawsMany(h: *const mtp.Head, st: cuda.Stream, a: std.mem.Allocator, scor var row0: usize = 0; for (ds, sms, masks, outs) |d, sm, mask, out| { defer row0 += d.rows; - if (!b.on or !matching(sm, mask, k)) { + if (!group or !matching(sm, mask, k)) { try draw.draws(h, st, a, d, sm, mask, out); continue; } diff --git a/zig/src/families/flashnext/cuda_draw_batch_test.zig b/zig/src/families/flashnext/cuda_draw_batch_test.zig index 6a62cc587be..d2fddb5e1d6 100644 --- a/zig/src/families/flashnext/cuda_draw_batch_test.zig +++ b/zig/src/families/flashnext/cuda_draw_batch_test.zig @@ -56,6 +56,18 @@ test "Flash Next batch draws: eight mixed streams match serial draws, two grids try t.expectEqualSlices(usize, &.{ 1, 2 }, D.functions[0..D.launches]); try t.expectEqualSlices(u32, &.{ 8, 8 }, D.grids[0..D.launches]); try t.expectEqual(@as(usize, 2), D.waits); + // A lone stream takes its own per-stream draw: the same launches and waits as serial, no group download + D.reset(); + try draw.draws(&h, st, a, refs[0], sms[0], masks[0], &baseline[0]); + const serial: [2]usize = .{ D.launches, D.waits }; + var serial_fn: [8]usize = undefined; + const serial_n = D.launches; + @memcpy(serial_fn[0..serial_n], D.functions[0..serial_n]); + D.reset(); + try batch.drawsMany(&h, st, a, 0x4000, refs[0..1], sms[0..1], masks[0..1], outs[0..1]); + try t.expectEqual(baseline[0], got[0]); + try t.expectEqual(serial, [2]usize{ D.launches, D.waits }); + try t.expectEqualSlices(usize, serial_fn[0..serial_n], D.functions[0..D.launches]); try t.expectEqual(@as(usize, 2), D.reads); // A mismatched K uses its complete smaller set; never a prefix of the larger column-ordered set. sms[1].?.top_k = 2; From 643db9472611dbf056a35b065aef95b6f6bdedc7 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sun, 15 Nov 2026 01:23:35 +0000 Subject: [PATCH 02/14] changelog: Unreleased above 1.2.9 --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 107cb50010f..4a722153d10 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 release notes](RELEASE-NOTES-1.0.0.md) for the native binary's supported models and migration details. +## Unreleased + ## 1.2.9 - Flash Next on CUDA: a lone stream draws on its own path again; the batched draws #2927 added now run only when two or more streams share a step, so one sampled stream no longer pays the group's whole-buffer download each step. Tokens are unchanged (#3391, after #2927). From 9088db9f9be48ab2640d3b3dfb71a87566cf52ee Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Fri, 6 Nov 2026 09:57:58 -0600 Subject: [PATCH 03/14] uocr: Unlimited-OCR-2 on native Metal baidu/Unlimited-OCR-2 at its released bf16 weights on M5-class GPUs: the publisher's preprocessing (bit-exact), the SAM and CLIP image encoder, the DASH MoE decoder with greedy generation, chunked prefill (bit-identical at any cut), serving through tensorfold-native --vision with the family's chat template, and every kernel under the contract. The SAM encoder, the decoder's attention, its page2d rotary and its MoE gate are written from the papers and from the release's modules measured through their inputs and outputs. tf-uocr-blocks gates each encoder step alone against float32, tf-uocr-vision and tf-uocr-decode gate a page's stages, and tools/zig/uocr_reference.py makes their cases from the release's own code. Fed torch bf16's reply, tf-uocr-decode accepts a departure only as a tie: the same two contenders on both sides, each margin within one bf16 step (the reference records every step's two highest logits); --reply-reported reports them instead. The server's built-in templates share one helper (hf_text_parse.zig): Nemotron Parse's replaces the checkpoint's, this family's fills in when the checkpoint ships none, and a --chat-template wins over both. --- THIRD_PARTY_NOTICES.md | 26 + docs/recipes/README.md | 1 + docs/recipes/unlimited-ocr-metal.md | 125 +++++ tools/zig/uocr_reference.py | 344 ++++++++++++ zig/build/dsv41_draft.zig | 1 + zig/build/metal_targets.zig | 4 + zig/build/server.zig | 1 + zig/kernels/metal/sources.zig | 3 + zig/kernels/metal/uocr/decoder.metal | 526 ++++++++++++++++++ zig/kernels/metal/uocr/vision.metal | 328 +++++++++++ zig/src/cli/hub.zig | 1 + zig/src/core/contract/registry_joins.zig | 3 +- .../core/contract/uocr_decoder_records.zig | 16 + zig/src/core/contract/uocr_records.zig | 2 + .../contract/uocr_vision_attn_records.zig | 5 + .../contract/uocr_vision_glue_records.zig | 11 + .../contract/uocr_vision_maps_records.zig | 8 + zig/src/families/uocr/chat.zig | 3 + zig/src/families/uocr/chat_template.jinja | 21 + zig/src/families/uocr/config.zig | 220 ++++++++ zig/src/families/uocr/decoder.zig | 246 ++++++++ zig/src/families/uocr/decoder_pass.zig | 242 ++++++++ zig/src/families/uocr/gate.zig | 116 ++++ zig/src/families/uocr/generate.zig | 80 +++ zig/src/families/uocr/kernels.zig | 138 +++++ zig/src/families/uocr/preprocess.zig | 171 ++++++ zig/src/families/uocr/prompt.zig | 201 +++++++ zig/src/families/uocr/resize.zig | 151 +++++ zig/src/families/uocr/serve.zig | 225 ++++++++ zig/src/families/uocr/uocr.zig | 16 + zig/src/families/uocr/vision.zig | 416 ++++++++++++++ zig/src/families/uocr/weights.zig | 271 +++++++++ zig/src/native/metal.zig | 10 +- zig/src/native/uocr.zig | 106 ++++ zig/src/server/hf_text.zig | 2 +- zig/src/server/hf_text_parse.zig | 36 +- zig/src/server/root.zig | 1 + zig/src/server/uocr_chat_test.zig | 42 ++ zig/src/tensorfold.zig | 3 + zig/tests/contract/metal_limits.zig | 5 + zig/tests/contract/metal_main.zig | 3 + zig/tests/contract/metal_uocr.zig | 86 +++ .../contract/metal_uocr_decoder_attend.zig | 292 ++++++++++ .../contract/metal_uocr_decoder_common.zig | 195 +++++++ zig/tests/contract/metal_uocr_decoder_ffn.zig | 329 +++++++++++ .../contract/metal_uocr_decoder_gate.zig | 268 +++++++++ .../contract/metal_uocr_decoder_glue.zig | 344 ++++++++++++ zig/tests/contract/metal_uocr_decoder_mv.zig | 353 ++++++++++++ zig/tests/contract/metal_uocr_decoder_qk.zig | 446 +++++++++++++++ .../contract/metal_uocr_decoder_route.zig | 433 ++++++++++++++ zig/tests/contract/metal_uocr_vision.zig | 178 ++++++ zig/tests/contract/metal_uocr_vision_attn.zig | 348 ++++++++++++ zig/tests/contract/metal_uocr_vision_glue.zig | 323 +++++++++++ zig/tests/contract/metal_uocr_vision_maps.zig | 345 ++++++++++++ zig/tests/uocr/blocks.zig | 133 +++++ zig/tests/uocr/decode.zig | 300 ++++++++++ zig/tests/uocr/vision.zig | 156 ++++++ 57 files changed, 8649 insertions(+), 10 deletions(-) create mode 100644 docs/recipes/unlimited-ocr-metal.md create mode 100644 tools/zig/uocr_reference.py create mode 100644 zig/kernels/metal/uocr/decoder.metal create mode 100644 zig/kernels/metal/uocr/vision.metal create mode 100644 zig/src/core/contract/uocr_decoder_records.zig create mode 100644 zig/src/core/contract/uocr_records.zig create mode 100644 zig/src/core/contract/uocr_vision_attn_records.zig create mode 100644 zig/src/core/contract/uocr_vision_glue_records.zig create mode 100644 zig/src/core/contract/uocr_vision_maps_records.zig create mode 100644 zig/src/families/uocr/chat.zig create mode 100644 zig/src/families/uocr/chat_template.jinja create mode 100644 zig/src/families/uocr/config.zig create mode 100644 zig/src/families/uocr/decoder.zig create mode 100644 zig/src/families/uocr/decoder_pass.zig create mode 100644 zig/src/families/uocr/gate.zig create mode 100644 zig/src/families/uocr/generate.zig create mode 100644 zig/src/families/uocr/kernels.zig create mode 100644 zig/src/families/uocr/preprocess.zig create mode 100644 zig/src/families/uocr/prompt.zig create mode 100644 zig/src/families/uocr/resize.zig create mode 100644 zig/src/families/uocr/serve.zig create mode 100644 zig/src/families/uocr/uocr.zig create mode 100644 zig/src/families/uocr/vision.zig create mode 100644 zig/src/families/uocr/weights.zig create mode 100644 zig/src/native/uocr.zig create mode 100644 zig/src/server/uocr_chat_test.zig create mode 100644 zig/tests/contract/metal_uocr.zig create mode 100644 zig/tests/contract/metal_uocr_decoder_attend.zig create mode 100644 zig/tests/contract/metal_uocr_decoder_common.zig create mode 100644 zig/tests/contract/metal_uocr_decoder_ffn.zig create mode 100644 zig/tests/contract/metal_uocr_decoder_gate.zig create mode 100644 zig/tests/contract/metal_uocr_decoder_glue.zig create mode 100644 zig/tests/contract/metal_uocr_decoder_mv.zig create mode 100644 zig/tests/contract/metal_uocr_decoder_qk.zig create mode 100644 zig/tests/contract/metal_uocr_decoder_route.zig create mode 100644 zig/tests/contract/metal_uocr_vision.zig create mode 100644 zig/tests/contract/metal_uocr_vision_attn.zig create mode 100644 zig/tests/contract/metal_uocr_vision_glue.zig create mode 100644 zig/tests/contract/metal_uocr_vision_maps.zig create mode 100644 zig/tests/uocr/blocks.zig create mode 100644 zig/tests/uocr/decode.zig create mode 100644 zig/tests/uocr/vision.zig diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index ef5a54266a9..71e72105703 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -499,3 +499,29 @@ The fixtures in `zig/src/server/fixtures/thinking/` are unmodified release files `70ae7fac63274ff2eac54152031433374cb80f2f` (an MLX conversion of [Qwen/Qwen3.8-27B](https://huggingface.co/Qwen/Qwen3.8-27B), whose template it carries), under the Apache License 2.0. See [`LICENSES/Apache-2.0.txt`](LICENSES/Apache-2.0.txt). + +## Unlimited-OCR-2 + +The `unlimited-ocr` family (`zig/src/families/uocr/` and its kernels) follows these parts of the Python code that ships +with [baidu/Unlimited-OCR-2](https://huggingface.co/baidu/Unlimited-OCR-2) at revision +`0480966938291445591f69f08a13b041c073a96a`, the release's own files: + +- `modeling_unlimitedocr.py`: the page guard (`_uocr_page_count_guard`), gundam's tiles (`dynamic_preprocess`, + `find_closest_aspect_ratio`), the views' token layout and the prompt (`_uocr_build_inputs`, `infer`), which + `generate.zig`, `preprocess.zig`, `prompt.zig` and `chat_template.jinja` repeat; +- `deepencoder.py`, its CLIP section only (`CLIPVisionEmbeddings`, `NoTPTransformer`, `VitModel`, `quick_gelu`, + `get_abs_pos`; the release's own code, citing no library there): the class row, the position table resized to a + tile, the pre-norm, `quick_gelu`'s 1.702 and the layer order, which `vision.zig`'s CLIP steps repeat; +- `dash_attention.py` and `modeling_deepseekv2.py`: the DASH router (block keys, page-aware candidates, top 16, + entmax-1.5). + +The release ships no LICENSE file; its model card states `license: mit`, and these notices carry that licence's text +("MIT License text" above). The SAM encoder, the decoder's attention, its page2d rotary and its MoE gate follow none of +the release's code: they are written from the papers and from the release's modules measured through their inputs and +outputs. `resize.zig` follows no code either: it is the antialiased bicubic the release asks of torch +(`F.interpolate(mode="bicubic", antialias=True, align_corners=False)`, Keys' cubic with a = -0.5, taps spread by the +scale and normalised) for the position tables, written to that operator's definition, with its fp32 rounding order fixed +by measuring torch's output on the release's tables bit for bit. + +TensorFold ships none of these files and no Unlimited-OCR-2 weights; `tools/zig/uocr_reference.py` runs the release's +own code as the reference. diff --git a/docs/recipes/README.md b/docs/recipes/README.md index 7b8d7762288..ba941b0e436 100644 --- a/docs/recipes/README.md +++ b/docs/recipes/README.md @@ -31,6 +31,7 @@ For agent-assisted contributions, read the [TensorFold contributor skill](SKILL. | Spark-X2.6-4B | [Native CUDA](spark-x2.6-4b-cuda.md), [native Metal, the bf16 release, contexts to 1M](spark-x2.6-4b-metal.md) | | Nanbeige4.3-33B | [Native Metal, the bf16 and INT4 releases, the Llama family](nanbeige-4.3-33b-metal.md) | | Recursive Flint | [Native Metal, the publisher's affine 4-bit export, reasoning and tool calls](flint.md) | +| Unlimited-OCR-2 | [Native Metal, the bf16 release: page images to structured text, 131k context](unlimited-ocr-metal.md) | [Persisted serving-state identities](persisted-serving-keys.md) lists the disk owners, their compatibility keys and stale-state host checks. diff --git a/docs/recipes/unlimited-ocr-metal.md b/docs/recipes/unlimited-ocr-metal.md new file mode 100644 index 00000000000..6ac4eccecff --- /dev/null +++ b/docs/recipes/unlimited-ocr-metal.md @@ -0,0 +1,125 @@ +# Unlimited-OCR-2 on Metal + +The native Metal engine serves Baidu's BF16 `baidu/Unlimited-OCR-2` at revision +`0480966938291445591f69f08a13b041c073a96a`, as published: the release's safetensors are read directly, with no +converted pack and no Python or libtorch in the served engine. It was qualified with Zig 0.17.0 on an M5 Ultra +(256 GB); the family needs the M5's tensor units and refuses other GPUs. + +## Build and start + +```sh +zig build native -Doptimize=ReleaseFast +zig-out/native/bin/tensorfold-native serve \ + --name Unlimited-OCR-2 --host 127.0.0.1 --port 8896 --vision --vision-max-images 64 \ + --context 131072 --max-tokens 131072 --no-update-check +``` + +The release ships no chat template, so the server uses the family's own (`zig/src/families/uocr/chat_template.jinja`): +one page marker and image per image part, then the user's text, or the publisher's default instruction +`Multi page parsing.` when there is none. A checkpoint's own template, or `--chat-template`, takes its place. +JPEG pages need libjpeg-turbo 3.1.4.1 (`TENSORFOLD_LIBTURBOJPEG`), which keeps their pixels equal to the reference's; +PNG and WebP need nothing extra. + +## Requests + +Send page images as `image_url` parts (data URLs) in one user message of a `/v1/chat/completions` request, in reading +order. The reply is the publisher's layout format: one `` per page, then `` lines naming each block's +kind, its box on a 0-999 page grid and its text, with tables as HTML and formulas as LaTeX. The model writes no +reasoning block; the reply is always `content`. + +- **Page modes.** Each page takes gundam mode (the 1024 global view and 640 tiles, the publisher's server default) + when its tokens fit the request's image budget, else base mode (the global view alone, 273 tokens). Without + `--vision-image-tokens` the budget lets every page take gundam's widest grid (2,033 tokens a page). +- **Decoding.** Greedy, under the publisher's page guard: the reply ends after the last page's text. A request + without `max_tokens` may use all the room its pages leave in the context, as the publisher's `infer` does. +- **Streams.** One request at a time; a second waits for the first. A `--parallel` above 1 is refused. + +## Memory + +The weights take 6.3 GiB and the caches 66 KiB a token (bf16 keys and values, fp32 router keys): 8.25 GiB at the full +131,072 tokens. The served process measured 17 GB resident at that context. + +## Checks + +`tools/zig/uocr_reference.py` is the reference. It runs the release's own code on the CPU (transformers 4.52.1, the +model card's) and reads it only through its modules' inputs and outputs: + +- `pages` writes the check pages (two synthetic report pages and three pages of the paper the release ships). +- `capture` runs `infer` in torch bf16 and keeps the prompt ids, generated ids and text. +- `dump` keeps a page's stages, from torch bf16 and from float32 on the same bf16 pixels: each view's pixels and its + SAM, CLIP and projector outputs, the decoder's input rows, every layer's prompt rows, the first logits and the reply. +- `blocks` takes one view of a dump through float32 and keeps each step's input and output (every SAM block, the neck + and its two convolutions, CLIP's embedding and pre-norm, every CLIP layer, the projector), then runs torch bf16 on + each step alone from the same input rounded to bf16. + +Three tools gate the engine against float32. Each limit is twice torch bf16's own distance from float32 (or bf16 +rounding's), in cosine error and in the worst row's relative error: + +- `tf-uocr-blocks` runs each step of the image encoder alone on the reference's input, and every step must be within + its limits. +- `tf-uocr-vision` encodes a dump's views (after checking that its own preprocessing gives the same pixels bit for + bit). SAM's output must be within its limits; CLIP's and the projector's are reported against the same limits but + not gated. CLIP takes SAM's output, and a few of its rows magnify bf16 rounding there: on the first gundam page + (report-1), the tile view 1's CLIP row 79 is 0.186 from float32 in relative error, against a limit of 0.166 (twice + torch bf16's worst row, 0.083), though every step on the way there is within its limits alone (at most 0.53 of them). +- `tf-uocr-decode` runs a page end to end: the prompt ids and the text rows must equal torch's, and with + `--their-embeds` (the decoder alone on torch's input rows) every layer and the first logits must be within their + limits. From our own image rows they are reported, as CLIP is. `--chunk ROWS` checks that a prompt cut into chunks + gives the same bits, and every tool runs twice and must repeat byte for byte. + +On report-1 (gundam, 909 prompt tokens) and on the same page in base mode (279): + +- Each step alone passes on the tile view 1 and the global view: SAM blocks at most 0.53 of their limits, the neck + 0.27, CLIP's front 0.50, CLIP layers 0.52, the projector 0.50. A 5% error planted in one row of each kind of step + fails it. +- Decode passes in both modes. With torch's input rows, ours picks torch bf16's token at all 197 steps. From our own + rows, the reply equals torch float32's for all 197 tokens; torch bf16's departs from float32's at token 10. Layer 8's + worst row is reported over its limit there (2.93 against 2.88); it is within it from torch's rows (1.44). + +On the five-page document (4,525 prompt tokens) one row does the same: from our own rows, row 1934 is over the worst-row +limit at layers 8 to 10 (3.12 against 2.93 at layer 8), with every layer's cosine and the first logits within their +limits; from torch's rows it is 1.45 at layer 8 and every gate passes. + +Measured on the served engine (M5 Ultra; another model's server loaded on the same GPU, idle) with the recipe +harness's `ocr` plan, each case once, again and as two requests at once: + +| Pages | Prompt tokens | Reply tokens | First token | Decode | Text vs reference | Box coordinates moved | +|---|---:|---:|---:|---:|---|---:| +| report-1 | 909 | 198 | 0.48 s | 299.4 tok/s | identical | 2 / 16 (at most 2) | +| report-2 | 909 | 141 | 0.28 s | 301.1 tok/s | identical | 0 / 16 | +| paper-1 | 909 | 543 | 0.28 s | 297.1 tok/s | identical | 1 / 44 (1) | +| paper-3 | 909 | 911 | 0.28 s | 301.1 tok/s | citations written as `$ [5, 6, ...] $` | 1 / 44 (1) | +| paper-10 | 909 | 2,004 | 0.29 s | 298.3 tok/s | table headers written in LaTeX | 0 / 28 | +| all five as one document | 4,525 | 3,767 | 1.70 s | 282.5 tok/s | differs; 34 boxes against 35 | 98 / 136 (at most 824) | + +The reference is the release's own `infer` in torch bf16 on the CPU; its float32 run departs from it too (paper-3 at +token 13, paper-10 at 1,660, the document at 16). **The single pages are what this recipe claims:** fed torch bf16's +reply, `tf-uocr-decode` picks otherwise at 2 of report-1's 197 steps, 1 of paper-1's 542, 2 of paper-3's 898 and 1 of +paper-10's 1,958 (report-2 has none), and each is a tie under the one-step policy, the same two contenders on both +sides with both margins within one bf16 step, which the tool now gates: report-1 step 10 (torch 2892 and 4774 equal, +ours 4774 by one step) and step 33 (torch 27738 and 29037 equal, ours 29037 by one), paper-1 step 88 (torch 10410 and +10669 equal, ours 10669 by one), paper-3 step 145 (torch 764 over 223 by one step, ours 223 by 0), step 557 (torch 27343 +and 26670 equal, ours 27343 by one step) and paper-10 step 67 (torch 7233 over 3289 by one step, ours 3289 by 0). +report-1's and paper-1's other tokens render the same text, so their transcripts are identical. **The five-page document +is reported beside them, outside that policy:** of its 4 departures in 3,763 steps, 16 (torch 6420 over 6207 by one +step, ours 6207 by 0) and 757 (torch 26934 over 25282 by one step, ours 25282 by 0) are ties, but at step 300 torch +bf16 holds 16259 and 16208 equal where ours has 16259 by two steps, and at 431 torch has 13636 over 12326 by one step +where ours has 12326 by three. Float32 sits on our side of both (16259 by 1.7 steps, 12326 by 2.1); on torch's own +image rows (`--their-embeds`) only 431 departs, by one step, so the two wider margins come from our image rows (row +1934 of page 3, which `tf-uocr-blocks` finds no further from float32 than torch bf16 at any stage). The tool's +`--reply-reported` runs the document this way. A different pick sends the rest of the reply its own way; in the document +that moves a box and the coordinates after it. Repeats and concurrent requests give the same replies. + +The harness pairs boxes in reading order. In the document the reference writes one box that ours does not, an empty +`other` block spanning paper-3's three contribution items after their own boxes, so from there each of our boxes is +compared with the reference's next one: that is the 824. Set that box aside and the other 34 pair up, with 74 of their +136 coordinates moved, by at most 3. + +## Supported scope + +BF16 on M5 GPUs, one stream, greedy, up to 131,072 tokens. A request takes 4 pages by default, and +`--vision-max-images` raises that to 64. Sampling, the publisher's optional n-gram repetition filter, a prompt cache, drafts, tools +and structured output are not offered. The family's 24 Metal kernels (12 in the image encoder, 12 in the decoder) are +registered with the kernel contract, each with a launch record, through 30 gate cases (a case per dispatch form: +`uv_attention` for SAM and for CLIP, `uv_im2col` for its three convolutions, `ud_attend` for prompt rows and steps, +`ud_norm` alone and with each of its two additions). diff --git a/tools/zig/uocr_reference.py b/tools/zig/uocr_reference.py new file mode 100644 index 00000000000..74596611939 --- /dev/null +++ b/tools/zig/uocr_reference.py @@ -0,0 +1,344 @@ +#!/usr/bin/env python3 +"""Unlimited-OCR-2's reference: the release's own code on the CPU, in torch bf16 and float32 (see --help).""" + +USAGE = """Unlimited-OCR-2's reference: the release's own `infer` (modeling_unlimitedocr.py) on the CPU, greedy, in +torch bf16 and float32: the transcripts, stage dumps and block cases the native engine is compared with. It reads the +release's modules only through their inputs and outputs (forward hooks). + +Pinned: baidu/Unlimited-OCR-2 at 0480966938291445591f69f08a13b041c073a96a, transformers 4.52.1 (the model card's), +torch 2.15.0 (the card tests 2.13.0 on CUDA; this runs on the CPU), Pillow 13.0.0, PyMuPDF 1.27.2.2. + + pages DIR MODEL writes the check pages to DIR: two synthetic report pages (A4 at 150 dpi, macOS's Arial) + and pages 1, 3 and 10 of the paper the release ships (Unlimited-OCR-2.pdf) at 150 dpi + capture MODEL OUT CASE=PAGE[,PAGE...] ... [--base] + runs `infer` on each case's pages in order (gundam mode, the publisher's server default; + --base for the global view alone) and writes OUT/.json: the prompt ids, the + generated ids and the text + dump MODEL OUT PAGE[,PAGE...] [--base] + the stage dumps tf-uocr-vision and tf-uocr-decode read: `infer` in bf16 with hooks writes + OUT.safetensors (each image encoder call's pixels{i}, sam{i}, clip{i} and projector{i}; the + decoder's input rows `embeds`, each layer's prompt rows layer{l}, the first `logits`) and + OUT.json (prompt and generated ids, text, and `top2`: each step's two highest logits, + id and value, which tf-uocr-decode's tie check reads); the float32 model on the same bf16 + pixels and prompt writes OUT-f32.safetensors and OUT-f32.json (its own greedy reply) + blocks MODEL DUMP OUT --call I --view V + the block cases tf-uocr-blocks reads, for one view of a dump: float32 runs SAM and CLIP on + its pixels and keeps each SAM block's and CLIP layer's input and output; torch bf16 then + runs each alone on its float32 input rounded to bf16. OUT.safetensors holds, per tower + (sam, clip), _in [blocks, rows, width] bf16, _f32 and _bf16 outputs; + and the steps between them the same way: SAM's neck and convolutions (neck_*), CLIP's + embedding and pre-norm (front_*) and the projector (project_cx, project_m3, project_*) + +Compare a served reply with the reference's text: `tensorfold-native serve MODEL --vision`, then the same pages in +one chat request.""" + +import argparse +import json +import sys +import time +from pathlib import Path + +FONT = "/System/Library/Fonts/Supplemental/Arial.ttf" +BOLD = "/System/Library/Fonts/Supplemental/Arial Bold.ttf" +PAPER_PAGES = (1, 3, 10) + + +def _report(lines, path): + from PIL import Image, ImageDraw, ImageFont + im = Image.new("RGB", (1240, 1754), "white") + d = ImageDraw.Draw(im) + y = 110 + for kind, text in lines: + if kind == "h": + d.text((110, y), text, font=ImageFont.truetype(BOLD, 44), fill="black") + y += 80 + elif kind == "p": + for row in text: + d.text((110, y), row, font=ImageFont.truetype(FONT, 28), fill="black") + y += 40 + y += 24 + elif kind == "t": + f = ImageFont.truetype(FONT, 26) + for row in text: + for c, cell in enumerate(row): + d.text((120 + 330 * c, y + 8), cell, font=f, fill="black") + d.line([(110, y), (1100, y)], fill="black", width=2) + y += 48 + d.line([(110, y), (1100, y)], fill="black", width=2) + y += 40 + im.save(path) + + +def pages(out: Path, model: Path) -> None: + import fitz # PyMuPDF + out.mkdir(parents=True, exist_ok=True) + _report([("h", "1. Quarterly Report"), + ("p", ["The third quarter closed with revenue of 4.2 million dollars,", "an increase of 12 percent over the same period last year.", + "Operating costs rose by 3 percent, mostly from new hiring."]), + ("t", [["Region", "Revenue", "Growth"], ["North", "1.6 M", "+14%"], ["South", "1.1 M", "+9%"], ["West", "1.5 M", "+12%"]]), + ("p", ["The board approved a dividend of 0.25 per share, payable", "on the fifteenth of December to holders of record."])], + out / "report-1.png") + _report([("h", "2. Outlook"), + ("p", ["For the fourth quarter we expect revenue between 4.3 and", "4.6 million dollars. The new warehouse in Leeds opens", + "in January and will shorten delivery times by two days."]), + ("h", "3. Risks"), + ("p", ["Currency movements and shipping costs remain the main risks.", "A 10 percent rise in freight rates would reduce the", + "operating margin by about one point."])], + out / "report-2.png") + doc = fitz.open(model / "Unlimited-OCR-2.pdf") + for n in PAPER_PAGES: + doc[n - 1].get_pixmap(dpi=150).save(out / f"paper-{n}.png") + for p in sorted(out.glob("*.png")): + print(p) + + +def _load(model: Path, dtype): + import torch + from transformers import AutoModel, AutoTokenizer + torch.Tensor.cuda = lambda self, *a, **k: self # the release's code moves masks with .cuda(); this runs on the CPU + tok = AutoTokenizer.from_pretrained(model, trust_remote_code=True) + m = AutoModel.from_pretrained(model, trust_remote_code=True, use_safetensors=True, torch_dtype=dtype).eval() + return m, tok + + +def capture(model: Path, out: Path, cases: list[str], base: bool) -> None: + import torch + m, tok = _load(model, torch.bfloat16) + out.mkdir(parents=True, exist_ok=True) + for case in cases: + name, files = case.split("=", 1) + files = files.split(",") + t = time.time() + res = m.infer(tok, image_file=files if len(files) > 1 else files[0], crop_mode=not base, return_dict=True) + keep = {k: (v.tolist() if hasattr(v, "tolist") else v) for k, v in res.items() + if isinstance(v, (str, list, int, float)) or hasattr(v, "tolist")} + keep.update(pages=files, mode="base" if base else "gundam", seconds=round(time.time() - t, 1)) + (out / f"{name}.json").write_text(json.dumps(keep)) + print(f"{name}: {len(keep.get('token_ids', []))} tokens in {keep['seconds']} s", flush=True) + + +class _Stop(Exception): + pass + + +def _first(o): + return o[0] if isinstance(o, tuple) else o + + +def _infer_hooked(m, tok, files, base, pixels=None): + """`infer` with hooks; `pixels` (one per encoder call) replace the views' pixels when given.""" + import torch + mm = m.model + cap = {"ids": None, "emb": None, "layers": {}, "logits": None, "top2": [], "calls": []} + hs = [] + + def sam_pre(mod, a): + i = len(cap["calls"]) + px = (a[0] if pixels is None else pixels[i]).to(next(mod.parameters()).dtype) + cap["calls"].append({"pixels": px.detach().clone()}) + return (px,) + tuple(a[1:]) + + def vision_pre(mod, a): + px = a[0] if pixels is None else pixels[len(cap["calls"]) - 1] + return (px.to(next(mod.parameters()).dtype),) + tuple(a[1:]) + + def keep(name): + def f(mod, a, o): + cap["calls"][-1][name] = _first(o).detach().clone() + return f + + def ids_hook(mod, a, o): + if cap["ids"] is None: + cap["ids"] = a[0][0].tolist() + + def emb_hook(mod, a, kw): + if cap["emb"] is None: + cap["emb"] = (a[0] if a else kw["hidden_states"]).detach().clone() + + def layer_hook(l): + def f(mod, a, o): + if l not in cap["layers"]: + cap["layers"][l] = _first(o).detach().clone() + return f + + def head_hook(mod, a, o): + last = o[0, -1].detach().float() + if cap["logits"] is None: + cap["logits"] = last.clone() + top = torch.topk(last, 2) # the step's two contenders, for the engine's tie check + cap["top2"].append([int(top.indices[0]), float(top.values[0]), int(top.indices[1]), float(top.values[1])]) + + hs += [mm.sam_model.register_forward_pre_hook(sam_pre), mm.vision_model.register_forward_pre_hook(vision_pre), + mm.sam_model.register_forward_hook(keep("sam")), mm.vision_model.register_forward_hook(keep("clip")), + mm.projector.register_forward_hook(keep("projector")), mm.embed_tokens.register_forward_hook(ids_hook), + mm.layers[0].register_forward_pre_hook(emb_hook, with_kwargs=True), + m.lm_head.register_forward_hook(head_hook)] + hs += [layer.register_forward_hook(layer_hook(l)) for l, layer in enumerate(mm.layers)] + try: + with torch.no_grad(): + res = m.infer(tok, image_file=files if len(files) > 1 else files[0], crop_mode=not base, return_dict=True) + finally: + for h in hs: + h.remove() + return cap, res + + +def _save_dump(cap, res, out: Path, gen): + import torch + from safetensors.torch import save_file + t = {"embeds": cap["emb"].contiguous(), "logits": cap["logits"][None].contiguous()} + for i, c in enumerate(cap["calls"]): + for k in ("pixels", "sam", "clip", "projector"): + t[f"{k}{i}"] = c[k].contiguous() + for l, v in cap["layers"].items(): + t[f"layer{l}"] = v.contiguous() + save_file(t, f"{out}.safetensors") + top2 = cap["top2"][:len(gen)] # one lm_head call a step; a trailing call after the last token is dropped + Path(f"{out}.json").write_text(json.dumps({"prompt": cap["ids"], "gen": gen, "text": res.get("text", ""), "top2": top2})) + + +def dump(model: Path, out: Path, files: list[str], base: bool) -> None: + import gc + import torch + m, tok = _load(model, torch.bfloat16) + cap, res = _infer_hooked(m, tok, files, base) + gen = [int(x) for x in res.get("token_ids", [])] + _save_dump(cap, res, out, gen) + print(f"{out}: {len(cap['calls'])} encoder calls, prompt {len(cap['ids'])}, reply {len(gen)}", flush=True) + pixels = [c["pixels"] for c in cap["calls"]] + del m, cap + gc.collect() + m, tok = _load(model, torch.float32) + cap, res = _infer_hooked(m, tok, files, base, pixels=pixels) + gen = [int(x) for x in res.get("token_ids", [])] + _save_dump(cap, res, Path(f"{out}-f32"), gen) + print(f"{out}-f32: {len(cap['calls'])} encoder calls, reply {len(gen)}", flush=True) + + +def _cast(x, dtype): + import torch + if isinstance(x, torch.Tensor) and x.is_floating_point(): + return x.to(dtype, copy=True) + if isinstance(x, (list, tuple)): + return type(x)(_cast(v, dtype) for v in x) + if isinstance(x, dict): + return {k: _cast(v, dtype) for k, v in x.items()} + return x + + +def blocks(model: Path, dump_path: Path, out: Path, call: int, view: int) -> None: + import gc + import torch + from safetensors.torch import load_file, save_file + px = load_file(dump_path)[f"pixels{call}"][view:view + 1] + m, _ = _load(model, torch.float32) + mm = m.model + towers = {"sam": list(mm.sam_model.blocks), "clip": list(mm.vision_model.transformer.layers)} + seen = {t: [] for t in towers} + hs = [] + for t, mods in towers.items(): + for b in mods: + def pre(mod, a, kw, t=t): + seen[t].append({"args": _cast(a, torch.float32), "kw": kw}) + def post(mod, a, kw, o, t=t): + seen[t][-1]["out"] = _first(o).detach().clone() + hs += [b.register_forward_pre_hook(pre, with_kwargs=True), b.register_forward_hook(post, with_kwargs=True)] + with torch.no_grad(): + p = px.float() + feat = mm.sam_model(p) + cl = mm.vision_model(p, feat) + # the projector takes CLIP's rows (without the class row) beside SAM's + proj = mm.projector(torch.cat((cl[:, 1:], feat.flatten(2).permute(0, 2, 1)), dim=-1)) + for h in hs: + h.remove() + del m + gc.collect() + m, _ = _load(model, torch.bfloat16) + mm = m.model + towers = {"sam": list(mm.sam_model.blocks), "clip": list(mm.vision_model.transformer.layers)} + t = {} + with torch.no_grad(): + for name, mods in towers.items(): + ins, f32s, bfs = [], [], [] + for b, s in zip(mods, seen[name]): + x = s["args"][0] + ins.append(x.to(torch.bfloat16).reshape(-1, x.shape[-1])) + f32s.append(s["out"].reshape(-1, x.shape[-1])) + y = b(*_cast(s["args"], torch.bfloat16), **_cast(s["kw"], torch.bfloat16)) + bfs.append(_first(y).reshape(-1, x.shape[-1])) + t[f"{name}_in"] = torch.stack(ins).contiguous() + t[f"{name}_f32"] = torch.stack(f32s).float().contiguous() + t[f"{name}_bf16"] = torch.stack(bfs).to(torch.bfloat16).contiguous() + bf = torch.bfloat16 + rows = lambda x: x.flatten(2).permute(0, 2, 1)[0] # SAM's [1, 1024, side, side] as rows + pb = px.to(bf) + # the neck and its convolutions: SAM in bf16 with block 11's output replaced by float32's, rounded + last = seen["sam"][-1]["out"] + h = mm.sam_model.blocks[-1].register_forward_hook(lambda mod, a, o: last.to(bf)) + t["neck_in"] = last.to(bf).reshape(-1, last.shape[-1]).contiguous() + t["neck_f32"] = rows(feat).float().contiguous() + t["neck_bf16"] = rows(mm.sam_model(pb)).to(bf).contiguous() + h.remove() + # CLIP's embedding and pre-norm: CLIP in bf16 on float32's SAM output, rounded, up to layer 0's input + got = {} + def front(mod, a, kw): + got["x"] = a[0] if a else kw["hidden_states"] + raise _Stop() + h = mm.vision_model.transformer.layers[0].register_forward_pre_hook(front, with_kwargs=True) + try: + mm.vision_model(pb, feat.to(bf)) + except _Stop: + pass + h.remove() + x0 = seen["clip"][0]["args"][0] + t["front_in"] = rows(feat).to(bf).contiguous() + t["front_f32"] = x0.reshape(-1, x0.shape[-1]).float().contiguous() + t["front_bf16"] = got["x"].reshape(-1, x0.shape[-1]).to(bf).contiguous() + # the projector on float32's CLIP and SAM rows, rounded + t["project_cx"] = cl[0].to(bf).contiguous() + t["project_m3"] = rows(feat).to(bf).contiguous() + t["project_f32"] = proj[0].float().contiguous() + fused = torch.cat((cl[:, 1:].to(bf), feat.flatten(2).permute(0, 2, 1).to(bf)), dim=-1) + t["project_bf16"] = mm.projector(fused)[0].to(bf).contiguous() + t["pixels"] = px.contiguous() + save_file(t, f"{out}.safetensors") + shapes = ", ".join(f"{k} {tuple(v.shape)}" for k, v in t.items()) + print(f"{out}: view {view} of call {call} ({px.shape[-1]}), {shapes}", flush=True) + + +def main(argv=None) -> int: + p = argparse.ArgumentParser(description=USAGE, formatter_class=argparse.RawDescriptionHelpFormatter) + sub = p.add_subparsers(dest="cmd", required=True) + pg = sub.add_parser("pages", help="write the check pages") + pg.add_argument("dir", type=Path) + pg.add_argument("model", type=Path) + cp = sub.add_parser("capture", help="the reference's transcripts of CASE=PAGE[,PAGE...]") + cp.add_argument("model", type=Path) + cp.add_argument("out", type=Path) + cp.add_argument("cases", nargs="+") + cp.add_argument("--base", action="store_true", help="the global view alone (crop_mode=False)") + dp = sub.add_parser("dump", help="the stage dumps of PAGE[,PAGE...] (OUT and OUT-f32)") + dp.add_argument("model", type=Path) + dp.add_argument("out", type=Path) + dp.add_argument("pages") + dp.add_argument("--base", action="store_true", help="the global view alone (crop_mode=False)") + bp = sub.add_parser("blocks", help="the block cases of one view of a dump") + bp.add_argument("model", type=Path) + bp.add_argument("dump", type=Path) + bp.add_argument("out", type=Path) + bp.add_argument("--call", type=int, default=0) + bp.add_argument("--view", type=int, default=0) + a = p.parse_args(argv) + if a.cmd == "pages": + pages(a.dir, a.model.expanduser()) + elif a.cmd == "capture": + capture(a.model.expanduser(), a.out, a.cases, a.base) + elif a.cmd == "dump": + dump(a.model.expanduser(), a.out, a.pages.split(","), a.base) + else: + blocks(a.model.expanduser(), a.dump, a.out, a.call, a.view) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/zig/build/dsv41_draft.zig b/zig/build/dsv41_draft.zig index bb0e5daa49c..8fb3acdd52f 100644 --- a/zig/build/dsv41_draft.zig +++ b/zig/build/dsv41_draft.zig @@ -76,6 +76,7 @@ pub fn serverOn(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.b m.addImport("json", engine.import_table.get("dsv41_serve").?.import_table.get("json").?); m.addImport("dsv41_serve", engine.import_table.get("dsv41_serve").?); m.addImport("dsv41_chat", engine.import_table.get("dsv41_serve").?); + m.addImport("uocr_chat", b.createModule(.{ .root_source_file = b.path("zig/src/families/uocr/chat.zig"), .target = target, .optimize = optimize })); // the server's Drama voice catalog reads the prompt builder; this engine set has no drama3 family to share m.addImport("drama_prompt", b.createModule(.{ .root_source_file = b.path("zig/src/families/drama3/prompt.zig"), .target = target, .optimize = optimize })); const exe = b.addExecutable(.{ .name = name, .root_module = m }); diff --git a/zig/build/metal_targets.zig b/zig/build/metal_targets.zig index b4fedda3b90..0211c0aca39 100644 --- a/zig/build/metal_targets.zig +++ b/zig/build/metal_targets.zig @@ -145,6 +145,7 @@ pub fn nativeServer(b: *std.Build, target: std.Build.ResolvedTarget, optimize: s engines.addImport("lanes", api.import_table.get("lanes").?); b.step("test-draft-metal-host", "Metal draft source metadata without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = engines, .filters = &.{"draft sources:"} })).step); b.step("test-drafter-skip-metal-host", "Counted shared draft skips without device execution").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = engine, .filters = &.{"zero grant:"} })).step); + b.step("test-uocr", "Unlimited-OCR-2's tests (its kernels compile on this GPU)").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = engine, .filters = &.{"uocr:"} })).step); b.step("test-native", "The Metal engines module's host-side tests").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = engines })).step); const reuse = b.addExecutable(.{ .name = "tf-flashnext-reuse", .root_module = b.createModule(.{ .root_source_file = b.path("zig/tests/flashnext_reuse.zig"), @@ -351,6 +352,9 @@ pub fn metalTargets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: s .{ .name = "tf-moss-image-decoder", .path = "zig/tests/moss_image_decoder.zig", .about = "MOSS-Image's image decoder on latents, gated against float64 beside torch float32, then timed" }, .{ .name = "tf-moss-image-blocks", .path = "zig/tests/moss_image_blocks.zig", .about = "MOSS-Image's transformer on one step, each block alone gated against float32, repeated byte for byte" }, .{ .name = "tf-moss-image-generate", .path = "zig/tests/moss_image_generate.zig", .about = "MOSS-Image from options alone: prompts, schedule and noise, then the decoder's picture" }, + .{ .name = "tf-uocr-decode", .path = "zig/tests/uocr/decode.zig", .about = "Unlimited-OCR-2 end to end on a page against a reference dump: prompt, layers, logits, greedy reply" }, + .{ .name = "tf-uocr-vision", .path = "zig/tests/uocr/vision.zig", .about = "Unlimited-OCR-2's image encoder on a reference dump's pixels: SAM gated against float32, CLIP and the projector reported" }, + .{ .name = "tf-uocr-blocks", .path = "zig/tests/uocr/blocks.zig", .about = "Unlimited-OCR-2's image encoder step by step: each SAM block, the neck, CLIP's front, each CLIP layer and the projector alone against float32" }, .{ .name = "tf-glm-attn-probe", .path = "zig/tests/glm_attn_probe.zig", .about = "GLM-5.3-Flash's dense latent attention kernels on given inputs (scores, probabilities, outputs)" }, .{ .name = "tf-moe-bench", .path = "zig/tests/moe_bench.zig", .about = "Routed-expert prompt kernels from .metal files on a skewed routing: chained speed, bits against the first" }, .{ .name = "tf-mm-bench", .path = "zig/tests/mm_bench.zig", .about = "Prompt matmul kernels from .metal files: chained speed at one shape, bits against the first, error against fp64" }, diff --git a/zig/build/server.zig b/zig/build/server.zig index 21e55c9e8bd..f581c6bd36c 100644 --- a/zig/build/server.zig +++ b/zig/build/server.zig @@ -55,6 +55,7 @@ pub fn addTo( .optimize = optimize, .imports = &.{.{ .name = "json", .module = j }}, })); + m.addImport("uocr_chat", b.createModule(.{ .root_source_file = b.path("zig/src/families/uocr/chat.zig"), .target = target, .optimize = optimize })); const family = if (m.import_table.get("native_engines")) |engines| engines.import_table.get("drama3") else null; if (family) |drama3| { const source = b.addWriteFiles().add("drama_prompt.zig", diff --git a/zig/kernels/metal/sources.zig b/zig/kernels/metal/sources.zig index 90556bce078..290235b0c67 100644 --- a/zig/kernels/metal/sources.zig +++ b/zig/kernels/metal/sources.zig @@ -150,6 +150,9 @@ pub const core_qwen_vision = vision_glue ++ @embedFile("core/qwen_vision.metal") pub const qwen_image = @embedFile("prefill/attention_nax.metal") ++ @embedFile("qwen_image.metal"); /// MOSS-Image: the prefill attention template, then its transformer's and encoder's steps (gemms: core_qwen_vision). pub const moss_image = @embedFile("prefill/attention_nax.metal") ++ @embedFile("moss_image.metal") ++ @embedFile("moss_image_encoder.metal"); +/// Unlimited-OCR-2: its image encoder's and decoder's own steps (projections: core_qwen_vision). +pub const uocr = @embedFile("uocr/vision.metal"); +pub const uocr_decoder = @embedFile("uocr/decoder.metal"); /// MOSS-Image's image decoder: its own float32 steps, without a template. pub const moss_image_decoder = @embedFile("moss_image_decoder.metal"); /// A prompt chunk's KDA layer in three passes, appended to the generated kda_rows source (its helpers). diff --git a/zig/kernels/metal/uocr/decoder.metal b/zig/kernels/metal/uocr/decoder.metal new file mode 100644 index 00000000000..c768098aef1 --- /dev/null +++ b/zig/kernels/metal/uocr/decoder.metal @@ -0,0 +1,526 @@ +// Unlimited-OCR-2's decoder steps on Metal: norms, rotary, the block router, attention and the experts' glue. + +#include +using namespace metal; + +constant constexpr uint UD_H = 1280, UD_HD = 128, UD_HEADS = 10, UD_BLK = 32, UD_LOCAL = 128, UD_RD = 128; +constant constexpr uint UD_READ = 12, UD_TOP = 16, UD_EXPERTS = 64, UD_PICK = 6, UD_PROJ = 4096; +// The router's last block a query may read sits this many blocks before its own (the local window's blocks). +constant constexpr uint UD_LOCAL_BLOCKS = 4; +// Scores past these clamp, and the release's floor under a block's entmax weight. +constant constexpr float UD_CLAMP = 1.0e4f, UD_FLOOR = 1.0e-4f; +// 1 / sqrt(128) and 128 / sqrt(128) rounded to fp32: the scores' scale and the router's. +constant constexpr float UD_INV_SQRT_HD = 0.0883883476483184405f, UD_ROUTER_SCALE = 11.3137084989847604f; + +inline float ud_bf(float x) { return float(bfloat(x)); } + +// The release's clamp at +-1e4: NaN stays NaN. +inline float ud_clamp(float x) { return isnan(x) ? x : clamp(x, -UD_CLAMP, UD_CLAMP); } + +// One threadgroup's sum of every thread's `v` (at most 1,024 threads), returned to all of them. +inline float ud_sum(float v, threadgroup float* part, uint n, uint lane, uint sg) { + v = simd_sum(v); + if (lane == 0) part[sg] = v; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg == 0) { + float s = lane < (n + 31) / 32 ? part[lane] : 0.0f; + s = simd_sum(s); + if (lane == 0) part[32] = s; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + const float out = part[32]; + threadgroup_barrier(mem_flags::mem_threadgroup); + return out; +} + +// Gathered rows: y[i] = x[rows[i]] (1280 wide). +[[max_total_threads_per_threadgroup(256)]] [[kernel]] void ud_gather( + const device bfloat* x [[buffer(0)]], const device uint* rows [[buffer(1)]], device bfloat* y [[buffer(2)]], + uint2 at [[thread_position_in_grid]]) { + if (at.x >= UD_H) return; + y[ulong(at.y) * UD_H + at.x] = x[ulong(rows[at.y]) * UD_H + at.x]; +} + +struct UdMv { + uint n; // output rows + uint k; // input width, a multiple of 8 +}; + +// One token's projection y[n] = bf16(W[n, :] . x) with fp32 sums: 4 rows a simdgroup, 8 simdgroups a group. +[[max_total_threads_per_threadgroup(256)]] [[kernel]] void ud_matvec( + const device bfloat* x [[buffer(0)]], const device bfloat* W [[buffer(1)]], device bfloat* y [[buffer(2)]], + constant UdMv& p [[buffer(3)]], uint tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + const uint row0 = (tg * 8 + sg) * 4; + if (row0 >= p.n) return; + float acc[4] = {0.0f, 0.0f, 0.0f, 0.0f}; + for (uint k = lane * 8; k < p.k; k += 256) { + const float4 x0 = float4(*(const device bfloat4*)(x + k)), x1 = float4(*(const device bfloat4*)(x + k + 4)); + for (uint r = 0; r < 4; r++) { + if (row0 + r >= p.n) break; + const device bfloat* w = W + ulong(row0 + r) * p.k + k; + acc[r] += dot(x0, float4(*(const device bfloat4*)w)) + dot(x1, float4(*(const device bfloat4*)(w + 4))); + } + } + for (uint r = 0; r < 4; r++) { + const float s = simd_sum(acc[r]); + if (lane == 0 && row0 + r < p.n) y[row0 + r] = bfloat(s); + } +} + +struct UdNorm { + uint add; // 1: the residual takes the added rows first + float eps; +}; + +// A row a group of 256: with `add`, R = bf16(R + A) first; then Y = bf16(w * bf16(r * rsqrt(mean(r^2) + eps))). +[[max_total_threads_per_threadgroup(256)]] [[kernel]] void ud_norm( + device bfloat* R [[buffer(0)]], const device bfloat* A [[buffer(1)]], const device bfloat* w [[buffer(2)]], + device bfloat* Y [[buffer(3)]], constant UdNorm& p [[buffer(4)]], uint row [[threadgroup_position_in_grid]], + uint t [[thread_index_in_threadgroup]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + threadgroup float part[33]; + device bfloat* r = R + ulong(row) * UD_H; + float v[5]; + float ss = 0.0f; + for (uint i = 0; i < 5; i++) { + const uint c = t + 256 * i; + float x = float(r[c]); + if (p.add != 0) { + x = ud_bf(x + float(A[ulong(row) * UD_H + c])); + r[c] = bfloat(x); + } + v[i] = x; + ss += x * x; + } + ss = ud_sum(ss, part, 256, lane, sg); + const float inv = precise::rsqrt(ss / float(UD_H) + p.eps); + for (uint i = 0; i < 5; i++) { + const uint c = t + 256 * i; + Y[ulong(row) * UD_H + c] = bfloat(float(w[c]) * ud_bf(v[i] * inv)); + } +} + +struct UdQk { + uint pos0; // the cache position of row 0 + float eps; +}; + +// Rotary on one value of a 128-wide head in torch's bf16 steps: bf16(bf16(x c) + bf16(rot(x) s)). +inline float ud_rope(float x, float partner, uint d, const device bfloat* cs, const device bfloat* sn) { + const float c = float(cs[d % 64]), s = float(sn[d % 64]); + const float rot = d < 64 ? -partner : partner; + return ud_bf(ud_bf(x * c) + ud_bf(rot * s)); +} + +// The router's norm of a 128-wide row in fp32, (1 + w) scaled, clamped at +-1e4 before and after the scale; bf16 out. +inline float ud_router_norm(float x, const device bfloat* w, uint d, float eps, threadgroup float* part, uint lane, + uint sg) { + const float ss = ud_sum(x * x, part, UD_RD, lane, sg); + const float n = ud_clamp(x * precise::rsqrt(ss / float(UD_RD) + eps)); + return ud_bf(ud_clamp(n * (1.0f + float(w[d])))); +} + +// A row's projections P (q | k | v | router q | router k) into rotated q, the caches at pos0 + row and the router's q. +[[max_total_threads_per_threadgroup(128)]] [[kernel]] void ud_qk( + const device bfloat* P [[buffer(0)]], const device bfloat* COS [[buffer(1)]], const device bfloat* SIN [[buffer(2)]], + const device bfloat* qn [[buffer(3)]], const device bfloat* kn [[buffer(4)]], device bfloat* Q [[buffer(5)]], + device bfloat* K [[buffer(6)]], device bfloat* V [[buffer(7)]], device bfloat* RQ [[buffer(8)]], + device bfloat* RK [[buffer(9)]], constant UdQk& p [[buffer(10)]], uint row [[threadgroup_position_in_grid]], + uint d [[thread_index_in_threadgroup]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + threadgroup float part[33]; + threadgroup float rr[2][UD_RD]; + const device bfloat* x = P + ulong(row) * UD_PROJ; + const device bfloat* cs = COS + ulong(row) * 64; + const device bfloat* sn = SIN + ulong(row) * 64; + const ulong at = ulong(p.pos0 + row) * UD_H; + const uint pd = d ^ 64; + for (uint h = 0; h < UD_HEADS; h++) { + const uint o = h * UD_HD; + Q[ulong(row) * UD_H + o + d] = bfloat(ud_rope(float(x[o + d]), float(x[o + pd]), d, cs, sn)); + K[at + o + d] = bfloat(ud_rope(float(x[UD_H + o + d]), float(x[UD_H + o + pd]), d, cs, sn)); + V[at + o + d] = x[2 * UD_H + o + d]; + } + rr[0][d] = ud_router_norm(float(x[3 * UD_H + d]), qn, d, p.eps, part, lane, sg); + rr[1][d] = ud_router_norm(float(x[3 * UD_H + UD_RD + d]), kn, d, p.eps, part, lane, sg); + threadgroup_barrier(mem_flags::mem_threadgroup); + RQ[ulong(row) * UD_RD + d] = bfloat(ud_rope(rr[0][d], rr[0][pd], d, cs, sn)); + RK[ulong(p.pos0 + row) * UD_RD + d] = bfloat(ud_rope(rr[1][d], rr[1][pd], d, cs, sn)); +} + +// Block c0 + b's summary key (fp32): its 32 router keys weighted by a softmax of their dot with head_cls / sqrt(128). +[[max_total_threads_per_threadgroup(32)]] [[kernel]] void ud_block_keys( + const device bfloat* RK [[buffer(0)]], const device bfloat* hc [[buffer(1)]], device float* KB [[buffer(2)]], + constant uint& c0 [[buffer(3)]], uint b [[threadgroup_position_in_grid]], uint j [[thread_index_in_simdgroup]]) { + const ulong c = c0 + b; + const device bfloat* k = RK + (c * UD_BLK + j) * UD_RD; + float aw = 0.0f; + for (uint d = 0; d < UD_RD; d++) aw += float(k[d]) * float(hc[d]); + aw = ud_clamp(aw * UD_INV_SQRT_HD); + const float e = precise::exp(aw - simd_max(aw)); + const float w = precise::divide(e, max(simd_sum(e), 1.0e-6f)); + for (uint d = j; d < UD_RD; d += 32) { + float acc = 0.0f; + for (uint i = 0; i < UD_BLK; i++) acc += simd_shuffle(w, i) * float(RK[(c * UD_BLK + i) * UD_RD + d]); + KB[c * UD_RD + d] = acc; + } +} + +struct UdRoute { + uint pos0; // the position of row 0 + uint words; // u32 words a candidate mask row holds +}; + +// A sum kept as two floats (hi + lo exact), so a running total rounds to fp32 once at each read, as a double would. +struct UdTwo { + float hi, lo; +}; + +inline UdTwo ud_two_add(UdTwo a, float b) { + const float s = a.hi + b; + const float bb = s - a.hi; + const float err = (a.hi - (s - bb)) + (b - bb); + const float lo = a.lo + err; + const float hi = s + lo; + return {hi, lo - (hi - s)}; +} + +// One query row's router: remote block scores, page candidates, entmax-1.5 over the top 16; SEL/BIAS the top 12. +[[max_total_threads_per_threadgroup(256)]] [[kernel]] void ud_route( + const device bfloat* RQ [[buffer(0)]], const device float* KB [[buffer(1)]], const device uint* masks [[buffer(2)]], + const device int* qmask [[buffer(3)]], device uint* SEL [[buffer(4)]], device float* BIAS [[buffer(5)]], + constant UdRoute& p [[buffer(6)]], uint row [[threadgroup_position_in_grid]], uint t [[thread_index_in_threadgroup]], + uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]]) { + threadgroup float part[33]; + threadgroup float q[UD_RD]; + threadgroup float score[4096]; + threadgroup float best_v[8]; + threadgroup uint best_i[8]; + threadgroup float top_v[UD_TOP]; + threadgroup uint top_i[UD_TOP]; + const uint pos = p.pos0 + row; + const uint nrem = pos / UD_BLK >= UD_LOCAL_BLOCKS ? pos / UD_BLK - UD_LOCAL_BLOCKS + 1 : 0; + if (t < UD_RD) q[t] = float(RQ[ulong(row) * UD_RD + t]); + threadgroup_barrier(mem_flags::mem_threadgroup); + const int m = qmask[row]; + float own = 0.0f; + for (uint c = t; c < nrem; c += 256) { + const device float* kb = KB + ulong(c) * UD_RD; + float z = 0.0f; + for (uint d = 0; d < UD_RD; d++) z += q[d] * kb[d]; + z = ud_clamp(z * UD_INV_SQRT_HD); + const bool cand = m < 0 || (c / 32 < p.words && ((masks[ulong(m) * p.words + c / 32] >> (c % 32)) & 1u) != 0); + score[c] = cand ? z * UD_ROUTER_SCALE : -INFINITY; + own += cand ? 1.0f : 0.0f; + } + // no candidate on the query's page among the remote blocks: every remote block is one + if (ud_sum(own, part, 256, lane, sg) == 0.0f) { + for (uint c = t; c < nrem; c += 256) { + const device float* kb = KB + ulong(c) * UD_RD; + float z = 0.0f; + for (uint d = 0; d < UD_RD; d++) z += q[d] * kb[d]; + z = ud_clamp(z * UD_INV_SQRT_HD); + score[c] = z * UD_ROUTER_SCALE; + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + // the 16 best in order, ties to the lower block + uint n = 0; + for (; n < UD_TOP; n++) { + float bv = -INFINITY; + uint bi = 0xffffffffu; + for (uint c = t; c < nrem; c += 256) { + const float v = score[c]; + if (v > bv || (v == bv && v != -INFINITY && c < bi)) { + bv = v; + bi = c; + } + } + for (uint off = 16; off > 0; off /= 2) { + const float ov = simd_shuffle_down(bv, off); + const uint oi = simd_shuffle_down(bi, off); + if (ov > bv || (ov == bv && oi < bi)) { + bv = ov; + bi = oi; + } + } + if (lane == 0) { + best_v[sg] = bv; + best_i[sg] = bi; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t == 0) { + float v = best_v[0]; + uint i = best_i[0]; + for (uint s = 1; s < 8; s++) + if (best_v[s] > v || (best_v[s] == v && best_i[s] < i)) { + v = best_v[s]; + i = best_i[s]; + } + top_v[n] = v; + top_i[n] = i; + if (i != 0xffffffffu) score[i] = -INFINITY; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (top_i[n] == 0xffffffffu) break; + } + if (t != 0) return; + device uint* sel = SEL + ulong(row) * UD_READ; + device float* bias = BIAS + ulong(row) * UD_READ; + const uint keep = min(n, UD_READ); + // entmax-1.5 over the n sorted scores: X = (x - max) / 2, the threshold from running means, Y = max(X - tau, 0)^2 + float X[UD_TOP], tau[UD_TOP]; + UdTwo s1 = {0.0f, 0.0f}, s2 = {0.0f, 0.0f}; + uint support = 0; + for (uint i = 0; i < n; i++) { + X[i] = (top_v[i] - top_v[0]) / 2.0f; + s1 = ud_two_add(s1, X[i]); + s2 = ud_two_add(s2, X[i] * X[i]); + const float rho = float(i + 1); + const float mean = precise::divide(s1.hi + s1.lo, rho), msq = precise::divide(s2.hi + s2.lo, rho); + const float ss = rho * (msq - mean * mean); + const float delta = precise::divide(1.0f - ss, rho); + tau[i] = mean - precise::sqrt(max(delta, 0.0f)); + support += tau[i] <= X[i] ? 1 : 0; + } + const float ts = n > 0 ? tau[max(support, 1u) - 1] : 0.0f; + float logp[UD_READ]; + UdTwo total = {0.0f, 0.0f}; + for (uint i = 0; i < keep; i++) { + const float y = max(X[i] - ts, 0.0f); + logp[i] = precise::log(max(y * y, UD_FLOOR)); + total = ud_two_add(total, logp[i]); + } + const float mu = precise::divide(total.hi + total.lo, float(max(keep, 1u))); + for (uint i = 0; i < UD_READ; i++) { + sel[i] = i < keep ? top_i[i] : 0xffffffffu; + bias[i] = i < keep ? logp[i] - mu : 0.0f; + } +} + +struct UdAttend { + uint pos0; // the position of row 0 + uint bf16_bias; // 1: the blocks' biases round to bf16 first (the prompt's mask is bf16) +}; + +// The largest of every thread's `v` in a threadgroup, returned to all of them. +inline float ud_max(float v, threadgroup float* part, uint n, uint lane, uint sg) { + v = simd_max(v); + if (lane == 0) part[sg] = v; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg == 0) { + float s = lane < (n + 31) / 32 ? part[lane] : -INFINITY; + s = simd_max(s); + if (lane == 0) part[32] = s; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + const float out = part[32]; + threadgroup_barrier(mem_flags::mem_threadgroup); + return out; +} + +// One (head, row) of fp32 attention over the last 128 keys and the read blocks (biased); simdgroups stride keys. +[[max_total_threads_per_threadgroup(256)]] [[kernel]] void ud_attend( + const device bfloat* Q [[buffer(0)]], const device bfloat* K [[buffer(1)]], const device bfloat* V [[buffer(2)]], + const device uint* SEL [[buffer(3)]], const device float* BIAS [[buffer(4)]], device bfloat* O [[buffer(5)]], + constant UdAttend& p [[buffer(6)]], uint2 g [[threadgroup_position_in_grid]], uint t [[thread_index_in_threadgroup]], + uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]]) { + constexpr uint MAXK = UD_LOCAL + UD_READ * UD_BLK; + threadgroup uint keys[MAXK]; + threadgroup float kbias[MAXK]; + threadgroup float sc[MAXK]; + threadgroup float4 pv[8][32]; + threadgroup float part[33]; + threadgroup uint start[UD_READ + 1]; + const uint h = g.x, row = g.y; + const uint pos = p.pos0 + row; + const uint lo = pos >= UD_LOCAL - 1 ? pos - (UD_LOCAL - 1) : 0; + const uint nloc = pos - lo + 1; + const device uint* sel = SEL + ulong(row) * UD_READ; + const device float* bias = BIAS + ulong(row) * UD_READ; + if (t == 0) { + uint n = nloc; + for (uint s = 0; s < UD_READ; s++) { + start[s] = n; + const uint c = sel[s]; + if (c != 0xffffffffu && c * UD_BLK < lo) n += min(UD_BLK, lo - c * UD_BLK); + } + start[UD_READ] = n; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + const uint total = start[UD_READ]; + for (uint i = t; i < total; i += 256) { + if (i < nloc) { + keys[i] = lo + i; + kbias[i] = 0.0f; + } else { + uint s = 0; + while (start[s + 1] <= i) s++; + keys[i] = sel[s] * UD_BLK + (i - start[s]); + kbias[i] = p.bf16_bias != 0 ? ud_bf(bias[s]) : bias[s]; + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + const uint o = h * UD_HD + 4 * lane; + const float4 q = float4(*(const device bfloat4*)(Q + ulong(row) * UD_H + o)); + for (uint i = sg; i < total; i += 8) { + const float4 k = float4(*(const device bfloat4*)(K + ulong(keys[i]) * UD_H + o)); + const float s = simd_sum(dot(q, k)); + if (lane == 0) sc[i] = s * UD_INV_SQRT_HD + kbias[i]; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + float top = -INFINITY; + for (uint i = t; i < total; i += 256) top = max(top, sc[i]); + top = ud_max(top, part, 256, lane, sg); + float mass = 0.0f; + for (uint i = t; i < total; i += 256) { + const float e = precise::exp(sc[i] - top); + sc[i] = e; + mass += e; + } + mass = ud_sum(mass, part, 256, lane, sg); + for (uint i = t; i < total; i += 256) sc[i] = precise::divide(sc[i], mass); + threadgroup_barrier(mem_flags::mem_threadgroup); + float4 acc = 0.0f; + for (uint i = sg; i < total; i += 8) acc += sc[i] * float4(*(const device bfloat4*)(V + ulong(keys[i]) * UD_H + o)); + pv[sg][lane] = acc; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg != 0) return; + for (uint s = 1; s < 8; s++) acc += pv[s][lane]; + *(device bfloat4*)(O + ulong(row) * UD_H + o) = bfloat4(acc); +} + +// A row's fp32 logits against the gate's 64 rows, their softmax, the 6 largest in order (ties to the lower expert). +[[max_total_threads_per_threadgroup(1024)]] [[kernel]] void ud_moe_gate( + const device bfloat* X [[buffer(0)]], const device bfloat* G [[buffer(1)]], device uint* IDS [[buffer(2)]], + device float* WTS [[buffer(3)]], uint row [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + threadgroup float logit[UD_EXPERTS]; + const device bfloat* x = X + ulong(row) * UD_H; + float acc[2] = {0.0f, 0.0f}; + for (uint k = lane * 8; k < UD_H; k += 256) { + const float4 x0 = float4(*(const device bfloat4*)(x + k)), x1 = float4(*(const device bfloat4*)(x + k + 4)); + for (uint r = 0; r < 2; r++) { + const device bfloat* g = G + ulong(sg * 2 + r) * UD_H + k; + acc[r] += dot(x0, float4(*(const device bfloat4*)g)) + dot(x1, float4(*(const device bfloat4*)(g + 4))); + } + } + for (uint r = 0; r < 2; r++) { + const float s = simd_sum(acc[r]); + if (lane == 0) logit[sg * 2 + r] = s; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg != 0) return; + float v[2] = {logit[lane], logit[lane + 32]}; + const float top = simd_max(max(v[0], v[1])); + v[0] = precise::exp(v[0] - top); + v[1] = precise::exp(v[1] - top); + const float mass = simd_sum(v[0] + v[1]); + v[0] = precise::divide(v[0], mass); + v[1] = precise::divide(v[1], mass); + // a NaN probability ranks below every number and above a taken expert, so a row of NaN picks experts 0 to 5 + bool taken[2] = {false, false}; + for (uint k = 0; k < UD_PICK; k++) { + const float a = taken[0] ? -2.0f : (isnan(v[0]) ? -1.0f : v[0]); + const float b = taken[1] ? -2.0f : (isnan(v[1]) ? -1.0f : v[1]); + const float best = simd_max(max(a, b)); + const uint e = simd_min(a == best ? lane : (b == best ? lane + 32 : UD_EXPERTS)); + const float wt = simd_shuffle(e < 32 ? v[0] : v[1], e % 32); + if (e == lane) taken[0] = true; + if (e == lane + 32) taken[1] = true; + if (lane == 0) { + IDS[ulong(row) * UD_PICK + k] = e; + WTS[ulong(row) * UD_PICK + k] = wt; + } + } +} + +struct UdAct { + uint width; // values a row + uint gstride; // the gate's row stride + uint ustride; // the up's row stride +}; + +// SwiGLU in torch's bf16 steps: Y = bf16(bf16(silu(g)) * u), silu in fp32. +[[max_total_threads_per_threadgroup(256)]] [[kernel]] void ud_silu_mul( + const device bfloat* G [[buffer(0)]], const device bfloat* U [[buffer(1)]], device bfloat* Y [[buffer(2)]], + constant UdAct& p [[buffer(3)]], uint2 at [[thread_position_in_grid]]) { + if (at.x >= p.width) return; + const float g = float(G[ulong(at.y) * p.gstride + at.x]); + const float a = ud_bf(precise::divide(g, 1.0f + precise::exp(-g))); + Y[ulong(at.y) * p.width + at.x] = bfloat(a * float(U[ulong(at.y) * p.ustride + at.x])); +} + +// A routed expert's three projections, by their GPU addresses. +struct UdExpert { + device const bfloat* gate; + device const bfloat* up; + device const bfloat* down; +}; + +struct UdExp { + uint width; // the expert's hidden width (896) +}; + +// One token's picked experts' gate and up rows: GU[j] = [gate . x | up . x] for each of its 6 experts, fp32 sums. +[[max_total_threads_per_threadgroup(256)]] [[kernel]] void ud_expert_gu( + const device bfloat* x [[buffer(0)]], const device UdExpert* E [[buffer(1)]], const device uint* ids [[buffer(2)]], + device bfloat* GU [[buffer(3)]], constant UdExp& p [[buffer(4)]], uint tg [[threadgroup_position_in_grid]], + uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]]) { + const uint row0 = (tg * 8 + sg) * 4; + if (row0 >= UD_PICK * 2 * p.width) return; + const uint j = row0 / (2 * p.width), r0 = row0 % (2 * p.width); + const UdExpert ex = E[ids[j]]; + float acc[4] = {0.0f, 0.0f, 0.0f, 0.0f}; + for (uint k = lane * 8; k < UD_H; k += 256) { + const float4 x0 = float4(*(const device bfloat4*)(x + k)), x1 = float4(*(const device bfloat4*)(x + k + 4)); + for (uint r = 0; r < 4; r++) { + const uint rr = r0 + r; + const device bfloat* w = (rr < p.width ? ex.gate + ulong(rr) * UD_H : ex.up + ulong(rr - p.width) * UD_H) + k; + acc[r] += dot(x0, float4(*(const device bfloat4*)w)) + dot(x1, float4(*(const device bfloat4*)(w + 4))); + } + } + for (uint r = 0; r < 4; r++) { + const float s = simd_sum(acc[r]); + if (lane == 0) GU[ulong(row0) + r] = bfloat(s); + } +} + +// One token's picked experts' down rows: D[j] = down_j . act_j (1280 each), fp32 sums. +[[max_total_threads_per_threadgroup(256)]] [[kernel]] void ud_expert_down( + const device bfloat* A [[buffer(0)]], const device UdExpert* E [[buffer(1)]], const device uint* ids [[buffer(2)]], + device bfloat* D [[buffer(3)]], constant UdExp& p [[buffer(4)]], uint tg [[threadgroup_position_in_grid]], + uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]]) { + const uint row0 = (tg * 8 + sg) * 4; + if (row0 >= UD_PICK * UD_H) return; + const uint j = row0 / UD_H, r0 = row0 % UD_H; + const device bfloat* x = A + ulong(j) * p.width; + const device bfloat* W = E[ids[j]].down; + float acc[4] = {0.0f, 0.0f, 0.0f, 0.0f}; + for (uint k = lane * 8; k < p.width; k += 256) { + const float4 x0 = float4(*(const device bfloat4*)(x + k)), x1 = float4(*(const device bfloat4*)(x + k + 4)); + for (uint r = 0; r < 4; r++) { + const device bfloat* w = W + ulong(r0 + r) * p.width + k; + acc[r] += dot(x0, float4(*(const device bfloat4*)w)) + dot(x1, float4(*(const device bfloat4*)(w + 4))); + } + } + for (uint r = 0; r < 4; r++) { + const float s = simd_sum(acc[r]); + if (lane == 0) D[ulong(row0) + r] = bfloat(s); + } +} + +// The experts' sum for a row: bf16(sum_j D[slot[r, j]] w[r, j]) in fp32, then the shared expert's rows added in bf16. +[[max_total_threads_per_threadgroup(256)]] [[kernel]] void ud_combine( + const device bfloat* D [[buffer(0)]], const device uint* slot [[buffer(1)]], const device float* WTS [[buffer(2)]], + const device bfloat* S [[buffer(3)]], device bfloat* Y [[buffer(4)]], uint2 at [[thread_position_in_grid]]) { + if (at.x >= UD_H) return; + float acc = 0.0f; + for (uint j = 0; j < UD_PICK; j++) { + const ulong i = ulong(at.y) * UD_PICK + j; + acc += float(D[ulong(slot[i]) * UD_H + at.x]) * WTS[i]; + } + const ulong o = ulong(at.y) * UD_H + at.x; + Y[o] = bfloat(ud_bf(acc) + float(S[o])); +} diff --git a/zig/kernels/metal/uocr/vision.metal b/zig/kernels/metal/uocr/vision.metal new file mode 100644 index 00000000000..47543ef01e6 --- /dev/null +++ b/zig/kernels/metal/uocr/vision.metal @@ -0,0 +1,328 @@ +// Unlimited-OCR-2's image encoder steps (SAM ViT-B, its neck, CLIP-L), rounded to bf16 where torch rounds. + +#include +using namespace metal; + +inline float uv_bf(float x) { return float(bfloat(x)); } + +// One threadgroup's sum of every thread's `v` (at most 1,024 threads), returned to all of them. +inline float uv_sum(float v, threadgroup float* part, uint n, uint lane, uint sg) { + v = simd_sum(v); + if (lane == 0) part[sg] = v; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg == 0) { + float s = lane < (n + 31) / 32 ? part[lane] : 0.0f; + s = simd_sum(s); + if (lane == 0) part[32] = s; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + const float out = part[32]; + threadgroup_barrier(mem_flags::mem_threadgroup); + return out; +} + +// y = bf16(a + b) over `n` values (torch's bf16 add: both widened, one rounding). +[[max_total_threads_per_threadgroup(256)]] [[kernel]] void uv_add( + const device bfloat* a [[buffer(0)]], const device bfloat* b [[buffer(1)]], device bfloat* y [[buffer(2)]], + constant uint& n [[buffer(3)]], uint i [[thread_position_in_grid]]) { + if (i < n) y[i] = bfloat(float(a[i]) + float(b[i])); +} + +// y [rows, width] = bf16(c + b): fp32 sums and a bias vector, rounded once (a Linear's bias in its sums). +[[max_total_threads_per_threadgroup(256)]] [[kernel]] void uv_bias( + const device float* c [[buffer(0)]], const device bfloat* b [[buffer(1)]], device bfloat* y [[buffer(2)]], + constant uint& width [[buffer(3)]], uint2 at [[thread_position_in_grid]]) { + if (at.x >= width) return; + const ulong i = ulong(at.y) * width + at.x; + y[i] = bfloat(c[i] + float(b[at.x])); +} + +struct UvNorm { + uint width; + float eps; +}; + +// nn.LayerNorm on bf16 rows: the mean and variance of the widened row, the affine in fp32, one rounding. +[[max_total_threads_per_threadgroup(256)]] [[kernel]] void uv_layer_norm( + const device bfloat* x [[buffer(0)]], const device bfloat* w [[buffer(1)]], const device bfloat* b [[buffer(2)]], + device bfloat* y [[buffer(3)]], constant UvNorm& p [[buffer(4)]], uint row [[threadgroup_position_in_grid]], + uint t [[thread_position_in_threadgroup]], uint n [[threads_per_threadgroup]], + uint lane [[thread_index_in_simdgroup]], uint sg [[simdgroup_index_in_threadgroup]]) { + threadgroup float part[33]; + const device bfloat* xr = x + ulong(row) * p.width; + device bfloat* yr = y + ulong(row) * p.width; + float s = 0.0f; + for (uint i = t; i < p.width; i += n) s += float(xr[i]); + const float mean = uv_sum(s, part, n, lane, sg) / float(p.width); + float v = 0.0f; + for (uint i = t; i < p.width; i += n) { + const float d = float(xr[i]) - mean; + v += d * d; + } + const float inv = metal::precise::rsqrt(uv_sum(v, part, n, lane, sg) / float(p.width) + p.eps); + for (uint i = t; i < p.width; i += n) yr[i] = bfloat((float(xr[i]) - mean) * inv * float(w[i]) + float(b[i])); +} + +// erf to under one ulp (Juffa's faithfully rounded erff, as spark25/glue.metal's sp_erf). +inline float uv_erf(float x) { + const float t = fabs(x), s = x * x; + float r; + if (t > 0.927734375f) { + r = fma(-1.72853470e-5f, t, 3.83197126e-4f); + const float u = fma(-3.88396438e-3f, t, 2.42546219e-2f); + r = fma(r, s, u); + r = fma(r, t, -1.06777877e-1f); + r = fma(r, t, -6.34846687e-1f); + r = fma(r, t, -1.28717512e-1f); + r = fma(r, t, -t); + r = copysign(1.0f - precise::exp(r), x); + } else { + r = -5.96761703e-4f; + r = fma(r, s, 4.99119423e-3f); + r = fma(r, s, -2.67681349e-2f); + r = fma(r, s, 1.12819925e-1f); + r = fma(r, s, -3.76125336e-1f); + r = fma(r, s, 1.28379166e-1f); + r = fma(r, x, x); + } + return r; +} + +// nn.GELU (erf) on bf16 values, in fp32, one rounding. +[[max_total_threads_per_threadgroup(256)]] [[kernel]] void uv_gelu( + device bfloat* x [[buffer(0)]], constant uint& n [[buffer(1)]], uint i [[thread_position_in_grid]]) { + if (i >= n) return; + const float v = float(x[i]); + x[i] = bfloat(0.5f * v * (1.0f + uv_erf(v * 0.70710678118654752f))); +} + +// CLIP's quick_gelu as its module runs it on bf16: bf16(x * bf16(sigmoid(bf16(1.702 * x)))). +[[max_total_threads_per_threadgroup(256)]] [[kernel]] void uv_quick_gelu( + device bfloat* x [[buffer(0)]], constant uint& n [[buffer(1)]], uint i [[thread_position_in_grid]]) { + if (i >= n) return; + const float v = float(x[i]); + const float z = uv_bf(1.702f * v); + const float s = uv_bf(1.0f / (1.0f + metal::precise::exp(-z))); + x[i] = bfloat(v * s); +} + +struct UvCat { + uint rows, left, right; +}; + +// y [rows, left + right] = [a row | b row]: CLIP's rows (past its class row) beside SAM's. +[[max_total_threads_per_threadgroup(256)]] [[kernel]] void uv_concat( + const device bfloat* a [[buffer(0)]], const device bfloat* b [[buffer(1)]], device bfloat* y [[buffer(2)]], + constant UvCat& p [[buffer(3)]], uint2 at [[thread_position_in_grid]]) { + const uint width = p.left + p.right; + if (at.x >= width || at.y >= p.rows) return; + y[ulong(at.y) * width + at.x] = at.x < p.left ? a[ulong(at.y) * p.left + at.x] : b[ulong(at.y) * p.right + at.x - p.left]; +} + +// CLIP's embeddings on SAM's map: y[0] = bf16(cls + pos[0]), y[r] = bf16(sam[r - 1] + pos[r]); rows of `width`. +[[max_total_threads_per_threadgroup(256)]] [[kernel]] void uv_clip_embed( + const device bfloat* cls [[buffer(0)]], const device bfloat* sam [[buffer(1)]], const device bfloat* pos [[buffer(2)]], + device bfloat* y [[buffer(3)]], constant uint& width [[buffer(4)]], uint2 at [[thread_position_in_grid]]) { + if (at.x >= width) return; + const float v = at.y == 0 ? float(cls[at.x]) : float(sam[ulong(at.y - 1) * width + at.x]); + y[ulong(at.y) * width + at.x] = bfloat(v + float(pos[ulong(at.y) * width + at.x])); +} + +struct UvCols { + uint channels, in_side, out_side, span, stride, pad, cstride, pstride; +}; + +// Convolution rows [out_side^2, channels span^2], columns (c, ky, kx); map value (c, y, x) at c cs + (y side + x) ps. +[[max_total_threads_per_threadgroup(256)]] [[kernel]] void uv_im2col( + const device bfloat* x [[buffer(0)]], device bfloat* y [[buffer(1)]], constant UvCols& p [[buffer(2)]], + uint2 at [[thread_position_in_grid]]) { + const uint taps = p.span * p.span, width = p.channels * taps; + if (at.x >= width || at.y >= p.out_side * p.out_side) return; + const uint c = at.x / taps, t = at.x % taps; + const int iy = int((at.y / p.out_side) * p.stride + t / p.span) - int(p.pad); + const int ix = int((at.y % p.out_side) * p.stride + t % p.span) - int(p.pad); + const bool inside = iy >= 0 && ix >= 0 && iy < int(p.in_side) && ix < int(p.in_side); + y[ulong(at.y) * width + at.x] = + inside ? x[ulong(c) * p.cstride + (ulong(iy) * p.in_side + uint(ix)) * p.pstride] : bfloat(0.0f); +} + +struct UvWindow { + uint side, padded, window, channels; +}; + +// The map's rows [side^2, channels] as the padded map's window x window squares, both in row order; padding rows are 0. +[[max_total_threads_per_threadgroup(256)]] [[kernel]] void uv_window( + const device bfloat* x [[buffer(0)]], device bfloat* y [[buffer(1)]], constant UvWindow& p [[buffer(2)]], + uint2 at [[thread_position_in_grid]]) { + if (at.x >= p.channels || at.y >= p.padded * p.padded) return; + const uint area = p.window * p.window, across = p.padded / p.window; + const uint w = at.y / area, i = at.y % area; + const uint r = (w / across) * p.window + i / p.window, c = (w % across) * p.window + i % p.window; + y[ulong(at.y) * p.channels + at.x] = r < p.side && c < p.side ? x[(ulong(r) * p.side + c) * p.channels + at.x] : bfloat(0.0f); +} + +// The windows' rows back onto the map, added to it in place: x = bf16(x + window row); padding rows are dropped. +[[max_total_threads_per_threadgroup(256)]] [[kernel]] void uv_unwindow_add( + device bfloat* x [[buffer(0)]], const device bfloat* win [[buffer(1)]], constant UvWindow& p [[buffer(2)]], + uint2 at [[thread_position_in_grid]]) { + if (at.x >= p.channels || at.y >= p.side * p.side) return; + const uint r = at.y / p.side, c = at.y % p.side, across = p.padded / p.window; + const uint w = (r / p.window) * across + c / p.window, i = (r % p.window) * p.window + c % p.window; + const ulong to = ulong(at.y) * p.channels + at.x; + x[to] = bfloat(float(x[to]) + float(win[(ulong(w) * p.window * p.window + i) * p.channels + at.x])); +} + +struct UvRel { + uint groups, side, heads, width; +}; + +// Relative-position terms: for query i at (a, b) of its group, rel_h[h, i, j] = bf16(q . Rh[a - j + side - 1]); w by b. +[[max_total_threads_per_threadgroup(256)]] [[kernel]] void uv_rel_pos( + const device bfloat* qkv [[buffer(0)]], const device bfloat* rh [[buffer(1)]], const device bfloat* rw [[buffer(2)]], + device bfloat* out_h [[buffer(3)]], device bfloat* out_w [[buffer(4)]], constant UvRel& p [[buffer(5)]], + uint3 at [[thread_position_in_grid]]) { + const uint len = p.side * p.side, rows = p.groups * len; + if (at.x >= 2 * p.side || at.y >= rows || at.z >= p.heads) return; + const bool across = at.x >= p.side; + const uint j = across ? at.x - p.side : at.x, i = at.y % len; + const uint from = (across ? i % p.side : i / p.side) + p.side - 1 - j; + const device bfloat* q = qkv + ulong(at.y) * 3 * p.width + at.z * 64; + const device bfloat* r = (across ? rw : rh) + ulong(from) * 64; + float s = 0.0f; + for (uint c = 0; c < 64; c++) s = fma(float(q[c]), float(r[c]), s); + (across ? out_w : out_h)[(ulong(at.z) * rows + at.y) * p.side + j] = bfloat(s); +} + +struct UvAttn { + uint groups, len, heads, width, side; + float scale; +}; + +constant constexpr uint uv_q_rows = 8; // query rows a simdgroup +constant constexpr uint uv_keys = 32; // keys a step +constant constexpr uint uv_head = 64; // head width +constant constexpr uint uv_block = 512; // keys a softmax block: its own running top score +constant constexpr uint uv_blocks = 8; // blocks a row at most (4,096 keys) + +// One step's scores of this simdgroup's 8 query rows against the 32 keys in `ks`, into `stage` [8, 32] (fp32 sums). +inline void uv_scores(thread simdgroup_float8x8* qf, threadgroup const float* ks, threadgroup float* stage) { + for (uint kc = 0; kc < uv_keys / 8; kc++) { + simdgroup_float8x8 s = make_filled_simdgroup_matrix(0.0f); + for (uint dc = 0; dc < uv_head / 8; dc++) { + simdgroup_float8x8 kt; + simdgroup_load(kt, ks + kc * 8 * uv_head + dc * 8, uv_head, ulong2(0, 0), true); + simdgroup_multiply_accumulate(s, qf[dc], kt, s); + } + simdgroup_store(s, stage + kc * 8, uv_keys); + } +} + +// A score as the softmax sees it: scale * (q . k) plus its query's two relative-position terms summed in bf16. +inline float uv_logit(float dot, uint key, uint row, uint head, constant UvAttn& p, const device bfloat* rel_h, + const device bfloat* rel_w) { + float s = p.scale * dot; + if (p.side > 0) { + const ulong at = (ulong(head) * p.groups * p.len + row) * p.side; + s += float(bfloat(float(rel_h[at + key / p.side]) + float(rel_w[at + key % p.side]))); + } + return s; +} + +// Attention in groups of len rows, 512-key blocks: fp32 weights on each block's running top, bf16 ones times values. +[[max_total_threads_per_threadgroup(128)]] [[kernel]] void uv_attention( + const device bfloat* qkv [[buffer(0)]], const device bfloat* rel_h [[buffer(1)]], + const device bfloat* rel_w [[buffer(2)]], device bfloat* o [[buffer(3)]], constant UvAttn& p [[buffer(4)]], + uint3 tg [[threadgroup_position_in_grid]], uint t [[thread_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]], uint sg [[simdgroup_index_in_threadgroup]]) { + threadgroup float ks[uv_keys * uv_head]; + threadgroup float vs[uv_keys * uv_head]; + threadgroup float stages[4 * uv_q_rows * uv_head]; + threadgroup float* stage = stages + sg * uv_q_rows * uv_head; + const uint head = tg.y, base = tg.z * p.len, stride = 3 * p.width; + const uint q0 = tg.x * 4 * uv_q_rows + sg * uv_q_rows; + // this simdgroup's queries, rows past the group as zeros + for (uint e = lane; e < uv_q_rows * uv_head; e += 32) { + const uint r = q0 + e / uv_head; + stage[e] = r < p.len ? float(qkv[ulong(base + r) * stride + head * uv_head + e % uv_head]) : 0.0f; + } + simdgroup_barrier(mem_flags::mem_threadgroup); + simdgroup_float8x8 qf[uv_head / 8]; + for (uint dc = 0; dc < uv_head / 8; dc++) simdgroup_load(qf[dc], stage + dc * 8, uv_head); + // lane: row lane / 4 of the 8, keys (lane % 4) * 8 .. + 8 of each step + const uint my = lane / 4, part = lane % 4, qr = min(q0 + my, p.len - 1), row = base + qr; + float top[uv_blocks]; + for (uint b = 0; b < uv_blocks; b++) top[b] = -INFINITY; + for (uint k0 = 0; k0 < p.len; k0 += uv_keys) { + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint e = t; e < uv_keys * uv_head; e += 128) { + const uint key = k0 + e / uv_head; + ks[e] = key < p.len ? float(qkv[ulong(base + key) * stride + p.width + head * uv_head + e % uv_head]) : 0.0f; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + uv_scores(qf, ks, stage); + simdgroup_barrier(mem_flags::mem_threadgroup); + for (uint j = 0; j < 8; j++) { + const uint key = k0 + part * 8 + j; + if (key < p.len) top[k0 / uv_block] = max(top[k0 / uv_block], uv_logit(stage[my * uv_keys + part * 8 + j], key, row, head, p, rel_h, rel_w)); + } + simdgroup_barrier(mem_flags::mem_threadgroup); + } + for (uint b = 0; b < uv_blocks; b++) { + top[b] = max(top[b], simd_shuffle_xor(top[b], 1)); + top[b] = max(top[b], simd_shuffle_xor(top[b], 2)); + if (b > 0) top[b] = max(top[b], top[b - 1]); + } + simdgroup_float8x8 acc[uv_head / 8]; + for (uint dc = 0; dc < uv_head / 8; dc++) acc[dc] = make_filled_simdgroup_matrix(0.0f); + float mass = 0.0f; + for (uint k0 = 0; k0 < p.len; k0 += uv_keys) { + const uint b = k0 / uv_block; + if (b > 0 && k0 % uv_block == 0) { + // a new block: the row's sums so far times exp(previous top - this top), as a diagonal product + const float c = metal::precise::exp(top[b - 1] - top[b]); + mass *= c; + simdgroup_barrier(mem_flags::mem_threadgroup); + for (uint e = lane; e < 64; e += 32) stage[e] = 0.0f; + simdgroup_barrier(mem_flags::mem_threadgroup); + if (part == 0) stage[my * 9] = c; + simdgroup_barrier(mem_flags::mem_threadgroup); + simdgroup_float8x8 d; + simdgroup_load(d, stage, 8); + for (uint dc = 0; dc < uv_head / 8; dc++) simdgroup_multiply(acc[dc], d, acc[dc]); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint e = t; e < uv_keys * uv_head; e += 128) { + const uint key = k0 + e / uv_head; + const ulong at = ulong(base + key) * stride + head * uv_head + e % uv_head; + ks[e] = key < p.len ? float(qkv[at + p.width]) : 0.0f; + vs[e] = key < p.len ? float(qkv[at + 2 * p.width]) : 0.0f; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + uv_scores(qf, ks, stage); + simdgroup_barrier(mem_flags::mem_threadgroup); + for (uint j = 0; j < 8; j++) { + const uint key = k0 + part * 8 + j, at = my * uv_keys + part * 8 + j; + const float w = key < p.len ? metal::precise::exp(uv_logit(stage[at], key, row, head, p, rel_h, rel_w) - top[b]) : 0.0f; + mass += w; + stage[at] = float(bfloat(w)); + } + simdgroup_barrier(mem_flags::mem_threadgroup); + for (uint kc = 0; kc < uv_keys / 8; kc++) { + simdgroup_float8x8 pf; + simdgroup_load(pf, stage + kc * 8, uv_keys); + for (uint dc = 0; dc < uv_head / 8; dc++) { + simdgroup_float8x8 vf; + simdgroup_load(vf, vs + kc * 8 * uv_head + dc * 8, uv_head); + simdgroup_multiply_accumulate(acc[dc], pf, vf, acc[dc]); + } + } + simdgroup_barrier(mem_flags::mem_threadgroup); + } + mass += simd_shuffle_xor(mass, 1); + mass += simd_shuffle_xor(mass, 2); + for (uint dc = 0; dc < uv_head / 8; dc++) simdgroup_store(acc[dc], stage + dc * 8, uv_head); + simdgroup_barrier(mem_flags::mem_threadgroup); + if (q0 + my >= p.len) return; + device bfloat* out = o + ulong(row) * p.width + head * uv_head; + for (uint c = part * 16; c < part * 16 + 16; c++) out[c] = bfloat(stage[my * uv_head + c] / mass); +} diff --git a/zig/src/cli/hub.zig b/zig/src/cli/hub.zig index 22ed74182ea..25efe2c11a1 100644 --- a/zig/src/cli/hub.zig +++ b/zig/src/cli/hub.zig @@ -25,6 +25,7 @@ const titles = [_]struct { model_type: []const u8, title: []const u8 }{ .{ .model_type = "llama", .title = "Llama architecture (Nanbeige4.3-33B)" }, .{ .model_type = "flint", .title = "Flint" }, .{ .model_type = "lfm2_moe", .title = "LFM2.5-24B-A2B" }, + .{ .model_type = "unlimited-ocr", .title = "Unlimited-OCR-2" }, }; /// The family that serves `model_type` from the engine registry, or null when Zig cannot serve it (the 0.6 line may). diff --git a/zig/src/core/contract/registry_joins.zig b/zig/src/core/contract/registry_joins.zig index 4cdbc7a7bf1..86eb07d031d 100644 --- a/zig/src/core/contract/registry_joins.zig +++ b/zig/src/core/contract/registry_joins.zig @@ -80,7 +80,8 @@ pub const all_metal = @import("lane_q8_records.zig").records ++ @import("ling_route_records.zig").records ++ @import("qwen27_moe_records.zig").records ++ @import("affine_gather_records.zig").records ++ - @import("flint_records.zig").records; + @import("flint_records.zig").records ++ + @import("uocr_records.zig").records; pub const landed_cuda = registry.cuda ++ @import("dory_cuda_records.zig").cuda ++ registry.gradient_pending ++ diff --git a/zig/src/core/contract/uocr_decoder_records.zig b/zig/src/core/contract/uocr_decoder_records.zig new file mode 100644 index 00000000000..083fb3c143a --- /dev/null +++ b/zig/src/core/contract/uocr_decoder_records.zig @@ -0,0 +1,16 @@ +//! Unlimited-OCR-2's decoder launches: each reserves its group's threads; M1/M2 from tf-kernel-contract --offline. +const M = @import("limits.zig").MetalLaunch; +pub const records = [_]M{ + .{ .name = "uocr decoder rows ud_gather", .threads = 256, .tg_memory = 0, .reserved = 256, .m1 = 256, .m2 = 256 }, + .{ .name = "uocr decoder step products ud_matvec", .threads = 256, .tg_memory = 0, .reserved = 256, .m1 = 256, .m2 = 256 }, + .{ .name = "uocr decoder norm ud_norm", .threads = 256, .tg_memory = 144, .reserved = 256, .m1 = 256, .m2 = 256 }, + .{ .name = "uocr decoder rotary ud_qk", .threads = 128, .tg_memory = 1168, .reserved = 128, .m1 = 128, .m2 = 128 }, + .{ .name = "uocr decoder block keys ud_block_keys", .threads = 32, .tg_memory = 0, .reserved = 32, .m1 = 32, .m2 = 32 }, + .{ .name = "uocr decoder router ud_route", .threads = 256, .tg_memory = 17232, .reserved = 256, .m1 = 256, .m2 = 256 }, + .{ .name = "uocr decoder attention ud_attend", .threads = 256, .tg_memory = 10432, .reserved = 256, .m1 = 256, .m2 = 256 }, + .{ .name = "uocr decoder expert gate ud_moe_gate", .threads = 1024, .tg_memory = 256, .reserved = 1024, .m1 = 1024, .m2 = 1024 }, + .{ .name = "uocr decoder swiglu ud_silu_mul", .threads = 256, .tg_memory = 0, .reserved = 256, .m1 = 256, .m2 = 256 }, + .{ .name = "uocr decoder step experts ud_expert_gu", .threads = 256, .tg_memory = 0, .reserved = 256, .m1 = 256, .m2 = 256 }, + .{ .name = "uocr decoder step experts ud_expert_down", .threads = 256, .tg_memory = 0, .reserved = 256, .m1 = 256, .m2 = 256 }, + .{ .name = "uocr decoder combine ud_combine", .threads = 256, .tg_memory = 0, .reserved = 256, .m1 = 256, .m2 = 256 }, +}; diff --git a/zig/src/core/contract/uocr_records.zig b/zig/src/core/contract/uocr_records.zig new file mode 100644 index 00000000000..4cce41fb4b4 --- /dev/null +++ b/zig/src/core/contract/uocr_records.zig @@ -0,0 +1,2 @@ +//! Unlimited-OCR-2's Metal launches, one file a kernel group; the contract's limits gate checks them in all_metal. +pub const records = @import("uocr_vision_glue_records.zig").records ++ @import("uocr_vision_maps_records.zig").records ++ @import("uocr_vision_attn_records.zig").records ++ @import("uocr_decoder_records.zig").records; diff --git a/zig/src/core/contract/uocr_vision_attn_records.zig b/zig/src/core/contract/uocr_vision_attn_records.zig new file mode 100644 index 00000000000..345fae415de --- /dev/null +++ b/zig/src/core/contract/uocr_vision_attn_records.zig @@ -0,0 +1,5 @@ +//! Unlimited-OCR-2's image-encoder attention launch (zig/tests/contract/metal_uocr_vision_attn.zig). +const M = @import("limits.zig").MetalLaunch; +pub const records = [_]M{ + .{ .name = "uocr vision attention uv_attention", .threads = 128, .tg_memory = 24576, .reserved = 128, .m1 = 128, .m2 = 128 }, +}; diff --git a/zig/src/core/contract/uocr_vision_glue_records.zig b/zig/src/core/contract/uocr_vision_glue_records.zig new file mode 100644 index 00000000000..302b855cbe5 --- /dev/null +++ b/zig/src/core/contract/uocr_vision_glue_records.zig @@ -0,0 +1,11 @@ +//! Unlimited-OCR-2's image-encoder glue launches (zig/tests/contract/metal_uocr_vision_glue.zig). +const M = @import("limits.zig").MetalLaunch; +pub const records = [_]M{ + .{ .name = "uocr vision add uv_add", .threads = 256, .tg_memory = 0, .reserved = 256, .m1 = 256, .m2 = 256 }, + .{ .name = "uocr vision bias uv_bias", .threads = 256, .tg_memory = 0, .reserved = 256, .m1 = 256, .m2 = 256 }, + .{ .name = "uocr vision norm uv_layer_norm", .threads = 256, .tg_memory = 144, .reserved = 256, .m1 = 256, .m2 = 256 }, + .{ .name = "uocr vision GELU uv_gelu", .threads = 256, .tg_memory = 0, .reserved = 256, .m1 = 256, .m2 = 256 }, + .{ .name = "uocr vision quick GELU uv_quick_gelu", .threads = 256, .tg_memory = 0, .reserved = 256, .m1 = 256, .m2 = 256 }, + .{ .name = "uocr vision concat uv_concat", .threads = 256, .tg_memory = 0, .reserved = 256, .m1 = 256, .m2 = 256 }, + .{ .name = "uocr vision CLIP embed uv_clip_embed", .threads = 256, .tg_memory = 0, .reserved = 256, .m1 = 256, .m2 = 256 }, +}; diff --git a/zig/src/core/contract/uocr_vision_maps_records.zig b/zig/src/core/contract/uocr_vision_maps_records.zig new file mode 100644 index 00000000000..82687203b0a --- /dev/null +++ b/zig/src/core/contract/uocr_vision_maps_records.zig @@ -0,0 +1,8 @@ +//! Unlimited-OCR-2's image-encoder map launches (zig/tests/contract/metal_uocr_vision_maps.zig). +const M = @import("limits.zig").MetalLaunch; +pub const records = [_]M{ + .{ .name = "uocr vision convolution rows uv_im2col", .threads = 256, .tg_memory = 0, .reserved = 256, .m1 = 256, .m2 = 256 }, + .{ .name = "uocr vision windows uv_window", .threads = 256, .tg_memory = 0, .reserved = 256, .m1 = 256, .m2 = 256 }, + .{ .name = "uocr vision windows back uv_unwindow_add", .threads = 256, .tg_memory = 0, .reserved = 256, .m1 = 256, .m2 = 256 }, + .{ .name = "uocr vision relative positions uv_rel_pos", .threads = 256, .tg_memory = 0, .reserved = 256, .m1 = 256, .m2 = 256 }, +}; diff --git a/zig/src/families/uocr/chat.zig b/zig/src/families/uocr/chat.zig new file mode 100644 index 00000000000..ab58af90941 --- /dev/null +++ b/zig/src/families/uocr/chat.zig @@ -0,0 +1,3 @@ +//! Unlimited-OCR-2's chat template, served when the checkpoint ships none (the release has no template). +pub const model_type = "unlimited-ocr"; +pub const source = @embedFile("chat_template.jinja"); diff --git a/zig/src/families/uocr/chat_template.jinja b/zig/src/families/uocr/chat_template.jinja new file mode 100644 index 00000000000..795ffaf7700 --- /dev/null +++ b/zig/src/families/uocr/chat_template.jinja @@ -0,0 +1,21 @@ +{#- Unlimited-OCR-2: every image part is a page, "" in order, then the instruction (the user's text with + its own "" and "" left out; "Multi page parsing." when none), as the publisher's infer() builds it. -#} +{{- bos_token -}} +{%- set ns = namespace(text='') -%} +{%- for message in messages -%} +{%- if message['role'] == 'user' -%} +{%- if message['content'] is string -%} +{%- set ns.text = ns.text + message['content'] -%} +{%- else -%} +{%- for part in message['content'] -%} +{%- if part['type'] == 'image_url' or part['type'] == 'image' -%} + +{%- elif part['type'] == 'text' -%} +{%- set ns.text = ns.text + part['text'] -%} +{%- endif -%} +{%- endfor -%} +{%- endif -%} +{%- endif -%} +{%- endfor -%} +{%- set instruction = ns.text.replace('', '').replace('', '') | trim -%} +{{- instruction if instruction else 'Multi page parsing.' -}} diff --git a/zig/src/families/uocr/config.zig b/zig/src/families/uocr/config.zig new file mode 100644 index 00000000000..acee7757085 --- /dev/null +++ b/zig/src/families/uocr/config.zig @@ -0,0 +1,220 @@ +//! Unlimited-OCR-2's geometry (baidu/Unlimited-OCR-2), and the check that a checkpoint's config.json is that geometry. +const std = @import("std"); + +// The decoder: DeepSeek-V2's skeleton with plain multi-head attention, the first layer dense, the rest routed. +pub const hidden = 1280; +pub const layers = 12; +pub const heads = 10; +pub const head_dim = 128; +pub const dense_ffn = 6848; +pub const experts = 64; +pub const expert_ffn = 896; +pub const shared_ffn = 2 * expert_ffn; +pub const top_k = 6; +pub const vocab = 129280; +pub const eps: f32 = 1e-6; + +// The attention every query reads: its own last 128 keys, and 12 remote blocks of 32 a router picks. +pub const block = 32; +pub const local_blocks = 4; +pub const local = block * local_blocks; +pub const read_blocks = 12; +pub const ranked_blocks = 16; +pub const router_dim = 128; +pub const router_floor: f32 = 1e-4; +/// The router's score scale: dash_scale_per_layer (128) over sqrt(index_dim). +pub const router_scale: f32 = 128.0 / @sqrt(@as(f32, router_dim)); +/// Image tokens a page holds in the release's decode-side page count for images before any . +pub const page_image_tokens = 273; + +// The page2d rotary: pairs 0-62 turn with the token's place in its page (10000^(-i/63)), pair 63 with page parity. +pub const rope_pairs = 64; +pub const tok_pairs = 63; +pub const tok_theta: f32 = 10000.0; +pub const page_mod = 2; + +/// Pair i's inverse frequency as the release's fp32 steps give it: 1 / 10000^(f32(i) / 63), each step in fp32. +pub fn invTok(i: usize) f32 { + const e = @as(f32, @floatFromInt(i)) / @as(f32, tok_pairs); + const p: f32 = @floatCast(std.math.pow(f64, tok_theta, e)); + return 1.0 / p; +} + +/// A position's rotary row: the cosine and sine of each pair's fp32 angle, rounded once to fp32, then to bf16. +pub fn rope(tok: u32, page: u32, cos: *[rope_pairs]u16, sin: *[rope_pairs]u16) void { + for (0..rope_pairs) |i| { + const angle: f32 = if (i < tok_pairs) @as(f32, @floatFromInt(tok)) * invTok(i) else @floatFromInt(page % page_mod); + cos[i] = bf16(@floatCast(@cos(@as(f64, angle)))); + sin[i] = bf16(@floatCast(@sin(@as(f64, angle)))); + } +} + +/// fp32 to bf16, to nearest even. +fn bf16(x: f32) u16 { + const b: u32 = @bitCast(x); + if (std.math.isNan(x)) return @truncate((b >> 16) | 0x40); + return @truncate((b +% 0x7fff +% ((b >> 16) & 1)) >> 16); +} + +// The ids the prompt and the reply use. +pub const bos = 0; +pub const eos = 1; +pub const image_token = 128815; +pub const page_token = 128827; +/// "Multi page parsing." as the release's tokenizer splits it: the default instruction after the pages. +pub const instruction = [_]u32{ 37460, 4366, 76466, 16 }; +/// Tokens a page may run to before the reply's page guard closes it (infer's max_page_tokens). +pub const max_page_tokens = 20000; +/// The longest sequence the publisher generates to (its max_length). +pub const max_context = 131072; + +// The image encoder: SAM ViT-B's 12 blocks (global attention in four), its neck, then CLIP-L's 24 on SAM's map. +pub const base_size = 1024; +pub const tile_size = 640; +pub const max_tiles = 16; +pub const patch = 16; +pub const sam_width = 768; +pub const sam_layers = 12; +pub const sam_heads = 12; +pub const sam_head_dim = 64; +pub const sam_ffn = 3072; +pub const sam_window = 14; +pub const sam_global = [_]usize{ 2, 5, 8, 11 }; +pub const sam_grid = base_size / patch; +pub const neck_width = 256; +pub const net2_width = 512; +pub const net3_width = 1024; +pub const sam_eps: f32 = 1e-6; +pub const clip_width = 1024; +pub const clip_layers = 24; +pub const clip_heads = 16; +pub const clip_head_dim = 64; +pub const clip_ffn = 4096; +pub const clip_positions = 257; +pub const clip_eps: f32 = 1e-5; +/// CLIP's rows then SAM's, side by side, into the projector. +pub const fused = clip_width + net3_width; + +/// Feature rows a side: a 1024 view's 16, a 640 tile's 10 (SAM's grid after its two stride-2 convolutions). +pub fn side(size: usize) usize { + return size / patch / 4; +} + +/// Whether SAM block `i` attends globally rather than in 14 x 14 windows. +pub fn isGlobal(i: usize) bool { + return std.mem.indexOfScalar(usize, &sam_global, i) != null; +} + +/// Why `config.json` is not Unlimited-OCR-2's geometry, or null when it is. +pub fn problem(gpa: std.mem.Allocator, text: []const u8) !?[]const u8 { + const parsed = std.json.parseFromSlice(std.json.Value, gpa, text, .{}) catch return "config.json is not JSON"; + defer parsed.deinit(); + const root = parsed.value; + if (root != .object) return "config.json is not an object"; + const o = root.object; + const want_ints = .{ + .{ "hidden_size", hidden }, .{ "num_hidden_layers", layers }, .{ "num_attention_heads", heads }, + .{ "num_key_value_heads", heads }, .{ "intermediate_size", dense_ffn }, .{ "moe_intermediate_size", expert_ffn }, + .{ "n_routed_experts", experts }, .{ "n_shared_experts", 2 }, .{ "num_experts_per_tok", top_k }, + .{ "first_k_dense_replace", 1 }, .{ "moe_layer_freq", 1 }, .{ "vocab_size", vocab }, + .{ "bos_token_id", bos }, .{ "eos_token_id", eos }, + }; + inline for (want_ints) |w| { + const v = o.get(w[0]) orelse return "config.json lacks " ++ w[0]; + if (v != .integer or v.integer != w[1]) return w[0] ++ " is not Unlimited-OCR-2's"; + } + const mt = o.get("model_type") orelse return "config.json has no model_type"; + if (mt != .string or !std.mem.eql(u8, mt.string, "unlimited-ocr")) return "model_type is not unlimited-ocr"; + const flags = .{ .{ "norm_topk_prob", false }, .{ "use_mla", false }, .{ "attention_bias", false }, .{ "tie_word_embeddings", false } }; + inline for (flags) |f| { + if (o.get(f[0])) |v| if (v != .bool or v.bool != f[1]) return f[0] ++ " is not Unlimited-OCR-2's"; + } + const strings = .{ .{ "topk_method", "greedy" }, .{ "scoring_func", "softmax" }, .{ "hidden_act", "silu" } }; + inline for (strings) |s| { + const v = o.get(s[0]) orelse return "config.json lacks " ++ s[0]; + if (v != .string or !std.mem.eql(u8, v.string, s[1])) return s[0] ++ " is not Unlimited-OCR-2's"; + } + if (o.get("routed_scaling_factor")) |v| if (number(v) != 1.0) return "routed_scaling_factor is not 1"; + if (o.get("rms_norm_eps")) |v| if (number(v) != 1e-6) return "rms_norm_eps is not 1e-6"; + const sp = (o.get("sparse_attention_config") orelse return "config.json has no sparse_attention_config"); + if (sp != .object) return "sparse_attention_config is not an object"; + const sp_ints = .{ + .{ "sparse_block_size", block }, .{ "sparse_local_block", local_blocks }, .{ "dash_topk_blocks", read_blocks }, + .{ "image_token_id", image_token }, .{ "page_token_id", page_token }, .{ "sparse_rope_page_pairs", 1 }, + .{ "sparse_rope_page_mod", 2 }, .{ "per_page_image_tokens", page_image_tokens }, + }; + inline for (sp_ints) |w| { + if (sp.object.get(w[0])) |v| { + if (v != .integer or v.integer != w[1]) return "sparse_attention_config." ++ w[0] ++ " is not Unlimited-OCR-2's"; + } else return "sparse_attention_config lacks " ++ w[0]; + } + const sp_strings = .{ .{ "sparse_main_rope_mode", "page2d" }, .{ "sparse_rope_mode", "page2d" }, .{ "dash_stage0", "head_cls" } }; + inline for (sp_strings) |s| { + const v = sp.object.get(s[0]) orelse return "sparse_attention_config lacks " ++ s[0]; + if (v != .string or !std.mem.eql(u8, v.string, s[1])) return "sparse_attention_config." ++ s[0] ++ " is not Unlimited-OCR-2's"; + } + const sp_numbers = .{ .{ "sparse_rope_tok_theta", 10000.0 }, .{ "sparse_rope_page_theta", 256.0 }, .{ "dash_sigma", 1.0 } }; + inline for (sp_numbers) |s| { + const v = sp.object.get(s[0]) orelse return "sparse_attention_config lacks " ++ s[0]; + if (number(v) != s[1]) return "sparse_attention_config." ++ s[0] ++ " is not Unlimited-OCR-2's"; + } + const tok_mode = sp.object.get("sparse_main_rope_tok_freq_mode") orelse return "sparse_attention_config lacks sparse_main_rope_tok_freq_mode"; + if (tok_mode != .string or !std.mem.eql(u8, tok_mode.string, "resample")) return "sparse_attention_config.sparse_main_rope_tok_freq_mode is not resample"; + const per_layer = .{ .{ "dash_scale_per_layer", @as(f64, router_dim) }, .{ "dash_floor_per_layer", @as(f64, router_floor) } }; + inline for (per_layer) |pl| { + const v = sp.object.get(pl[0]) orelse return "sparse_attention_config lacks " ++ pl[0]; + if (v != .array or v.array.items.len != layers) return "sparse_attention_config." ++ pl[0] ++ " is not one value a layer"; + for (v.array.items) |x| if (@abs(number(x) - pl[1]) > 1e-6 * pl[1]) return "sparse_attention_config." ++ pl[0] ++ " is not Unlimited-OCR-2's"; + } + return null; +} + +fn number(v: std.json.Value) f64 { + return switch (v) { + .integer => |i| @floatFromInt(i), + .float => |f| f, + else => std.math.nan(f64), + }; +} + +/// Fails with the reason when `config.json` is not Unlimited-OCR-2's geometry. +pub fn check(gpa: std.mem.Allocator, text: []const u8) !void { + if (try problem(gpa, text)) |why| { + std.log.err("unlimited ocr: {s}", .{why}); + return error.UnsupportedConfig; + } +} + +test "uocr: the release's geometry is admitted and a changed one is refused with its reason" { + const good = + \\{"model_type":"unlimited-ocr","hidden_size":1280,"num_hidden_layers":12,"num_attention_heads":10, + \\"num_key_value_heads":10,"intermediate_size":6848,"moe_intermediate_size":896,"n_routed_experts":64, + \\"n_shared_experts":2,"num_experts_per_tok":6,"first_k_dense_replace":1,"moe_layer_freq":1,"vocab_size":129280, + \\"bos_token_id":0,"eos_token_id":1,"norm_topk_prob":false,"use_mla":false,"attention_bias":false, + \\"tie_word_embeddings":false,"topk_method":"greedy","scoring_func":"softmax","hidden_act":"silu", + \\"routed_scaling_factor":1.0,"rms_norm_eps":1e-06,"sparse_attention_config":{"sparse_block_size":32, + \\"sparse_local_block":4,"dash_topk_blocks":12,"image_token_id":128815,"page_token_id":128827, + \\"sparse_rope_page_pairs":1,"sparse_rope_page_mod":2,"per_page_image_tokens":273,"sparse_main_rope_mode":"page2d","sparse_rope_mode":"page2d", + \\"dash_stage0":"head_cls","sparse_rope_tok_theta":10000.0,"sparse_rope_page_theta":256.0,"dash_sigma":1.0, + \\"sparse_main_rope_tok_freq_mode":"resample","dash_scale_per_layer":[128,128,128,128,128,128,128,128,128,128,128,128], + \\"dash_floor_per_layer":[1e-4,1e-4,1e-4,1e-4,1e-4,1e-4,1e-4,1e-4,1e-4,1e-4,1e-4,1e-4]}} + ; + try std.testing.expect(try problem(std.testing.allocator, good) == null); + const bad = try std.mem.replaceOwned(u8, std.testing.allocator, good, "\"num_experts_per_tok\":6", "\"num_experts_per_tok\":8"); + defer std.testing.allocator.free(bad); + try std.testing.expectEqualStrings("num_experts_per_tok is not Unlimited-OCR-2's", (try problem(std.testing.allocator, bad)).?); +} + +test "uocr: the rotary's inverse frequencies and a row's values are the release's" { + // the release's fp32 buffer at pairs 0-3, and its bf16 cos and sin at place 1 (pairs 0-3) and 27,143 (pair 0) + for ([_]u32{ 0x3f800000, 0x3f5d2e59, 0x3f3f190e, 0x3f251b3a }, 0..) |bits, i| try std.testing.expectEqual(bits, @as(u32, @bitCast(invTok(i)))); + var c: [rope_pairs]u16 = undefined; + var s: [rope_pairs]u16 = undefined; + rope(1, 3, &c, &s); + for ([_]f32{ 0.5390625, 0.6484375, 0.734375, 0.80078125 }, c[0..4]) |want, got| try std.testing.expectEqual(bf16(want), got); + for ([_]f32{ 0.83984375, 0.76171875, 0.6796875, 0.6015625 }, s[0..4]) |want, got| try std.testing.expectEqual(bf16(want), got); + try std.testing.expectEqual(bf16(0.5390625), c[63]); + rope(27143, 7, &c, &s); + try std.testing.expectEqual(bf16(0.9375), c[0]); + try std.testing.expectEqual(bf16(-0.353515625), s[0]); +} diff --git a/zig/src/families/uocr/decoder.zig b/zig/src/families/uocr/decoder.zig new file mode 100644 index 00000000000..cdd222c3cb6 --- /dev/null +++ b/zig/src/families/uocr/decoder.zig @@ -0,0 +1,246 @@ +//! Unlimited-OCR-2's decoder on Metal: the prompt in chunks of rows, then a token a step, over exact bf16 caches. +const std = @import("std"); +const mtl = @import("metal"); +const cfg = @import("config.zig"); +const ks = @import("kernels.zig"); +const wts = @import("weights.zig"); +const prompt_mod = @import("prompt.zig"); +const pass_mod = @import("decoder_pass.zig"); +const Ref = ks.Ref; + +const H = cfg.hidden; +const D = cfg.router_dim; + +/// A layer's caches: bf16 keys, values [cap, 1280] and router keys [cap, 128]; f32 block summaries [cap / 32, 128]. +pub const Cache = struct { k: mtl.Buffer, v: mtl.Buffer, rk: mtl.Buffer, kb: mtl.Buffer }; + +/// A forward's working rows, each part 256-aligned in one buffer. +pub const Scratch = struct { + pub const Part = enum { x, y, proj, q, att, o, ffn, act, mlp, shared, ids, wts, xe, ge, ue, ae, de, gidx, slot, ident, rq, sel, bias, cos, sin, qmask, logits }; + buf: mtl.Buffer, + offs: [std.enums.values(Part).len]usize, + + fn bytes(part: Part, r: usize) usize { + const e = cfg.expert_ffn; + return switch (part) { + .x, .y, .q, .att, .o, .mlp, .shared => r * H * 2, + .proj => r * pass_mod.proj_width * 2, + .ffn => r * 2 * cfg.dense_ffn * 2, + .act => r * cfg.dense_ffn * 2, + .ids, .gidx, .slot, .ident => r * cfg.top_k * 4, + .wts => r * cfg.top_k * 4, + .xe, .de => r * cfg.top_k * H * 2, + .ge, .ue, .ae => r * cfg.top_k * 2 * e * 2, + .rq => r * D * 2, + .sel, .bias => r * cfg.read_blocks * 4, + .cos, .sin => r * cfg.rope_pairs * 2, + .qmask => r * 4, + .logits => cfg.vocab * 2, + }; + } + + fn make(device: mtl.Device, r: usize) !Scratch { + var s: Scratch = undefined; + var total: usize = 0; + for (std.enums.values(Part), 0..) |p, i| { + s.offs[i] = total; + total += std.mem.alignForward(usize, bytes(p, r), 256); + } + s.buf = try device.buffer(total, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); + return s; + } + + pub fn at(s: Scratch, p: Part) Ref { + return .{ .buf = s.buf, .off = s.offs[@backingInt(p)] }; + } + + pub fn host(s: Scratch, comptime T: type, p: Part, n: usize) []T { + return @as([*]T, @ptrCast(@alignCast(s.at(p).addr())))[0..n]; + } +}; + +pub const Decoder = struct { + gpa: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + k: *const ks.Kernels, + w: *const wts.Weights, + /// Positions the caches hold, and positions filled so far. + cap: usize = 0, + len: usize = 0, + /// Prompt rows a prefill pass takes at once. + rows: usize = 0, + /// For checks: each layer's output rows during a prefill, and each layer's attention and MLP outputs. + trace: ?[][]u16 = null, + trace_parts: ?[2][][]u16 = null, + caches: [cfg.layers]Cache = undefined, + /// The projections a pass reads as one: [q | k | v | router q | router k] and [gate | up] a layer. + cat: mtl.Buffer = undefined, + attn_cat: [cfg.layers]Ref = undefined, + ffn_cat: [cfg.layers]Ref = undefined, + /// The routed experts' GPU addresses, [layer][expert] of (gate, up, down), and the buffers they point into. + experts: mtl.Buffer = undefined, + held: [8]mtl.Buffer = undefined, + nheld: usize = 0, + scratch: Scratch = undefined, + /// The prompt's candidate rows (prompt.zig), grown as prompts need. + masks: ?mtl.Buffer = null, + mask_bytes: usize = 0, + words: usize = 0, + + /// A decoder for up to `cap` positions, prefilling `rows` prompt rows a pass. + pub fn init(gpa: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, k: *const ks.Kernels, w: *const wts.Weights, cap: usize, rows: usize) !Decoder { + if (cap == 0 or cap > cfg.max_context or rows == 0) return error.UocrDecoderSize; + var d: Decoder = .{ .gpa = gpa, .device = device, .queue = queue, .k = k, .w = w, .cap = cap, .rows = rows }; + const opts = mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked; + const blocks = std.math.divCeil(usize, cap, cfg.block) catch unreachable; + var made: usize = 0; + errdefer for (d.caches[0..made]) |c| inline for (.{ "k", "v", "rk", "kb" }) |f| @field(c, f).deinit(); + for (&d.caches) |*c| { + c.k = try device.buffer(cap * H * 2, opts); + errdefer c.k.deinit(); + c.v = try device.buffer(cap * H * 2, opts); + errdefer c.v.deinit(); + c.rk = try device.buffer(cap * D * 2, opts); + errdefer c.rk.deinit(); + c.kb = try device.buffer(blocks * D * 4, opts); + made += 1; + } + try d.concat(); + errdefer d.cat.deinit(); + d.experts = try expertTable(device, w); + errdefer d.experts.deinit(); + for (w.layers[1..]) |layer| for (layer.experts) |e| for ([_]Ref{ e.gate, e.up, e.down }) |r| { + for (d.held[0..d.nheld]) |b| { + if (b.id == r.buf.id) break; + } else { + if (d.nheld == d.held.len) return error.UocrExpertBuffers; + d.held[d.nheld] = r.buf; + d.nheld += 1; + } + }; + d.scratch = try Scratch.make(device, @max(rows, 1)); + errdefer d.scratch.buf.deinit(); + for (d.scratch.host(u32, .ident, rows * cfg.top_k), 0..) |*v, i| v.* = @intCast(i); + return d; + } + + pub fn deinit(d: *Decoder) void { + for (d.caches) |c| inline for (.{ "k", "v", "rk", "kb" }) |f| @field(c, f).deinit(); + d.cat.deinit(); + d.experts.deinit(); + d.scratch.buf.deinit(); + if (d.masks) |m| m.deinit(); + d.* = undefined; + } + + /// Each layer's projections copied side by side, so one product makes all of a step's. + fn concat(d: *Decoder) !void { + const w = d.w; + var total: usize = 0; + for (0..cfg.layers) |l| total += pass_mod.proj_width * H * 2 + ffnRows(l) * H * 2; + d.cat = try d.device.buffer(total, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); + var at: usize = 0; + for (w.layers, 0..) |layer, l| { + d.attn_cat[l] = .{ .buf = d.cat, .off = at }; + const r = layer.router; + for ([_]struct { Ref, usize }{ .{ layer.q, H }, .{ layer.k, H }, .{ layer.v, H }, .{ r.q, D }, .{ r.k, D } }) |part| { + @memcpy((d.cat.contents() + at)[0 .. part[1] * H * 2], part[0].addr()[0 .. part[1] * H * 2]); + at += part[1] * H * 2; + } + d.ffn_cat[l] = .{ .buf = d.cat, .off = at }; + const half = ffnRows(l) / 2; + for ([_]Ref{ layer.ffn.gate, layer.ffn.up }) |part| { + @memcpy((d.cat.contents() + at)[0 .. half * H * 2], part.addr()[0 .. half * H * 2]); + at += half * H * 2; + } + } + } + + /// Prefill a prompt: `image_rows` (bf16 [image tokens, 1280]) at its image tokens, the token embeddings elsewhere. + pub fn prefill(d: *Decoder, p: prompt_mod.Prompt, image_rows: []const u16) !void { + const n = p.len(); + if (n == 0 or n > d.cap) return error.UocrPromptTooLong; + var images: usize = 0; + for (p.ids) |id| images += @intFromBool(id == cfg.image_token); + if (image_rows.len != images * H) return error.UocrImageRows; + try d.upload(p); + var tr: ?pass_mod.Trace = null; + if (d.trace != null or d.trace_parts != null) tr = try pass_mod.Trace.init(d.device, n); + defer if (tr) |*t| t.deinit(); + d.len = 0; + var img: usize = 0; + var s0: usize = 0; + const embed: [*]const u16 = @ptrCast(@alignCast(d.w.embed.addr())); + while (s0 < n) { + const r = @min(d.rows, n - s0); + const x = d.scratch.host(u16, .x, r * H); + for (0..r) |i| { + const id = p.ids[s0 + i]; + if (id == cfg.image_token) { + @memcpy(x[i * H ..][0..H], image_rows[img * H ..][0..H]); + img += 1; + } else @memcpy(x[i * H ..][0..H], embed[@as(usize, id) * H ..][0..H]); + d.coords(i, .{ .tok = p.tok[s0 + i], .page = p.page[s0 + i], .mask = p.mask[s0 + i] }); + } + try pass_mod.forward(d, s0, r, true, if (tr) |*t| t else null); + s0 += r; + d.len = s0; + } + if (tr) |t| t.copyOut(d.trace, d.trace_parts, n); + } + + /// One decode step for token `id` at the next position, with its coordinates from prompt.Step. + pub fn step(d: *Decoder, id: u32, c: prompt_mod.Coord) !void { + if (d.len >= d.cap) return error.UocrContextFull; + if (id >= cfg.vocab) return error.UocrBadToken; + const embed: [*]const u16 = @ptrCast(@alignCast(d.w.embed.addr())); + @memcpy(d.scratch.host(u16, .x, H), embed[@as(usize, id) * H ..][0..H]); + d.coords(0, c); + try pass_mod.forward(d, d.len, 1, false, null); + d.len += 1; + } + + /// Row i's rotary values and candidate row. + fn coords(d: *Decoder, i: usize, c: prompt_mod.Coord) void { + const cos = d.scratch.host(u16, .cos, (i + 1) * cfg.rope_pairs); + const sin = d.scratch.host(u16, .sin, (i + 1) * cfg.rope_pairs); + cfg.rope(c.tok, c.page, cos[i * cfg.rope_pairs ..][0..cfg.rope_pairs], sin[i * cfg.rope_pairs ..][0..cfg.rope_pairs]); + d.scratch.host(i32, .qmask, i + 1)[i] = c.mask; + } + + /// The prompt's candidate rows into the masks buffer. + fn upload(d: *Decoder, p: prompt_mod.Prompt) !void { + const need = @max(p.masks.len * 4, 16); + if (d.masks == null or d.mask_bytes < need) { + if (d.masks) |m| m.deinit(); + d.masks = null; + d.masks = try d.device.buffer(need, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); + d.mask_bytes = need; + } + @memcpy(d.masks.?.contents()[0 .. p.masks.len * 4], std.mem.sliceAsBytes(p.masks)); + d.words = p.words; + } + + /// The last row's logits, bf16 [vocab]. + pub fn logits(d: *Decoder) ![]const u16 { + if (d.len == 0) return error.UocrNothingDecoded; + return d.scratch.host(u16, .logits, cfg.vocab); + } +}; + +/// Rows of a layer's gate | up: the dense layer's 2 x 6,848, a routed layer's shared expert's 2 x 1,792. +pub fn ffnRows(l: usize) usize { + return 2 * @as(usize, if (l == 0) cfg.dense_ffn else cfg.shared_ffn); +} + +/// The routed experts' (gate, up, down) GPU addresses, [layer][expert], as decoder.metal's UdExpert reads them. +fn expertTable(device: mtl.Device, w: *const wts.Weights) !mtl.Buffer { + const buf = try device.buffer(cfg.layers * cfg.experts * 3 * 8, mtl.ResourceOptions.shared); + const t: [*]u64 = @ptrCast(@alignCast(buf.contents())); + @memset(t[0 .. cfg.layers * cfg.experts * 3], 0); + for (w.layers[1..], 1..) |layer, l| for (layer.experts, 0..) |e, j| { + for ([_]Ref{ e.gate, e.up, e.down }, 0..) |r, i| t[(l * cfg.experts + j) * 3 + i] = r.buf.gpuAddress() + r.off; + }; + return buf; +} diff --git a/zig/src/families/uocr/decoder_pass.zig b/zig/src/families/uocr/decoder_pass.zig new file mode 100644 index 00000000000..684d667bcd9 --- /dev/null +++ b/zig/src/families/uocr/decoder_pass.zig @@ -0,0 +1,242 @@ +//! One forward of rows (a prompt chunk or a decode step) through the 12 layers; a prompt's experts group on the CPU. +const std = @import("std"); +const mtl = @import("metal"); +const cfg = @import("config.zig"); +const ks = @import("kernels.zig"); +const decoder_mod = @import("decoder.zig"); +const Ref = ks.Ref; +const Decoder = decoder_mod.Decoder; +const Part = decoder_mod.Scratch.Part; + +const H = cfg.hidden; +const E = cfg.expert_ffn; + +/// The width of a layer's joint projection: q, k and v (1280 each), then the router's q and k (128 each). +pub const proj_width = 3 * H + 2 * cfg.router_dim; + +const UdMv = extern struct { n: u32, k: u32 }; +const UdNorm = extern struct { add: u32, eps: f32 }; +const UdQk = extern struct { pos0: u32, eps: f32 }; +const UdRoute = extern struct { pos0: u32, words: u32 }; +const UdAttend = extern struct { pos0: u32, bf16_bias: u32 }; +const UdAct = extern struct { width: u32, gstride: u32, ustride: u32 }; +const UdExp = extern struct { width: u32 }; + +/// A prompt's per-layer rows kept for checks: [attention, MLP, layer output][layer][row][1280] bf16. +pub const Trace = struct { + buf: mtl.Buffer, + n: usize, + + pub fn init(device: mtl.Device, n: usize) !Trace { + return .{ .buf = try device.buffer(3 * cfg.layers * n * H * 2, mtl.ResourceOptions.shared), .n = n }; + } + + pub fn deinit(t: *Trace) void { + t.buf.deinit(); + } + + fn at(t: Trace, part: usize, l: usize, row: usize) Ref { + return .{ .buf = t.buf, .off = ((part * cfg.layers + l) * t.n + row) * H * 2 }; + } + + pub fn copyOut(t: Trace, layers: ?[][]u16, parts: ?[2][][]u16, n: usize) void { + const all: [*]const u16 = @ptrCast(@alignCast(t.buf.contents())); + for (0..cfg.layers) |l| { + if (layers) |ls| @memcpy(ls[l][0 .. n * H], all[(2 * cfg.layers + l) * t.n * H ..][0 .. n * H]); + if (parts) |ps| for (0..2) |p| @memcpy(ps[p][l][0 .. n * H], all[(p * cfg.layers + l) * t.n * H ..][0 .. n * H]); + } + } +}; + +const Pass = struct { + d: *Decoder, + s0: usize, + r: usize, + prompt: bool, + tr: ?*Trace, + cb: mtl.CommandBuffer = undefined, + enc: mtl.ComputeEncoder = undefined, + + fn open(p: *Pass) void { + p.cb = p.d.queue.commandBuffer(); + p.enc = p.cb.compute(.concurrent); + for (p.d.held[0..p.d.nheld]) |b| p.enc.useResource(b, mtl.ResourceUsage.read); + } + + /// Run what is encoded and wait for it. + fn flush(p: *Pass) !void { + p.enc.end(); + p.cb.commit(); + p.cb.wait(); + if (p.cb.failure()) |msg| { + std.log.err("uocr decoder: {s}", .{msg}); + return error.UocrGpu; + } + } + + fn s(p: *Pass, part: Part) Ref { + return p.d.scratch.at(part); + } + + fn bind(p: *Pass, comptime name: []const u8, refs: []const Ref, params: anytype) void { + ks.Kernels.bind(p.enc, p.d.k.get(name), refs, params); + } + + fn groups(p: *Pass, n: usize, threads: usize) void { + p.enc.dispatchGroups(mtl.Size.of(n, 1, 1), mtl.Size.of(threads, 1, 1)); + p.enc.barrier(); + } + + fn grid(p: *Pass, x: usize, y: usize) void { + p.enc.dispatchThreads(mtl.Size.of(x, y, 1), mtl.Size.of(256, 1, 1)); + p.enc.barrier(); + } + + /// y [r, n] = x [r, k] w^T: the tiled product for a prompt's rows, the one-row product for a step. + fn mm(p: *Pass, x: Ref, w: Ref, y: Ref, n: usize, k: usize) void { + if (p.prompt) { + p.d.k.linear(p.enc, x, w, y, p.r, n, k); + p.enc.barrier(); + } else { + p.bind("ud_matvec", &.{ x, w, y }, UdMv{ .n = @intCast(n), .k = @intCast(k) }); + p.groups((n + 31) / 32, 256); + } + } + + fn matvec(p: *Pass, x: Ref, w: Ref, y: Ref, n: usize, k: usize) void { + p.bind("ud_matvec", &.{ x, w, y }, UdMv{ .n = @intCast(n), .k = @intCast(k) }); + p.groups((n + 31) / 32, 256); + } + + /// With `add`: x = bf16(x + a); then y = the norm of x under `w`. + fn norm(p: *Pass, add: bool, a: Part, w: Ref) void { + p.bind("ud_norm", &.{ p.s(.x), p.s(a), w, p.s(.y) }, UdNorm{ .add = @intFromBool(add), .eps = cfg.eps }); + p.groups(p.r, 256); + } + + fn silu(p: *Pass, g: Ref, u: Ref, y: Ref, rows: usize, width: usize, stride: usize) void { + p.bind("ud_silu_mul", &.{ g, u, y }, UdAct{ .width = @intCast(width), .gstride = @intCast(stride), .ustride = @intCast(stride) }); + p.grid(width, rows); + } + + /// The prompt's rows `part` into the trace at `which` (0 attention, 1 MLP, 2 layer output). + fn keep(p: *Pass, part: Part, which: usize, l: usize) void { + const t = p.tr orelse return; + p.bind("ud_gather", &.{ p.s(part), p.s(.ident), t.at(which, l, p.s0) }, {}); + p.grid(H, p.r); + } + + fn attention(p: *Pass, l: usize) void { + const d = p.d; + const layer = d.w.layers[l]; + const c = d.caches[l]; + const pos0: u32 = @intCast(p.s0); + p.mm(p.s(.y), d.attn_cat[l], p.s(.proj), proj_width, H); + const cache = struct { + fn ref(b: mtl.Buffer) Ref { + return .{ .buf = b }; + } + }.ref; + p.bind("ud_qk", &.{ p.s(.proj), p.s(.cos), p.s(.sin), layer.router.q_norm, layer.router.k_norm, p.s(.q), cache(c.k), cache(c.v), p.s(.rq), cache(c.rk) }, UdQk{ .pos0 = pos0, .eps = cfg.eps }); + p.groups(p.r, cfg.router_dim); + const c0 = p.s0 / cfg.block; + const c1 = (p.s0 + p.r) / cfg.block; + if (c1 > c0) { + p.bind("ud_block_keys", &.{ cache(c.rk), layer.router.head_cls, cache(c.kb) }, @as(u32, @intCast(c0))); + p.groups(c1 - c0, 32); + } + const masks: Ref = .{ .buf = d.masks.? }; + p.bind("ud_route", &.{ p.s(.rq), cache(c.kb), masks, p.s(.qmask), p.s(.sel), p.s(.bias) }, UdRoute{ .pos0 = pos0, .words = @intCast(d.words) }); + p.groups(p.r, 256); + p.bind("ud_attend", &.{ p.s(.q), cache(c.k), cache(c.v), p.s(.sel), p.s(.bias), p.s(.att) }, UdAttend{ .pos0 = pos0, .bf16_bias = @intFromBool(p.prompt) }); + p.enc.dispatchGroups(mtl.Size.of(cfg.heads, p.r, 1), mtl.Size.of(256, 1, 1)); + p.enc.barrier(); + p.mm(p.s(.att), layer.o, p.s(.o), H, H); + } + + /// The layer's MLP rows from y into .mlp: the dense FFN, or the shared expert plus the 6 routed ones. + fn ffn(p: *Pass, l: usize) !void { + const d = p.d; + const layer = d.w.layers[l]; + const width: usize = if (l == 0) cfg.dense_ffn else cfg.shared_ffn; + const f = p.s(.ffn); + p.mm(p.s(.y), d.ffn_cat[l], f, 2 * width, H); + p.silu(f, f.at(width * 2), p.s(.act), p.r, width, 2 * width); + p.mm(p.s(.act), layer.ffn.down, p.s(if (l == 0) .mlp else .shared), H, width); + if (l == 0) return; + p.bind("ud_moe_gate", &.{ p.s(.y), layer.gate.?, p.s(.ids), p.s(.wts) }, {}); + p.groups(p.r, 1024); + if (p.prompt) return p.experts(l); + const table: Ref = .{ .buf = d.experts, .off = l * cfg.experts * 3 * 8 }; + p.bind("ud_expert_gu", &.{ p.s(.y), table, p.s(.ids), p.s(.ge) }, UdExp{ .width = E }); + p.groups(cfg.top_k * 2 * E / 32, 256); + p.silu(p.s(.ge), p.s(.ge).at(E * 2), p.s(.ae), cfg.top_k, E, 2 * E); + p.bind("ud_expert_down", &.{ p.s(.ae), table, p.s(.ids), p.s(.de) }, UdExp{ .width = E }); + p.groups(cfg.top_k * H / 32, 256); + p.bind("ud_combine", &.{ p.s(.de), p.s(.ident), p.s(.wts), p.s(.shared), p.s(.mlp) }, {}); + p.grid(H, 1); + } + + /// A prompt's routed experts: the gate's picks read back, rows grouped by expert, one product an expert. + fn experts(p: *Pass, l: usize) !void { + const d = p.d; + try p.flush(); + p.open(); + const n = p.r * cfg.top_k; + const ids = d.scratch.host(u32, .ids, n); + var start: [cfg.experts + 1]usize = @splat(0); + for (ids) |e| start[e + 1] += 1; + for (1..start.len) |e| start[e] += start[e - 1]; + var fill = start; + const gidx = d.scratch.host(u32, .gidx, n); + const slot = d.scratch.host(u32, .slot, n); + for (ids, 0..) |e, i| { + gidx[fill[e]] = @intCast(i / cfg.top_k); + slot[i] = @intCast(fill[e]); + fill[e] += 1; + } + p.bind("ud_gather", &.{ p.s(.y), p.s(.gidx), p.s(.xe) }, {}); + p.grid(H, n); + const layer = d.w.layers[l]; + for (layer.experts, 0..) |ex, e| { + const m = start[e + 1] - start[e]; + if (m == 0) continue; + const at = start[e]; + d.k.linear(p.enc, p.s(.xe).at(at * H * 2), ex.gate, p.s(.ge).at(at * E * 2), m, E, H); + d.k.linear(p.enc, p.s(.xe).at(at * H * 2), ex.up, p.s(.ue).at(at * E * 2), m, E, H); + } + p.enc.barrier(); + p.silu(p.s(.ge), p.s(.ue), p.s(.ae), n, E, E); + for (layer.experts, 0..) |ex, e| { + const m = start[e + 1] - start[e]; + if (m == 0) continue; + d.k.linear(p.enc, p.s(.ae).at(start[e] * E * 2), ex.down, p.s(.de).at(start[e] * H * 2), m, H, E); + } + p.enc.barrier(); + p.bind("ud_combine", &.{ p.s(.de), p.s(.slot), p.s(.wts), p.s(.shared), p.s(.mlp) }, {}); + p.grid(H, p.r); + } +}; + +/// Rows s0 .. s0 + r through every layer (inputs in the scratch): the caches take their keys, the last row its logits. +pub fn forward(d: *Decoder, s0: usize, r: usize, prompt: bool, tr: ?*Trace) !void { + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + var p: Pass = .{ .d = d, .s0 = s0, .r = r, .prompt = prompt, .tr = tr }; + p.open(); + for (0..cfg.layers) |l| { + const layer = d.w.layers[l]; + // the previous layer's MLP rows join the residual first + p.norm(l > 0, .mlp, layer.in_norm); + if (l > 0) p.keep(.x, 2, l - 1); + p.attention(l); + p.keep(.o, 0, l); + p.norm(true, .o, layer.post_norm); + try p.ffn(l); + p.keep(.mlp, 1, l); + } + p.norm(true, .mlp, d.w.norm); + p.keep(.x, 2, cfg.layers - 1); + p.matvec(p.s(.y).at((r - 1) * H * 2), d.w.head, p.s(.logits), cfg.vocab, H); + try p.flush(); +} diff --git a/zig/src/families/uocr/gate.zig b/zig/src/families/uocr/gate.zig new file mode 100644 index 00000000000..5dac41f1c8c --- /dev/null +++ b/zig/src/families/uocr/gate.zig @@ -0,0 +1,116 @@ +//! A run's rows against float32 ones, gated by the reference's bf16 distance (twice it, at most); a reply's ties. +const std = @import("std"); +const resize = @import("resize.zig"); + +pub const Match = struct { cosine: f64, worst_row: f64, worst_at: usize }; + +/// The cosine over all values and the largest relative L2 error of one row of `width`. +pub fn match(ours: []const f32, exact: []const f32, width: usize) Match { + var dot: f64 = 0; + var aa: f64 = 0; + var bb: f64 = 0; + var m: Match = .{ .cosine = 0, .worst_row = 0, .worst_at = 0 }; + var row: usize = 0; + while (row < ours.len) : (row += width) { + var rd: f64 = 0; + var rb: f64 = 0; + for (ours[row..][0..width], exact[row..][0..width]) |a32, b32| { + const a: f64 = a32; + const b: f64 = b32; + dot += a * b; + aa += a * a; + bb += b * b; + rd += (a - b) * (a - b); + rb += b * b; + } + const rel = @sqrt(rd / @max(rb, 1e-30)); + if (rel > m.worst_row) { + m.worst_row = rel; + m.worst_at = row / width; + } + } + m.cosine = dot / @sqrt(@max(aa * bb, 1e-300)); + return m; +} + +/// The float32 rows rounded to bf16, against themselves: the closest any bf16 result can be. +pub fn rounding(a: std.mem.Allocator, exact: []const f32, width: usize) !Match { + const r = try a.alloc(f32, exact.len); + defer a.free(r); + for (r, exact) |*o, x| o.* = resize.widen(resize.bf16(x)); + return match(r, exact, width); +} + +pub const factor = 2.0; + +pub const Verdict = struct { pass: bool, cosine_err: f64, cosine_limit: f64, row: f64, row_at: usize, row_limit: f64 }; + +/// Ours within `factor` of the larger of the reference's bf16 error and bf16 rounding's, in cosine and worst row. +pub fn verdict(ours: Match, reference: Match, rounded: Match) Verdict { + const cosine_limit = factor * (1 - @min(reference.cosine, rounded.cosine)); + const row_limit = factor * @max(reference.worst_row, rounded.worst_row); + const cosine_err = 1 - ours.cosine; + return .{ .pass = cosine_err <= cosine_limit and ours.worst_row <= row_limit, .cosine_err = cosine_err, .cosine_limit = cosine_limit, .row = ours.worst_row, .row_at = ours.worst_at, .row_limit = row_limit }; +} + +test "uocr: a run equal to float32 passes, and one twice as far as the reference fails" { + const exact = [_]f32{ 1, 2, 3, 4, 5, 6, 7, 8 }; + const near = [_]f32{ 1.01, 2, 3, 4, 5, 6, 7, 8 }; + const far = [_]f32{ 1.5, 2, 3, 4, 5, 6, 7, 8 }; + const ref = match(&near, &exact, 4); + const rnd = try rounding(std.testing.allocator, &exact, 4); + try std.testing.expect(verdict(match(&exact, &exact, 4), ref, rnd).pass); + try std.testing.expect(!verdict(match(&far, &exact, 4), ref, rnd).pass); +} + +/// How many bf16 steps apart two logits are, a step being bf16's spacing at the larger one's size. +pub fn bf16Steps(x: f32, y: f32) f32 { + const size = @max(@abs(x), @abs(y)); + if (size == 0) return 0; + const ulp = std.math.ldexp(@as(f32, 1), std.math.frexp(size).exponent - 1 - 7); + return @abs(x - y) / ulp; +} + +test "uocr: bf16 steps between two logits follow bf16's spacing at their size" { + try std.testing.expectEqual(@as(f32, 0), bf16Steps(24.5, 24.5)); + try std.testing.expectEqual(@as(f32, 1), bf16Steps(24.0, 24.125)); // [16, 32): a step is 0.125 + try std.testing.expectEqual(@as(f32, 2), bf16Steps(40.0, 40.5)); // [32, 64): a step is 0.25 + try std.testing.expectEqual(@as(f32, 4), bf16Steps(-30.0, -29.5)); + try std.testing.expectEqual(@as(f32, 0.5), bf16Steps(1.0, 1.00390625)); // [1, 2): a step is 1/128 +} + +/// A reference step's two highest logits: id, logit, id, logit. +pub const Top2 = [4]f64; + +/// A departure from torch bf16's pick is a tie when both runs weigh the same two tokens, each within one bf16 step. +pub const Departure = struct { + same_two: bool, + ours: f32, + theirs: f32, + pub fn tie(d: Departure) bool { + return d.same_two and d.ours <= 1 and d.theirs <= 1; + } +}; + +/// Our bf16 logits `lg` picked `ours` where the reference picked `want`, with the reference's `top2` at that step. +pub fn departure(lg: []const u16, ours: u32, want: u32, top2: Top2) Departure { + const t0: u32 = @intFromFloat(top2[0]); + const t1: u32 = @intFromFloat(top2[2]); + return .{ + .same_two = (t0 == ours and t1 == want) or (t0 == want and t1 == ours), + .ours = bf16Steps(resize.widen(lg[ours]), resize.widen(lg[want])), + .theirs = bf16Steps(@floatCast(top2[1]), @floatCast(top2[3])), + }; +} + +test "uocr: a departure is a tie only with the same two contenders and both margins within one bf16 step" { + var lg = std.mem.zeroes([8]u16); + lg[3] = resize.bf16(24.125); + lg[5] = resize.bf16(24.0); + const t = departure(&lg, 3, 5, .{ 5, 24.0625, 3, 24.0 }); + try std.testing.expect(t.tie() and t.same_two and t.ours == 1 and t.theirs == 0.5); + try std.testing.expect(!departure(&lg, 3, 5, .{ 5, 24.0625, 7, 24.0 }).tie()); // torch's second is another token + try std.testing.expect(!departure(&lg, 3, 5, .{ 5, 24.5, 3, 24.0 }).tie()); // torch's margin is four steps + lg[3] = resize.bf16(24.5); + try std.testing.expect(!departure(&lg, 3, 5, .{ 5, 24.0625, 3, 24.0 }).tie()); // ours is four steps +} diff --git a/zig/src/families/uocr/generate.zig b/zig/src/families/uocr/generate.zig new file mode 100644 index 00000000000..a49711e637b --- /dev/null +++ b/zig/src/families/uocr/generate.zig @@ -0,0 +1,80 @@ +//! The publisher's generation: greedy under PageCountGuard (EOS only after every page's marker, 20,000 tokens a page). +const std = @import("std"); +const cfg = @import("config.zig"); +const prompt_mod = @import("prompt.zig"); +const decoder_mod = @import("decoder.zig"); +const resize = @import("resize.zig"); + +/// The guard's count of the reply so far. +pub const Guard = struct { + expected: u32, + marks: u32 = 0, + page_len: u32 = 0, + + pub fn init(p: prompt_mod.Prompt) Guard { + var n: u32 = 0; + for (p.ids) |id| n += @intFromBool(id == cfg.page_token); + return .{ .expected = n }; + } + + /// The one token the guard forces, or null when it only bars EOS or lets every token through. + fn forced(g: Guard) ?u32 { + if (g.marks > g.expected) return cfg.eos; + if (g.page_len >= cfg.max_page_tokens) return if (g.marks < g.expected) cfg.page_token else cfg.eos; + return null; + } + + /// The greedy pick under the guard from bf16 logits (the first of equal maxima, as torch's argmax gives). + pub fn pick(g: Guard, logits: []const u16) u32 { + if (g.forced()) |only| return only; + const bar_eos = g.marks < g.expected; + var best: u32 = 0; + var best_v = -std.math.inf(f32); + for (logits, 0..) |h, i| { + if (bar_eos and i == cfg.eos) continue; + const v = resize.widen(h); + if (v > best_v) { + best_v = v; + best = @intCast(i); + } + } + return best; + } + + pub fn take(g: *Guard, id: u32) void { + if (id == cfg.page_token) { + g.marks += 1; + g.page_len = 0; + } else g.page_len += 1; + } +}; + +/// Greedy tokens after a prefill, up to `max_new` or EOS (not included), into `out`; `on_token` sees each one. +pub fn greedy(d: *decoder_mod.Decoder, p: prompt_mod.Prompt, max_new: usize, out: *std.ArrayList(u32), a: std.mem.Allocator, ctx: anytype, comptime on_token: fn (@TypeOf(ctx), u32) void) !void { + var guard = Guard.init(p); + var st = prompt_mod.Step.init(p); + var lg = try d.logits(); + while (out.items.len < max_new and d.len + 1 < cfg.max_context) { + const id = guard.pick(lg); + if (id == cfg.eos) break; + try out.append(a, id); + on_token(ctx, id); + guard.take(id); + if (out.items.len == max_new) break; + try d.step(id, st.next(id)); + lg = try d.logits(); + } +} + +test "uocr: the guard bars EOS until the pages are done, then forces it" { + var logits: [8]u16 = @splat(resize.bf16(0)); + logits[cfg.eos] = resize.bf16(5); + logits[3] = resize.bf16(1); + var g: Guard = .{ .expected = 1 }; + try std.testing.expectEqual(@as(u32, 3), g.pick(&logits)); + g.take(cfg.page_token); + try std.testing.expectEqual(@as(u32, cfg.eos), g.pick(&logits)); + g.marks = 2; + logits[cfg.eos] = resize.bf16(-5); + try std.testing.expectEqual(@as(u32, cfg.eos), g.pick(&logits)); +} diff --git a/zig/src/families/uocr/kernels.zig b/zig/src/families/uocr/kernels.zig new file mode 100644 index 00000000000..911169ddba1 --- /dev/null +++ b/zig/src/families/uocr/kernels.zig @@ -0,0 +1,138 @@ +//! Unlimited-OCR-2's Metal pipelines: core_qwen_vision's bf16 and fp32-sum projections, then its own steps. +const std = @import("std"); +const mtl = @import("metal"); +const sources = @import("kernel_sources"); +const frags = @import("../../core/frags.zig"); +pub const Ref = @import("weights.zig").Ref; + +/// Each pipeline by its function: the four bf16 projections, the two fp32-sum ones, then this family's. +pub const names = [_][]const u8{ + "qwv_gemm_bf16_nt_00", + "qwv_gemm_bf16_nt_01", + "qwv_gemm_bf16_nt_10", + "qwv_gemm_bf16_nt_11", + "custom_kernel_tf_gemm_splitk_nax_bf16_n_t_n_t_64_64_256_2_2_bfloat16_t_bfloat16_t_int32_t_float", + "custom_kernel_tf_gemm_splitk_nax_bf16_n_t_t_t_64_64_256_2_2_bfloat16_t_bfloat16_t_int32_t_float", + "uv_im2col", + "uv_add", + "uv_bias", + "uv_layer_norm", + "uv_gelu", + "uv_quick_gelu", + "uv_window", + "uv_unwindow_add", + "uv_rel_pos", + "uv_attention", + "uv_concat", + "uv_clip_embed", + // the decoder's + "ud_gather", + "ud_matvec", + "ud_norm", + "ud_qk", + "ud_block_keys", + "ud_route", + "ud_attend", + "ud_moe_gate", + "ud_silu_mul", + "ud_expert_gu", + "ud_expert_down", + "ud_combine", +}; +const tower_count = 6; +/// The decoder's pipelines start at the first "ud_" name and come from its own library. +const decoder_first = blk: { + for (names, 0..) |n, i| if (std.mem.startsWith(u8, n, "ud_")) break :blk i; + @compileError("no decoder pipelines"); +}; +const sums = 4; + +pub const Kernels = struct { + tower: mtl.Library, + own: mtl.Library, + decoder: mtl.Library, + p: [names.len]mtl.Pipeline, + + pub fn load(gpa: std.mem.Allocator, device: mtl.Device) !Kernels { + const src = try frags.source(device, gpa, sources.core_qwen_vision); + defer gpa.free(src); + var k: Kernels = undefined; + k.tower = try mtl.Library.fromSource(device, src, mtl.CompileOptions.mlx()); + errdefer k.tower.deinit(); + k.own = try mtl.Library.fromSource(device, sources.uocr, mtl.CompileOptions.mlx()); + errdefer k.own.deinit(); + k.decoder = try mtl.Library.fromSource(device, sources.uocr_decoder, mtl.CompileOptions.mlx()); + errdefer k.decoder.deinit(); + var made: usize = 0; + errdefer for (k.p[0..made]) |p| p.deinit(); + for (names, 0..) |name, i| { + k.p[i] = try mtl.Pipeline.init(device, if (i < tower_count) k.tower else if (i < decoder_first) k.own else k.decoder, name, false); + made += 1; + } + return k; + } + + pub fn deinit(k: *Kernels) void { + for (k.p) |p| p.deinit(); + k.decoder.deinit(); + k.own.deinit(); + k.tower.deinit(); + } + + pub fn get(k: *const Kernels, comptime name: []const u8) mtl.Pipeline { + inline for (names, 0..) |n, i| if (comptime std.mem.eql(u8, n, name)) return k.p[i]; + @compileError("no pipeline " ++ name); + } + + /// y [M, N] = bf16(x [M, K] w^T) with fp32 sums (tfp::gemm_nax), w as stored [N, K]; K a multiple of 32. + pub fn linear(k: *const Kernels, e: mtl.ComputeEncoder, x: Ref, w: Ref, y: Ref, M: usize, N: usize, K: usize) void { + std.debug.assert(K % 32 == 0); + const tn = (N + 127) / 128; + const tm = (M + 63) / 64; + e.setPipeline(k.p[@as(usize, @intFromBool(M % 64 == 0)) * 2 + @intFromBool(N % 128 == 0)]); + e.setBuffer(x.buf, x.off, 0); + e.setBuffer(w.buf, w.off, 1); + var p: [16]i32 = @splat(0); + const vals = [_]usize{ M, N, K, K, K, N, tn, tm, 2, K / 256 }; + for (vals, 0..) |v, i| p[i] = @intCast(v); + e.setBytes(std.mem.asBytes(&p), 2); + e.setBuffer(y.buf, y.off, 3); + e.dispatchThreads(mtl.Size.of(tn * 4 * 32, (tm + 3) / 4 * 4, 2), mtl.Size.of(32, 4, 2)); + } + + /// y [M, N] = bf16(x w^T + b): one split-K part's fp32 sums into `sum`, then the bias, one rounding (N % 64 = 0). + pub fn linearBias(k: *const Kernels, e: mtl.ComputeEncoder, x: Ref, w: Ref, b: Ref, sum: Ref, y: Ref, M: usize, N: usize, K: usize) void { + std.debug.assert(N % 64 == 0 and K % 256 == 0); + const tn = N / 64; + const tm = (M + 63) / 64; + const swz: u6 = if (tm <= 3) 0 else 1; + e.setPipeline(k.p[sums + @as(usize, @intFromBool(M % 64 == 0))]); + e.setBuffer(x.buf, x.off, 0); + e.setBuffer(w.buf, w.off, 1); + var p: [16]i32 = @splat(0); + const vals = [_]usize{ M, N, K, K, K, N, tn, tm, 1, M * N, K, swz, 0, 0 }; + for (vals, 0..) |v, i| p[i] = @intCast(v); + e.setBytes(std.mem.asBytes(&p), 2); + e.setBuffer(sum.buf, sum.off, 3); + const tiles = (tn << swz) * ((tm + (@as(usize, 1) << swz) - 1) >> swz); + e.dispatchThreads(mtl.Size.of(tiles * 32, 2, 2), mtl.Size.of(32, 2, 2)); + bind(e, k.get("uv_bias"), &.{ sum, b, y }, @as(u32, @intCast(N))); + e.dispatchThreads(mtl.Size.of(N, M, 1), mtl.Size.of(256, 1, 1)); + } + + /// One kernel's buffers in order, then its parameters (if any) at the next index. + pub fn bind(e: mtl.ComputeEncoder, p: mtl.Pipeline, refs: []const Ref, params: anytype) void { + e.setPipeline(p); + for (refs, 0..) |r, i| e.setBuffer(r.buf, r.off, i); + if (@TypeOf(params) != void) e.setValue(params, refs.len); + } +}; + +test "uocr: every Unlimited-OCR-2 pipeline compiles and loads on this GPU" { + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const device = mtl.Device.init() catch return error.SkipZigTest; + defer device.deinit(); + var k = try Kernels.load(std.testing.allocator, device); + k.deinit(); +} diff --git a/zig/src/families/uocr/preprocess.zig b/zig/src/families/uocr/preprocess.zig new file mode 100644 index 00000000000..e13873a4f79 --- /dev/null +++ b/zig/src/families/uocr/preprocess.zig @@ -0,0 +1,171 @@ +//! A page to the encoder's views as the publisher's processor makes them: the 1024 letterbox, gundam's 640 tiles. +const std = @import("std"); +const picture = @import("../../core/picture/picture.zig"); +const resample = picture.resample; +const cfg = @import("config.zig"); +const resize = @import("resize.zig"); + +/// Fewest and most tiles a gundam page splits into. +pub const min_tiles = 2; +pub const max_tiles = 16; +const pad_gray: u8 = 127; + +/// A page's views: the global one [3, 1024, 1024] and `across` x `down` tiles [3, 640, 640] each (none when 1 x 1). +pub const Views = struct { + global: []u16, + tiles: []u16, + across: usize, + down: usize, + + pub fn tileCount(v: Views) usize { + return if (v.across * v.down > 1) v.across * v.down else 0; + } + + pub fn tile(v: Views, i: usize) []const u16 { + const n = 3 * cfg.tile_size * cfg.tile_size; + return v.tiles[i * n ..][0..n]; + } + + /// The page's image tokens: the global block and separator, and the tiles' rows with their newlines. + pub fn tokens(v: Views) usize { + const g = cfg.side(cfg.base_size); + const t = cfg.side(cfg.tile_size); + return g * (g + 1) + 1 + if (v.tileCount() > 0) (t * v.across + 1) * (t * v.down) else 0; + } + + pub fn deinit(v: *Views, a: std.mem.Allocator) void { + a.free(v.global); + a.free(v.tiles); + v.* = undefined; + } +}; + +/// RGB rows as Pillow's convert('RGB') gives them: alpha dropped, never composited, no EXIF transpose. +pub fn rgbOf(a: std.mem.Allocator, s: picture.Samples) ![]u8 { + const out = try a.alloc(u8, s.width * s.height * 3); + for (0..s.width * s.height) |i| @memcpy(out[i * 3 ..][0..3], s.data[i * s.channels ..][0..3]); + return out; +} + +/// A decoded page: RGB rows the caller frees. +pub const Page = struct { + rgb: []u8, + width: usize, + height: usize, + + pub fn deinit(p: *Page, a: std.mem.Allocator) void { + a.free(p.rgb); + p.* = undefined; + } +}; + +/// A PNG, JPEG or WebP file's page, taken as the publisher's Image.open(...).convert('RGB') takes it. +pub fn decode(io: std.Io, a: std.mem.Allocator, bytes: []const u8) picture.Error!Page { + const s = switch (picture.sniff(bytes)) { + .png => try picture.png.decodeWithLimits(a, bytes, .{}), + .jpeg => try picture.jpeg.decodeWithLimits(io, a, bytes, .{}), + .webp => try picture.webp.decodeWithLimits(io, a, bytes, .{}), + .unknown => return error.Invalid, + }; + defer a.free(s.data); + return .{ .rgb = try rgbOf(a, s), .width = s.width, .height = s.height }; +} + +/// Python's round() of a float: halves to even. +fn roundEven(x: f64) usize { + const f = @floor(x); + const d = x - f; + const r = if (d > 0.5) f + 1 else if (d < 0.5) f else if (@mod(f, 2) == 0) f else f + 1; + return @intFromFloat(r); +} + +/// ToTensor and Normalize(0.5, 0.5) in float32, then bf16: [3, side, side] from packed RGB rows. +fn normalize(rgb: []const u8, side: usize, out: []u16) void { + for (0..side * side) |p| for (0..3) |c| { + const x: f32 = @as(f32, @floatFromInt(rgb[p * 3 + c])) / 255.0; + out[c * side * side + p] = resize.bf16((x - 0.5) / 0.5); + }; +} + +/// The tile grid dynamic_preprocess picks: its candidate order, the closest aspect ratio, ties to the later one. +pub fn grid(width: usize, height: usize) [2]usize { + const aspect = @as(f64, @floatFromInt(width)) / @as(f64, @floatFromInt(height)); + const area: f64 = @floatFromInt(width * height); + var best: [2]usize = .{ 1, 1 }; + var best_diff = std.math.inf(f64); + for (candidates) |r| { + const diff = @abs(aspect - @as(f64, @floatFromInt(r[0])) / @as(f64, @floatFromInt(r[1]))); + if (diff < best_diff) { + best_diff = diff; + best = r; + } else if (diff == best_diff and area > 0.5 * @as(f64, @floatFromInt(cfg.tile_size * cfg.tile_size * r[0] * r[1]))) best = r; + } + return best; +} + +/// Every (i, j) with 2 <= i*j <= 16 in CPython's set iteration order, stably sorted by i*j (the publisher's order). +const candidates = [_][2]usize{ + .{ 1, 2 }, .{ 2, 1 }, .{ 3, 1 }, .{ 1, 3 }, .{ 2, 2 }, .{ 4, 1 }, .{ 1, 4 }, .{ 5, 1 }, .{ 1, 5 }, .{ 1, 6 }, + .{ 6, 1 }, .{ 3, 2 }, .{ 2, 3 }, .{ 7, 1 }, .{ 1, 7 }, .{ 4, 2 }, .{ 2, 4 }, .{ 1, 8 }, .{ 8, 1 }, .{ 1, 9 }, + .{ 3, 3 }, .{ 9, 1 }, .{ 2, 5 }, .{ 5, 2 }, .{ 10, 1 }, .{ 1, 10 }, .{ 11, 1 }, .{ 1, 11 }, .{ 12, 1 }, .{ 3, 4 }, + .{ 4, 3 }, .{ 1, 12 }, .{ 6, 2 }, .{ 2, 6 }, .{ 13, 1 }, .{ 1, 13 }, .{ 14, 1 }, .{ 2, 7 }, .{ 1, 14 }, .{ 7, 2 }, + .{ 1, 15 }, .{ 5, 3 }, .{ 15, 1 }, .{ 3, 5 }, .{ 1, 16 }, .{ 2, 8 }, .{ 16, 1 }, .{ 8, 2 }, .{ 4, 4 }, +}; + +/// A page's views from its RGB rows; `tiles` is gundam mode (the publisher's default for a single page). +pub fn views(a: std.mem.Allocator, rgb: []const u8, width: usize, height: usize, tiles: bool) !Views { + if (width == 0 or height == 0) return error.EmptyPage; + const src = resample.View.of(rgb, width, height); + const B = cfg.base_size; + // ImageOps.contain then pad: the long side to 1024, the short one rounded, centred on gray + var rw: usize = B; + var rh: usize = B; + if (width > height) rh = roundEven(@as(f64, @floatFromInt(height)) / @as(f64, @floatFromInt(width)) * B); + if (width < height) rw = roundEven(@as(f64, @floatFromInt(width)) / @as(f64, @floatFromInt(height)) * B); + const canvas = try a.alloc(u8, B * B * 3); + defer a.free(canvas); + @memset(canvas, pad_gray); + if (rw > 0 and rh > 0) { + const fitted = try resample.resize(a, .pillow, src, rw, rh); + defer a.free(fitted); + const x0 = roundEven(@as(f64, @floatFromInt(B - rw)) * 0.5); + const y0 = roundEven(@as(f64, @floatFromInt(B - rh)) * 0.5); + for (0..rh) |y| @memcpy(canvas[((y0 + y) * B + x0) * 3 ..][0 .. rw * 3], fitted[y * rw * 3 ..][0 .. rw * 3]); + } + var v: Views = .{ .global = try a.alloc(u16, 3 * B * B), .tiles = &.{}, .across = 1, .down = 1 }; + errdefer a.free(v.global); + normalize(canvas, B, v.global); + const T = cfg.tile_size; + if (!tiles or (width <= T and height <= T)) return v; + const g = grid(width, height); + v.across = g[0]; + v.down = g[1]; + const big = try resample.resize(a, .pillow, src, T * g[0], T * g[1]); + defer a.free(big); + v.tiles = try a.alloc(u16, g[0] * g[1] * 3 * T * T); + const crop = try a.alloc(u8, T * T * 3); + defer a.free(crop); + for (0..g[0] * g[1]) |t| { + const x0 = (t % g[0]) * T; + const y0 = (t / g[0]) * T; + for (0..T) |y| @memcpy(crop[y * T * 3 ..][0 .. T * 3], big[((y0 + y) * T * g[0] + x0) * 3 ..][0 .. T * 3]); + normalize(crop, T, v.tiles[t * 3 * T * T ..][0 .. 3 * T * T]); + } + return v; +} + +test "uocr: Python's rounding, the tile grids the publisher's code picks, and the page's token counts" { + try std.testing.expectEqual(@as(usize, 2), roundEven(2.5)); + try std.testing.expectEqual(@as(usize, 4), roundEven(3.5)); + try std.testing.expectEqual(@as(usize, 724), roundEven(724.0775)); + // find_closest_aspect_ratio's reference answers: A4 at 150 dpi both ways, a square tie, a strip, just over 640 + try std.testing.expectEqual([2]usize{ 2, 3 }, grid(1240, 1754)); + try std.testing.expectEqual([2]usize{ 4, 3 }, grid(1754, 1240)); + try std.testing.expectEqual([2]usize{ 4, 4 }, grid(2000, 2000)); + try std.testing.expectEqual([2]usize{ 16, 1 }, grid(10000, 300)); + try std.testing.expectEqual([2]usize{ 2, 2 }, grid(700, 650)); + const v: Views = .{ .global = &.{}, .tiles = &.{}, .across = 2, .down = 2 }; + try std.testing.expectEqual(@as(usize, 693), v.tokens()); + const b: Views = .{ .global = &.{}, .tiles = &.{}, .across = 1, .down = 1 }; + try std.testing.expectEqual(@as(usize, 273), b.tokens()); +} diff --git a/zig/src/families/uocr/prompt.zig b/zig/src/families/uocr/prompt.zig new file mode 100644 index 00000000000..b63ab7ee018 --- /dev/null +++ b/zig/src/families/uocr/prompt.zig @@ -0,0 +1,201 @@ +//! A request's ids and each position's rotary coordinates and router blocks, as measured black-box on the release. +const std = @import("std"); +const cfg = @import("config.zig"); + +/// One position's rotary coordinates and router candidates: `mask` is a row of `Prompt.masks`, or -1 for every block. +pub const Coord = struct { tok: u32, page: u32, mask: i32 }; + +pub const Prompt = struct { + ids: []u32, + /// Per position: its place inside its page (tok) and its page, the rotary's two axes. + tok: []u32, + page: []u32, + /// Per position: the candidate row its router reads, or -1 for every remote block. + mask: []i32, + /// Candidate rows of `words` u32 (bit b: block b may be read): the prompt's `pages` rows, then decode's. + masks: []u32, + words: usize, + pages: usize, + /// Tokens each rotary page held up to the last image token (page 0 first). + counts: []u32, + /// Where the prompt left the coordinates, for the reply's positions. + seed: Step, + + pub fn deinit(p: *Prompt, a: std.mem.Allocator) void { + a.free(p.ids); + a.free(p.tok); + a.free(p.page); + a.free(p.mask); + a.free(p.masks); + a.free(p.counts); + p.* = undefined; + } + + pub fn len(p: Prompt) usize { + return p.ids.len; + } + + /// The candidate rows a launch reads, at least one row so the buffer is never empty. + pub fn maskRows(p: Prompt) usize { + return @max(p.masks.len / @max(p.words, 1), 1); + } +}; + +/// The prompt for pages of `image_tokens` image tokens each, then `instruction`: [BOS] ([PAGE] [image] x n)... text. +pub fn build(a: std.mem.Allocator, image_tokens: []const usize, instruction: []const u32) !Prompt { + var ids: std.ArrayList(u32) = .empty; + errdefer ids.deinit(a); + try ids.append(a, cfg.bos); + for (image_tokens) |n| { + try ids.append(a, cfg.page_token); + try ids.appendNTimes(a, cfg.image_token, n); + } + try ids.appendSlice(a, instruction); + return positions(a, try ids.toOwnedSlice(a)); +} + +/// Reply tokens: page 0's count until a ; the k-th goes to page min(k, last); rows read pages spanning k - 1. +pub const Step = struct { + counts: []const u32 = &.{}, + page: u32 = 0, + tok: u32 = 0, + replies: u32 = 0, + /// The rows decode's candidates start at, and how many there are. + rows_at: u32 = 0, + rows: u32 = 0, + + pub fn init(p: Prompt) Step { + return p.seed; + } + + pub fn next(s: *Step, id: u32) Coord { + if (id == cfg.page_token) { + s.replies += 1; + s.page = @min(s.replies, @as(u32, @intCast(s.counts.len)) - 1); + s.tok = s.counts[s.page]; + } else s.tok +%= 1; + return .{ .tok = s.tok, .page = s.page, .mask = if (s.replies >= 1 and s.replies - 1 < s.rows) @intCast(s.rows_at + s.replies - 1) else -1 }; + } +}; + +/// A prompt from its ids (owning `ids`); without an image token it is refused (the release turns to 1-D rotary). +pub fn positions(a: std.mem.Allocator, ids: []u32) !Prompt { + errdefer a.free(ids); + const n = ids.len; + const last = std.mem.lastIndexOfScalar(u32, ids, cfg.image_token) orelse return error.UocrNoImage; + const tok = try a.alloc(u32, n); + errdefer a.free(tok); + const page = try a.alloc(u32, n); + errdefer a.free(page); + const mask = try a.alloc(i32, n); + errdefer a.free(mask); + + // up to the last image token: page k from the k-th , each page counting its own tokens from 0 + var counts: std.ArrayList(u32) = .empty; + errdefer counts.deinit(a); + try counts.append(a, 0); + for (ids[0 .. last + 1], 0..) |id, i| { + if (id == cfg.page_token) try counts.append(a, 0); + const cur = counts.items.len - 1; + tok[i] = counts.items[cur]; + page[i] = @intCast(cur); + counts.items[cur] += 1; + mask[i] = @as(i32, @intCast(cur)) - 1; + } + const pages = counts.items.len - 1; + const nblk = std.math.divCeil(usize, n, cfg.block) catch unreachable; + const words = std.math.divCeil(usize, nblk, 32) catch unreachable; + const decode_rows = decodePages(ids, pages); + const masks = try a.alloc(u32, (pages + decode_rows) * words); + errdefer a.free(masks); + @memset(masks, 0); + fillMasks(ids, masks, words, pages, decode_rows); + + const held = try counts.toOwnedSlice(a); + var s: Step = .{ .counts = held, .tok = held[0] -% 1, .rows_at = @intCast(pages), .rows = @intCast(decode_rows) }; + for (ids[last + 1 ..], last + 1..) |id, i| { + const c = s.next(id); + tok[i] = c.tok; + page[i] = c.page; + // a prompt row reads the blocks holding its page's images, as every prompt position does + mask[i] = if (s.replies >= 1 and s.replies - 1 < pages) @intCast(s.replies - 1) else -1; + } + return .{ .ids = ids, .tok = tok, .page = page, .mask = mask, .masks = masks, .words = words, .pages = pages, .counts = held, .seed = s }; +} + +/// Decode's page of each image token: marker-numbered, or (count - 1) / 273 before the first marker. +fn decodePage(cum: usize, run: usize) usize { + return if (cum > 0) cum - 1 else (run - 1) / cfg.page_image_tokens; +} + +/// Decode rows: one for every page an image token takes under decode's numbering. +fn decodePages(ids: []const u32, pages: usize) usize { + var cum: usize = 0; + var run: usize = 0; + var most = pages; + for (ids) |id| { + cum += @intFromBool(id == cfg.page_token); + if (id != cfg.image_token) continue; + run += 1; + most = @max(most, decodePage(cum, run) + 1); + } + return most; +} + +fn setBit(row: []u32, b: usize) void { + row[b / 32] |= @as(u32, 1) << @intCast(b % 32); +} + +/// Prompt rows: blocks holding page k's images. Decode rows: blocks whose image pages (decode numbering) span k. +fn fillMasks(ids: []const u32, masks: []u32, words: usize, pages: usize, decode_rows: usize) void { + var cum: usize = 0; + var run: usize = 0; + var b: usize = 0; + while (b * cfg.block < ids.len) : (b += 1) { + var lo: usize = std.math.maxInt(usize); + var hi: usize = 0; + for (ids[b * cfg.block .. @min(ids.len, (b + 1) * cfg.block)]) |id| { + cum += @intFromBool(id == cfg.page_token); + if (id != cfg.image_token) continue; + run += 1; + if (cum > 0) setBit(masks[(cum - 1) * words ..][0..words], b); + const dp = decodePage(cum, run); + lo = @min(lo, dp); + hi = @max(hi, dp); + } + if (lo > hi) continue; + for (lo..@min(hi, decode_rows - 1) + 1) |k| setBit(masks[(pages + k) * words ..][0..words], b); + } +} + +test "uocr: page coordinates, a page's markers and the reply's pages" { + const a = std.testing.allocator; + const P = cfg.page_token; + const I = cfg.image_token; + // [B P I I t P I I I t t]: two pages, a text token inside page 1, the instruction after the last image + var p = try positions(a, try a.dupe(u32, &.{ 0, P, I, I, 9, P, I, I, I, 10, 11 })); + defer p.deinit(a); + try std.testing.expectEqualSlices(u32, &.{ 0, 0, 1, 2, 3, 0, 1, 2, 3, 1, 2 }, p.tok); + try std.testing.expectEqualSlices(u32, &.{ 0, 1, 1, 1, 1, 2, 2, 2, 2, 0, 0 }, p.page); + try std.testing.expectEqualSlices(i32, &.{ -1, 0, 0, 0, 0, 1, 1, 1, 1, -1, -1 }, p.mask); + var s = Step.init(p); + const want = [_]Coord{ .{ .tok = 3, .page = 0, .mask = -1 }, .{ .tok = 4, .page = 1, .mask = 2 }, .{ .tok = 5, .page = 1, .mask = 2 }, .{ .tok = 4, .page = 2, .mask = 3 }, .{ .tok = 4, .page = 2, .mask = -1 } }; + for ([_]u32{ 12, P, 13, P, P }, want) |id, w| try std.testing.expectEqual(w, s.next(id)); +} + +test "uocr: a marker in the instruction starts the reply's pages, and images before any marker are page 0's" { + const a = std.testing.allocator; + const P = cfg.page_token; + const I = cfg.image_token; + var p = try positions(a, try a.dupe(u32, &.{ 0, P, I, I, 7, P, 8, 9 })); + defer p.deinit(a); + try std.testing.expectEqualSlices(u32, &.{ 0, 0, 1, 2, 1, 3, 4, 5 }, p.tok); + try std.testing.expectEqualSlices(u32, &.{ 0, 1, 1, 1, 0, 1, 1, 1 }, p.page); + try std.testing.expectEqualSlices(i32, &.{ -1, 0, 0, 0, -1, 0, 0, 0 }, p.mask); + var q = try positions(a, try a.dupe(u32, &.{ 0, I, I, I, P, I, I, 7, 8 })); + defer q.deinit(a); + try std.testing.expectEqualSlices(u32, &.{ 0, 1, 2, 3, 0, 1, 2, 4, 5 }, q.tok); + try std.testing.expectEqualSlices(u32, &.{ 0, 0, 0, 0, 1, 1, 1, 0, 0 }, q.page); + try std.testing.expectEqualSlices(i32, &.{ -1, -1, -1, -1, 0, 0, 0, -1, -1 }, q.mask); + try std.testing.expectError(error.UocrNoImage, positions(a, try a.dupe(u32, &.{ 0, P, 5 }))); +} diff --git a/zig/src/families/uocr/resize.zig b/zig/src/families/uocr/resize.zig new file mode 100644 index 00000000000..595c5091e7d --- /dev/null +++ b/zig/src/families/uocr/resize.zig @@ -0,0 +1,151 @@ +//! bf16 helpers, and a 640 tile's resized tables in the release's own fp32 steps (measured bit for bit, black box). +const std = @import("std"); + +pub fn bf16(v: f32) u16 { + const u: u32 = @bitCast(v); + if (std.math.isNan(v)) return 0x7fc0; + return @truncate((u +% 0x7fff +% ((u >> 16) & 1)) >> 16); +} + +pub fn widen(h: u16) f32 { + return @bitCast(@as(u32, h) << 16); +} + +/// Keys' cubic kernel (a = -0.5) at x >= 0, in fp32 with fused steps, as the release's resize rounds it. +fn cubic(x: f32) f32 { + const a: f32 = -0.5; + if (x < 1) return @mulAdd(f32, @mulAdd(f32, a + 2, x, -(a + 3)) * x, x, 1); + if (x < 2) return @mulAdd(f32, @mulAdd(f32, @mulAdd(f32, a, x, -(5 * a)), x, 8 * a), x, -(4 * a)); + return 0; +} + +/// One output's taps: inputs `lo` .. `lo + w.len` with their weights. +const Taps = struct { lo: usize, w: []f32 }; + +/// Antialiased bicubic shrink taps, all in fp32: output i centred at (i + 0.5) scale, weights divided by their sum. +fn bicubicTaps(a: std.mem.Allocator, n_in: usize, n_out: usize) ![]Taps { + std.debug.assert(n_out <= n_in); + const scale = @as(f32, @floatFromInt(n_in)) / @as(f32, @floatFromInt(n_out)); + const support = 2 * scale; + const inv = 1 / scale; + const out = try a.alloc(Taps, n_out); + for (out, 0..) |*t, i| { + const centre = scale * (@as(f32, @floatFromInt(i)) + 0.5); + const lo: usize = @intCast(@max(@as(i64, @intFromFloat(centre - support + 0.5)), 0)); + const hi: usize = @intCast(@min(@as(i64, @intFromFloat(centre + support + 0.5)), @as(i64, @intCast(n_in)))); + t.* = .{ .lo = lo, .w = try a.alloc(f32, hi - lo) }; + var total: f32 = 0; + for (t.w, lo..) |*w, j| { + w.* = cubic(@abs(@mulAdd(f32, @as(f32, @floatFromInt(j)) - centre, inv, 0.5 * inv))); + total += w.*; + } + for (t.w) |*w| w.* /= total; + } + return out; +} + +/// One output's fp32 sum over its taps, left to right, each tap after the first fused: `at(j)` reads input j. +fn tapSum(t: Taps, at: anytype) f32 { + var s = at.get(t.lo) * t.w[0]; + for (t.w[1..], t.lo + 1..) |w, j| s = @mulAdd(f32, at.get(j), w, s); + return s; +} + +/// Rows [n_in^2, ch] bf16 shrunk to fp32 [n_out^2, ch] by the bicubic taps, along each row first, then down columns. +pub fn bicubicGrid32(gpa: std.mem.Allocator, src: []const u16, n_in: usize, n_out: usize, ch: usize, out: []f32) !void { + std.debug.assert(src.len == n_in * n_in * ch and out.len == n_out * n_out * ch); + var arena = std.heap.ArenaAllocator.init(gpa); + defer arena.deinit(); + const a = arena.allocator(); + const taps = try bicubicTaps(a, n_in, n_out); + const mid = try a.alloc(f32, n_in * n_out * ch); + const Src = struct { + rows: []const u16, + step: usize, + fn get(r: @This(), j: usize) f32 { + return widen(r.rows[j * r.step]); + } + }; + const Mid = struct { + rows: []const f32, + step: usize, + fn get(r: @This(), j: usize) f32 { + return r.rows[j * r.step]; + } + }; + for (0..n_in) |y| for (taps, 0..) |t, x| for (0..ch) |c| { + mid[(y * n_out + x) * ch + c] = tapSum(t, Src{ .rows = src[y * n_in * ch + c ..], .step = ch }); + }; + for (taps, 0..) |t, y| for (0..n_out) |x| for (0..ch) |c| { + out[(y * n_out + x) * ch + c] = tapSum(t, Mid{ .rows = mid[x * ch + c ..], .step = n_out * ch }); + }; +} + +/// bicubicGrid32, each value then rounded to bf16 (the tables the encoder adds). +pub fn bicubicGrid(gpa: std.mem.Allocator, src: []const u16, n_in: usize, n_out: usize, ch: usize, out: []u16) !void { + const wide = try gpa.alloc(f32, out.len); + defer gpa.free(wide); + try bicubicGrid32(gpa, src, n_in, n_out, ch, wide); + for (out, wide) |*o, v| o.* = bf16(v); +} + +/// Rows [n_in, ch] bf16 resized linearly to fp32 [n_out, ch]: output i at max(fma(scale, i + 0.5, -0.5), 0), fused. +pub fn linearRows32(src: []const u16, n_in: usize, n_out: usize, ch: usize, out: []f32) void { + std.debug.assert(src.len == n_in * ch and out.len == n_out * ch); + const scale = @as(f32, @floatFromInt(n_in)) / @as(f32, @floatFromInt(n_out)); + for (0..n_out) |i| { + const x = @max(@mulAdd(f32, scale, @as(f32, @floatFromInt(i)) + 0.5, -0.5), 0); + const lo: usize = @intFromFloat(x); + const hi = if (lo < n_in - 1) lo + 1 else lo; + const f1 = x - @as(f32, @floatFromInt(lo)); + const f0 = 1 - f1; + for (out[i * ch ..][0..ch], 0..) |*o, c| { + o.* = @mulAdd(f32, widen(src[lo * ch + c]), f0, widen(src[hi * ch + c]) * f1); + } + } +} + +/// linearRows32, each value then rounded to bf16. +pub fn linearRows(gpa: std.mem.Allocator, src: []const u16, n_in: usize, n_out: usize, ch: usize, out: []u16) !void { + const wide = try gpa.alloc(f32, out.len); + defer gpa.free(wide); + linearRows32(src, n_in, n_out, ch, wide); + for (out, wide) |*o, v| o.* = bf16(v); +} + +/// The test inputs: bf16 bits of mixed signs and magnitudes (2^-7 to 2^8) from a fixed formula. +fn probe(i: usize) u16 { + return @intCast((i * 7919) % 2 << 15 | (120 + (i * 31) % 16) << 7 | (i * 97) % 128); +} + +test "uocr: the tile resizes give the release's fp32 bits (outputs of its resize on these inputs)" { + const a = std.testing.allocator; + // a 9 x 9 grid of 2 channels shrunk to 5 x 5; rounding the float64 result once to fp32 misses 47 of these 50 + const cubic_bits = [_]u32{ + 0x42da1050, 0xc330c4d0, 0x42077b28, 0xc136b7e0, 0xbd89eb9f, 0x40c69083, 0xc0a210e3, 0xc1399d6a, 0x42723fcf, 0xc35a83b9, + 0x421b757f, 0xc11424d3, 0x3f69afdc, 0x40c5d996, 0xc0e78ef1, 0xc1970b63, 0x423f2169, 0xc32323c4, 0x42d444b4, 0xc2797333, + 0x3ed21167, 0x410cca44, 0xc0d807ef, 0xc1b4f941, 0x42366ec4, 0xc33b1445, 0x428fb517, 0xc292637b, 0x4094e1d6, 0x40615566, + 0xc0c52b32, 0xc1f6e533, 0x424cf01c, 0xc34c55bb, 0x42a7d07c, 0xc279521c, 0x40e8f5f0, 0x409e3179, 0xbf5466a4, 0x40a52bf4, + 0x425e016a, 0xc380e610, 0x42b32dff, 0xc29be992, 0x409ee987, 0x4098fa32, 0xbf727214, 0x40a0c01f, 0x3caa4021, 0xc291bca3, + }; + var grid: [9 * 9 * 2]u16 = undefined; + for (&grid, 0..) |*v, i| v.* = probe(i); + var got: [5 * 5 * 2]f32 = undefined; + try bicubicGrid32(a, &grid, 9, 5, 2, &got); + for (cubic_bits, got) |want, v| try std.testing.expectEqual(want, @as(u32, @bitCast(v))); + // 13 rows of 3 resized to 7; float64 rounded once misses 18 of these 21 + const linear_bits = [_]u32{ + 0x3ffa4001, 0xbf4c6db8, 0x3eac524a, 0xc2eecbdd, 0x424b60eb, 0xc1a7ea8d, 0x424e724a, 0xc1b22493, 0x41182001, 0x3f3a0000, + 0xbe9b0000, 0x3e7c0000, 0xbc0edba0, 0xc3c0da8f, 0x43264869, 0xc1672484, 0x40b66dac, 0xc0d5248a, 0xbf33b6e4, 0x3e8b492d, + 0xbdea4932, + }; + var line: [13 * 3]u16 = undefined; + for (&line, 0..) |*v, i| v.* = probe(i + 1000); + var rows: [7 * 3]f32 = undefined; + linearRows32(&line, 13, 7, 3, &rows); + for (linear_bits, rows) |want, v| try std.testing.expectEqual(want, @as(u32, @bitCast(v))); + // the bf16 entry points round those same values + var half: [5 * 5 * 2]u16 = undefined; + try bicubicGrid(a, &grid, 9, 5, 2, &half); + for (half, got) |h, v| try std.testing.expectEqual(bf16(v), h); +} diff --git a/zig/src/families/uocr/serve.zig b/zig/src/families/uocr/serve.zig new file mode 100644 index 00000000000..a8e25ca1674 --- /dev/null +++ b/zig/src/families/uocr/serve.zig @@ -0,0 +1,225 @@ +//! Unlimited-OCR-2 on the lane host: one stream, pages prepared on the HTTP thread, tower and decode on the lane's. +const std = @import("std"); +const mtl = @import("metal"); +const lanes = @import("lanes"); +const be = lanes.backend; +const picture = @import("../../core/picture/picture.zig"); +const cfg = @import("config.zig"); +const wts = @import("weights.zig"); +const ks = @import("kernels.zig"); +const vision = @import("vision.zig"); +const preprocess = @import("preprocess.zig"); +const prompt_mod = @import("prompt.zig"); +const decoder_mod = @import("decoder.zig"); +const generate = @import("generate.zig"); +const resize = @import("resize.zig"); + +const H = cfg.hidden; + +/// Prompt rows a prefill pass takes at once (the decoder's scratch); larger prompts run in chunks of these. +pub const prompt_rows = 2048; + +/// The most image tokens one page takes: the global view and the widest tile grid gundam mode picks. +pub fn maxPageTokens() u32 { + const g = cfg.side(cfg.base_size); + const t = cfg.side(cfg.tile_size); + var most: usize = 0; + for (1..preprocess.max_tiles + 1) |across| for (1..preprocess.max_tiles / across + 1) |down| { + if (across * down < preprocess.min_tiles) continue; + most = @max(most, (t * across + 1) * (t * down)); + }; + return @intCast(g * (g + 1) + 1 + most); +} + +/// A page in base mode alone: the 1024 view's tokens. +pub fn basePageTokens() u32 { + const g = cfg.side(cfg.base_size); + return @intCast(g * (g + 1) + 1); +} + +pub const Model = struct { + gpa: std.mem.Allocator, + io: std.Io, + device: mtl.Device, + queue: mtl.Queue, + weights: wts.Weights, + kernels: ks.Kernels, + encoder: vision.Encoder, + decoder: decoder_mod.Decoder, + /// The one stream the decoder holds, and its prompt's state. + stream: ?*lanes.Stream = null, + prompt: ?prompt_mod.Prompt = null, + step: prompt_mod.Step = undefined, + guard: generate.Guard = undefined, + + /// The release's weights from `dir`, with caches for `context` tokens. + pub fn load(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, context: usize) !*Model { + const device = try mtl.Device.init(); + if (!device.tensorUnits()) return error.NoTensorUnits; + const m = try gpa.create(Model); + errdefer gpa.destroy(m); + m.* = .{ .gpa = gpa, .io = io, .device = device, .queue = try device.queue(), .weights = undefined, .kernels = undefined, .encoder = undefined, .decoder = undefined }; + errdefer m.queue.deinit(); + m.weights = try wts.load(gpa, io, device, dir); + errdefer m.weights.deinit(); + m.kernels = try ks.Kernels.load(gpa, device); + errdefer m.kernels.deinit(); + m.encoder = try vision.Encoder.init(gpa, device, m.queue, &m.kernels, &m.weights); + errdefer m.encoder.deinit(); + m.decoder = try decoder_mod.Decoder.init(gpa, device, m.queue, &m.kernels, &m.weights, context, @min(prompt_rows, context)); + return m; + } + + pub fn deinit(m: *Model) void { + if (m.prompt) |*p| p.deinit(m.gpa); + m.decoder.deinit(); + m.encoder.deinit(); + m.kernels.deinit(); + m.weights.deinit(); + m.queue.deinit(); + m.gpa.destroy(m); + } + + /// One page's views as f32-widened bf16 (global first): gundam tiles when they fit `max_tokens`, else base. + pub fn prepare(m: *Model, a: std.mem.Allocator, bytes: []const u8, max_tokens: u32) !Prepared { + if (max_tokens < basePageTokens()) return error.ImageTooSmall; + var page = try preprocess.decode(m.io, a, bytes); + defer page.deinit(a); + var v = try preprocess.views(a, page.rgb, page.width, page.height, true); + if (v.tokens() > max_tokens) { + v.deinit(a); + v = try preprocess.views(a, page.rgb, page.width, page.height, false); + } + defer v.deinit(a); + const pixels = try a.alloc(f32, v.global.len + v.tiles.len); + for (v.global, pixels[0..v.global.len]) |h, *f| f.* = resize.widen(h); + for (v.tiles, pixels[v.global.len..]) |h, *f| f.* = resize.widen(h); + const grid = [2]u32{ @intCast(v.down), @intCast(v.across) }; + return .{ .pixels = pixels, .gh = grid[0], .gw = grid[1], .tokens = @intCast(v.tokens()), .hash = picture.identity.withGrid(picture.identity.ofBytes(0x0c12, bytes), grid) }; + } + + pub const Prepared = struct { pixels: []f32, gh: u32, gw: u32, tokens: u32, hash: u64 }; + + /// Every image of the stream through the tower, laid out as its image tokens in prompt order. + fn encodeImages(m: *Model, a: std.mem.Allocator, images: []const lanes.stream.Image) ![]u16 { + var total: usize = 0; + for (images) |img| total += img.tokens; + const rows = try a.alloc(u16, total * H); + const g = cfg.side(cfg.base_size); + const t = cfg.side(cfg.tile_size); + const global_px = 3 * cfg.base_size * cfg.base_size; + const tile_px = 3 * cfg.tile_size * cfg.tile_size; + var at: usize = 0; + for (images) |img| { + const across: usize = img.gw; + const down: usize = img.gh; + const tiles: usize = if (across * down > 1) across * down else 0; + if (img.pixels.len != global_px + tiles * tile_px) return error.ImageShape; + const px = try a.alloc(u16, img.pixels.len); + defer a.free(px); + for (img.pixels, px) |f, *h| h.* = resize.bf16(f); + const global = try a.alloc(u16, g * g * H); + defer a.free(global); + try m.encoder.encode(cfg.base_size, px[0..global_px], global, .{}); + const tile_rows = try a.alloc(u16, tiles * t * t * H); + defer a.free(tile_rows); + for (0..tiles) |i| try m.encoder.encode(cfg.tile_size, px[global_px + i * tile_px ..][0..tile_px], tile_rows[i * t * t * H ..][0 .. t * t * H], .{}); + const out = rows[at * H ..][0 .. @as(usize, img.tokens) * H]; + vision.layout(&m.weights, global, tile_rows, across, down, out); + at += img.tokens; + } + return rows; + } + + pub fn facts(_: *const Model) lanes.Model { + // one stream, one token a round: no drafts, no copy windows + return .{ .exact_width = 1, .copy_drafts = false, .lone_copies = false, .drafts = 1, .max_streams = 1, .mtp = false, .speculate = false, .speculate_early = false }; + } + + pub fn backend(m: *Model) be.Backend { + return .{ .ptr = m, .vtable = &.{ .prefill = prefillFn, .first = firstFn, .queue = queueFn, .read = readFn, .verify = verifyFn, .keep = keepFn, .draft = draftFn, .release = releaseFn } }; + } + + fn cast(ptr: *anyopaque) *Model { + return @ptrCast(@alignCast(ptr)); + } + + fn prefillFn(ptr: *anyopaque, stream: *lanes.Stream) !void { + const m = cast(ptr); + if (m.stream != null) return error.UocrBusy; + const ids = stream.prompt(); + // the prompt's rows, then a row for every reply token fed back: all but the last, which ends the reply + if (ids.len == 0 or ids.len + @max(stream.max_new, 1) - 1 > m.decoder.cap) return error.UocrPromptTooLong; + var arena: std.heap.ArenaAllocator = .init(m.gpa); + defer arena.deinit(); + const rows = try m.encodeImages(arena.allocator(), stream.images); + var p = try prompt_mod.positions(m.gpa, try m.gpa.dupe(u32, ids)); + errdefer p.deinit(m.gpa); + try m.decoder.prefill(p, rows); + m.guard = generate.Guard.init(p); + m.step = prompt_mod.Step.init(p); + m.prompt = p; + m.stream = stream; + stream.cached = 0; + } + + fn firstFn(ptr: *anyopaque, stream: *lanes.Stream, _: u64) !u64 { + const m = cast(ptr); + if (m.stream != stream) return error.UocrUnknownStream; + return m.guard.pick(try m.decoder.logits()); + } + + /// The fed token through one decode step; the next token's greedy pick under the page guard is the handle. + fn queueFn(ptr: *anyopaque, stream: *lanes.Stream, f: be.Feed, _: u64) !u64 { + const m = cast(ptr); + if (m.stream != stream) return error.UocrUnknownStream; + return try m.advance(switch (f) { + .handle => |h| @intCast(h), + .value => |v| v, + }); + } + + fn advance(m: *Model, id: u32) !u32 { + if (id >= cfg.vocab) return error.UocrBadToken; + m.guard.take(id); + try m.decoder.step(id, m.step.next(id)); + return m.guard.pick(try m.decoder.logits()); + } + + fn readFn(_: *anyopaque, handle: u64) !u32 { + return @intCast(handle); + } + + /// A one-row window (no drafts): its pending token through a decode step, as `queue` runs it. + fn verifyFn(ptr: *anyopaque, windows: []const be.Window, out: []be.Verified) !void { + const m = cast(ptr); + if (windows.len != out.len) return error.UocrBadWindows; + for (windows, out) |w, o| { + if (w.rows() != 1 or o.sampled.len != 1 or o.drafts.len != 0) return error.UocrHasNoDrafts; + if (m.stream != w.stream) return error.UocrUnknownStream; + o.sampled[0] = try m.advance(w.pending); + } + } + + /// One-row windows keep their row: nothing to roll back. + fn keepFn(_: *anyopaque, windows: []const be.Window, paths: []const []const u32) !void { + for (windows, paths) |w, path| if (w.rows() != 1 or path.len != 1 or path[0] != 0) return error.UocrHasNoDrafts; + } + + fn draftFn(_: *anyopaque, requests: []const be.DraftRequest) !void { + for (requests) |r| if (r.depth != 0) return error.UocrHasNoDraftHead; + } + + fn releaseFn(ptr: *anyopaque, stream: *lanes.Stream) void { + const m = cast(ptr); + if (m.stream != stream) return; + if (m.prompt) |*p| p.deinit(m.gpa); + m.prompt = null; + m.stream = null; + } +}; + +test "uocr: a page's token bounds" { + try std.testing.expectEqual(@as(u32, 273), basePageTokens()); + try std.testing.expect(maxPageTokens() > basePageTokens()); +} diff --git a/zig/src/families/uocr/uocr.zig b/zig/src/families/uocr/uocr.zig new file mode 100644 index 00000000000..cfb41ac6ee7 --- /dev/null +++ b/zig/src/families/uocr/uocr.zig @@ -0,0 +1,16 @@ +//! Unlimited-OCR-2 (baidu/Unlimited-OCR-2) on Metal: document pages to text, the release's bf16 weights as published. +pub const config = @import("config.zig"); +pub const weights = @import("weights.zig"); +pub const kernels = @import("kernels.zig"); +pub const vision = @import("vision.zig"); +pub const resize = @import("resize.zig"); +pub const gate = @import("gate.zig"); +pub const preprocess = @import("preprocess.zig"); +pub const prompt = @import("prompt.zig"); +pub const decoder = @import("decoder.zig"); +pub const generate = @import("generate.zig"); +pub const serve = @import("serve.zig"); + +test { + @import("std").testing.refAllDecls(@This()); +} diff --git a/zig/src/families/uocr/vision.zig b/zig/src/families/uocr/vision.zig new file mode 100644 index 00000000000..637979d9282 --- /dev/null +++ b/zig/src/families/uocr/vision.zig @@ -0,0 +1,416 @@ +//! Unlimited-OCR-2's image encoder on Metal: SAM ViT-B, its neck and CLIP-L to the projector's rows, a view a pass. +const std = @import("std"); +const mtl = @import("metal"); +const cfg = @import("config.zig"); +const wts = @import("weights.zig"); +const ks = @import("kernels.zig"); +const resize = @import("resize.zig"); +const Ref = ks.Ref; + +const S = cfg.sam_width; +const C = cfg.clip_width; +const H = cfg.hidden; +const N = cfg.neck_width; + +/// A view's sizes: its patch grid, the padded window grid, and the feature side after the neck. +const View = struct { + size: usize, + grid: usize, + padded: usize, + side: usize, + + fn of(size: usize) View { + const grid = size / cfg.patch; + return .{ .size = size, .grid = grid, .padded = (std.math.divCeil(usize, grid, cfg.sam_window) catch unreachable) * cfg.sam_window, .side = cfg.side(size) }; + } +}; + +/// Intermediate rows a check may ask for: SAM's output [side^2, 1024] and CLIP's [side^2 + 1, 1024]. +pub const Taps = struct { sam: ?[]u16 = null, clip: ?[]u16 = null }; + +pub const Encoder = struct { + gpa: std.mem.Allocator, + queue: mtl.Queue, + k: *const ks.Kernels, + w: *const wts.Weights, + scratch: Scratch, + /// A 640 tile's tables: SAM's positions, CLIP's, and the global blocks' relative positions (h then w). + tile: mtl.Buffer, + + /// An encoder on `queue` (the caller's, which outlives it). + pub fn init(gpa: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, k: *const ks.Kernels, w: *const wts.Weights) !Encoder { + var e: Encoder = .{ .gpa = gpa, .queue = queue, .k = k, .w = w, .scratch = undefined, .tile = undefined }; + e.scratch = try Scratch.make(device, View.of(cfg.base_size)); + errdefer e.scratch.buf.deinit(); + e.tile = try tileTables(gpa, device, w); + return e; + } + + pub fn deinit(e: *Encoder) void { + e.tile.deinit(); + e.scratch.buf.deinit(); + } + + /// The projector's rows [side^2, 1280] bf16 for one view's normalized pixels [3, size, size] bf16. + pub fn encode(e: *Encoder, size: usize, pixels: []const u16, out: []u16, taps: Taps) !void { + if (size != cfg.base_size and size != cfg.tile_size) return error.ViewSize; + const v = View.of(size); + if (pixels.len != 3 * size * size or out.len != v.side * v.side * H) return error.ViewRows; + const s = e.scratch; + @memcpy(halves(s.at(.pix), pixels.len), pixels); + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = e.queue.commandBuffer(); + const enc = cb.compute(.serial); + e.sam(enc, v); + e.clip(enc, v); + e.project(enc, v); + const n = v.side * v.side; + enc.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |msg| { + std.log.err("unlimited ocr: the image encoder failed on the GPU: {s}", .{msg}); + return error.GpuFailure; + } + @memcpy(out, halves(s.at(.proj_out), out.len)); + if (taps.sam) |t| @memcpy(t, halves(s.at(.m3), n * cfg.net3_width)); + if (taps.clip) |t| @memcpy(t, halves(s.at(.cx), (n + 1) * C)); + } + + /// One piece of `encode`: a SAM block, the neck, CLIP's front, a CLIP layer, or the projector. + pub const Step = union(enum) { sam: usize, neck, front, clip: usize, project }; + + /// A step's bf16 input rows: SAM's x [grid^2, 768], its output m3 [side^2, 1024], CLIP's cx [side^2 + 1, 1024]. + pub const Rows = struct { x: ?[]const u16 = null, m3: ?[]const u16 = null, cx: ?[]const u16 = null }; + + /// `st` alone for a view of `size` on `in` (the rows it reads), its rows into `out`: the code `encode` runs. + pub fn step(e: *Encoder, size: usize, st: Step, in: Rows, out: []u16) !void { + if (size != cfg.base_size and size != cfg.tile_size) return error.ViewSize; + const v = View.of(size); + const s = e.scratch; + const want: struct { x: bool, m3: bool, cx: bool }, const part: Scratch.Part = switch (st) { + .sam => .{ .{ .x = true, .m3 = false, .cx = false }, .x }, + .neck => .{ .{ .x = true, .m3 = false, .cx = false }, .m3 }, + .front => .{ .{ .x = false, .m3 = true, .cx = false }, .cx }, + .clip => .{ .{ .x = false, .m3 = false, .cx = true }, .cx }, + .project => .{ .{ .x = false, .m3 = true, .cx = true }, .proj_out }, + }; + inline for (.{ .{ "x", Scratch.Part.x }, .{ "m3", Scratch.Part.m3 }, .{ "cx", Scratch.Part.cx } }) |p| { + if (@field(want, p[0])) { + const rows = @field(in, p[0]) orelse return error.ViewRows; + if (rows.len != rowsOf(p[1], v)) return error.ViewRows; + @memcpy(halves(s.at(p[1]), rows.len), rows); + } + } + if (out.len != rowsOf(part, v)) return error.ViewRows; + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = e.queue.commandBuffer(); + const enc = cb.compute(.serial); + switch (st) { + .sam => |i| e.samBlock(enc, v, i), + .neck => e.neck(enc, v), + .front => e.clipFront(enc, v), + .clip => |i| e.clipLayer(enc, v, i), + .project => e.project(enc, v), + } + enc.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |msg| { + std.log.err("unlimited ocr: the image encoder failed on the GPU: {s}", .{msg}); + return error.GpuFailure; + } + @memcpy(out, halves(s.at(part), out.len)); + } + + /// The bf16 values a step reads or leaves in `part` for a view. + fn rowsOf(part: Scratch.Part, v: View) usize { + const n = v.side * v.side; + return switch (part) { + .x => v.grid * v.grid * S, + .m3 => n * cfg.net3_width, + .cx => (n + 1) * C, + .proj_out => n * H, + else => unreachable, + }; + } + + /// The projector's rows from CLIP's (`.cx`, its class row left out) beside SAM's (`.m3`), into `.proj_out`. + fn project(e: *Encoder, enc: mtl.ComputeEncoder, v: View) void { + const s = e.scratch; + const n = v.side * v.side; + ks.Kernels.bind(enc, e.k.get("uv_concat"), &.{ s.at(.cx).at(C * 2), s.at(.m3), s.at(.fused) }, [3]u32{ @intCast(n), C, cfg.net3_width }); + enc.dispatchThreads(mtl.Size.of(cfg.fused, n, 1), mtl.Size.of(256, 1, 1)); + e.k.linearBias(enc, s.at(.fused), e.w.projector_w, e.w.projector_b, s.at(.sum), s.at(.proj_out), n, H, cfg.fused); + } + + /// SAM's tower and neck on the view's pixels (`.pix`), its output in `.m3` [side^2, 1024]. + fn sam(e: *Encoder, enc: mtl.ComputeEncoder, v: View) void { + const s = e.scratch; + const k = e.k; + const g2 = v.grid * v.grid; + const x = s.at(.x); + // the 16 x 16 patches as rows, their convolution, then the position table (resized for a tile) + cols(enc, k, s.at(.pix), s.at(.cols), .{ .channels = 3, .in_side = @intCast(v.size), .out_side = @intCast(v.grid), .span = cfg.patch, .stride = cfg.patch, .pad = 0, .cstride = @intCast(v.size * v.size), .pstride = 1 }); + k.linearBias(enc, s.at(.cols), e.w.sam.patch_w, e.w.sam.patch_b, s.at(.sum), x, g2, S, 3 * cfg.patch * cfg.patch); + add(enc, k, x, if (v.size == cfg.base_size) e.w.sam.pos else Ref{ .buf = e.tile, .off = 0 }, x, g2 * S); + for (0..e.w.sam.blocks.len) |i| e.samBlock(enc, v, i); + e.neck(enc, v); + } + + /// The neck on `.x` (channels last: its channel norms are row norms), then two stride-2 convolutions, into `.m3`. + fn neck(e: *Encoder, enc: mtl.ComputeEncoder, v: View) void { + const s = e.scratch; + const k = e.k; + const g2 = v.grid * v.grid; + const x = s.at(.x); + const w = &e.w.sam; + k.linear(enc, x, w.neck0, s.at(.n0), g2, N, S); + norm(enc, k.get("uv_layer_norm"), s.at(.n0), w.neck1_w, w.neck1_b, s.at(.n1), g2, N, cfg.sam_eps); + cols(enc, k, s.at(.n1), s.at(.cols), .{ .channels = N, .in_side = @intCast(v.grid), .out_side = @intCast(v.grid), .span = 3, .stride = 1, .pad = 1, .cstride = 1, .pstride = N }); + k.linear(enc, s.at(.cols), w.neck2, s.at(.n0), g2, N, N * 9); + norm(enc, k.get("uv_layer_norm"), s.at(.n0), w.neck3_w, w.neck3_b, s.at(.n1), g2, N, cfg.sam_eps); + const half = v.grid / 2; + cols(enc, k, s.at(.n1), s.at(.cols), .{ .channels = N, .in_side = @intCast(v.grid), .out_side = @intCast(half), .span = 3, .stride = 2, .pad = 1, .cstride = 1, .pstride = N }); + k.linear(enc, s.at(.cols), w.net2, s.at(.m2), half * half, cfg.net2_width, N * 9); + cols(enc, k, s.at(.m2), s.at(.cols), .{ .channels = cfg.net2_width, .in_side = @intCast(half), .out_side = @intCast(v.side), .span = 3, .stride = 2, .pad = 1, .cstride = 1, .pstride = cfg.net2_width }); + k.linear(enc, s.at(.cols), w.net3, s.at(.m3), v.side * v.side, cfg.net3_width, cfg.net2_width * 9); + } + + /// SAM block `i` on `.x` [grid^2, 768], in place. + fn samBlock(e: *Encoder, enc: mtl.ComputeEncoder, v: View, i: usize) void { + const s = e.scratch; + const k = e.k; + const b = e.w.sam.blocks[i]; + const g2 = v.grid * v.grid; + const x = s.at(.x); + norm(enc, k.get("uv_layer_norm"), x, b.norm1_w, b.norm1_b, s.at(.ln), g2, S, cfg.sam_eps); + const win: UvWindow = .{ .side = @intCast(v.grid), .padded = @intCast(v.padded), .window = cfg.sam_window, .channels = S }; + const scale = 1.0 / @sqrt(@as(f32, cfg.sam_head_dim)); + if (std.mem.indexOfScalar(usize, &cfg.sam_global, i)) |global| { + const rel = if (v.size == cfg.base_size) [2]Ref{ b.rel_h, b.rel_w } else relTiles(e.tile, global); + k.linearBias(enc, s.at(.ln), b.qkv_w, b.qkv_b, s.at(.sum), s.at(.qkv), g2, 3 * S, S); + relPos(enc, k, s.at(.qkv), rel, s.at(.rel_h), s.at(.rel_w), .{ .groups = 1, .side = @intCast(v.grid), .heads = cfg.sam_heads, .width = S }); + attention(enc, k, s.at(.qkv), s.at(.rel_h), s.at(.rel_w), s.at(.att), .{ .groups = 1, .len = @intCast(g2), .heads = cfg.sam_heads, .width = S, .side = @intCast(v.grid), .scale = scale }); + k.linearBias(enc, s.at(.att), b.proj_w, b.proj_b, s.at(.sum), s.at(.proj), g2, S, S); + add(enc, k, x, s.at(.proj), x, g2 * S); + } else { + const p2 = v.padded * v.padded; + const groups = p2 / (cfg.sam_window * cfg.sam_window); + ks.Kernels.bind(enc, k.get("uv_window"), &.{ s.at(.ln), s.at(.win) }, win); + enc.dispatchThreads(mtl.Size.of(S, p2, 1), mtl.Size.of(256, 1, 1)); + k.linearBias(enc, s.at(.win), b.qkv_w, b.qkv_b, s.at(.sum), s.at(.qkv), p2, 3 * S, S); + relPos(enc, k, s.at(.qkv), .{ b.rel_h, b.rel_w }, s.at(.rel_h), s.at(.rel_w), .{ .groups = @intCast(groups), .side = cfg.sam_window, .heads = cfg.sam_heads, .width = S }); + attention(enc, k, s.at(.qkv), s.at(.rel_h), s.at(.rel_w), s.at(.att), .{ .groups = @intCast(groups), .len = cfg.sam_window * cfg.sam_window, .heads = cfg.sam_heads, .width = S, .side = cfg.sam_window, .scale = scale }); + k.linearBias(enc, s.at(.att), b.proj_w, b.proj_b, s.at(.sum), s.at(.proj), p2, S, S); + ks.Kernels.bind(enc, k.get("uv_unwindow_add"), &.{ x, s.at(.proj) }, win); + enc.dispatchThreads(mtl.Size.of(S, g2, 1), mtl.Size.of(256, 1, 1)); + } + norm(enc, k.get("uv_layer_norm"), x, b.norm2_w, b.norm2_b, s.at(.ln), g2, S, cfg.sam_eps); + k.linearBias(enc, s.at(.ln), b.lin1_w, b.lin1_b, s.at(.sum), s.at(.hid), g2, cfg.sam_ffn, S); + pointwise(enc, k.get("uv_gelu"), s.at(.hid), g2 * cfg.sam_ffn); + k.linearBias(enc, s.at(.hid), b.lin2_w, b.lin2_b, s.at(.sum), s.at(.proj), g2, S, cfg.sam_ffn); + add(enc, k, x, s.at(.proj), x, g2 * S); + } + + fn clip(e: *Encoder, enc: mtl.ComputeEncoder, v: View) void { + e.clipFront(enc, v); + for (0..e.w.clip.blocks.len) |i| e.clipLayer(enc, v, i); + } + + /// CLIP's rows from SAM's (`.m3`): the class row, the positions, then the pre-norm, into `.cx`. + fn clipFront(e: *Encoder, enc: mtl.ComputeEncoder, v: View) void { + const s = e.scratch; + const k = e.k; + const L = v.side * v.side + 1; + const pos = if (v.size == cfg.base_size) e.w.clip.pos else Ref{ .buf = e.tile, .off = clipPosOffset() }; + ks.Kernels.bind(enc, k.get("uv_clip_embed"), &.{ e.w.clip.cls, s.at(.m3), pos, s.at(.cln) }, @as(u32, C)); + enc.dispatchThreads(mtl.Size.of(C, L, 1), mtl.Size.of(256, 1, 1)); + norm(enc, k.get("uv_layer_norm"), s.at(.cln), e.w.clip.pre_w, e.w.clip.pre_b, s.at(.cx), L, C, cfg.clip_eps); + } + + /// CLIP layer `i` on `.cx` [side^2 + 1, 1024], in place. + fn clipLayer(e: *Encoder, enc: mtl.ComputeEncoder, v: View, i: usize) void { + const s = e.scratch; + const k = e.k; + const b = e.w.clip.blocks[i]; + const L = v.side * v.side + 1; + const x = s.at(.cx); + norm(enc, k.get("uv_layer_norm"), x, b.ln1_w, b.ln1_b, s.at(.cln), L, C, cfg.clip_eps); + k.linearBias(enc, s.at(.cln), b.qkv_w, b.qkv_b, s.at(.sum), s.at(.qkv), L, 3 * C, C); + attention(enc, k, s.at(.qkv), s.at(.rel_h), s.at(.rel_w), s.at(.att), .{ .groups = 1, .len = @intCast(L), .heads = cfg.clip_heads, .width = C, .side = 0, .scale = 1.0 / @sqrt(@as(f32, cfg.clip_head_dim)) }); + k.linearBias(enc, s.at(.att), b.out_w, b.out_b, s.at(.sum), s.at(.proj), L, C, C); + add(enc, k, x, s.at(.proj), x, L * C); + norm(enc, k.get("uv_layer_norm"), x, b.ln2_w, b.ln2_b, s.at(.cln), L, C, cfg.clip_eps); + k.linearBias(enc, s.at(.cln), b.fc1_w, b.fc1_b, s.at(.sum), s.at(.hid), L, cfg.clip_ffn, C); + pointwise(enc, k.get("uv_quick_gelu"), s.at(.hid), L * cfg.clip_ffn); + k.linearBias(enc, s.at(.hid), b.fc2_w, b.fc2_b, s.at(.sum), s.at(.proj), L, C, cfg.clip_ffn); + add(enc, k, x, s.at(.proj), x, L * C); + } +}; + +/// A page's image-token rows in the publisher's order: tile rows with newlines, the global view's, the separator. +pub fn layout(w: *const wts.Weights, global: []const u16, tiles: []const u16, across: usize, down: usize, out: []u16) void { + const newline = halves(w.newline, H); + var at: usize = 0; + const put = struct { + fn row(o: []u16, i: *usize, r: []const u16) void { + @memcpy(o[i.* * H ..][0..H], r); + i.* += 1; + } + }.row; + const t = cfg.side(cfg.tile_size); + if (across * down > 1) for (0..t * down) |r| { + for (0..across) |tc| for (0..t) |c| { + const tile = (r / t) * across + tc; + put(out, &at, tiles[(tile * t * t + (r % t) * t + c) * H ..][0..H]); + }; + put(out, &at, newline); + }; + const g = cfg.side(cfg.base_size); + for (0..g) |r| { + for (0..g) |c| put(out, &at, global[(r * g + c) * H ..][0..H]); + put(out, &at, newline); + } + put(out, &at, halves(w.separator, H)); + std.debug.assert(at * H == out.len); +} + +const UvWindow = extern struct { side: u32, padded: u32, window: u32, channels: u32 }; +const UvRel = extern struct { groups: u32, side: u32, heads: u32, width: u32 }; +const UvCols = extern struct { channels: u32, in_side: u32, out_side: u32, span: u32, stride: u32, pad: u32, cstride: u32, pstride: u32 }; + +fn add(enc: mtl.ComputeEncoder, k: *const ks.Kernels, a: Ref, b: Ref, y: Ref, n: usize) void { + ks.Kernels.bind(enc, k.get("uv_add"), &.{ a, b, y }, @as(u32, @intCast(n))); + enc.dispatchThreads(mtl.Size.of(n, 1, 1), mtl.Size.of(256, 1, 1)); +} + +fn pointwise(enc: mtl.ComputeEncoder, p: mtl.Pipeline, x: Ref, n: usize) void { + ks.Kernels.bind(enc, p, &.{x}, @as(u32, @intCast(n))); + enc.dispatchThreads(mtl.Size.of(n, 1, 1), mtl.Size.of(256, 1, 1)); +} + +fn norm(enc: mtl.ComputeEncoder, p: mtl.Pipeline, x: Ref, w: Ref, b: Ref, y: Ref, rows: usize, width: usize, eps: f32) void { + ks.Kernels.bind(enc, p, &.{ x, w, b, y }, extern struct { width: u32, eps: f32 }{ .width = @intCast(width), .eps = eps }); + enc.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(256, 1, 1)); +} + +/// A convolution's input rows [out_side^2, channels x span^2] from a square map (see uv_im2col). +fn cols(enc: mtl.ComputeEncoder, k: *const ks.Kernels, x: Ref, y: Ref, p: UvCols) void { + ks.Kernels.bind(enc, k.get("uv_im2col"), &.{ x, y }, p); + enc.dispatchThreads(mtl.Size.of(p.channels * p.span * p.span, p.out_side * p.out_side, 1), mtl.Size.of(256, 1, 1)); +} + +/// The relative-position terms of every query row against each key row and column, bf16 [heads, rows, side] each. +fn relPos(enc: mtl.ComputeEncoder, k: *const ks.Kernels, qkv: Ref, table: [2]Ref, rel_h: Ref, rel_w: Ref, p: UvRel) void { + ks.Kernels.bind(enc, k.get("uv_rel_pos"), &.{ qkv, table[0], table[1], rel_h, rel_w }, p); + enc.dispatchThreads(mtl.Size.of(2 * p.side, p.groups * p.side * p.side, p.heads), mtl.Size.of(32, 8, 1)); +} + +const UvAttn = extern struct { groups: u32, len: u32, heads: u32, width: u32, side: u32, scale: f32 }; + +/// Attention within groups of `len` rows of qkv, heads of 64, into o; side > 0 adds relPos's terms to the scores. +fn attention(enc: mtl.ComputeEncoder, k: *const ks.Kernels, qkv: Ref, rel_h: Ref, rel_w: Ref, o: Ref, p: UvAttn) void { + std.debug.assert(p.len <= 4096); // uv_attention keeps 8 blocks of 512 keys a row + ks.Kernels.bind(enc, k.get("uv_attention"), &.{ qkv, rel_h, rel_w, o }, p); + enc.dispatchGroups(mtl.Size.of((p.len + 31) / 32, p.heads, p.groups), mtl.Size.of(128, 1, 1)); +} + +/// A 640 tile's tables, 256-aligned in `Encoder.tile`: SAM's positions, CLIP's, each global block's offsets h and w. +const tile_grid = cfg.tile_size / cfg.patch; +const tile_rel = 2 * tile_grid - 1; +const tile_clip = cfg.side(cfg.tile_size) * cfg.side(cfg.tile_size) + 1; +const tile_rels = 2 * cfg.sam_global.len; +const tile_rel_parts: [tile_rels]usize = @splat(tile_rel * cfg.sam_head_dim); +const tile_parts = [_]usize{ tile_grid * tile_grid * S, tile_clip * C } ++ tile_rel_parts; + +fn tileOffset(part: usize) usize { + var at: usize = 0; + for (tile_parts[0..part]) |n| at += std.mem.alignForward(usize, n * 2, 256); + return at; +} + +/// Where the 640 tile's CLIP position table starts in `Encoder.tile`. +fn clipPosOffset() usize { + return tileOffset(1); +} + +/// The 640 tile's relative position tables (h, w) of the `nth` global block. +fn relTiles(tile: mtl.Buffer, nth: usize) [2]Ref { + return .{ .{ .buf = tile, .off = tileOffset(2 + 2 * nth) }, .{ .buf = tile, .off = tileOffset(3 + 2 * nth) } }; +} + +/// A 640 tile's tables (SAM's and CLIP's positions, the global blocks' relative positions) in one shared buffer. +fn tileTables(gpa: std.mem.Allocator, device: mtl.Device, w: *const wts.Weights) !mtl.Buffer { + const buf = try device.buffer(tileOffset(tile_parts.len), mtl.ResourceOptions.shared); + errdefer buf.deinit(); + const at = struct { + fn f(b: mtl.Buffer, part: usize) []u16 { + return halves(.{ .buf = b, .off = tileOffset(part) }, tile_parts[part]); + } + }.f; + try resize.bicubicGrid(gpa, halves(w.sam.pos, cfg.sam_grid * cfg.sam_grid * S), cfg.sam_grid, tile_grid, S, at(buf, 0)); + // CLIP's class position is kept; its grid (the 1024 view's 16 x 16) shrinks to the tile's 10 x 10 + const clip_grid = cfg.side(cfg.base_size); + const cpos = halves(w.clip.pos, cfg.clip_positions * C); + const ctile = at(buf, 1); + @memcpy(ctile[0..C], cpos[0..C]); + try resize.bicubicGrid(gpa, cpos[C..], clip_grid, cfg.side(cfg.tile_size), C, ctile[C..]); + for (cfg.sam_global, 0..) |bi, n| { + const b = w.sam.blocks[bi]; + for ([2]Ref{ b.rel_h, b.rel_w }, 0..) |r, hw| { + try resize.linearRows(gpa, halves(r, b.rel_len * cfg.sam_head_dim), b.rel_len, tile_rel, cfg.sam_head_dim, at(buf, 2 + 2 * n + hw)); + } + } + return buf; +} + +fn halves(r: Ref, n: usize) []u16 { + return @as([*]u16, @ptrCast(@alignCast(r.addr())))[0..n]; +} + +/// One buffer's parts for the largest view, each 256-aligned. +const Scratch = struct { + const Part = enum { pix, cols, x, ln, win, qkv, att, proj, hid, sum, rel_h, rel_w, n0, n1, m2, m3, cx, cln, fused, proj_out }; + buf: mtl.Buffer, + offs: [std.enums.values(Part).len]usize, + + fn bytes(p: Part, v: View) usize { + const g2 = v.grid * v.grid; + const p2 = v.padded * v.padded; + const L = v.side * v.side + 1; + return switch (p) { + .pix => 3 * v.size * v.size * 2, + .cols => @max(g2 * N * 9, g2 * 3 * cfg.patch * cfg.patch) * 2, + .x => g2 * S * 2, + .ln, .win, .att, .proj => @max(p2 * S, L * C) * 2, + .qkv => @max(p2 * 3 * S, L * 3 * C) * 2, + .hid => @max(g2 * cfg.sam_ffn, L * cfg.clip_ffn) * 2, + .sum => @max(p2 * 3 * S, g2 * cfg.sam_ffn) * 4, + .rel_h, .rel_w => cfg.sam_heads * @max(g2 * v.grid, p2 * cfg.sam_window) * 2, + .n0, .n1 => g2 * N * 2, + .m2 => (v.grid / 2) * (v.grid / 2) * cfg.net2_width * 2, + .m3 => v.side * v.side * cfg.net3_width * 2, + .cx, .cln => L * C * 2, + .fused => (L - 1) * cfg.fused * 2, + .proj_out => (L - 1) * H * 2, + }; + } + + fn make(device: mtl.Device, v: View) !Scratch { + var s: Scratch = undefined; + var total: usize = 0; + for (std.enums.values(Part), 0..) |p, i| { + s.offs[i] = total; + total += std.mem.alignForward(usize, bytes(p, v), 256); + } + s.buf = try device.buffer(total, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); + return s; + } + + fn at(s: Scratch, p: Part) Ref { + return .{ .buf = s.buf, .off = s.offs[@backingInt(p)] }; + } +}; diff --git a/zig/src/families/uocr/weights.zig b/zig/src/families/uocr/weights.zig new file mode 100644 index 00000000000..1f985e53dba --- /dev/null +++ b/zig/src/families/uocr/weights.zig @@ -0,0 +1,271 @@ +//! Unlimited-OCR-2's tensors, bf16 as stored, in shared Metal buffers; every tensor is accounted for. +const std = @import("std"); +const mtl = @import("metal"); +const ck = @import("../../core/checkpoint_metal.zig"); +const index_format = @import("../../core/checkpoint_index.zig"); +const cfg = @import("config.zig"); +pub const Ref = @import("../../core/qwen_vl/weights.zig").Ref; + +/// A SAM block. The relative positions are [len, 64] with len 27 (windowed) or 127 (global). +pub const SamBlock = struct { norm1_w: Ref, norm1_b: Ref, qkv_w: Ref, qkv_b: Ref, proj_w: Ref, proj_b: Ref, rel_h: Ref, rel_w: Ref, rel_len: usize, norm2_w: Ref, norm2_b: Ref, lin1_w: Ref, lin1_b: Ref, lin2_w: Ref, lin2_b: Ref }; + +/// SAM ViT-B. The convolutions' weights are [out, in x kh x kw] as stored ([out, in, kh, kw]). +pub const Sam = struct { + patch_w: Ref, // [768, 3 x 16 x 16] + patch_b: Ref, + pos: Ref, // [64, 64, 768] + blocks: [cfg.sam_layers]SamBlock, + neck0: Ref, // [256, 768] (1 x 1) + neck1_w: Ref, + neck1_b: Ref, + neck2: Ref, // [256, 256 x 3 x 3] + neck3_w: Ref, + neck3_b: Ref, + net2: Ref, // [512, 256 x 3 x 3], stride 2 + net3: Ref, // [1024, 512 x 3 x 3], stride 2 +}; + +pub const ClipBlock = struct { ln1_w: Ref, ln1_b: Ref, qkv_w: Ref, qkv_b: Ref, out_w: Ref, out_b: Ref, ln2_w: Ref, ln2_b: Ref, fc1_w: Ref, fc1_b: Ref, fc2_w: Ref, fc2_b: Ref }; + +/// CLIP-L's trunk on SAM's map: its own patch embedding is never read. +pub const Clip = struct { cls: Ref, pos: Ref, pre_w: Ref, pre_b: Ref, blocks: [cfg.clip_layers]ClipBlock }; + +/// The router a layer's attention ranks remote blocks by: its own single-head q and k, Gemma-style norms, head_cls. +pub const Router = struct { q: Ref, k: Ref, q_norm: Ref, k_norm: Ref, head_cls: Ref }; + +/// A routed expert's three projections, each [rows, cols] as stored. +pub const Expert = struct { gate: Ref, up: Ref, down: Ref }; + +pub const Layer = struct { + in_norm: Ref, + post_norm: Ref, + q: Ref, + k: Ref, + v: Ref, + o: Ref, + router: Router, + /// Layer 0's dense FFN, or a routed layer's shared expert (1,792 wide). + ffn: Expert, + /// Routed layers only: the gate [64, 1280] and the 64 experts. + gate: ?Ref, + experts: [cfg.experts]Expert, +}; + +pub const Weights = struct { + ck: ck.Checkpoint, + sam: Sam, + clip: Clip, + projector_w: Ref, // [1280, 2048] + projector_b: Ref, + newline: Ref, + separator: Ref, + embed: Ref, // [vocab, 1280] + layers: [cfg.layers]Layer, + norm: Ref, + head: Ref, // [vocab, 1280], not tied + + pub fn deinit(w: *Weights) void { + w.ck.deinit(); + } +}; + +/// The release's shard files, from its index's weight map. +fn shards(arena: std.mem.Allocator, io: std.Io, dir: []const u8) ![][:0]const u8 { + var files: std.StringArrayHashMapUnmanaged(void) = .empty; + const index = try std.fs.path.join(arena, &.{ dir, "model.safetensors.index.json" }); + const text = try std.Io.Dir.cwd().readFileAlloc(io, index, arena, .limited(16 << 20)); + const doc = try std.json.parseFromSliceLeaky(std.json.Value, arena, text, .{}); + var it = (try index_format.weightMap(doc)).iterator(); + while (it.next()) |kv| try files.put(arena, kv.value_ptr.string, {}); + const out = try arena.alloc([:0]const u8, files.count()); + for (files.keys(), out) |name, *path| path.* = try std.fmt.allocPrintSentinel(arena, "{s}/{s}", .{ dir, name }, 0); + return out; +} + +const Taker = struct { + c: *const ck.Checkpoint, + read: usize = 0, + name: [128]u8 = undefined, + + /// The bf16 tensor `name` (formatted), whose dims multiply out to exactly `shape`'s. + fn take(t: *Taker, comptime fmt: []const u8, args: anytype, shape: []const usize) !Ref { + const name = try std.fmt.bufPrint(&t.name, fmt, args); + const x = try t.c.get(name); + var want: usize = 1; + for (shape) |s| want *= s; + var have: usize = 1; + for (x.shape[0..x.rank]) |s| have *= s; + if (x.dtype != .bf16 or have != want or x.shape[0] != shape[0]) { + std.log.err("unlimited ocr: {s} is {t} {any}; this family reads bf16 {any}", .{ name, x.dtype, x.shape[0..x.rank], shape }); + return error.UnexpectedTensor; + } + if (x.offset % 16 != 0) return error.UnalignedTensor; + t.read += 1; + return .{ .buf = x.buffer, .off = x.offset }; + } + + /// The first dimension of `name` (a relative-position table's length). + fn rows(t: *Taker, comptime fmt: []const u8, args: anytype) !usize { + const name = try std.fmt.bufPrint(&t.name, fmt, args); + return (try t.c.get(name)).shape[0]; + } +}; + +/// 256-aligned copies of the tensors stored 8 bytes off a 16-byte boundary (the tensor units read 16-byte fragments). +fn realign(c: *ck.Checkpoint, device: mtl.Device) !void { + var total: usize = 0; + var it = c.tensors.valueIterator(); + while (it.next()) |t| if (t.offset % 16 != 0) { + total += std.mem.alignForward(usize, t.bytes, ck.alignment); + }; + if (total == 0) return; + const buf = try device.buffer(total, mtl.ResourceOptions.shared); + c.own(buf, total) catch |err| { + buf.deinit(); + return err; + }; + var at: usize = 0; + it = c.tensors.valueIterator(); + while (it.next()) |t| { + if (t.offset % 16 == 0) continue; + @memcpy((buf.contents() + at)[0..t.bytes], (t.buffer.contents() + t.offset)[0..t.bytes]); + t.buffer = buf; + t.offset = at; + at += std.mem.alignForward(usize, t.bytes, ck.alignment); + } +} + +/// Tensors this family never reads: the unused indexer, CLIP's own patch embedding and its position ids. +fn unused(name: []const u8) bool { + return std.mem.indexOf(u8, name, ".self_attn.indexer.") != null or + std.mem.eql(u8, name, "model.vision_model.embeddings.patch_embedding.weight") or + std.mem.eql(u8, name, "model.vision_model.embeddings.position_ids"); +} + +/// The release folder `dir`: config checked, then every tensor this family reads, and none unaccounted for. +pub fn load(gpa: std.mem.Allocator, io: std.Io, device: mtl.Device, dir: []const u8) !Weights { + var arena_state = std.heap.ArenaAllocator.init(gpa); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + const config_path = try std.fs.path.join(arena, &.{ dir, "config.json" }); + try cfg.check(gpa, try std.Io.Dir.cwd().readFileAlloc(io, config_path, arena, .limited(1 << 20))); + var w: Weights = undefined; + w.ck = ck.Checkpoint.init(gpa); + errdefer w.ck.deinit(); + for (try shards(arena, io, dir)) |path| try w.ck.addFile(device, path, ""); + try realign(&w.ck, device); + var t: Taker = .{ .c = &w.ck }; + const H = cfg.hidden; + const S = cfg.sam_width; + const C = cfg.clip_width; + + const sp = "model.sam_model."; + w.sam.patch_w = try t.take(sp ++ "patch_embed.proj.weight", .{}, &.{ S, 3 * cfg.patch * cfg.patch }); + w.sam.patch_b = try t.take(sp ++ "patch_embed.proj.bias", .{}, &.{S}); + w.sam.pos = try t.take(sp ++ "pos_embed", .{}, &.{ 1, cfg.sam_grid * cfg.sam_grid * S }); + for (&w.sam.blocks, 0..) |*b, i| { + const len = try t.rows(sp ++ "blocks.{d}.attn.rel_pos_h", .{i}); + const want: usize = if (cfg.isGlobal(i)) 2 * cfg.sam_grid - 1 else 2 * cfg.sam_window - 1; + if (len != want) return error.UnexpectedTensor; + b.rel_len = len; + b.norm1_w = try t.take(sp ++ "blocks.{d}.norm1.weight", .{i}, &.{S}); + b.norm1_b = try t.take(sp ++ "blocks.{d}.norm1.bias", .{i}, &.{S}); + b.qkv_w = try t.take(sp ++ "blocks.{d}.attn.qkv.weight", .{i}, &.{ 3 * S, S }); + b.qkv_b = try t.take(sp ++ "blocks.{d}.attn.qkv.bias", .{i}, &.{3 * S}); + b.proj_w = try t.take(sp ++ "blocks.{d}.attn.proj.weight", .{i}, &.{ S, S }); + b.proj_b = try t.take(sp ++ "blocks.{d}.attn.proj.bias", .{i}, &.{S}); + b.rel_h = try t.take(sp ++ "blocks.{d}.attn.rel_pos_h", .{i}, &.{ len, cfg.sam_head_dim }); + b.rel_w = try t.take(sp ++ "blocks.{d}.attn.rel_pos_w", .{i}, &.{ len, cfg.sam_head_dim }); + b.norm2_w = try t.take(sp ++ "blocks.{d}.norm2.weight", .{i}, &.{S}); + b.norm2_b = try t.take(sp ++ "blocks.{d}.norm2.bias", .{i}, &.{S}); + b.lin1_w = try t.take(sp ++ "blocks.{d}.mlp.lin1.weight", .{i}, &.{ cfg.sam_ffn, S }); + b.lin1_b = try t.take(sp ++ "blocks.{d}.mlp.lin1.bias", .{i}, &.{cfg.sam_ffn}); + b.lin2_w = try t.take(sp ++ "blocks.{d}.mlp.lin2.weight", .{i}, &.{ S, cfg.sam_ffn }); + b.lin2_b = try t.take(sp ++ "blocks.{d}.mlp.lin2.bias", .{i}, &.{S}); + } + const N = cfg.neck_width; + w.sam.neck0 = try t.take(sp ++ "neck.0.weight", .{}, &.{ N, S }); + w.sam.neck1_w = try t.take(sp ++ "neck.1.weight", .{}, &.{N}); + w.sam.neck1_b = try t.take(sp ++ "neck.1.bias", .{}, &.{N}); + w.sam.neck2 = try t.take(sp ++ "neck.2.weight", .{}, &.{ N, N * 9 }); + w.sam.neck3_w = try t.take(sp ++ "neck.3.weight", .{}, &.{N}); + w.sam.neck3_b = try t.take(sp ++ "neck.3.bias", .{}, &.{N}); + w.sam.net2 = try t.take(sp ++ "net_2.weight", .{}, &.{ cfg.net2_width, N * 9 }); + w.sam.net3 = try t.take(sp ++ "net_3.weight", .{}, &.{ cfg.net3_width, cfg.net2_width * 9 }); + + const vp = "model.vision_model."; + w.clip.cls = try t.take(vp ++ "embeddings.class_embedding", .{}, &.{C}); + w.clip.pos = try t.take(vp ++ "embeddings.position_embedding.weight", .{}, &.{ cfg.clip_positions, C }); + w.clip.pre_w = try t.take(vp ++ "pre_layrnorm.weight", .{}, &.{C}); + w.clip.pre_b = try t.take(vp ++ "pre_layrnorm.bias", .{}, &.{C}); + for (&w.clip.blocks, 0..) |*b, i| { + const lp = vp ++ "transformer.layers.{d}."; + b.ln1_w = try t.take(lp ++ "layer_norm1.weight", .{i}, &.{C}); + b.ln1_b = try t.take(lp ++ "layer_norm1.bias", .{i}, &.{C}); + b.qkv_w = try t.take(lp ++ "self_attn.qkv_proj.weight", .{i}, &.{ 3 * C, C }); + b.qkv_b = try t.take(lp ++ "self_attn.qkv_proj.bias", .{i}, &.{3 * C}); + b.out_w = try t.take(lp ++ "self_attn.out_proj.weight", .{i}, &.{ C, C }); + b.out_b = try t.take(lp ++ "self_attn.out_proj.bias", .{i}, &.{C}); + b.ln2_w = try t.take(lp ++ "layer_norm2.weight", .{i}, &.{C}); + b.ln2_b = try t.take(lp ++ "layer_norm2.bias", .{i}, &.{C}); + b.fc1_w = try t.take(lp ++ "mlp.fc1.weight", .{i}, &.{ cfg.clip_ffn, C }); + b.fc1_b = try t.take(lp ++ "mlp.fc1.bias", .{i}, &.{cfg.clip_ffn}); + b.fc2_w = try t.take(lp ++ "mlp.fc2.weight", .{i}, &.{ C, cfg.clip_ffn }); + b.fc2_b = try t.take(lp ++ "mlp.fc2.bias", .{i}, &.{C}); + } + w.projector_w = try t.take("model.projector.layers.weight", .{}, &.{ H, cfg.fused }); + w.projector_b = try t.take("model.projector.layers.bias", .{}, &.{H}); + w.newline = try t.take("model.image_newline", .{}, &.{H}); + w.separator = try t.take("model.view_seperator", .{}, &.{H}); + + w.embed = try t.take("model.embed_tokens.weight", .{}, &.{ cfg.vocab, H }); + w.norm = try t.take("model.norm.weight", .{}, &.{H}); + w.head = try t.take("lm_head.weight", .{}, &.{ cfg.vocab, H }); + const D = cfg.router_dim; + for (&w.layers, 0..) |*l, i| { + const lp = "model.layers.{d}."; + l.in_norm = try t.take(lp ++ "input_layernorm.weight", .{i}, &.{H}); + l.post_norm = try t.take(lp ++ "post_attention_layernorm.weight", .{i}, &.{H}); + l.q = try t.take(lp ++ "self_attn.q_proj.weight", .{i}, &.{ H, H }); + l.k = try t.take(lp ++ "self_attn.k_proj.weight", .{i}, &.{ H, H }); + l.v = try t.take(lp ++ "self_attn.v_proj.weight", .{i}, &.{ H, H }); + l.o = try t.take(lp ++ "self_attn.o_proj.weight", .{i}, &.{ H, H }); + const rp = lp ++ "self_attn.dash_router."; + l.router = .{ + .q = try t.take(rp ++ "q_proj.weight", .{i}, &.{ D, H }), + .k = try t.take(rp ++ "k_proj.weight", .{i}, &.{ D, H }), + .q_norm = try t.take(rp ++ "q_norm.weight", .{i}, &.{D}), + .k_norm = try t.take(rp ++ "k_norm.weight", .{i}, &.{D}), + .head_cls = try t.take(rp ++ "head_cls", .{i}, &.{D}), + }; + if (i == 0) { + l.ffn = .{ + .gate = try t.take(lp ++ "mlp.gate_proj.weight", .{i}, &.{ cfg.dense_ffn, H }), + .up = try t.take(lp ++ "mlp.up_proj.weight", .{i}, &.{ cfg.dense_ffn, H }), + .down = try t.take(lp ++ "mlp.down_proj.weight", .{i}, &.{ H, cfg.dense_ffn }), + }; + l.gate = null; + l.experts = undefined; + continue; + } + l.ffn = .{ + .gate = try t.take(lp ++ "mlp.shared_experts.gate_proj.weight", .{i}, &.{ cfg.shared_ffn, H }), + .up = try t.take(lp ++ "mlp.shared_experts.up_proj.weight", .{i}, &.{ cfg.shared_ffn, H }), + .down = try t.take(lp ++ "mlp.shared_experts.down_proj.weight", .{i}, &.{ H, cfg.shared_ffn }), + }; + l.gate = try t.take(lp ++ "mlp.gate.weight", .{i}, &.{ cfg.experts, H }); + for (&l.experts, 0..) |*e, j| e.* = .{ + .gate = try t.take(lp ++ "mlp.experts.{d}.gate_proj.weight", .{ i, j }, &.{ cfg.expert_ffn, H }), + .up = try t.take(lp ++ "mlp.experts.{d}.up_proj.weight", .{ i, j }, &.{ cfg.expert_ffn, H }), + .down = try t.take(lp ++ "mlp.experts.{d}.down_proj.weight", .{ i, j }, &.{ H, cfg.expert_ffn }), + }; + } + var skipped: usize = 0; + var it = w.ck.tensors.keyIterator(); + while (it.next()) |name| skipped += @intFromBool(unused(name.*)); + if (t.read + skipped != w.ck.tensors.count()) { + std.log.err("unlimited ocr: the release has {d} tensors; this family reads {d} and knows {d} unused", .{ w.ck.tensors.count(), t.read, skipped }); + return error.UnexpectedTensors; + } + return w; +} diff --git a/zig/src/native/metal.zig b/zig/src/native/metal.zig index 314045d8220..a1682b4ebbd 100644 --- a/zig/src/native/metal.zig +++ b/zig/src/native/metal.zig @@ -65,6 +65,7 @@ pub const families: []const api.Family = &.{ .{ .model_type = "minimax_m3_vl", .formats = &.{ "mlx-q3g64", "mlx-q8g64" } }, .{ .model_type = "llama", .formats = &.{ "bf16", "compressed-tensors-int4-g32" } }, .{ .model_type = "flint", .formats = &.{"mlx-q4g64"} }, + .{ .model_type = "unlimited-ocr", .formats = &.{"bf16"} }, }; /// Gemma 4 31B (gemma4) and 12B (gemma4_unified, its text model): one native family, gemma4.zig's host. @@ -152,8 +153,9 @@ pub fn open(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]c if (std.mem.eql(u8, o.model_type, "qwen4_exp")) return openFlashNext(a, gpa, io, o, problem); if (std.mem.eql(u8, o.model_type, "glm5_next")) return openGlm(a, gpa, io, o, problem); if (isGemma4(o.model_type)) return @import("gemma4.zig").open(a, gpa, io, o, problem); + if (std.mem.eql(u8, o.model_type, "unlimited-ocr")) return @import("uocr.zig").open(a, gpa, io, o, problem); if (o.vision != null and !std.mem.eql(u8, o.model_type, "step5_vl") and !std.mem.eql(u8, o.model_type, "minimax_m3_vl")) { - problem.* = try std.fmt.allocPrint(a, "--vision: the native engine reads images for GLM-5.3-Flash, Qwen3.8-27B, Qwen3.8 Flash Next, Gemma 4, Step-5 and MiniMax-M3.1-Flash only, not {s} checkpoints", .{o.model_type}); + problem.* = try std.fmt.allocPrint(a, "--vision: the native engine reads images for GLM-5.3-Flash, Qwen3.8-27B, Qwen3.8 Flash Next, Gemma 4, Step-5, MiniMax-M3.1-Flash and Unlimited-OCR-2 only, not {s} checkpoints", .{o.model_type}); return null; } if (std.mem.eql(u8, o.model_type, "glm_moe_dsa")) return openGlmDsa(a, gpa, io, o, problem); @@ -291,14 +293,14 @@ fn refusal(a: Allocator, o: api.Open, dense: bool) !?[]const u8 { if (o.prompt_int8) return prompt_int8_refusal; if (!learners.supports(t)) if (try o.slideRefusal(a, "Macs")) |why| return why; if (o.drafter != null and !dense and !isGemma4(t) and !std.mem.eql(u8, t, "llama") and !std.mem.eql(u8, t, "qwen3_5_moe")) return "--drafter is supported for Qwen3.8-27B-class checkpoints (qwen3_5 with its own output head), Qwen3.5-MoE (qwen3_5_moe), Gemma 4 dense and Llama (a smaller Llama on the same tokenizer)"; - const one_mac: ?[]const u8 = if (std.mem.eql(u8, t, "nemotron_h")) "Nemotron" else if (std.mem.eql(u8, t, "lfm2_moe")) "LFM2.5-24B-A2B" else if (isGemma4(t)) "Gemma 4" else if (std.mem.eql(u8, t, "step5_vl")) "Step-5" else if (std.mem.eql(u8, t, "spark2_5")) "Spark-X2.6" else if (std.mem.eql(u8, t, "minimax_m3_vl")) "MiniMax-M3.1-Flash" else if (std.mem.eql(u8, t, "qwen3_5_moe")) "Qwen3.5-MoE" else if (std.mem.eql(u8, t, "llama")) "Llama" else if (std.mem.eql(u8, t, "flint")) "Flint" else if (!std.mem.eql(u8, t, "qwen3_5")) null else if (dense) "Qwen3.8-27B" else "Qwen3.5-2B"; + const one_mac: ?[]const u8 = if (std.mem.eql(u8, t, "nemotron_h")) "Nemotron" else if (std.mem.eql(u8, t, "lfm2_moe")) "LFM2.5-24B-A2B" else if (isGemma4(t)) "Gemma 4" else if (std.mem.eql(u8, t, "step5_vl")) "Step-5" else if (std.mem.eql(u8, t, "spark2_5")) "Spark-X2.6" else if (std.mem.eql(u8, t, "minimax_m3_vl")) "MiniMax-M3.1-Flash" else if (std.mem.eql(u8, t, "qwen3_5_moe")) "Qwen3.5-MoE" else if (std.mem.eql(u8, t, "llama")) "Llama" else if (std.mem.eql(u8, t, "flint")) "Flint" else if (std.mem.eql(u8, t, "unlimited-ocr")) "Unlimited-OCR-2" else if (!std.mem.eql(u8, t, "qwen3_5")) null else if (dense) "Qwen3.8-27B" else "Qwen3.5-2B"; if (o.speed_up != null) if (one_mac) |name| return try std.fmt.allocPrint(a, "--speed-up joins two Macs for Flash Next, GLM-5.3-Flash and GLM-5.3 only: serve {s} without it", .{name}); if (o.recall and std.mem.eql(u8, t, "qwen4_exp")) return recall_refusal; if (spill.refusal(o)) |why| return why; if (o.learn == null) return null; // the 27B writes conversation states if (o.learn_conversations and std.mem.eql(u8, t, "qwen3_5") and dense) return null; - const name: []const u8 = if (std.mem.eql(u8, t, "glm_moe_dsa")) "GLM-5.3 (EXLR8)" else if (std.mem.eql(u8, t, "lfm2_moe")) "LFM2.5-24B-A2B" else if (isGemma4(t)) "Gemma 4" else if (std.mem.eql(u8, t, "step5_vl")) "Step-5" else if (std.mem.eql(u8, t, "spark2_5")) "Spark-X2.6" else if (std.mem.eql(u8, t, "minimax_m3_vl")) "MiniMax-M3.1-Flash" else if (std.mem.eql(u8, t, "qwen3_5_moe")) "Qwen3.5-MoE" else if (std.mem.eql(u8, t, "llama")) "Llama" else if (std.mem.eql(u8, t, "flint")) "Flint" else if (!std.mem.eql(u8, t, "qwen3_5")) return null else if (dense) "Qwen3.8-27B" else "Qwen3.5-2B"; + const name: []const u8 = if (std.mem.eql(u8, t, "glm_moe_dsa")) "GLM-5.3 (EXLR8)" else if (std.mem.eql(u8, t, "lfm2_moe")) "LFM2.5-24B-A2B" else if (isGemma4(t)) "Gemma 4" else if (std.mem.eql(u8, t, "step5_vl")) "Step-5" else if (std.mem.eql(u8, t, "spark2_5")) "Spark-X2.6" else if (std.mem.eql(u8, t, "minimax_m3_vl")) "MiniMax-M3.1-Flash" else if (std.mem.eql(u8, t, "qwen3_5_moe")) "Qwen3.5-MoE" else if (std.mem.eql(u8, t, "llama")) "Llama" else if (std.mem.eql(u8, t, "flint")) "Flint" else if (std.mem.eql(u8, t, "unlimited-ocr")) "Unlimited-OCR-2" else if (!std.mem.eql(u8, t, "qwen3_5")) return null else if (dense) "Qwen3.8-27B" else "Qwen3.5-2B"; if (o.learn_conversations) return try std.fmt.allocPrint(a, "{s} keeps conversation states on disk for Qwen3.8-27B, Nemotron, Flash Next and GLM-5.3-Flash: serve {s} without it", .{ spill.flag(o), name }); const or_talks: []const u8 = if (dense and std.mem.eql(u8, t, "qwen3_5")) " (Qwen3.8-27B keeps conversation states on disk with --learn-conversations)" else ""; return try std.fmt.allocPrint(a, "--learn learns prompt prefixes for Nemotron, Flash Next and GLM-5.3-Flash only{s}: serve {s} without --learn, --learn-dir or --learn-gib", .{ or_talks, name }); @@ -393,6 +395,7 @@ test { _ = spill; _ = @import("metal_link.zig"); _ = metal_shared; + _ = @import("uocr.zig"); } /// GLM-5.3-Flash's caches hold this many tokens unless --context asks otherwise (its window is 1,048,576). @@ -532,6 +535,7 @@ test "slide admission: Metal entry points refuse before checkpoint or device acc try check(@import("step5.zig").open, "Macs", &.{"step5_vl"}); try check(@import("spark25.zig").open, "Macs", &.{"spark2_5"}); try check(@import("minimax_m3.zig").open, "Macs", &.{"minimax_m3_vl"}); + try check(@import("uocr.zig").open, "Macs", &.{"unlimited-ocr"}); try check(openFlashNext, "Macs", &.{"qwen4_exp"}); } diff --git a/zig/src/native/uocr.zig b/zig/src/native/uocr.zig new file mode 100644 index 00000000000..803475f0bf9 --- /dev/null +++ b/zig/src/native/uocr.zig @@ -0,0 +1,106 @@ +//! Unlimited-OCR-2 on Metal served by the lane host: page images in, the greedy reply out, one request at a time. +const std = @import("std"); +const mtl = @import("metal"); +const api = @import("engine_api"); +const tf = @import("tensorfold"); +const fl = tf.uocr; +const lanes = tf.lanes; + +const Host = struct { + gpa: std.mem.Allocator, + io: std.Io, + model: *fl.serve.Model, + config: lanes.Config, + clock: lanes.backend.WallClock, + core: lanes.Engine, + host: api.LaneHost, + markers: [2]u32 = .{ fl.config.page_token, fl.config.image_token }, + + fn close(ctx: *anyopaque) void { + const h: *Host = @ptrCast(@alignCast(ctx)); + h.host.stop(); + h.core.deinit(); + h.config.deinit(h.gpa); + h.model.deinit(); + h.gpa.destroy(h); + } +}; + +pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Open, problem: *[]const u8) !?api.Opened { + if (try o.slideRefusal(a, "Macs")) |why| { + problem.* = why; + return null; + } + if (o.lanes_fixed and o.lanes > 1) { + problem.* = "Unlimited-OCR-2 serves one stream: serve it without --parallel"; + return null; + } + const vis_open = o.vision orelse { + problem.* = "Unlimited-OCR-2 reads page images: serve it with --vision"; + return null; + }; + const context: i64 = o.context orelse fl.config.max_context; + if (context < 1 or context > fl.config.max_context) { + problem.* = try std.fmt.allocPrint(a, "--context {d}: Unlimited-OCR-2 runs to {d} tokens", .{ context, fl.config.max_context }); + return null; + } + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const model = fl.serve.Model.load(gpa, io, o.dir, @intCast(context)) catch |err| { + problem.* = if (err == error.NoTensorUnits) "Unlimited-OCR-2 needs an M5-class GPU (tensor units)" else try std.fmt.allocPrint(a, "the native Unlimited-OCR-2 engine cannot load this checkpoint ({s})", .{@errorName(err)}); + return null; + }; + errdefer model.deinit(); + std.log.info("unlimited-ocr: context {d} tokens, one request at a time", .{context}); + const h = try gpa.create(Host); + errdefer gpa.destroy(h); + h.* = .{ .gpa = gpa, .io = io, .model = model, .config = undefined, .clock = .{ .io = io }, .core = undefined, .host = undefined }; + h.config = try lanes.Config.init(gpa, model.facts(), 1, 0); + errdefer h.config.deinit(gpa); + h.core = lanes.Engine.init(gpa, &h.config, model.backend(), h.clock.clock()); + errdefer h.core.deinit(); + // a page at most the widest gundam grid; without --vision-image-tokens, every allowed page may take it + const image_tokens = if (vis_open.image_tokens_set) vis_open.image_tokens else vis_open.max_images * fl.serve.maxPageTokens(); + const vis: api.Vision = .{ .ctx = h, .prepare = prepareImage, .image_token = fl.config.image_token, .markers = &h.markers, .image_tokens = image_tokens, .max_images = vis_open.max_images }; + h.host = api.LaneHost.init(gpa, io, &h.core, .{ .lanes = 1, .context_window = @intCast(context), .vision = vis, .greedy_only = true, .reasoning = false }); + try h.host.start(); + return .{ .engine = h.host.engine(), .close = Host.close, .ctx = h }; +} + +/// Info.vision's prepare (on the HTTP thread): a page's views, gundam tiles when they fit `max_tokens`. +fn prepareImage(ctx: *anyopaque, a: std.mem.Allocator, bytes: []const u8, max_tokens: u32) anyerror!api.PreparedImage { + const h: *Host = @ptrCast(@alignCast(ctx)); + const p = try h.model.prepare(a, bytes, max_tokens); + return .{ .pixels = p.pixels, .gh = p.gh, .gw = p.gw, .tokens = p.tokens, .hash = p.hash }; +} + +test "Unlimited-OCR-2 refuses a named --parallel above one before reading the checkpoint" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + var problem: []const u8 = ""; + const asked: api.Open = .{ .dir = "missing", .model_type = "unlimited-ocr", .lanes = 4, .lanes_fixed = true }; + try std.testing.expectEqual(null, try open(arena.allocator(), std.testing.allocator, std.testing.io, asked, &problem)); + try std.testing.expectEqualStrings("Unlimited-OCR-2 serves one stream: serve it without --parallel", problem); + const one: api.Open = .{ .dir = "missing", .model_type = "unlimited-ocr", .lanes = 1, .lanes_fixed = true }; + try std.testing.expectEqual(null, try open(arena.allocator(), std.testing.allocator, std.testing.io, one, &problem)); + try std.testing.expectEqualStrings("Unlimited-OCR-2 reads page images: serve it with --vision", problem); +} + +test "Unlimited-OCR-2 refuses a --context past its window or below one, naming both, before reading the checkpoint" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var problem: []const u8 = ""; + for ([_]i64{ fl.config.max_context + 1, 1 << 20, 0, -1 }) |context| { + const asked: api.Open = .{ .dir = "missing", .model_type = "unlimited-ocr", .vision = .{}, .context = context }; + try std.testing.expectEqual(null, try open(a, std.testing.allocator, std.testing.io, asked, &problem)); + try std.testing.expectEqualStrings(try std.fmt.allocPrint(a, "--context {d}: Unlimited-OCR-2 runs to 131072 tokens", .{context}), problem); + } + // the window and one below pass the check and reach the load: no checkpoint here, or no tensor units before M5 + for ([_]i64{ fl.config.max_context, fl.config.max_context - 1, 1 }) |context| { + const asked: api.Open = .{ .dir = "missing", .model_type = "unlimited-ocr", .vision = .{}, .context = context }; + try std.testing.expectEqual(null, try open(a, std.testing.allocator, std.testing.io, asked, &problem)); + try std.testing.expect(std.mem.startsWith(u8, problem, "the native Unlimited-OCR-2 engine cannot load this checkpoint (") or + std.mem.eql(u8, problem, "Unlimited-OCR-2 needs an M5-class GPU (tensor units)")); + } +} diff --git a/zig/src/server/hf_text.zig b/zig/src/server/hf_text.zig index b3a7f7af5b5..967001cb9ca 100644 --- a/zig/src/server/hf_text.zig +++ b/zig/src/server/hf_text.zig @@ -111,7 +111,7 @@ pub const HfText = struct { }; t.overridden = true; } else try t.readTemplates(io, a, dir, config); - if (template_override == null) t.source = @import("hf_text_parse.zig").template(model_config) orelse t.source; + if (template_override == null) t.source = @import("hf_text_parse.zig").builtIn(model_config, t.source) orelse t.source; // DeepSeek-V4.x releases ship encoding.py, not Jinja: a checkpoint's Jinja is a third party's (--chat-template) if (t.native_deepseek) { t.unread_template = t.source.len > 0 or t.tool_source.len > 0; diff --git a/zig/src/server/hf_text_parse.zig b/zig/src/server/hf_text_parse.zig index 7544c16f0c0..b1811b8937e 100644 --- a/zig/src/server/hf_text_parse.zig +++ b/zig/src/server/hf_text_parse.zig @@ -1,10 +1,36 @@ -//! Nemotron Parse's chat template, which hf_text.zig loads in place of the checkpoint's. +//! Built-in chat templates: Nemotron Parse's replaces the checkpoint's; Unlimited-OCR-2's fills in when it ships none. const std = @import("std"); -/// The bridge from server media parts to Parse's visual prefix (its OCR example passes images separately), else null. -pub fn template(model_config: std.json.Value) ?[]const u8 { +/// The template hf_text.zig serves in place of `checkpoint` (the checkpoint's own, "" when it has none), else null. +pub fn builtIn(model_config: std.json.Value, checkpoint: []const u8) ?[]const u8 { if (model_config != .object) return null; const kind = model_config.object.get("model_type") orelse return null; - if (kind != .string or !std.mem.eql(u8, kind.string, "nemotron_parse")) return null; - return @embedFile("fixtures/nemotron_parse.jinja"); + if (kind != .string) return null; + // the bridge from server media parts to Parse's visual prefix (its OCR example passes images separately) + if (std.mem.eql(u8, kind.string, "nemotron_parse")) return @embedFile("fixtures/nemotron_parse.jinja"); + const uocr = @import("uocr_chat"); + if (checkpoint.len == 0 and std.mem.eql(u8, kind.string, uocr.model_type)) return uocr.source; + return null; +} + +test "built-in templates: Parse's replaces the checkpoint's, Unlimited-OCR-2's only fills an empty one, others keep theirs" { + const a = std.testing.allocator; + const Case = struct { config: []const u8, checkpoint: []const u8, want: ?[]const u8 }; + const uocr = @import("uocr_chat"); + const parse = @embedFile("fixtures/nemotron_parse.jinja"); + for ([_]Case{ + .{ .config = "{\"model_type\":\"nemotron_parse\"}", .checkpoint = "", .want = parse }, + .{ .config = "{\"model_type\":\"nemotron_parse\"}", .checkpoint = "theirs", .want = parse }, + .{ .config = "{\"model_type\":\"unlimited-ocr\"}", .checkpoint = "", .want = uocr.source }, + .{ .config = "{\"model_type\":\"unlimited-ocr\"}", .checkpoint = "theirs", .want = null }, + .{ .config = "{\"model_type\":\"qwen3\"}", .checkpoint = "", .want = null }, + .{ .config = "{\"model_type\":\"qwen3\"}", .checkpoint = "theirs", .want = null }, + .{ .config = "{\"model_type\":7}", .checkpoint = "", .want = null }, + .{ .config = "[]", .checkpoint = "", .want = null }, + }) |c| { + const parsed = try std.json.parseFromSlice(std.json.Value, a, c.config, .{}); + defer parsed.deinit(); + const got = builtIn(parsed.value, c.checkpoint); + if (c.want) |w| try std.testing.expectEqualStrings(w, got.?) else try std.testing.expect(got == null); + } } diff --git a/zig/src/server/root.zig b/zig/src/server/root.zig index 29be9a21bd3..1a89f02651a 100644 --- a/zig/src/server/root.zig +++ b/zig/src/server/root.zig @@ -291,6 +291,7 @@ test { _ = @import("models_idle_audit_test.zig"); _ = @import("penalty_request_test.zig"); _ = @import("deepseek_fixture_test.zig"); + _ = @import("uocr_chat_test.zig"); } test { diff --git a/zig/src/server/uocr_chat_test.zig b/zig/src/server/uocr_chat_test.zig new file mode 100644 index 00000000000..6fe18af5b87 --- /dev/null +++ b/zig/src/server/uocr_chat_test.zig @@ -0,0 +1,42 @@ +//! Unlimited-OCR-2's built-in chat template: used when the checkpoint ships none; its own and --chat-template win. +const std = @import("std"); +const json = @import("json"); +const HfText = @import("hf_text.zig").HfText; + +test "Unlimited-OCR-2 serves its family's template when the checkpoint has none; the checkpoint's and the override win" { + const gpa = std.testing.allocator; + const io = std.testing.io; + var arena = std.heap.ArenaAllocator.init(gpa); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(io, .{ .sub_path = "tokenizer.json", .data = + \\{"model":{"type":"BPE","vocab":{"":0,"":1,"H":2},"merges":[]},"added_tokens":[{"id":0,"content":"","special":true},{"id":1,"content":"","special":true}]} + }); + try tmp.dir.writeFile(io, .{ .sub_path = "tokenizer_config.json", .data = "{\"bos_token\":\"\",\"eos_token\":\"\"}" }); + try tmp.dir.writeFile(io, .{ .sub_path = "config.json", .data = "{\"model_type\":\"unlimited-ocr\",\"bos_token_id\":0,\"eos_token_id\":1}" }); + const dir = try tmp.dir.realPathFileAlloc(io, ".", a); + var problem: []const u8 = ""; + const page = "{\"type\":\"image_url\",\"image_url\":{\"url\":\"data:,\"}}"; + const messages = (try json.parse(a, "[{\"role\":\"user\",\"content\":[" ++ page ++ "," ++ page ++ ",{\"type\":\"text\",\"text\":\"Free OCR.\"}]}]")).ok; + const bare = (try json.parse(a, "[{\"role\":\"user\",\"content\":[" ++ page ++ "]}]")).ok; + const built_in = try HfText.load(gpa, io, dir, null, a, &problem); + defer built_in.deinit(); + try std.testing.expectEqualStrings("Free OCR.", (try built_in.text().render(a, messages, .{}, &problem)).text); + try std.testing.expectEqualStrings("Multi page parsing.", (try built_in.text().render(a, bare, .{}, &problem)).text); + try tmp.dir.writeFile(io, .{ .sub_path = "override.jinja", .data = "override" }); + const override = try std.fmt.allocPrint(a, "{s}/override.jinja", .{dir}); + const overridden = try HfText.load(gpa, io, dir, override, a, &problem); + defer overridden.deinit(); + try std.testing.expectEqualStrings("override", (try overridden.text().render(a, messages, .{}, &problem)).text); + try tmp.dir.writeFile(io, .{ .sub_path = "chat_template.jinja", .data = "checkpoint" }); + const shipped = try HfText.load(gpa, io, dir, null, a, &problem); + defer shipped.deinit(); + try std.testing.expectEqualStrings("checkpoint", (try shipped.text().render(a, messages, .{}, &problem)).text); + try tmp.dir.deleteFile(io, "chat_template.jinja"); + try tmp.dir.writeFile(io, .{ .sub_path = "config.json", .data = "{\"model_type\":\"other\",\"bos_token_id\":0,\"eos_token_id\":1}" }); + const other = try HfText.load(gpa, io, dir, null, a, &problem); + defer other.deinit(); + try std.testing.expectEqual(@as(usize, 0), other.source.len); +} diff --git a/zig/src/tensorfold.zig b/zig/src/tensorfold.zig index fec3bf28da4..e7555688ca7 100644 --- a/zig/src/tensorfold.zig +++ b/zig/src/tensorfold.zig @@ -16,6 +16,8 @@ pub const qwen_vl_tower = @import("core/qwen_vl/metal.zig"); pub const qwen_image = @import("families/qwen_image/qwen_image.zig"); /// MOSS-Image's transformer on Metal: a denoiser driven by tf-moss-image, outside the lane engine. pub const moss_image = @import("families/moss_image/moss_image.zig"); +/// Unlimited-OCR-2 on Metal: document pages to text (its image encoder and decoder). +pub const uocr = @import("families/uocr/uocr.zig"); pub const checkpoint = @import("core/checkpoint_metal.zig"); pub const shard_edit = @import("core/shard_edit.zig"); pub const lora_merge = @import("core/lora_merge_dir.zig"); @@ -75,6 +77,7 @@ pub const lfm3 = @import("families/lfm3/lfm3.zig"); test { std.testing.refAllDecls(@This()); + _ = @import("families/uocr/uocr.zig"); _ = lora_merge; _ = @import("families/lfm3/backend.zig"); _ = @import("families/lfm3/state.zig"); diff --git a/zig/tests/contract/metal_limits.zig b/zig/tests/contract/metal_limits.zig index 4feef181901..3ab1cc348b0 100644 --- a/zig/tests/contract/metal_limits.zig +++ b/zig/tests/contract/metal_limits.zig @@ -190,6 +190,11 @@ fn resolve(a: std.mem.Allocator, device: mtl.Device, d: limits.MetalLaunch, comp const t = try @import("metal_minimax.zig").limitsText(a, device, d.name); return .{ .decl = d, .function = fun, .here = t.here, .pre_m5 = t.pre_m5 }; } + if (std.mem.startsWith(u8, d.name, "uocr ")) { + if (!assemble) return undefined; + const t = try @import("metal_uocr.zig").limitsText(a, device, d.name); + return .{ .decl = d, .function = fun, .here = t.here, .pre_m5 = t.pre_m5 }; + } if (std.mem.startsWith(u8, d.name, "spark25 attention ")) { if (!assemble) return undefined; const t = try @import("metal_spark25_attention.zig").limitsText(a, device, d.name); diff --git a/zig/tests/contract/metal_main.zig b/zig/tests/contract/metal_main.zig index 72b8879b9e5..a10a594e1c1 100644 --- a/zig/tests/contract/metal_main.zig +++ b/zig/tests/contract/metal_main.zig @@ -454,6 +454,9 @@ pub fn main(init: std.process.Init) !u8 { var minimax: minimax_k.Suite = .{ .a = a, .device = device, .queue = queue, .kernels = &kernels }; defer minimax.deinit(); try minimax.collect(o.only); + var uocr: @import("metal_uocr.zig").Suite = .{ .a = a, .device = device, .queue = queue, .kernels = &kernels }; + defer uocr.deinit(); + try uocr.collect(o.only); var mma_operand: @import("metal_mma_operand.zig").Suite = .{ .a = a, .device = device, .queue = queue, .kernels = &kernels }; defer mma_operand.deinit(); try mma_operand.collect(o.only); diff --git a/zig/tests/contract/metal_uocr.zig b/zig/tests/contract/metal_uocr.zig new file mode 100644 index 00000000000..6786598e85b --- /dev/null +++ b/zig/tests/contract/metal_uocr.zig @@ -0,0 +1,86 @@ +//! Unlimited-OCR-2's Metal kernels under the contract, one file per group (metal_uocr_*.zig). +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const sources = @import("kernel_sources"); + +const c = contract.spec; +const g = contract.gates; +const groups = .{ @import("metal_uocr_vision.zig"), @import("metal_uocr_decoder_glue.zig"), @import("metal_uocr_decoder_mv.zig"), @import("metal_uocr_decoder_qk.zig"), @import("metal_uocr_decoder_attend.zig"), @import("metal_uocr_decoder_route.zig"), @import("metal_uocr_decoder_gate.zig"), @import("metal_uocr_decoder_ffn.zig") }; +const fields = .{ "vision", "decoder_glue", "decoder_mv", "decoder_qk", "decoder_attend", "decoder_route", "decoder_gate", "decoder_ffn" }; + +/// A launch's two texts: this GPU's and the pre-M5 one (the family's sources include no nax.h, so they are equal). +pub const Texts = struct { here: []const u8, pre_m5: []const u8 }; + +/// The family's two libraries: the tower's own steps (uv_*) and the decoder's (ud_*). +pub const Library = enum { vision, decoder }; + +pub fn source(which: Library) []const u8 { + return switch (which) { + .vision => sources.uocr, + .decoder => sources.uocr_decoder, + }; +} + +/// One of the family's kernels, compiled as families/uocr/kernels.zig compiles it (MLX's options). +pub fn pipeline(device: mtl.Device, which: Library, name: []const u8) !mtl.Pipeline { + const lib = try mtl.Library.fromSource(device, source(which), mtl.CompileOptions.mlx()); + defer lib.deinit(); + return mtl.Pipeline.init(device, lib, name, false); +} + +/// The served widths (the release's config): decoder residual, heads, head width, router, experts, dense; SAM, CLIP. +pub const hidden = 1280; +pub const heads = 10; +pub const head_dim = 128; +pub const router_dim = 128; +pub const experts = 64; +pub const topk = 6; +pub const expert_ffn = 896; +pub const shared_ffn = 2 * expert_ffn; +pub const dense_ffn = 6848; +pub const vocab = 129280; +pub const sam_width = 768; +pub const clip_width = 1024; + +pub fn noSums(_: c.Shape) usize { + return 0; +} + +/// A value as fp32 then bf16 rounds it (to nearest even, twice): an fp32 step on exact inputs, then the bf16 point. +pub fn bf(v: f64) f64 { + return c.fromBf16(c.toBf16(@floatCast(v))); +} + +pub const planted = [_]f32{ std.math.nan(f32), std.math.inf(f32), -std.math.inf(f32) }; + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + vision: groups[0].Suite = undefined, + decoder_glue: groups[1].Suite = undefined, + decoder_mv: groups[2].Suite = undefined, + decoder_qk: groups[3].Suite = undefined, + decoder_attend: groups[4].Suite = undefined, + decoder_route: groups[5].Suite = undefined, + decoder_gate: groups[6].Suite = undefined, + decoder_ffn: groups[7].Suite = undefined, + + pub fn collect(s: *Suite, only: ?[]const u8) !void { + inline for (fields) |f| { + @field(s, f) = .{ .a = s.a, .device = s.device, .queue = s.queue, .kernels = s.kernels }; + try @field(s, f).collect(only); + } + } + pub fn deinit(s: *Suite) void { + inline for (fields) |f| @field(s, f).deinit(); + } +}; + +/// Gate 5's texts for a `uocr ` registration: the group whose launches it names compiles it. +pub fn limitsText(a: std.mem.Allocator, device: mtl.Device, name: []const u8) !Texts { + inline for (groups) |grp| if (try grp.limitsText(a, device, name)) |t| return t; + return error.UnknownLaunch; +} diff --git a/zig/tests/contract/metal_uocr_decoder_attend.zig b/zig/tests/contract/metal_uocr_decoder_attend.zig new file mode 100644 index 00000000000..b8ef9129539 --- /dev/null +++ b/zig/tests/contract/metal_uocr_decoder_attend.zig @@ -0,0 +1,292 @@ +//! ud_attend under the contract: the window's keys and the read blocks' (biased), for prompt rows and a step. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); +const k = @import("metal_uocr_decoder_common.zig"); + +const c = contract.spec; +const g = contract.gates; +const H = k.hidden; +const HD = k.head_dim; +const Mutation = k.Mutation; +const bf = k.bf; +const none: u32 = 0xffffffff; +const max_keys = k.local + k.read_blocks * k.block; + +/// A score's 128-term dot (4 a lane, then the simd_sum tree), the scale and the bias. +fn scoreDepth(_: c.Shape) usize { + return 4 + 5 + 2; +} + +pub const Attend = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + m: Mutation, + /// A prompt's rows (biases rounded to bf16 first, as the prompt's bf16 mask holds them), else a step's. + prompt: bool, + shape: c.Shape = undefined, + fill: g.Fill = .random, + q: []u16 = &.{}, + kv: [2][]u16 = .{ &.{}, &.{} }, + sel: []u32 = &.{}, + bias: []f32 = &.{}, + ins: [5]rig_.Ref = undefined, + out: rig_.Ref = undefined, + + /// Rows: query rows, the last of `k` positions; n: the width (10 heads of 128). + pub fn spec(prompt: bool) c.Spec { + return .{ + .name = if (prompt) "metal uocr decoder ud_attend prompt rows, bf16 biases" else "metal uocr decoder ud_attend step, fp32 biases", + .accum = .f32, + .depth = scoreDepth, + .out = .bf16, + .served = if (prompt) + &.{ .{ .rows = k.prompt_rows, .n = H, .k = k.prompt_rows }, .{ .rows = 37, .n = H, .k = 1061 } } + else + &.{ .{ .rows = 1, .n = H, .k = 4096 }, .{ .rows = 1, .n = H, .k = 100 } }, + // the scores' dots sum exactly in fp32 at gate 4; the softmax's mass and the weighted values do not + .sums = .{ .exact = false }, + }; + } + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, m: Mutation, prompt: bool) !Attend { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try k.pipeline(a, device, m, "ud_attend"), .m = m, .prompt = prompt }; + } + pub fn deinit(t: *Attend) void { + t.free(); + t.rig.deinit(); + t.pipe.deinit(); + } + fn free(t: *Attend) void { + inline for (.{ "q", "sel", "bias" }) |f| { + t.a.free(@field(t, f)); + @field(t, f) = &.{}; + } + for (&t.kv) |*x| { + t.a.free(x.*); + x.* = &.{}; + } + } + pub fn kernel(t: *Attend) g.Kernel { + return k.mark(.{ .spec = spec(t.prompt), .ctx = t, .vt = &vt }, t.m); + } + const vt = g.hooks(Attend); + + fn pos0(t: *const Attend) usize { + return t.shape.k - t.shape.rows; + } + + pub fn prepare(t: *Attend, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n != H or shape.k < shape.rows) return false; + t.rig.reset(); + t.free(); + t.shape = shape; + t.fill = fill; + const rows = shape.rows; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + t.q = try t.a.alloc(u16, rows * H); + for (&t.kv) |*x| x.* = try t.a.alloc(u16, shape.k * H); + if (fill == .stress) { + // per head: q's halves mirror with the sign turned, keys' mirror (8 nudged): huge partials, small scores + for (0..rows * k.heads) |hh| for (0..HD / 2) |d| { + const v: f32 = @floatFromInt(1 + rng.uintLessThan(u32, 7)); + t.q[hh * HD + d] = c.toBf16(v); + t.q[hh * HD + HD / 2 + d] = c.toBf16(-v); + }; + for (0..shape.k * k.heads) |hh| for (0..HD / 2) |d| { + const v: f32 = @floatFromInt(128 + rng.uintLessThan(u32, 128)); + t.kv[0][hh * HD + d] = c.toBf16(v); + t.kv[0][hh * HD + HD / 2 + d] = c.toBf16(v + @as(f32, if (d < 8) 1 else 0)); + }; + k.fillBf16(rng, t.kv[1], 2); + } else { + k.fillBf16(rng, t.q, 0.6); + k.fillBf16(rng, t.kv[0], 0.6); + k.fillBf16(rng, t.kv[1], 2); + } + // each row's read blocks: distinct remote blocks in a random order, gaps marked unread + t.sel = try t.a.alloc(u32, rows * k.read_blocks); + t.bias = try t.a.alloc(f32, rows * k.read_blocks); + for (0..rows) |r| { + const pos = t.pos0() + r; + const nrem = if (pos / k.block >= 4) pos / k.block - 3 else 0; + const s = t.sel[r * k.read_blocks ..][0..k.read_blocks]; + for (s, 0..) |*v, i| { + v.* = none; + if (nrem == 0 or rng.uintLessThan(u32, 8) == 0) continue; + const pick: u32 = @intCast(rng.uintLessThan(usize, nrem)); + if (std.mem.indexOfScalar(u32, s[0..i], pick) == null) v.* = pick; + } + for (t.bias[r * k.read_blocks ..][0..k.read_blocks]) |*b| b.* = if (fill == .stress) 0 else rng.float(f32) * 5 - 4; + } + if (fill == .nonfinite) { + // a key every row's window holds (head 0), a value (head 1, dim 9), a query (row 2, head 2) + t.kv[0][(shape.k - 3) * H + 5] = c.toBf16(k.nan32); + t.kv[1][(shape.k - 5) * H + HD + 9] = c.toBf16(k.inf32); + if (rows > 2) t.q[2 * H + 2 * HD] = c.toBf16(-k.inf32); + } + t.ins[0] = try t.rig.input(std.mem.sliceAsBytes(t.q)); + t.ins[1] = try t.rig.input(std.mem.sliceAsBytes(t.kv[0])); + t.ins[2] = try t.rig.input(std.mem.sliceAsBytes(t.kv[1])); + t.ins[3] = try t.rig.input(std.mem.sliceAsBytes(t.sel)); + t.ins[4] = try t.rig.input(std.mem.sliceAsBytes(t.bias)); + t.out = try t.rig.output(rows * H * 2); + return true; + } + + pub fn run(t: *Attend) !void { + const p = t.rig.begin(); + p.e.setPipeline(t.pipe); + for (t.ins, 0..) |r, i| p.e.setBuffer(r.buf, r.off, i); + p.e.setBuffer(t.out.buf, t.out.off, 5); + p.e.setValue(extern struct { pos0: u32, bf16_bias: u32 }{ .pos0 = @intCast(t.pos0()), .bf16_bias = @intFromBool(t.prompt) }, 6); + p.e.dispatchGroups(mtl.Size.of(k.heads, t.shape.rows, 1), mtl.Size.of(256, 1, 1)); + try t.rig.finish(p); + } + + pub fn count(t: *Attend) usize { + return t.shape.rows * H; + } + + /// Row r's keys: the window's, then each read block's before it, with their biases. + fn keys(t: *Attend, r: usize, at: *[max_keys]usize, kb: *[max_keys]f64) usize { + const pos = t.pos0() + r; + const lo = if (pos >= k.local - 1) pos - (k.local - 1) else 0; + var n: usize = 0; + for (lo..pos + 1) |p| { + at[n] = p; + kb[n] = 0; + n += 1; + } + for (t.sel[r * k.read_blocks ..][0..k.read_blocks], t.bias[r * k.read_blocks ..][0..k.read_blocks]) |s, b| { + if (s == none) continue; + var p: usize = s * k.block; + while (p < @min(lo, (s + 1) * k.block)) : (p += 1) { + at[n] = p; + kb[n] = if (t.prompt) bf(b) else b; + n += 1; + } + } + return n; + } + + fn el(x: []const u16, i: usize) f64 { + return c.fromBf16(x[i]); + } + + /// Outputs and their sum of |p v| (sums in `acc`, `order`); `err` gets each row and head's worst score error. + fn outputs(t: *Attend, acc: c.Accum, order: g.Order, out: []f64, mag: ?[]f64, err: ?[]f64) !void { + var at: [max_keys]usize = undefined; + var kb: [max_keys]f64 = undefined; + var sc: [max_keys]f64 = undefined; + var terms: [max_keys]f64 = undefined; + var dt: [HD]f64 = undefined; + const u = c.unit(.f32); + for (0..t.shape.rows) |r| { + const n = t.keys(r, &at, &kb); + for (0..k.heads) |h| { + const qo = r * H + h * HD; + var top = -std.math.inf(f64); + var worst: f64 = 0; + for (sc[0..n], at[0..n], kb[0..n]) |*s, p, b| { + var dot: f64 = 0; + var m: f64 = 0; + for (&dt, 0..) |*q, d| { + q.* = el(t.q, qo + d) * el(t.kv[0], p * H + h * HD + d); + dot += q.*; + m += @abs(q.*); + } + if (acc != .none) dot = contract.rows.sumIn(acc, order, &dt); + s.* = dot * k.inv_sqrt_hd + b; + if (!std.math.isNan(s.*)) top = @max(top, s.*); + worst = @max(worst, (if (t.fill == .stress) 0 else c.gamma(HD, u) * m) * k.inv_sqrt_hd + 3 * u * @abs(s.*)); + } + if (err) |e| e[r * k.heads + h] = worst; + var mass: f64 = 0; + for (sc[0..n], terms[0..n]) |*s, *q| { + s.* = @exp(s.* - top); + q.* = s.*; + mass += s.*; + } + if (acc != .none) mass = contract.rows.sumIn(acc, order, terms[0..n]); + for (0..HD) |d| { + var o: f64 = 0; + var m: f64 = 0; + for (terms[0..n], sc[0..n], at[0..n]) |*q, s, p| { + q.* = s / mass * el(t.kv[1], p * H + h * HD + d); + o += q.*; + m += @abs(q.*); + } + if (acc != .none) o = bf(contract.rows.sumIn(acc, order, terms[0..n])); + out[qo + d] = o; + if (mag) |ms| ms[qo + d] = if (std.math.isFinite(m)) m else 0; + } + } + } + } + + pub fn reference(t: *Attend, want: []f64, mag: []f64) !void { + try t.outputs(.none, .sequential, want, mag, null); + } + + pub fn simulate(t: *Attend, acc: c.Accum, order: g.Order, out: []f64) !void { + try t.outputs(acc, order, out, null, null); + } + + /// Weights within twice the worst score error, exp, mass and division; the PV chain; the bf16 point. + pub fn bounds(t: *Attend, want: []const f64, mag: []const f64, allow: []f64) !void { + const u = c.unit(.f32); + const scratch = try t.a.alloc(f64, 2 * want.len); + defer t.a.free(scratch); + const err = try t.a.alloc(f64, t.shape.rows * k.heads); + defer t.a.free(err); + try t.outputs(.none, .sequential, scratch[0..want.len], scratch[want.len..], err); + const sums = c.gamma(max_keys / 8 + 8 + 2, u); + for (allow, want, mag, 0..) |*l, w, m, i| { + const rel = 2 * (2 * err[i / HD] + 4 * u) + c.gamma(max_keys, u) + 2 * u; + l.* = if (std.math.isFinite(w)) (rel + sums) * m + 0x1p-8 * (@abs(w) + (rel + sums) * m) + 0x1p-133 else 0; + } + } +}; + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + probes: std.ArrayList(*Attend) = .empty, + + fn add(s: *Suite, only: ?[]const u8, m: Mutation, prompt: bool) !void { + const x = try s.a.create(Attend); + x.* = try Attend.init(s.a, s.device, s.queue, m, prompt); + const kern = x.kernel(); + if (!k.wanted(only, kern.spec.name)) { + x.deinit(); + s.a.destroy(x); + return; + } + try s.probes.append(s.a, x); + try s.kernels.append(s.a, kern); + } + + pub fn collect(s: *Suite, only: ?[]const u8) !void { + try s.add(only, .none, true); + try s.add(only, .none, false); + try s.add(only, .attend_no_bias, true); + } + + pub fn deinit(s: *Suite) void { + for (s.probes.items) |x| { + x.deinit(); + s.a.destroy(x); + } + s.probes.deinit(s.a); + } +}; + +/// Gate 5's texts for this group's launch. +pub fn limitsText(_: std.mem.Allocator, _: mtl.Device, name: []const u8) !?k.Texts { + return k.limitsText(name, &.{"ud_attend"}); +} diff --git a/zig/tests/contract/metal_uocr_decoder_common.zig b/zig/tests/contract/metal_uocr_decoder_common.zig new file mode 100644 index 00000000000..25f7d464639 --- /dev/null +++ b/zig/tests/contract/metal_uocr_decoder_common.zig @@ -0,0 +1,195 @@ +//! The decoder groups' shared parts: decoder.metal with a control's edit, value ranges, gate 5's texts. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const uocr = @import("metal_uocr.zig"); + +const c = contract.spec; +const g = contract.gates; +pub const Texts = uocr.Texts; + +pub const hidden = uocr.hidden; +pub const heads = uocr.heads; +pub const head_dim = uocr.head_dim; +pub const router_dim = uocr.router_dim; +pub const experts = uocr.experts; +pub const topk = uocr.topk; +pub const expert_ffn = uocr.expert_ffn; +pub const shared_ffn = uocr.shared_ffn; +pub const dense_ffn = uocr.dense_ffn; +pub const vocab = uocr.vocab; +pub const bf = uocr.bf; +pub const noSums = uocr.noSums; +pub const planted = uocr.planted; +pub const nan32 = std.math.nan(f32); +pub const inf32 = std.math.inf(f32); + +/// A prompt chunk's rows (serve.zig's prompt_rows), its experts' slots, and the longest context's blocks. +pub const prompt_rows = 2048; +pub const block = 32; +pub const context_blocks = 4096; +pub const read_blocks = 12; +pub const ranked_blocks = 16; +pub const local = 128; +pub const eps: f32 = 1e-6; +/// 1 / sqrt(128), as decoder.metal holds it. +pub const inv_sqrt_hd: f64 = @as(f32, 0.0883883476483184405); +pub const router_scale: f64 = @as(f32, 11.3137084989847604); + +/// The source a probe compiles: decoder.metal, or with one planted fault. +pub const Mutation = enum { + none, + gather_own_row, + matvec_drops_tail, + matvec_half_sums, + norm_mean_over_threads, + norm_add_wrong_sign, + silu_swapped, + combine_no_shared, + qk_rotation_sign, + clamp_drops_nan, + block_keys_unnormalized, + route_no_mean, + attend_no_bias, + gate_unnormalized, + expert_gu_ignores_ids, + expert_down_ignores_ids, + + pub fn name(m: Mutation) []const u8 { + return switch (m) { + .none => "", + .gather_own_row => "control: metal uocr decoder ud_gather, row i reads row i, not rows[i]", + .matvec_drops_tail => "control: metal uocr decoder ud_matvec, each lane's last 8 columns are dropped", + .matvec_half_sums => "control: metal uocr decoder ud_matvec, the dot products sum in half", + .norm_mean_over_threads => "control: metal uocr decoder ud_norm, the mean of squares divides by the threads", + .norm_add_wrong_sign => "control: metal uocr decoder ud_norm, the added rows are subtracted", + .silu_swapped => "control: metal uocr decoder ud_silu_mul, the gate is read from the up rows", + .combine_no_shared => "control: metal uocr decoder ud_combine, the shared expert is not added", + .qk_rotation_sign => "control: metal uocr decoder ud_qk, the rotation turns the other way", + .clamp_drops_nan => "control: metal uocr decoder ud_qk, the router's clamp turns NaN into -1e4", + .block_keys_unnormalized => "control: metal uocr decoder ud_block_keys, the weights are not divided by their sum", + .route_no_mean => "control: metal uocr decoder ud_route, the log-weights keep their mean", + .attend_no_bias => "control: metal uocr decoder ud_attend, the read blocks' biases are dropped", + .gate_unnormalized => "control: metal uocr decoder ud_moe_gate, the scores are not divided by their sum", + .expert_gu_ignores_ids => "control: metal uocr decoder ud_expert_gu, pick j reads expert j", + .expert_down_ignores_ids => "control: metal uocr decoder ud_expert_down, pick j reads expert j", + }; + } + + /// The gate that must go red. + pub fn gate(m: Mutation) ?g.Gate { + return switch (m) { + .none => null, + .matvec_half_sums => .sums, + .clamp_drops_nan => .nonfinite, + else => .shapes, + }; + } + + const Edit = struct { from: []const u8, to: []const u8 }; + + fn edit(m: Mutation) Edit { + return switch (m) { + .none => unreachable, + .gather_own_row => .{ .from = "x[ulong(rows[at.y]) * UD_H + at.x]", .to = "x[ulong(at.y) * UD_H + at.x]" }, + .matvec_drops_tail => .{ .from = "for (uint k = lane * 8; k < p.k; k += 256) {", .to = "for (uint k = lane * 8; k + 8 < p.k; k += 256) {" }, + .matvec_half_sums => .{ .from = "float acc[4] = {0.0f, 0.0f, 0.0f, 0.0f};\n for (uint k = lane * 8; k < p.k;", .to = "half acc[4] = {0.0h, 0.0h, 0.0h, 0.0h};\n for (uint k = lane * 8; k < p.k;" }, + .norm_mean_over_threads => .{ .from = "ss / float(UD_H) + p.eps", .to = "ss / 256.0f + p.eps" }, + .norm_add_wrong_sign => .{ .from = "x = ud_bf(x + float(A[", .to = "x = ud_bf(x - float(A[" }, + .silu_swapped => .{ .from = "const float g = float(G[ulong(at.y) * p.gstride + at.x]);", .to = "const float g = float(U[ulong(at.y) * p.ustride + at.x]);" }, + .combine_no_shared => .{ .from = "Y[o] = bfloat(ud_bf(acc) + float(S[o]));", .to = "Y[o] = bfloat(ud_bf(acc));" }, + .qk_rotation_sign => .{ .from = "const float rot = d < 64 ? -partner : partner;", .to = "const float rot = d < 64 ? partner : -partner;" }, + .clamp_drops_nan => .{ .from = "return isnan(x) ? x : clamp(x, -UD_CLAMP, UD_CLAMP);", .to = "return clamp(x, -UD_CLAMP, UD_CLAMP);" }, + .block_keys_unnormalized => .{ .from = "const float w = precise::divide(e, max(simd_sum(e), 1.0e-6f));", .to = "const float w = e;" }, + .route_no_mean => .{ .from = "bias[i] = i < keep ? logp[i] - mu : 0.0f;", .to = "bias[i] = i < keep ? logp[i] : 0.0f;" }, + .attend_no_bias => .{ .from = "kbias[i] = p.bf16_bias != 0 ? ud_bf(bias[s]) : bias[s];", .to = "kbias[i] = 0.0f;" }, + .gate_unnormalized => .{ .from = "const float mass = simd_sum(v[0] + v[1]);", .to = "const float mass = 1.0f;" }, + .expert_gu_ignores_ids => .{ .from = "const UdExpert ex = E[ids[j]];", .to = "const UdExpert ex = E[j];" }, + .expert_down_ignores_ids => .{ .from = "const device bfloat* W = E[ids[j]].down;", .to = "const device bfloat* W = E[j].down;" }, + }; + } +}; + +/// A decoder.metal kernel compiled as kernels.zig does, with a control's edit (an edit that finds nothing errors). +pub fn pipeline(a: std.mem.Allocator, device: mtl.Device, m: Mutation, name: []const u8) !mtl.Pipeline { + if (m == .none) return uocr.pipeline(device, .decoder, name); + const plain = uocr.source(.decoder); + const e = m.edit(); + if (std.mem.count(u8, plain, e.from) != 1) return error.ControlEditMissing; + const text = try std.mem.replaceOwned(u8, a, plain, e.from, e.to); + defer a.free(text); + const lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); + defer lib.deinit(); + return mtl.Pipeline.init(device, lib, name, false); +} + +/// A probe's kernel under a control's name and gate. +pub fn mark(k: g.Kernel, m: Mutation) g.Kernel { + var out = k; + if (m != .none) { + out.spec.name = m.name(); + out.control = m.gate(); + } + return out; +} + +/// A registration the run's --only selects (all without it). +pub fn wanted(only: ?[]const u8, name: []const u8) bool { + const o = only orelse return true; + return std.mem.indexOf(u8, name, o) != null; +} + +/// A value's spread through fp32 steps and bf16 rounding points. +pub const Range = struct { + lo: f64, + hi: f64, + pub fn point(v: f64) Range { + return .{ .lo = v, .hi = v }; + } + /// Each end moved out by `ulps` fp32 roundings of its own size (and fp32's least step). + pub fn fp32(a: Range, ulps: f64) Range { + const u = ulps * c.unit(.f32); + return .{ .lo = a.lo - u * @abs(a.lo) - 0x1p-149, .hi = a.hi + u * @abs(a.hi) + 0x1p-149 }; + } + /// Each end moved out by `e`. + pub fn widen(a: Range, e: f64) Range { + return .{ .lo = a.lo - e, .hi = a.hi + e }; + } + pub fn bf16(a: Range) Range { + return .{ .lo = bf(a.lo), .hi = bf(a.hi) }; + } + pub fn add(a: Range, b: Range) Range { + return .{ .lo = a.lo + b.lo, .hi = a.hi + b.hi }; + } + pub fn mul(a: Range, b: Range) Range { + const p = [_]f64{ a.lo * b.lo, a.lo * b.hi, a.hi * b.lo, a.hi * b.hi }; + return .{ .lo = @min(@min(p[0], p[1]), @min(p[2], p[3])), .hi = @max(@max(p[0], p[1]), @max(p[2], p[3])) }; + } +}; + +/// The allowance a range gives about `want`: the farther end. +pub fn spread(want: f64, r: Range) f64 { + return @max(@abs(want - r.lo), @abs(r.hi - want)); +} + +/// Bounds from a test's intervals: each output's allowance is its interval's farther end (none for non-finite ones). +pub fn boundsFromIntervals(a: std.mem.Allocator, t: anytype, want: []const f64, allow: []f64) !void { + const n = want.len; + const buf = try a.alloc(f64, 2 * n); + defer a.free(buf); + try t.intervals(buf[0..n], buf[n..]); + for (allow, want, buf[0..n], buf[n..]) |*l, w, lo, hi| l.* = if (std.math.isFinite(w)) @max(spread(w, .{ .lo = lo, .hi = hi }), 0x1p-133) else 0; +} + +/// Gate 5's texts for `uocr decoder ` launches naming one of `functions`: decoder.metal as is, on every chip. +pub fn limitsText(name: []const u8, functions: []const []const u8) ?Texts { + if (!std.mem.startsWith(u8, name, "uocr decoder ")) return null; + const fun = name[std.mem.lastIndexOfScalar(u8, name, ' ').? + 1 ..]; + for (functions) |f| if (std.mem.eql(u8, f, fun)) return .{ .here = uocr.source(.decoder), .pre_m5 = uocr.source(.decoder) }; + return null; +} + +/// Random bf16 values in (-s, s). +pub fn fillBf16(rng: std.Random, out: []u16, s: f32) void { + for (out) |*v| v.* = c.toBf16((rng.float(f32) * 2 - 1) * s); +} diff --git a/zig/tests/contract/metal_uocr_decoder_ffn.zig b/zig/tests/contract/metal_uocr_decoder_ffn.zig new file mode 100644 index 00000000000..c63b49f5b96 --- /dev/null +++ b/zig/tests/contract/metal_uocr_decoder_ffn.zig @@ -0,0 +1,329 @@ +//! The decoder's MLP glue under the contract: ud_silu_mul (SwiGLU's bf16 steps) and ud_combine (experts' weighted sum). +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); +const k = @import("metal_uocr_decoder_common.zig"); + +const c = contract.spec; +const g = contract.gates; +const H = k.hidden; +const Mutation = k.Mutation; +const Range = k.Range; +const bf = k.bf; + +// --- ud_silu_mul: Y = bf16(bf16(silu(g)) * u), silu in fp32 -------------------------------------------------------- + +fn silu(x: f64) f64 { + return x / (1 + @exp(-x)); +} + +/// silu's fp32 steps: exp (4 ulps), 1 + e, the division (2 ulps). +fn siluRange(x: f64) Range { + if (!std.math.isFinite(x)) return Range.point(silu(x)); + const e = Range.point(@exp(-x)).fp32(4); + const den = (Range{ .lo = 1 + e.lo, .hi = 1 + e.hi }).fp32(1); + const q: Range = if (x >= 0) .{ .lo = x / den.hi, .hi = x / den.lo } else .{ .lo = x / den.lo, .hi = x / den.hi }; + return q.fp32(2); +} + +pub const Silu = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + m: Mutation, + shape: c.Shape = undefined, + gu: []u16 = &.{}, + in: rig_.Ref = undefined, + out: rig_.Ref = undefined, + + /// Rows: tokens or expert slots; n: the width. Gate and up rows sit side by side, 2n apart (the joint product). + pub fn spec() c.Spec { + return .{ + .name = "metal uocr decoder ud_silu_mul", + .accum = .none, + .depth = k.noSums, + .out = .bf16, + .tiles = .{ .{}, .{ .size = 256, .step = 1, .min = 1 }, .{} }, + // the shared expert's and the dense layer's prompt rows, a chunk's expert slots, a step's 6 slots and rows + .served = &.{ .{ .rows = k.prompt_rows, .n = k.shared_ffn, .k = 1 }, .{ .rows = k.prompt_rows, .n = k.dense_ffn, .k = 1 }, .{ .rows = 6 * k.prompt_rows, .n = k.expert_ffn, .k = 1 }, .{ .rows = 6, .n = k.expert_ffn, .k = 1 }, .{ .rows = 1, .n = k.dense_ffn, .k = 1 } }, + }; + } + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, m: Mutation) !Silu { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try k.pipeline(a, device, m, "ud_silu_mul"), .m = m }; + } + pub fn deinit(t: *Silu) void { + t.a.free(t.gu); + t.rig.deinit(); + t.pipe.deinit(); + } + pub fn kernel(t: *Silu) g.Kernel { + return k.mark(.{ .spec = spec(), .ctx = t, .vt = &vt }, t.m); + } + const vt = g.hooks(Silu); + + pub fn prepare(t: *Silu, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n == 0) return false; + t.rig.reset(); + t.a.free(t.gu); + t.shape = shape; + const n = shape.n; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + t.gu = try t.a.alloc(u16, shape.rows * 2 * n); + // gates deep into silu's tails on both sides; nonzero, so an infinite up never meets a zero + for (t.gu) |*v| v.* = c.toBf16(@max(0x1p-6, rng.float(f32) * 24) * (if (rng.boolean()) @as(f32, 1) else -1)); + if (fill == .nonfinite) for (0..@min(shape.rows, 6)) |r| { + const at = r * 2 * n + (if (r < 3) 0 else n) + (r * 7) % n; + t.gu[at] = c.toBf16(k.planted[r % 3]); + }; + t.in = try t.rig.input(std.mem.sliceAsBytes(t.gu)); + t.out = try t.rig.output(shape.rows * n * 2); + return true; + } + + pub fn run(t: *Silu) !void { + const n: u32 = @intCast(t.shape.n); + const p = t.rig.begin(); + p.e.setPipeline(t.pipe); + p.e.setBuffer(t.in.buf, t.in.off, 0); + p.e.setBuffer(t.in.buf, t.in.off + n * 2, 1); + p.e.setBuffer(t.out.buf, t.out.off, 2); + p.e.setValue(extern struct { width: u32, gstride: u32, ustride: u32 }{ .width = n, .gstride = 2 * n, .ustride = 2 * n }, 3); + p.e.dispatchThreads(mtl.Size.of(t.shape.n, t.shape.rows, 1), mtl.Size.of(256, 1, 1)); + try t.rig.finish(p); + } + + pub fn count(t: *Silu) usize { + return t.shape.rows * t.shape.n; + } + + fn parts(t: *Silu, i: usize) [2]f64 { + const n = t.shape.n; + const at = (i / n) * 2 * n + i % n; + return .{ c.fromBf16(t.gu[at]), c.fromBf16(t.gu[at + n]) }; + } + + pub fn reference(t: *Silu, want: []f64, mag: []f64) !void { + for (want, mag, 0..) |*w, *m, i| { + const p = t.parts(i); + w.* = bf(bf(silu(p[0])) * p[1]); + m.* = 0; + } + } + + pub fn intervals(t: *Silu, low: []f64, high: []f64) !void { + for (low, high, 0..) |*l, *h, i| { + const p = t.parts(i); + const r = siluRange(p[0]).bf16().mul(Range.point(p[1])).fp32(1).bf16(); + l.* = r.lo; + h.* = r.hi; + } + } + + pub fn bounds(t: *Silu, want: []const f64, _: []const f64, allow: []f64) !void { + try k.boundsFromIntervals(t.a, t, want, allow); + } +}; + +// --- ud_combine: Y = bf16(bf16(sum_j D[slot[r, j]] w[r, j]) + S), the sum in fp32 ----------------------------------- + +/// The products and adds of 6 terms, one after another. +fn combineDepth(_: c.Shape) usize { + return 2 * k.topk; +} + +pub const Combine = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + m: Mutation, + shape: c.Shape = undefined, + fill: g.Fill = .random, + d: []u16 = &.{}, + slot: []u32 = &.{}, + wts: []f32 = &.{}, + s: []u16 = &.{}, + ins: [4]rig_.Ref = undefined, + out: rig_.Ref = undefined, + + /// Rows: tokens; n: the width (1,280); k: the picks a row (6). + pub fn spec() c.Spec { + return .{ + .name = "metal uocr decoder ud_combine top 6 plus the shared expert", + .accum = .f32, + .depth = combineDepth, + .mids = 1, + .out = .bf16, + .served = &.{ .{ .rows = k.prompt_rows, .n = H, .k = k.topk }, .{ .rows = 1, .n = H, .k = k.topk } }, + }; + } + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, m: Mutation) !Combine { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try k.pipeline(a, device, m, "ud_combine"), .m = m }; + } + pub fn deinit(t: *Combine) void { + t.free(); + t.rig.deinit(); + t.pipe.deinit(); + } + fn free(t: *Combine) void { + inline for (.{ "d", "slot", "wts", "s" }) |f| { + t.a.free(@field(t, f)); + @field(t, f) = &.{}; + } + } + pub fn kernel(t: *Combine) g.Kernel { + return k.mark(.{ .spec = spec(), .ctx = t, .vt = &vt }, t.m); + } + const vt = g.hooks(Combine); + + pub fn prepare(t: *Combine, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n != H or shape.k != k.topk) return false; + t.rig.reset(); + t.free(); + t.shape = shape; + t.fill = fill; + const slots = shape.rows * k.topk; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + t.d = try t.a.alloc(u16, slots * H); + t.slot = try t.a.alloc(u32, slots); + t.wts = try t.a.alloc(f32, slots); + t.s = try t.a.alloc(u16, shape.rows * H); + // the slots in a shuffled order, as experts group a prompt's rows + for (t.slot, 0..) |*v, i| v.* = @intCast(i); + rng.shuffle(u32, t.slot); + if (fill == .stress) { + // per output: 2^16 or 2^17, an integer below 128, the large term's negative: exact only in fp32 + for (0..shape.rows) |r| for (0..H) |j| { + const big: f32 = if (rng.boolean()) 65536 else 131072; + const vals = [_]f32{ big, @floatFromInt(1 + rng.uintLessThan(u32, 127)), -big, 0, 0, 0 }; + for (vals, 0..) |v, q| t.d[@as(usize, t.slot[r * k.topk + q]) * H + j] = c.toBf16(v); + }; + @memset(t.wts, 1); + @memset(t.s, 0); + } else { + k.fillBf16(rng, t.d, 4); + for (t.wts) |*v| v.* = 0.02 + rng.float(f32) * 0.2; + k.fillBf16(rng, t.s, 2); + } + if (fill == .nonfinite) { + t.d[@as(usize, t.slot[0]) * H + 1] = c.toBf16(k.planted[0]); + if (shape.rows > 2) { + t.wts[1 * k.topk + 2] = k.planted[1]; + t.s[2 * H + 3] = c.toBf16(k.planted[2]); + } + } + t.ins[0] = try t.rig.input(std.mem.sliceAsBytes(t.d)); + t.ins[1] = try t.rig.input(std.mem.sliceAsBytes(t.slot)); + t.ins[2] = try t.rig.input(std.mem.sliceAsBytes(t.wts)); + t.ins[3] = try t.rig.input(std.mem.sliceAsBytes(t.s)); + t.out = try t.rig.output(shape.rows * H * 2); + return true; + } + + pub fn run(t: *Combine) !void { + const p = t.rig.begin(); + p.e.setPipeline(t.pipe); + for (t.ins, 0..) |r, i| p.e.setBuffer(r.buf, r.off, i); + p.e.setBuffer(t.out.buf, t.out.off, 4); + p.e.dispatchThreads(mtl.Size.of(H, t.shape.rows, 1), mtl.Size.of(256, 1, 1)); + try t.rig.finish(p); + } + + pub fn count(t: *Combine) usize { + return t.shape.rows * H; + } + + fn terms(t: *Combine, i: usize, out: *[k.topk]f64) void { + const r = i / H; + for (out, 0..) |*o, q| o.* = @as(f64, c.fromBf16(t.d[@as(usize, t.slot[r * k.topk + q]) * H + i % H])) * t.wts[r * k.topk + q]; + } + + fn outputs(t: *Combine, acc: c.Accum, order: g.Order, out: []f64, mag: ?[]f64) void { + var tm: [k.topk]f64 = undefined; + for (out, 0..) |*o, i| { + t.terms(i, &tm); + var s: f64 = 0; + var m: f64 = 0; + for (tm) |v| { + s += v; + m += @abs(v); + } + if (acc != .none) s = contract.rows.sumIn(acc, order, &tm); + o.* = bf(bf(s) + c.fromBf16(t.s[i])); + if (mag) |ms| ms[i] = if (std.math.isFinite(m)) m else 0; + } + } + + pub fn reference(t: *Combine, want: []f64, mag: []f64) !void { + t.outputs(.none, .sequential, want, mag); + } + + pub fn simulate(t: *Combine, acc: c.Accum, order: g.Order, out: []f64) !void { + t.outputs(acc, order, out, null); + } + + /// The fp32 sum within gamma(12) of its terms (exact at gate 4), its bf16 point, the shared add and its point. + pub fn intervals(t: *Combine, low: []f64, high: []f64) !void { + var tm: [k.topk]f64 = undefined; + for (low, high, 0..) |*l, *h, i| { + t.terms(i, &tm); + var s: f64 = 0; + var m: f64 = 0; + for (tm) |v| { + s += v; + m += @abs(v); + } + const e = if (t.fill == .stress) 0 else c.gamma(2 * k.topk, c.unit(.f32)) * m; + const r = Range.point(s).widen(e).bf16().add(Range.point(c.fromBf16(t.s[i]))).fp32(1).bf16(); + l.* = r.lo; + h.* = r.hi; + } + } + + pub fn bounds(t: *Combine, want: []const f64, _: []const f64, allow: []f64) !void { + try k.boundsFromIntervals(t.a, t, want, allow); + } +}; +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + silus: std.ArrayList(*Silu) = .empty, + combines: std.ArrayList(*Combine) = .empty, + + fn add(s: *Suite, comptime T: type, list: *std.ArrayList(*T), only: ?[]const u8, m: Mutation) !void { + const x = try s.a.create(T); + x.* = try T.init(s.a, s.device, s.queue, m); + const kern = x.kernel(); + if (!k.wanted(only, kern.spec.name)) { + x.deinit(); + s.a.destroy(x); + return; + } + try list.append(s.a, x); + try s.kernels.append(s.a, kern); + } + + pub fn collect(s: *Suite, only: ?[]const u8) !void { + for ([_]Mutation{ .none, .silu_swapped }) |m| try s.add(Silu, &s.silus, only, m); + for ([_]Mutation{ .none, .combine_no_shared }) |m| try s.add(Combine, &s.combines, only, m); + } + + pub fn deinit(s: *Suite) void { + inline for (.{ "silus", "combines" }) |f| { + for (@field(s, f).items) |x| { + x.deinit(); + s.a.destroy(x); + } + @field(s, f).deinit(s.a); + } + } +}; + +/// Gate 5's texts for this group's launches. +pub fn limitsText(_: std.mem.Allocator, _: mtl.Device, name: []const u8) !?k.Texts { + return k.limitsText(name, &.{ "ud_silu_mul", "ud_combine" }); +} diff --git a/zig/tests/contract/metal_uocr_decoder_gate.zig b/zig/tests/contract/metal_uocr_decoder_gate.zig new file mode 100644 index 00000000000..87ebb0d759e --- /dev/null +++ b/zig/tests/contract/metal_uocr_decoder_gate.zig @@ -0,0 +1,268 @@ +//! ud_moe_gate under the contract: softmax top 6; near-ties may swap, so the kernel's own picks are checked. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); +const k = @import("metal_uocr_decoder_common.zig"); + +const c = contract.spec; +const g = contract.gates; +const H = k.hidden; +const E = k.experts; +const P = k.topk; +const Mutation = k.Mutation; +const u = c.unit(.f32); + +/// A lane's two 4-wide dots and the add each 256 columns, then the simd_sum tree. +fn depth(s: c.Shape) usize { + return 6 * ((s.k + 255) / 256) + 5; +} + +pub const Gate = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + m: Mutation, + shape: c.Shape = undefined, + fill: g.Fill = .random, + x: []u16 = &.{}, + w: [E * H]u16 = undefined, + ins: [2]rig_.Ref = undefined, + wts: rig_.Ref = undefined, + ids: rig_.Ref = undefined, + msg: [200]u8 = undefined, + + /// Rows: tokens; n: experts (64); k: width (1280). Outputs: weights [rows, 6] (against float64), picks [rows, 6]. + pub fn spec() c.Spec { + return .{ + .name = "metal uocr decoder ud_moe_gate softmax top 6", + .accum = .f32, + .depth = depth, + .out = .f32, + .nan = .{ .stated = "a row with a NaN or +Inf logit gives NaN probabilities and picks experts 0 to 5; a -Inf logit's expert weighs 0" }, + .served = &.{ .{ .rows = k.prompt_rows, .n = E, .k = H }, .{ .rows = 1, .n = E, .k = H } }, + // the logits sum exactly in fp32 at gate 4; the softmax's mass does not + .sums = .{ .exact = false }, + }; + } + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, m: Mutation) !Gate { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try k.pipeline(a, device, m, "ud_moe_gate"), .m = m }; + } + pub fn deinit(t: *Gate) void { + t.a.free(t.x); + t.rig.deinit(); + t.pipe.deinit(); + } + pub fn kernel(t: *Gate) g.Kernel { + return k.mark(.{ .spec = spec(), .ctx = t, .vt = &vt }, t.m); + } + const vt = g.hooks(Gate); + + pub fn prepare(t: *Gate, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n != E or shape.k != H) return false; + t.rig.reset(); + t.a.free(t.x); + t.shape = shape; + t.fill = fill; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + t.x = try t.a.alloc(u16, shape.rows * H); + const h = H / 2; + if (fill == .stress) { + // rows' halves mirror (8 nudged) against gate rows mirrored with the sign turned: huge partials + for (0..shape.rows) |r| for (0..h) |i| { + const v: f32 = @floatFromInt(1 + rng.uintLessThan(u32, 64)); + t.x[r * H + i] = c.toBf16(v); + t.x[r * H + h + i] = c.toBf16(v + @as(f32, if (i < 8) 1 else 0)); + }; + for (0..E) |e| for (0..h) |i| { + const q: f32 = @floatFromInt(if (i < 8) rng.uintLessThan(u32, 2) else 1 + rng.uintLessThan(u32, 7)); + t.w[e * H + i] = c.toBf16(q); + t.w[e * H + h + i] = c.toBf16(-q); + }; + } else { + k.fillBf16(rng, t.x, 2); + k.fillBf16(rng, &t.w, 0.05); + } + if (fill == .nonfinite) { + // row 0 NaN, row 1 +Inf at column 3, expert 7 -Inf at column 5 (later rows hold 1 there) + t.x[0] = c.toBf16(k.nan32); + t.x[H + 3] = c.toBf16(k.inf32); + t.w[3] = c.toBf16(0.5); + t.w[7 * H + 5] = c.toBf16(-k.inf32); + for (2..shape.rows) |r| t.x[r * H + 5] = c.toBf16(1); + for (0..E) |e| if (e != 7) { + t.w[e * H + 5] = c.toBf16(0.25); + }; + } + t.ins[0] = try t.rig.input(std.mem.sliceAsBytes(t.x)); + t.ins[1] = try t.rig.input(std.mem.sliceAsBytes(&t.w)); + t.wts = try t.rig.output(shape.rows * P * 4); + t.ids = try t.rig.output(shape.rows * P * 4); + return true; + } + + pub fn run(t: *Gate) !void { + const p = t.rig.begin(); + p.e.setPipeline(t.pipe); + p.e.setBuffer(t.ins[0].buf, t.ins[0].off, 0); + p.e.setBuffer(t.ins[1].buf, t.ins[1].off, 1); + p.e.setBuffer(t.ids.buf, t.ids.off, 2); + p.e.setBuffer(t.wts.buf, t.wts.off, 3); + p.e.dispatchGroups(mtl.Size.of(t.shape.rows, 1, 1), mtl.Size.of(1024, 1, 1)); + try t.rig.finish(p); + } + + pub fn count(t: *Gate) usize { + return t.shape.rows * P; + } + + /// Row r's probabilities (logits and mass in `acc` and `order`) and each one's error bound in the kernel. + fn probs(t: *Gate, r: usize, acc: c.Accum, order: g.Order, p: *[E]f64, err: *[E]f64) void { + var terms: [H]f64 = undefined; + var logit: [E]f64 = undefined; + var worst: f64 = 0; + for (&logit, 0..) |*l, e| { + var s: f64 = 0; + var m: f64 = 0; + for (&terms, 0..) |*q, i| { + q.* = @as(f64, c.fromBf16(t.x[r * H + i])) * c.fromBf16(t.w[e * H + i]); + s += q.*; + m += @abs(q.*); + } + if (acc != .none) s = contract.rows.sumIn(acc, order, &terms); + l.* = s; + if (t.fill != .stress and std.math.isFinite(m)) worst = @max(worst, c.gamma(@floatFromInt(depth(t.shape)), u) * m); + } + var top = -std.math.inf(f64); + for (logit) |l| top = @max(top, l); + var mass: f64 = 0; + var far: f64 = 0; + for (p, logit) |*q, l| { + q.* = @exp(l - top); + mass += q.*; + if (std.math.isFinite(l - top)) far = @max(far, @abs(l - top)); + } + if (acc != .none) mass = contract.rows.sumIn(acc, order, p); + for (p) |*q| q.* /= mass; + // logit errors move a probability by twice the worst; exp, the mass's chain, the division + const rel = @exp(2 * worst + u * far) - 1 + 4 * u + c.gamma(E, u) + u; + for (err, p) |*e, q| e.* = rel * q + 0x1p-148; + } + + /// The 6 largest, ties to the lower expert; a row of NaN picks experts 0 to 5. + fn pick(p: *const [E]f64, out: *[P]usize) void { + var taken: [E]bool = @splat(false); + for (out) |*o| { + var best: usize = E; + for (p, 0..) |q, e| { + if (taken[e]) continue; + if (best == E or rankOf(q) > rankOf(p[best])) best = e; + } + o.* = best; + taken[best] = true; + } + } + + fn rankOf(q: f64) f64 { + return if (std.math.isNan(q)) -1 else q; + } + + fn outputs(t: *Gate, acc: c.Accum, order: g.Order, out: []f64) void { + var p: [E]f64 = undefined; + var err: [E]f64 = undefined; + var ids: [P]usize = undefined; + for (0..t.shape.rows) |r| { + t.probs(r, acc, order, &p, &err); + pick(&p, &ids); + for (ids, 0..) |e, j| out[r * P + j] = p[e]; + } + } + + pub fn reference(t: *Gate, want: []f64, mag: []f64) !void { + t.outputs(.none, .sequential, want); + for (mag, want) |*m, w| m.* = if (std.math.isFinite(w)) @abs(w) else 0; + } + + pub fn simulate(t: *Gate, acc: c.Accum, order: g.Order, out: []f64) !void { + t.outputs(acc, order, out); + } + + pub fn bounds(t: *Gate, _: []const f64, _: []const f64, allow: []f64) !void { + var p: [E]f64 = undefined; + var err: [E]f64 = undefined; + var ids: [P]usize = undefined; + for (0..t.shape.rows) |r| { + t.probs(r, .none, .sequential, &p, &err); + pick(&p, &ids); + for (ids, 0..) |e, j| allow[r * P + j] = err[e]; + } + } + + fn say(t: *Gate, comptime fmt: []const u8, args: anytype) []const u8 { + return std.fmt.bufPrint(&t.msg, fmt, args) catch "check failed (message too long)"; + } + + /// The kernel's picks and weights, row by row (gates 1 and 3). + pub fn check(t: *Gate, _: g.Gate) !?[]const u8 { + const wts = t.rig.bytes(t.wts, t.count() * 4); + const ids = std.mem.bytesAsSlice(u32, t.rig.bytes(t.ids, t.count() * 4)); + var p: [E]f64 = undefined; + var err: [E]f64 = undefined; + for (0..t.shape.rows) |r| { + t.probs(r, .none, .sequential, &p, &err); + const sel: []const u32 = @alignCast(ids[r * P ..][0..P]); + if (std.math.isNan(p[0])) { + for (sel, 0..) |e, j| if (e != j or !std.math.isNan(c.read(.f32, wts, r * P + j))) return t.say("row {d}: a NaN row picks expert {d} at {d}, or a number", .{ r, e, j }); + continue; + } + for (sel, 0..) |e, j| { + if (e >= E) return t.say("row {d} pick {d}: expert {d} out of range", .{ r, j, e }); + if (std.mem.indexOfScalar(u32, sel[0..j], e) != null) return t.say("row {d} pick {d}: expert {d} picked twice", .{ r, j, e }); + if (j > 0 and p[e] > p[sel[j - 1]] + err[e] + err[sel[j - 1]]) return t.say("row {d} pick {d}: expert {d} ranks above the pick before it", .{ r, j, e }); + const w = c.read(.f32, wts, r * P + j); + if (!(@abs(w - p[e]) <= err[e])) return t.say("row {d} pick {d} (expert {d}): weight {e:.6} where float64 gives {e:.6}", .{ r, j, e, w, p[e] }); + } + const last = sel[P - 1]; + for (0..E) |e| if (std.mem.indexOfScalar(u32, sel, @intCast(e)) == null and p[e] > p[last] + err[e] + err[last]) + return t.say("row {d}: expert {d} beats the last pick {d} but is not picked", .{ r, e, last }); + } + return null; + } +}; + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + probes: std.ArrayList(*Gate) = .empty, + + pub fn collect(s: *Suite, only: ?[]const u8) !void { + for ([_]Mutation{ .none, .gate_unnormalized }) |m| { + const x = try s.a.create(Gate); + x.* = try Gate.init(s.a, s.device, s.queue, m); + const kern = x.kernel(); + if (!k.wanted(only, kern.spec.name)) { + x.deinit(); + s.a.destroy(x); + continue; + } + try s.probes.append(s.a, x); + try s.kernels.append(s.a, kern); + } + } + + pub fn deinit(s: *Suite) void { + for (s.probes.items) |x| { + x.deinit(); + s.a.destroy(x); + } + s.probes.deinit(s.a); + } +}; + +/// Gate 5's texts for this group's launch. +pub fn limitsText(_: std.mem.Allocator, _: mtl.Device, name: []const u8) !?k.Texts { + return k.limitsText(name, &.{"ud_moe_gate"}); +} diff --git a/zig/tests/contract/metal_uocr_decoder_glue.zig b/zig/tests/contract/metal_uocr_decoder_glue.zig new file mode 100644 index 00000000000..f9c9e8ed089 --- /dev/null +++ b/zig/tests/contract/metal_uocr_decoder_glue.zig @@ -0,0 +1,344 @@ +//! The decoder's row glue under the contract: ud_gather and ud_norm (plain, and adding the residual first). +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); +const k = @import("metal_uocr_decoder_common.zig"); + +const c = contract.spec; +const g = contract.gates; +const H = k.hidden; +const Mutation = k.Mutation; +const Range = k.Range; +const bf = k.bf; + +// --- ud_gather: y[i] = x[rows[i]], 1280 wide ----------------------------------------------------------------------- + +pub const Gather = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + m: Mutation, + shape: c.Shape = undefined, + x: []u16 = &.{}, + rows: []u32 = &.{}, + ins: [2]rig_.Ref = undefined, + out: rig_.Ref = undefined, + + /// Rows: rows gathered; n: the width (1,280); k: rows to gather from. + pub fn spec() c.Spec { + return .{ + .name = "metal uocr decoder ud_gather rows", + .accum = .none, + .depth = k.noSums, + .out = .bf16, + // a prompt chunk's 6 expert slots a row, and its rows copied once (the checks' layer rows) + .served = &.{ .{ .rows = 6 * k.prompt_rows, .n = H, .k = k.prompt_rows }, .{ .rows = 279, .n = H, .k = 279 } }, + }; + } + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, m: Mutation) !Gather { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try k.pipeline(a, device, m, "ud_gather"), .m = m }; + } + pub fn deinit(t: *Gather) void { + t.a.free(t.x); + t.a.free(t.rows); + t.rig.deinit(); + t.pipe.deinit(); + } + pub fn kernel(t: *Gather) g.Kernel { + return k.mark(.{ .spec = spec(), .ctx = t, .vt = &vt }, t.m); + } + const vt = g.hooks(Gather); + + pub fn prepare(t: *Gather, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n != H or shape.k == 0) return false; + t.rig.reset(); + t.a.free(t.x); + t.a.free(t.rows); + t.shape = shape; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + t.x = try t.a.alloc(u16, shape.k * H); + k.fillBf16(rng, t.x, 4); + t.rows = try t.a.alloc(u32, shape.rows); + for (t.rows, 0..) |*r, i| r.* = @intCast((i * 7 + 1 + rng.uintLessThan(usize, shape.k)) % shape.k); + if (fill == .nonfinite) for (k.planted, 0..) |v, i| { + t.x[@as(usize, t.rows[i % shape.rows]) * H + 3 * i + 1] = c.toBf16(v); + }; + t.ins[0] = try t.rig.input(std.mem.sliceAsBytes(t.x)); + t.ins[1] = try t.rig.input(std.mem.sliceAsBytes(t.rows)); + t.out = try t.rig.output(shape.rows * H * 2); + return true; + } + + pub fn run(t: *Gather) !void { + const p = t.rig.begin(); + p.e.setPipeline(t.pipe); + p.e.setBuffer(t.ins[0].buf, t.ins[0].off, 0); + p.e.setBuffer(t.ins[1].buf, t.ins[1].off, 1); + p.e.setBuffer(t.out.buf, t.out.off, 2); + p.e.dispatchThreads(mtl.Size.of(H, t.shape.rows, 1), mtl.Size.of(256, 1, 1)); + try t.rig.finish(p); + } + + pub fn count(t: *Gather) usize { + return t.shape.rows * H; + } + + pub fn reference(t: *Gather, want: []f64, mag: []f64) !void { + for (want, mag, 0..) |*w, *m, i| { + w.* = c.fromBf16(t.x[@as(usize, t.rows[i / H]) * H + i % H]); + m.* = 0; + } + } +}; + +// --- ud_norm: optionally R = bf16(R + A), then Y = bf16(w * bf16(r * rsqrt(mean(r^2) + eps))) ---------------------- + +pub const NormCase = enum { + /// The norm alone (add 0): Y checked. + plain, + /// The residual's add (add 1): R checked, in place. + resid, + /// The norm of the added residual (add 1): Y checked. + normed, +}; + +/// A thread's 5 squares, the simd_sum tree, then 8 simdgroups' partials. +fn normDepth(_: c.Shape) usize { + return 5 + 5 + 8; +} + +pub const Norm = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + m: Mutation, + v: NormCase, + shape: c.Shape = undefined, + fill: g.Fill = .random, + r0: []u16 = &.{}, + add: []u16 = &.{}, + w: []u16 = &.{}, + resid: rig_.Ref = undefined, + y: rig_.Ref = undefined, + ins: [2]rig_.Ref = undefined, + + /// Rows: tokens; n: the width (1,280). + pub fn spec(v: NormCase) c.Spec { + const served: []const c.Shape = &.{ .{ .rows = k.prompt_rows, .n = H, .k = 1 }, .{ .rows = 1, .n = H, .k = 1 }, .{ .rows = 279, .n = H, .k = 1 } }; + if (v == .resid) return .{ .name = "metal uocr decoder ud_norm add, the residual", .accum = .none, .depth = k.noSums, .out = .bf16, .in_place = true, .served = served }; + return .{ + .name = if (v == .plain) "metal uocr decoder ud_norm" else "metal uocr decoder ud_norm add, the normed rows", + .accum = .f32, + .depth = normDepth, + // the mean's division, + eps, rsqrt, x * inv; then w times the bf16 point + .ops = 6, + .mids = 1, + .out = .bf16, + .served = served, + .sums = .{ .bf16 = 0, .why = "the bf16 output follows the sum of squares as ss^-1/2: a bf16 sum's error is a few output ulps" }, + }; + } + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, m: Mutation, v: NormCase) !Norm { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try k.pipeline(a, device, m, "ud_norm"), .m = m, .v = v }; + } + pub fn deinit(t: *Norm) void { + t.free(); + t.rig.deinit(); + t.pipe.deinit(); + } + fn free(t: *Norm) void { + inline for (.{ "r0", "add", "w" }) |f| { + t.a.free(@field(t, f)); + @field(t, f) = &.{}; + } + } + pub fn kernel(t: *Norm) g.Kernel { + return k.mark(.{ .spec = spec(t.v), .ctx = t, .vt = &vt }, t.m); + } + const vt = blk: { + var h = g.hooks(Norm); + h.overlap = overlap; + break :blk h; + }; + /// The residual is read and written in place where it is the checked output. + fn overlap(ctx: *anyopaque) bool { + const t: *Norm = @ptrCast(@alignCast(ctx)); + return t.v == .resid; + } + + pub fn prepare(t: *Norm, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n != H) return false; + t.rig.reset(); + t.free(); + t.shape = shape; + t.fill = fill; + const n = shape.rows * H; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + t.r0 = try t.a.alloc(u16, n); + t.add = try t.a.alloc(u16, n); + t.w = try t.a.alloc(u16, H); + if (fill == .stress) { + // integers whose squares sum exactly in fp32 (1,280 x 1,600 at most) and overflow fp16 in any order + for (t.r0) |*v| v.* = c.toBf16(@floatFromInt(@as(i32, @intCast(20 + rng.uintLessThan(u32, 21))) * (if (rng.boolean()) @as(i32, 1) else -1))); + @memset(t.add, 0); + for (t.w) |*v| v.* = c.toBf16(1); + } else { + k.fillBf16(rng, t.r0, 4); + k.fillBf16(rng, t.add, 2); + for (t.w) |*v| v.* = c.toBf16(0.5 + rng.float(f32)); + } + if (fill == .nonfinite) { + // a row each, one row holding both infinities; then an added NaN + const at = [_][2]usize{ .{ 0, 1 }, .{ 1, 2 }, .{ 2, 3 }, .{ 3, 4 }, .{ 3, 5 } }; + const vals = [_]f32{ k.planted[0], k.planted[1], k.planted[2], k.planted[1], k.planted[2] }; + for (at, vals) |p, v| if (p[0] < shape.rows) { + t.r0[p[0] * H + p[1]] = c.toBf16(v); + }; + if (shape.rows > 4 and t.v != .plain) t.add[4 * H + 6] = c.toBf16(k.planted[0]); + } + const rbytes = std.mem.sliceAsBytes(t.r0); + t.resid = switch (t.v) { + .plain => try t.rig.input(rbytes), + .resid => try t.rig.output(rbytes.len), + .normed => try t.rig.scratch(rbytes.len), + }; + t.ins[0] = try t.rig.input(std.mem.sliceAsBytes(t.add)); + t.ins[1] = try t.rig.input(std.mem.sliceAsBytes(t.w)); + t.y = if (t.v == .resid) try t.rig.scratch(n * 2) else try t.rig.output(n * 2); + return true; + } + + pub fn run(t: *Norm) !void { + // the residual starts from the prepared rows each run + if (t.v != .plain) @memcpy(t.rig.bytes(t.resid, t.r0.len * 2), std.mem.sliceAsBytes(t.r0)); + const p = t.rig.begin(); + p.e.setPipeline(t.pipe); + p.e.setBuffer(t.resid.buf, t.resid.off, 0); + p.e.setBuffer(t.ins[0].buf, t.ins[0].off, 1); + p.e.setBuffer(t.ins[1].buf, t.ins[1].off, 2); + p.e.setBuffer(t.y.buf, t.y.off, 3); + p.e.setValue(extern struct { add: u32, eps: f32 }{ .add = @intFromBool(t.v != .plain), .eps = k.eps }, 4); + p.e.dispatchGroups(mtl.Size.of(t.shape.rows, 1, 1), mtl.Size.of(256, 1, 1)); + try t.rig.finish(p); + } + + pub fn count(t: *Norm) usize { + return t.shape.rows * H; + } + + /// Row r's values after the add (if any). + fn row(t: *Norm, r: usize, out: []f64) void { + for (out, 0..) |*o, j| { + const x: f64 = c.fromBf16(t.r0[r * H + j]); + o.* = if (t.v == .plain) x else bf(x + c.fromBf16(t.add[r * H + j])); + } + } + + fn sumSquares(x: []const f64, acc: c.Accum, order: g.Order) f64 { + var sq: [H]f64 = undefined; + for (&sq, x) |*s, v| s.* = v * v; + return if (acc == .none) blk: { + var s: f64 = 0; + for (sq) |v| s += v; + break :blk s; + } else contract.rows.sumIn(acc, order, &sq); + } + + fn outputs(t: *Norm, acc: c.Accum, order: g.Order, out: []f64) void { + var x: [H]f64 = undefined; + for (0..t.shape.rows) |r| { + t.row(r, &x); + if (t.v == .resid) { + @memcpy(out[r * H ..][0..H], &x); + continue; + } + const inv = 1 / @sqrt(sumSquares(&x, acc, order) / H + @as(f64, k.eps)); + for (out[r * H ..][0..H], x, 0..) |*o, v, j| o.* = bf(c.fromBf16(t.w[j]) * bf(v * inv)); + } + } + + pub fn reference(t: *Norm, want: []f64, mag: []f64) !void { + t.outputs(.none, .sequential, want); + @memset(mag, 0); + } + + pub fn simulate(t: *Norm, acc: c.Accum, order: g.Order, out: []f64) !void { + t.outputs(acc, order, out); + } + + /// Squares' fp32 chain (exact at gate 4), mean, eps, rsqrt (4 roundings), x * inv, bf16, the weight, bf16. + pub fn intervals(t: *Norm, low: []f64, high: []f64) !void { + var x: [H]f64 = undefined; + for (0..t.shape.rows) |r| { + t.row(r, &x); + if (t.v == .resid) { + @memcpy(low[r * H ..][0..H], &x); + @memcpy(high[r * H ..][0..H], &x); + continue; + } + const ss = sumSquares(&x, .none, .sequential); + // gate 4's integers sum exactly in fp32 + const e = if (t.fill == .stress) 0 else c.gamma(@floatFromInt(normDepth(t.shape)), c.unit(.f32)) * ss; + const lo = (ss - e) / H + @as(f64, k.eps); + const hi = (ss + e) / H + @as(f64, k.eps); + const inv = (Range{ .lo = 1 / @sqrt(hi), .hi = 1 / @sqrt(lo) }).fp32(4); + for (x, 0..) |v, j| { + const y = Range.point(v).mul(inv).fp32(1).bf16().mul(Range.point(c.fromBf16(t.w[j]))).fp32(1).bf16(); + low[r * H + j] = y.lo; + high[r * H + j] = y.hi; + } + } + } + + pub fn bounds(t: *Norm, want: []const f64, _: []const f64, allow: []f64) !void { + try k.boundsFromIntervals(t.a, t, want, allow); + } +}; + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + gathers: std.ArrayList(*Gather) = .empty, + norms: std.ArrayList(*Norm) = .empty, + + fn add(s: *Suite, comptime T: type, list: *std.ArrayList(*T), only: ?[]const u8, m: Mutation, extra: anytype) !void { + const x = try s.a.create(T); + x.* = try @call(.auto, T.init, .{ s.a, s.device, s.queue, m } ++ extra); + try list.append(s.a, x); + const kern = x.kernel(); + if (!k.wanted(only, kern.spec.name)) { + list.items.len -= 1; + x.deinit(); + s.a.destroy(x); + return; + } + try s.kernels.append(s.a, kern); + } + + pub fn collect(s: *Suite, only: ?[]const u8) !void { + for ([_]Mutation{ .none, .gather_own_row }) |m| try s.add(Gather, &s.gathers, only, m, .{}); + for ([_]NormCase{ .plain, .resid, .normed }) |v| try s.add(Norm, &s.norms, only, .none, .{v}); + try s.add(Norm, &s.norms, only, .norm_mean_over_threads, .{NormCase.plain}); + try s.add(Norm, &s.norms, only, .norm_add_wrong_sign, .{NormCase.resid}); + } + + pub fn deinit(s: *Suite) void { + inline for (.{ "gathers", "norms" }) |f| { + for (@field(s, f).items) |x| { + x.deinit(); + s.a.destroy(x); + } + @field(s, f).deinit(s.a); + } + } +}; + +/// Gate 5's texts for this group's launches. +pub fn limitsText(_: std.mem.Allocator, _: mtl.Device, name: []const u8) !?k.Texts { + return k.limitsText(name, &.{ "ud_gather", "ud_norm" }); +} diff --git a/zig/tests/contract/metal_uocr_decoder_mv.zig b/zig/tests/contract/metal_uocr_decoder_mv.zig new file mode 100644 index 00000000000..f5a92bf687d --- /dev/null +++ b/zig/tests/contract/metal_uocr_decoder_mv.zig @@ -0,0 +1,353 @@ +//! A decode step's products under the contract: ud_matvec, and the experts' ud_expert_gu and ud_expert_down. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); +const k = @import("metal_uocr_decoder_common.zig"); + +const c = contract.spec; +const g = contract.gates; +const H = k.hidden; +const Mutation = k.Mutation; +const bf = k.bf; + +/// A lane's two 4-wide dots and the adds each 256 columns, then the simd_sum tree. +fn mvDepth(s: c.Shape) usize { + return 6 * ((s.k + 255) / 256) + 5; +} + +/// Gate 4's input row: integers, halves mirrored (8 nudged); against `stressRow` partials pass 2^17, the dot is small. +fn stressX(rng: std.Random, x: []u16) void { + const h = x.len / 2; + for (0..h) |i| { + const v: f32 = @floatFromInt(1 + rng.uintLessThan(u32, 64)); + x[i] = c.toBf16(v); + x[h + i] = c.toBf16(v + @as(f32, if (i < 8) 1 else 0)); + } +} + +fn stressRow(rng: std.Random, w: []u16) void { + const h = w.len / 2; + for (0..h) |i| { + const q: f32 = @floatFromInt(1 + rng.uintLessThan(u32, 7)); + w[i] = c.toBf16(q); + w[h + i] = c.toBf16(-q); + } +} + +/// y[n] = sum_j x[j] W[n, j] in f64 (want, mag), or in an accumulator and order (gate 4), each then at bf16. +fn dots(x: []const u16, w: []const u16, kk: usize, acc: c.Accum, order: g.Order, buf: []f64, want: []f64, mag: ?[]f64) void { + for (want, 0..) |*o, r| { + var s: f64 = 0; + var m: f64 = 0; + for (buf[0..kk], 0..) |*t, j| { + t.* = @as(f64, c.fromBf16(x[j])) * c.fromBf16(w[r * kk + j]); + s += t.*; + m += @abs(t.*); + } + if (acc != .none) s = contract.rows.sumIn(acc, order, buf[0..kk]); + o.* = if (acc == .none) s else bf(s); + if (mag) |ms| ms[r] = if (std.math.isFinite(m)) m else 0; + } +} + +/// Plants NaN in row 0, +Inf in row 1, -Inf in row 2 and both in row 3 of `w`, at columns `x` holds as 1. +fn plantRows(x: []u16, w: []u16, kk: usize, rows: usize) void { + const cols = [_]usize{ 1, kk / 3, kk / 2, kk - 1, 3 }; + const vals = [_]f32{ k.planted[0], k.planted[1], k.planted[2], k.planted[1], k.planted[2] }; + const on = [_]usize{ 0, 1, 2, 3, 3 }; + for (cols, vals, on) |j, v, r| if (r < rows) { + x[j] = c.toBf16(1); + w[r * kk + j] = c.toBf16(v); + }; +} + +pub const Matvec = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + m: Mutation, + shape: c.Shape = undefined, + x: []u16 = &.{}, + w: []u16 = &.{}, + ins: [2]rig_.Ref = undefined, + out: rig_.Ref = undefined, + + /// Rows: decode steps (a launch each); n: output rows; k: the input width. + pub fn spec() c.Spec { + return .{ + .name = "metal uocr decoder ud_matvec", + .accum = .f32, + .depth = mvDepth, + .out = .bf16, + .tiles = .{ .{}, .{ .size = 32, .step = 1, .min = 1 }, .{ .size = 256, .step = 8, .min = 8 } }, + // q | k | v | router q | router k, o, the shared expert's gate | up and down, the dense layer's, the head + .served = &.{ + .{ .rows = 1, .n = 3 * H + 2 * k.router_dim, .k = H }, .{ .rows = 1, .n = H, .k = H }, + .{ .rows = 1, .n = 2 * k.shared_ffn, .k = H }, .{ .rows = 1, .n = H, .k = k.shared_ffn }, + .{ .rows = 1, .n = 2 * k.dense_ffn, .k = H }, .{ .rows = 1, .n = H, .k = k.dense_ffn }, + .{ .rows = 1, .n = k.vocab, .k = H }, + }, + }; + } + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, m: Mutation) !Matvec { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try k.pipeline(a, device, m, "ud_matvec"), .m = m }; + } + pub fn deinit(t: *Matvec) void { + t.a.free(t.x); + t.a.free(t.w); + t.rig.deinit(); + t.pipe.deinit(); + } + pub fn kernel(t: *Matvec) g.Kernel { + return k.mark(.{ .spec = spec(), .ctx = t, .vt = &vt }, t.m); + } + const vt = g.hooks(Matvec); + + pub fn prepare(t: *Matvec, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n == 0 or shape.k == 0 or shape.k % 8 != 0) return false; + t.rig.reset(); + t.a.free(t.x); + t.a.free(t.w); + t.shape = shape; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + t.x = try t.a.alloc(u16, shape.rows * shape.k); + t.w = try t.a.alloc(u16, shape.n * shape.k); + if (fill == .stress) { + for (0..shape.rows) |r| stressX(rng, t.x[r * shape.k ..][0..shape.k]); + for (0..shape.n) |r| stressRow(rng, t.w[r * shape.k ..][0..shape.k]); + } else { + k.fillBf16(rng, t.x, 2); + k.fillBf16(rng, t.w, 0.1); + } + if (fill == .nonfinite) plantRows(t.x, t.w, shape.k, shape.n); + t.ins[0] = try t.rig.input(std.mem.sliceAsBytes(t.x)); + t.ins[1] = try t.rig.input(std.mem.sliceAsBytes(t.w)); + t.out = try t.rig.output(shape.rows * shape.n * 2); + return true; + } + + pub fn run(t: *Matvec) !void { + const p = t.rig.begin(); + p.e.setPipeline(t.pipe); + p.e.setBuffer(t.ins[1].buf, t.ins[1].off, 1); + p.e.setValue(extern struct { n: u32, k: u32 }{ .n = @intCast(t.shape.n), .k = @intCast(t.shape.k) }, 3); + for (0..t.shape.rows) |r| { + p.e.setBuffer(t.ins[0].buf, t.ins[0].off + r * t.shape.k * 2, 0); + p.e.setBuffer(t.out.buf, t.out.off + r * t.shape.n * 2, 2); + p.e.dispatchGroups(mtl.Size.of((t.shape.n + 31) / 32, 1, 1), mtl.Size.of(256, 1, 1)); + } + try t.rig.finish(p); + } + + pub fn count(t: *Matvec) usize { + return t.shape.rows * t.shape.n; + } + + fn outputs(t: *Matvec, acc: c.Accum, order: g.Order, want: []f64, mag: ?[]f64) !void { + const kk = t.shape.k; + const n = t.shape.n; + const buf = try t.a.alloc(f64, kk); + defer t.a.free(buf); + for (0..t.shape.rows) |r| dots(t.x[r * kk ..][0..kk], t.w, kk, acc, order, buf, want[r * n ..][0..n], if (mag) |ms| ms[r * n ..][0..n] else null); + } + + pub fn reference(t: *Matvec, want: []f64, mag: []f64) !void { + try t.outputs(.none, .sequential, want, mag); + } + + pub fn simulate(t: *Matvec, acc: c.Accum, order: g.Order, out: []f64) !void { + try t.outputs(acc, order, out, null); + } +}; + +/// Experts the test's table holds (the picks name 6 of them). +const table_experts = 8; + +pub const Expert = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + m: Mutation, + /// ud_expert_down: the picks' down rows; else ud_expert_gu: their gate and up rows. + down: bool, + shape: c.Shape = undefined, + width: usize = 0, + x: []u16 = &.{}, + w: []u16 = &.{}, + ids: []u32 = &.{}, + table: [table_experts * 3]u64 = undefined, + ins: [4]rig_.Ref = undefined, + out: rig_.Ref = undefined, + + /// Rows: decode steps (a launch each, 6 picks); n: each pick's outputs; k: its input width. + pub fn spec(down: bool) c.Spec { + return .{ + .name = if (down) "metal uocr decoder ud_expert_down picks 6" else "metal uocr decoder ud_expert_gu picks 6", + .accum = .f32, + .depth = mvDepth, + .out = .bf16, + .served = if (down) &.{.{ .rows = 1, .n = H, .k = k.expert_ffn }} else &.{.{ .rows = 1, .n = 2 * k.expert_ffn, .k = H }}, + }; + } + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, m: Mutation, down: bool) !Expert { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try k.pipeline(a, device, m, if (down) "ud_expert_down" else "ud_expert_gu"), .m = m, .down = down }; + } + pub fn deinit(t: *Expert) void { + t.a.free(t.x); + t.a.free(t.w); + t.a.free(t.ids); + t.rig.deinit(); + t.pipe.deinit(); + } + pub fn kernel(t: *Expert) g.Kernel { + return k.mark(.{ .spec = spec(t.down), .ctx = t, .vt = &vt }, t.m); + } + const vt = g.hooks(Expert); + + /// An expert's three matrices in the weights buffer: gate [w, 1280], up [w, 1280], down [1280, w]. + fn at(t: *const Expert, e: usize, which: usize) usize { + return (e * 3 + which) * t.width * H; + } + + /// The matrix pick j (of all steps' picks) multiplies by. + fn matrix(t: *const Expert, j: usize) []const u16 { + const e = t.ids[j]; + return if (t.down) t.w[t.at(e, 2)..][0 .. H * t.width] else t.w[t.at(e, 0)..][0 .. 2 * t.width * H]; + } + + /// x for pick j: its step's row (gate and up), or its own row (down). + fn input(t: *const Expert, j: usize) []const u16 { + return if (t.down) t.x[j * t.width ..][0..t.width] else t.x[(j / k.topk) * H ..][0..H]; + } + + pub fn prepare(t: *Expert, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0) return false; + const width = if (t.down) shape.k else shape.n / 2; + if ((if (t.down) shape.n != H else shape.k != H) or width == 0 or width % 8 != 0) return false; + t.rig.reset(); + t.a.free(t.x); + t.a.free(t.w); + t.a.free(t.ids); + t.shape = shape; + t.width = width; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + // six distinct experts a step, the first not expert 0, so a pick never reads its own index by chance alone + t.ids = try t.a.alloc(u32, shape.rows * k.topk); + for (0..shape.rows) |r| { + var order: [table_experts]u32 = undefined; + for (&order, 0..) |*o, i| o.* = @intCast(i); + rng.shuffle(u32, &order); + if (order[0] == 0) std.mem.swap(u32, &order[0], &order[1]); + @memcpy(t.ids[r * k.topk ..][0..k.topk], order[0..k.topk]); + } + const len = if (t.down) width else H; + t.x = try t.a.alloc(u16, if (t.down) shape.rows * k.topk * width else shape.rows * H); + t.w = try t.a.alloc(u16, table_experts * 3 * width * H); + if (fill == .stress) { + for (0..table_experts) |e| for (0..3) |which| { + const rows: usize = if (which == 2) H else width; + const cols: usize = if (which == 2) width else H; + for (0..rows) |r| stressRow(rng, t.w[t.at(e, which) + r * cols ..][0..cols]); + }; + for (0..t.x.len / len) |j| stressX(rng, t.x[j * len ..][0..len]); + } else { + k.fillBf16(rng, t.x, 2); + k.fillBf16(rng, t.w, 0.1); + } + // the first pick's first rows, against the first input row + if (fill == .nonfinite) plantRows(t.x[0..len], t.w[t.at(t.ids[0], if (t.down) 2 else 0)..], len, 4); + t.ins[0] = try t.rig.input(std.mem.sliceAsBytes(t.x)); + t.ins[1] = try t.rig.input(std.mem.sliceAsBytes(t.w)); + const base = t.ins[1].buf.gpuAddress() + t.ins[1].off; + for (0..table_experts) |e| for (0..3) |which| { + t.table[e * 3 + which] = base + t.at(e, which) * 2; + }; + t.ins[2] = try t.rig.input(std.mem.sliceAsBytes(&t.table)); + t.ins[3] = try t.rig.input(std.mem.sliceAsBytes(t.ids)); + t.out = try t.rig.output(shape.rows * k.topk * shape.n * 2); + return true; + } + + pub fn run(t: *Expert) !void { + const p = t.rig.begin(); + p.e.setPipeline(t.pipe); + p.e.useResource(t.ins[1].buf, mtl.ResourceUsage.read); + p.e.setBuffer(t.ins[2].buf, t.ins[2].off, 1); + p.e.setValue(@as(u32, @intCast(t.width)), 4); + const xs = (if (t.down) k.topk * t.width else H) * 2; + for (0..t.shape.rows) |r| { + p.e.setBuffer(t.ins[0].buf, t.ins[0].off + r * xs, 0); + p.e.setBuffer(t.ins[3].buf, t.ins[3].off + r * k.topk * 4, 2); + p.e.setBuffer(t.out.buf, t.out.off + r * k.topk * t.shape.n * 2, 3); + p.e.dispatchGroups(mtl.Size.of(k.topk * t.shape.n / 32, 1, 1), mtl.Size.of(256, 1, 1)); + } + try t.rig.finish(p); + } + + pub fn count(t: *Expert) usize { + return t.shape.rows * k.topk * t.shape.n; + } + + fn outputs(t: *Expert, acc: c.Accum, order: g.Order, want: []f64, mag: ?[]f64) !void { + const kk = t.shape.k; + const buf = try t.a.alloc(f64, kk); + defer t.a.free(buf); + const n = t.shape.n; + for (0..t.ids.len) |j| dots(t.input(j), t.matrix(j), kk, acc, order, buf, want[j * n ..][0..n], if (mag) |ms| ms[j * n ..][0..n] else null); + } + + pub fn reference(t: *Expert, want: []f64, mag: []f64) !void { + try t.outputs(.none, .sequential, want, mag); + } + + pub fn simulate(t: *Expert, acc: c.Accum, order: g.Order, out: []f64) !void { + try t.outputs(acc, order, out, null); + } +}; + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + matvecs: std.ArrayList(*Matvec) = .empty, + experts: std.ArrayList(*Expert) = .empty, + + fn add(s: *Suite, comptime T: type, list: *std.ArrayList(*T), only: ?[]const u8, m: Mutation, extra: anytype) !void { + const x = try s.a.create(T); + x.* = try @call(.auto, T.init, .{ s.a, s.device, s.queue, m } ++ extra); + const kern = x.kernel(); + if (!k.wanted(only, kern.spec.name)) { + x.deinit(); + s.a.destroy(x); + return; + } + try list.append(s.a, x); + try s.kernels.append(s.a, kern); + } + + pub fn collect(s: *Suite, only: ?[]const u8) !void { + for ([_]Mutation{ .none, .matvec_drops_tail, .matvec_half_sums }) |m| try s.add(Matvec, &s.matvecs, only, m, .{}); + for ([_]bool{ false, true }) |down| try s.add(Expert, &s.experts, only, .none, .{down}); + try s.add(Expert, &s.experts, only, .expert_gu_ignores_ids, .{false}); + try s.add(Expert, &s.experts, only, .expert_down_ignores_ids, .{true}); + } + + pub fn deinit(s: *Suite) void { + inline for (.{ "matvecs", "experts" }) |f| { + for (@field(s, f).items) |x| { + x.deinit(); + s.a.destroy(x); + } + @field(s, f).deinit(s.a); + } + } +}; + +/// Gate 5's texts for this group's launches. +pub fn limitsText(_: std.mem.Allocator, _: mtl.Device, name: []const u8) !?k.Texts { + return k.limitsText(name, &.{ "ud_matvec", "ud_expert_gu", "ud_expert_down" }); +} diff --git a/zig/tests/contract/metal_uocr_decoder_qk.zig b/zig/tests/contract/metal_uocr_decoder_qk.zig new file mode 100644 index 00000000000..2ae915becd0 --- /dev/null +++ b/zig/tests/contract/metal_uocr_decoder_qk.zig @@ -0,0 +1,446 @@ +//! The decoder's head projections under the contract: ud_qk (rotary, caches, router norm) and ud_block_keys. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); +const k = @import("metal_uocr_decoder_common.zig"); + +const c = contract.spec; +const g = contract.gates; +const H = k.hidden; +const D = k.router_dim; +const Mutation = k.Mutation; +const Range = k.Range; +const bf = k.bf; +const proj = 3 * H + 2 * D; +const clamp_at: f64 = 1e4; + +/// The release's clamp: NaN stays NaN. +fn clampNan(x: f64) f64 { + return if (std.math.isNan(x)) x else std.math.clamp(x, -clamp_at, clamp_at); +} + +fn clampRange(r: Range) Range { + return .{ .lo = std.math.clamp(r.lo, -clamp_at, clamp_at), .hi = std.math.clamp(r.hi, -clamp_at, clamp_at) }; +} + +/// Rotary in bf16 steps for dim d of a 128-wide head: bf16(bf16(x c) + bf16(rot s)), rot = -partner below 64. +fn rope(x: f64, partner: f64, d: usize, cs: f64, sn: f64) f64 { + const rot = if (d < 64) -partner else partner; + return bf(bf(x * cs) + bf(rot * sn)); +} + +/// The same over ranges of x and its partner: each product's bf16 point, their fp32 sum, its bf16 point. +fn ropeRange(x: Range, partner: Range, d: usize, cs: f64, sn: f64) Range { + const rot = if (d < 64) partner.mul(Range.point(-1)) else partner; + return x.mul(Range.point(cs)).bf16().add(rot.mul(Range.point(sn)).bf16()).fp32(1).bf16(); +} + +/// A thread's square, the simd_sum tree, then 4 simdgroups' partials. +fn routerDepth(_: c.Shape) usize { + return 1 + 5 + 4; +} + +pub const Qk = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + m: Mutation, + shape: c.Shape = undefined, + fill: g.Fill = .random, + p: []u16 = &.{}, + cs: []u16 = &.{}, + sn: []u16 = &.{}, + w: [2][D]u16 = undefined, + ins: [5]rig_.Ref = undefined, + outs: [5]rig_.Ref = undefined, + + /// Rows: tokens; n: the joint projection (4,096). Outputs: q, the k and v cache rows, the router's q and k rows. + pub fn spec() c.Spec { + return .{ + .name = "metal uocr decoder ud_qk rotary page2d, router norm", + .accum = .f32, + .depth = routerDepth, + .ops = 6, + .mids = 2, + .out = .bf16, + .served = &.{ .{ .rows = k.prompt_rows, .n = proj, .k = 1 }, .{ .rows = 1, .n = proj, .k = 1 } }, + .sums = .{ .bf16 = 0, .why = "the router's bf16 rows follow the sum of squares as ss^-1/2: a bf16 sum's error is a few output ulps" }, + }; + } + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, m: Mutation) !Qk { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try k.pipeline(a, device, m, "ud_qk"), .m = m }; + } + pub fn deinit(t: *Qk) void { + t.free(); + t.rig.deinit(); + t.pipe.deinit(); + } + fn free(t: *Qk) void { + inline for (.{ "p", "cs", "sn" }) |f| { + t.a.free(@field(t, f)); + @field(t, f) = &.{}; + } + } + pub fn kernel(t: *Qk) g.Kernel { + return k.mark(.{ .spec = spec(), .ctx = t, .vt = &vt }, t.m); + } + const vt = g.hooks(Qk); + + pub fn prepare(t: *Qk, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n != proj) return false; + t.rig.reset(); + t.free(); + t.shape = shape; + t.fill = fill; + const rows = shape.rows; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + t.p = try t.a.alloc(u16, rows * proj); + k.fillBf16(rng, t.p, 3); + t.cs = try t.a.alloc(u16, rows * 64); + t.sn = try t.a.alloc(u16, rows * 64); + for (t.cs, t.sn) |*cv, *sv| { + const angle = rng.float(f64) * 2 * std.math.pi; + cv.* = c.toBf16(@floatCast(@cos(angle))); + sv.* = c.toBf16(@floatCast(@sin(angle))); + } + for (&t.w) |*w| k.fillBf16(rng, w, 0.5); + if (fill == .stress) { + // the router's rows: integers whose squares sum exactly in fp32 (128 x 1,600) and overflow fp16 + for (0..rows) |r| for (t.p[r * proj + 3 * H ..][0 .. 2 * D]) |*v| { + v.* = c.toBf16(@floatFromInt(@as(i32, @intCast(20 + rng.uintLessThan(u32, 21))) * (if (rng.boolean()) @as(i32, 1) else -1))); + }; + for (&t.w) |*w| @memset(w, 0); + } + if (fill == .nonfinite) { + // a q value (and so its rotary partner), a value row's, the router's q row and key row + const at = [_][2]usize{ .{ 0, 5 }, .{ 1, 2 * H + 9 }, .{ 2, 3 * H + 3 }, .{ 3, 3 * H + D + 7 } }; + const vals = [_]f32{ k.nan32, k.inf32, k.nan32, k.inf32 }; + for (at, vals) |q, v| if (q[0] < rows) { + t.p[q[0] * proj + q[1]] = c.toBf16(v); + }; + } + t.ins[0] = try t.rig.input(std.mem.sliceAsBytes(t.p)); + t.ins[1] = try t.rig.input(std.mem.sliceAsBytes(t.cs)); + t.ins[2] = try t.rig.input(std.mem.sliceAsBytes(t.sn)); + t.ins[3] = try t.rig.input(std.mem.sliceAsBytes(&t.w[0])); + t.ins[4] = try t.rig.input(std.mem.sliceAsBytes(&t.w[1])); + for (&t.outs, [_]usize{ H, H, H, D, D }) |*o, width| o.* = try t.rig.output(rows * width * 2); + return true; + } + + pub fn run(t: *Qk) !void { + const p = t.rig.begin(); + p.e.setPipeline(t.pipe); + for (t.ins, 0..) |r, i| p.e.setBuffer(r.buf, r.off, i); + for (t.outs, 5..) |r, i| p.e.setBuffer(r.buf, r.off, i); + p.e.setValue(extern struct { pos0: u32, eps: f32 }{ .pos0 = 0, .eps = k.eps }, 10); + p.e.dispatchGroups(mtl.Size.of(t.shape.rows, 1, 1), mtl.Size.of(D, 1, 1)); + try t.rig.finish(p); + } + + pub fn count(t: *Qk) usize { + return t.shape.rows * (3 * H + 2 * D); + } + + fn val(t: *Qk, r: usize, i: usize) f64 { + return c.fromBf16(t.p[r * proj + i]); + } + + /// The router's row `which` (0 q, 1 k) of token r normed: its bf16 values, or (with `range`) their spread. + fn routerRow(t: *Qk, r: usize, which: usize, acc: c.Accum, order: g.Order, out: *[D]f64, range: ?*[D]Range) void { + var x: [D]f64 = undefined; + var sq: [D]f64 = undefined; + var ss: f64 = 0; + for (&x, &sq, 0..) |*v, *s, d| { + v.* = t.val(r, 3 * H + which * D + d); + s.* = v.* * v.*; + ss += s.*; + } + if (acc != .none) ss = contract.rows.sumIn(acc, order, &sq); + const inv = 1 / @sqrt(ss / D + @as(f64, k.eps)); + for (out, x, 0..) |*o, v, d| o.* = bf(clampNan(clampNan(v * inv) * (1 + @as(f64, c.fromBf16(t.w[which][d]))))); + const rg = range orelse return; + const e = if (t.fill == .stress) 0 else c.gamma(@floatFromInt(routerDepth(t.shape)), c.unit(.f32)) * ss; + const ir = (Range{ .lo = 1 / @sqrt((ss + e) / D + @as(f64, k.eps)), .hi = 1 / @sqrt((ss - e) / D + @as(f64, k.eps)) }).fp32(4); + for (rg, x, 0..) |*o, v, d| { + const one = Range.point(1 + @as(f64, c.fromBf16(t.w[which][d]))).fp32(1); + o.* = clampRange(clampRange(Range.point(v).mul(ir).fp32(1)).mul(one).fp32(1)).bf16(); + } + } + + /// Every output in order, or (with `low`) their intervals. + fn outputs(t: *Qk, acc: c.Accum, order: g.Order, out: []f64, high: ?[]f64) void { + var i: usize = 0; + const rows = t.shape.rows; + for (0..3) |part| for (0..rows) |r| for (0..H) |j| { + const d = j % 128; + const at = part * H + j; + const cs: f64 = c.fromBf16(t.cs[r * 64 + d % 64]); + const sn: f64 = c.fromBf16(t.sn[r * 64 + d % 64]); + if (part == 2) { + out[i] = t.val(r, at); + if (high) |h| h[i] = out[i]; + } else if (high) |h| { + const rr = ropeRange(Range.point(t.val(r, at)), Range.point(t.val(r, at ^ 64)), d, cs, sn); + out[i] = rr.lo; + h[i] = rr.hi; + } else out[i] = rope(t.val(r, at), t.val(r, at ^ 64), d, cs, sn); + i += 1; + }; + var nv: [D]f64 = undefined; + var nr: [D]Range = undefined; + for (0..2) |which| for (0..rows) |r| { + t.routerRow(r, which, acc, order, &nv, if (high != null) &nr else null); + for (0..D) |d| { + const cs: f64 = c.fromBf16(t.cs[r * 64 + d % 64]); + const sn: f64 = c.fromBf16(t.sn[r * 64 + d % 64]); + if (high) |h| { + const rr = ropeRange(nr[d], nr[d ^ 64], d, cs, sn); + out[i] = rr.lo; + h[i] = rr.hi; + } else out[i] = rope(nv[d], nv[d ^ 64], d, cs, sn); + i += 1; + } + }; + } + + pub fn reference(t: *Qk, want: []f64, mag: []f64) !void { + t.outputs(.none, .sequential, want, null); + @memset(mag, 0); + } + + pub fn simulate(t: *Qk, acc: c.Accum, order: g.Order, out: []f64) !void { + t.outputs(acc, order, out, null); + } + + /// q, k, v exact to bf16; router rows through the norm's fp32 steps, clamps, bf16, then rotary over both spreads. + pub fn intervals(t: *Qk, low: []f64, high: []f64) !void { + t.outputs(.none, .sequential, low, high); + } + + pub fn bounds(t: *Qk, want: []const f64, _: []const f64, allow: []f64) !void { + try k.boundsFromIntervals(t.a, t, want, allow); + } +}; + +// --- ud_block_keys: a block's 32 router keys weighted by a softmax of their dot with head_cls / sqrt(128) ----------- + +/// A key's 128-term dot, one after another. +fn keysDepth(_: c.Shape) usize { + return D; +} + +pub const BlockKeys = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + m: Mutation, + shape: c.Shape = undefined, + fill: g.Fill = .random, + rk: []u16 = &.{}, + hc: [D]u16 = undefined, + ins: [2]rig_.Ref = undefined, + out: rig_.Ref = undefined, + + /// Rows: blocks; n: the router's width (128); k: a block's keys (32). + pub fn spec() c.Spec { + return .{ + .name = "metal uocr decoder ud_block_keys blocks of 32", + .accum = .f32, + .depth = keysDepth, + .out = .f32, + // a prompt chunk's blocks, and the one block a step completes + .served = &.{ .{ .rows = k.prompt_rows / k.block, .n = D, .k = k.block }, .{ .rows = 1, .n = D, .k = k.block } }, + // the dots sum exactly in fp32 at gate 4; the softmax's mass and the weighted keys do not + .sums = .{ .exact = false }, + }; + } + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, m: Mutation) !BlockKeys { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try k.pipeline(a, device, m, "ud_block_keys"), .m = m }; + } + pub fn deinit(t: *BlockKeys) void { + t.a.free(t.rk); + t.rig.deinit(); + t.pipe.deinit(); + } + pub fn kernel(t: *BlockKeys) g.Kernel { + return k.mark(.{ .spec = spec(), .ctx = t, .vt = &vt }, t.m); + } + const vt = g.hooks(BlockKeys); + + pub fn prepare(t: *BlockKeys, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n != D or shape.k != k.block) return false; + t.rig.reset(); + t.a.free(t.rk); + t.shape = shape; + t.fill = fill; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + t.rk = try t.a.alloc(u16, shape.rows * k.block * D); + if (fill == .stress) { + // keys' halves mirror (8 nudged) against head_cls mirrored with the sign turned: huge partials + const h = D / 2; + for (0..h) |d| { + const q: f32 = @floatFromInt(1 + rng.uintLessThan(u32, 7)); + t.hc[d] = c.toBf16(q); + t.hc[h + d] = c.toBf16(-q); + } + for (0..shape.rows * k.block) |j| for (0..h) |d| { + const v: f32 = @floatFromInt(128 + rng.uintLessThan(u32, 128)); + t.rk[j * D + d] = c.toBf16(v); + t.rk[j * D + h + d] = c.toBf16(v + @as(f32, if (d < 8) 1 else 0)); + }; + } else { + k.fillBf16(rng, t.rk, 3); + k.fillBf16(rng, &t.hc, 1); + } + if (fill == .nonfinite) { + // block 0 reads a NaN key; block 1's key 2 is +Inf at dim 7, which head_cls weighs positively + t.rk[3 * D + 5] = c.toBf16(k.nan32); + t.hc[7] = c.toBf16(0.5); + if (shape.rows > 1) t.rk[(k.block + 2) * D + 7] = c.toBf16(k.inf32); + } + t.ins[0] = try t.rig.input(std.mem.sliceAsBytes(t.rk)); + t.ins[1] = try t.rig.input(std.mem.sliceAsBytes(&t.hc)); + t.out = try t.rig.output(shape.rows * D * 4); + return true; + } + + pub fn run(t: *BlockKeys) !void { + const p = t.rig.begin(); + p.e.setPipeline(t.pipe); + p.e.setBuffer(t.ins[0].buf, t.ins[0].off, 0); + p.e.setBuffer(t.ins[1].buf, t.ins[1].off, 1); + p.e.setBuffer(t.out.buf, t.out.off, 2); + p.e.setValue(@as(u32, 0), 3); + p.e.dispatchGroups(mtl.Size.of(t.shape.rows, 1, 1), mtl.Size.of(32, 1, 1)); + try t.rig.finish(p); + } + + pub fn count(t: *BlockKeys) usize { + return t.shape.rows * D; + } + + fn key(t: *BlockKeys, b: usize, j: usize, d: usize) f64 { + return c.fromBf16(t.rk[(b * k.block + j) * D + d]); + } + + /// Block b's weights (sums in `acc`, `order`); `err` gets each score's fp32 error (its dot's chain, the scale). + fn weights(t: *BlockKeys, b: usize, acc: c.Accum, order: g.Order, w: *[k.block]f64, err: *[k.block]f64) void { + var terms: [D]f64 = undefined; + var aw: [k.block]f64 = undefined; + var top = -std.math.inf(f64); + const u = c.unit(.f32); + for (&aw, err, 0..) |*s, *e, j| { + var sum: f64 = 0; + var m: f64 = 0; + for (&terms, 0..) |*q, d| { + q.* = t.key(b, j, d) * c.fromBf16(t.hc[d]); + sum += q.*; + m += @abs(q.*); + } + if (acc != .none) sum = contract.rows.sumIn(acc, order, &terms); + s.* = clampNan(sum * k.inv_sqrt_hd); + if (!std.math.isNan(s.*)) top = @max(top, s.*); + e.* = (if (t.fill == .stress) 0 else c.gamma(D, u) * m) * k.inv_sqrt_hd + 2 * u * @abs(s.*); + } + var e: [k.block]f64 = undefined; + var mass: f64 = 0; + for (&e, aw) |*v, s| { + v.* = @exp(s - top); + mass += v.*; + } + if (acc != .none) mass = contract.rows.sumIn(acc, order, &e); + for (w, e) |*o, v| o.* = v / @max(mass, 1e-6); + } + + fn outputs(t: *BlockKeys, acc: c.Accum, order: g.Order, out: []f64, mag: ?[]f64) void { + var w: [k.block]f64 = undefined; + var dm: [k.block]f64 = undefined; + var terms: [k.block]f64 = undefined; + for (0..t.shape.rows) |b| { + t.weights(b, acc, order, &w, &dm); + for (0..D) |d| { + var s: f64 = 0; + var m: f64 = 0; + for (&terms, w, 0..) |*q, wj, j| { + q.* = wj * t.key(b, j, d); + s += q.*; + m += @abs(q.*); + } + if (acc != .none) s = contract.rows.sumIn(acc, order, &terms); + out[b * D + d] = s; + if (mag) |ms| ms[b * D + d] = if (std.math.isFinite(m)) m else 0; + } + } + } + + pub fn reference(t: *BlockKeys, want: []f64, mag: []f64) !void { + t.outputs(.none, .sequential, want, mag); + } + + pub fn simulate(t: *BlockKeys, acc: c.Accum, order: g.Order, out: []f64) !void { + t.outputs(acc, order, out, null); + } + + /// Weights within twice the worst score error, exp, the mass's chain and the division; then the sum of 32. + pub fn bounds(t: *BlockKeys, want: []const f64, mag: []const f64, allow: []f64) !void { + const u = c.unit(.f32); + var w: [k.block]f64 = undefined; + var errs: [k.block]f64 = undefined; + for (0..t.shape.rows) |b| { + t.weights(b, .none, .sequential, &w, &errs); + var worst: f64 = 0; + for (errs) |e| worst = @max(worst, e); + const rel = 2 * (2 * worst + 4 * u) + c.gamma(k.block, u) + 2 * u; + for (0..D) |d| { + const i = b * D + d; + allow[i] = if (std.math.isFinite(want[i])) (rel + c.gamma(k.block + 1, u)) * mag[i] + u * @abs(want[i]) + 0x1p-149 else 0; + } + } + } +}; + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + qks: std.ArrayList(*Qk) = .empty, + keys: std.ArrayList(*BlockKeys) = .empty, + + fn add(s: *Suite, comptime T: type, list: *std.ArrayList(*T), only: ?[]const u8, m: Mutation) !void { + const x = try s.a.create(T); + x.* = try T.init(s.a, s.device, s.queue, m); + const kern = x.kernel(); + if (!k.wanted(only, kern.spec.name)) { + x.deinit(); + s.a.destroy(x); + return; + } + try list.append(s.a, x); + try s.kernels.append(s.a, kern); + } + + pub fn collect(s: *Suite, only: ?[]const u8) !void { + for ([_]Mutation{ .none, .qk_rotation_sign, .clamp_drops_nan }) |m| try s.add(Qk, &s.qks, only, m); + for ([_]Mutation{ .none, .block_keys_unnormalized }) |m| try s.add(BlockKeys, &s.keys, only, m); + } + + pub fn deinit(s: *Suite) void { + inline for (.{ "qks", "keys" }) |f| { + for (@field(s, f).items) |x| { + x.deinit(); + s.a.destroy(x); + } + @field(s, f).deinit(s.a); + } + } +}; + +/// Gate 5's texts for this group's launches. +pub fn limitsText(_: std.mem.Allocator, _: mtl.Device, name: []const u8) !?k.Texts { + return k.limitsText(name, &.{ "ud_qk", "ud_block_keys" }); +} diff --git a/zig/tests/contract/metal_uocr_decoder_route.zig b/zig/tests/contract/metal_uocr_decoder_route.zig new file mode 100644 index 00000000000..de861b346bd --- /dev/null +++ b/zig/tests/contract/metal_uocr_decoder_route.zig @@ -0,0 +1,433 @@ +//! ud_route under the contract: near-tied picks may swap, so the kernel's picks and bias intervals are checked. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); +const k = @import("metal_uocr_decoder_common.zig"); + +const c = contract.spec; +const g = contract.gates; +const D = k.router_dim; +const Mutation = k.Mutation; +const Range = k.Range; +const keep_n = k.read_blocks; +const rank_n = k.ranked_blocks; +const none: u32 = 0xffffffff; +const clamp_at: f64 = 1e4; +const floor: f64 = @as(f32, 1e-4); +const u = c.unit(.f32); +const masks_n = 4; + +fn clampNan(x: f64) f64 { + return if (std.math.isNan(x)) x else std.math.clamp(x, -clamp_at, clamp_at); +} + +/// A score's 128-term dot, the scale and the clamp, the router's scale. +fn depth(_: c.Shape) usize { + return D + 2; +} + +/// The entmax-1.5 threshold over sorted X (X[0] = 0): prefix taus from means, support = count(tau <= X). +fn thresholds(xs: []const f64, tau: []f64) usize { + var s1: f64 = 0; + var s2: f64 = 0; + var support: usize = 0; + for (xs, tau, 0..) |x, *t, i| { + s1 += x; + s2 += x * x; + const rho: f64 = @floatFromInt(i + 1); + const mean = s1 / rho; + const delta = (1 - rho * (s2 / rho - mean * mean)) / rho; + t.* = mean - @sqrt(@max(delta, 0)); + if (t.* <= x) support += 1; + } + return @max(support, 1) - 1; +} + +/// Each prefix's threshold error in the kernel: its inputs off by up to `ex` each, then its fp32 steps. +fn thresholdErrors(xs: []const f64, ex: f64, err: []f64) void { + var s1: f64 = 0; + var s2: f64 = 0; + for (xs, err, 0..) |x, *e, i| { + s1 += x; + s2 += x * x; + const rho: f64 = @floatFromInt(i + 1); + const mean = s1 / rho; + const msq = s2 / rho; + var dev: f64 = 0; + for (xs[0 .. i + 1]) |y| dev += @abs(y - mean); + const diff = msq - mean * mean; + const ss = rho * diff; + const delta = (1 - ss) / rho; + const e_mean = 2 * u * @abs(mean); + const e_diff = 3 * u * msq + 5 * u * mean * mean + u * @abs(diff); + const e_ss = rho * e_diff + u * @abs(ss) + u * @abs(1 - ss); + const e_delta = (4 * ex * dev + rho * 4 * ex * ex + e_ss) / rho + u * @abs(delta); + const d0 = @max(delta, 0); + const root = @max(@sqrt(d0 + e_delta) - @sqrt(d0), @sqrt(d0) - @sqrt(@max(d0 - e_delta, 0))) + 2 * u * @sqrt(d0 + e_delta); + e.* = ex + e_mean + root + u * (@abs(mean) + @sqrt(d0) + root); + } +} + +pub const Route = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + m: Mutation, + shape: c.Shape = undefined, + fill: g.Fill = .random, + words: usize = 0, + q: []u16 = &.{}, + kb: []f32 = &.{}, + masks: []u32 = &.{}, + qmask: []i32 = &.{}, + /// A row's scores and their error bounds, and whether each block is a candidate (scratch for one row). + v: []f64 = &.{}, + e: []f64 = &.{}, + cand: []bool = &.{}, + ins: [4]rig_.Ref = undefined, + bias: rig_.Ref = undefined, + sel: rig_.Ref = undefined, + msg: [240]u8 = undefined, + + /// Rows: query rows, the last of `k` positions; n: a row's read blocks (12). + pub fn spec() c.Spec { + return .{ + .name = "metal uocr decoder ud_route remote blocks, entmax-1.5", + .accum = .f32, + .depth = depth, + .out = .f32, + .nan = .{ .stated = "a NaN score is never picked (a row of NaN reads no block, biases 0); an infinite one clamps at 1e4" }, + // a prompt chunk, an odd one, the longest context's step, a short one + .served = &.{ + .{ .rows = k.prompt_rows, .n = keep_n, .k = k.prompt_rows }, .{ .rows = 37, .n = keep_n, .k = 1061 }, + .{ .rows = 1, .n = keep_n, .k = k.context_blocks * k.block }, .{ .rows = 1, .n = keep_n, .k = 700 }, + }, + // the scores' dots sum exactly in fp32 at gate 4; the entmax's means do not + .sums = .{ .exact = false }, + }; + } + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, m: Mutation) !Route { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try k.pipeline(a, device, m, "ud_route"), .m = m }; + } + pub fn deinit(t: *Route) void { + t.free(); + t.rig.deinit(); + t.pipe.deinit(); + } + fn free(t: *Route) void { + inline for (.{ "q", "kb", "masks", "qmask", "v", "e", "cand" }) |f| { + t.a.free(@field(t, f)); + @field(t, f) = &.{}; + } + } + pub fn kernel(t: *Route) g.Kernel { + return k.mark(.{ .spec = spec(), .ctx = t, .vt = &vt }, t.m); + } + const vt = g.hooks(Route); + + fn pos0(t: *const Route) usize { + return t.shape.k - t.shape.rows; + } + /// Row r's remote blocks: those wholly before its window's 4 blocks. + fn remote(t: *const Route, r: usize) usize { + const b = (t.pos0() + r) / k.block; + return if (b >= 4) b - 3 else 0; + } + + pub fn prepare(t: *Route, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n != keep_n or shape.k < shape.rows or shape.k > k.context_blocks * k.block) return false; + t.rig.reset(); + t.free(); + t.shape = shape; + t.fill = fill; + const rows = shape.rows; + const blocks = @max(t.remote(rows - 1), 1); + t.words = (blocks + 31) / 32; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + t.q = try t.a.alloc(u16, rows * D); + t.kb = try t.a.alloc(f32, blocks * D); + t.v = try t.a.alloc(f64, blocks); + t.e = try t.a.alloc(f64, blocks); + t.cand = try t.a.alloc(bool, blocks); + if (fill == .stress) { + // q's halves mirror with the sign turned, keys' too, dim 64 moved by a distinct integer: huge partials + const shift = try t.a.alloc(u32, blocks); + defer t.a.free(shift); + for (shift, 0..) |*x, i| x.* = @intCast(i); + rng.shuffle(u32, shift); + for (0..rows) |r| for (0..D / 2) |d| { + const x: f32 = if (d == 0) 1 else @floatFromInt(1 + rng.uintLessThan(u32, 7)); + t.q[r * D + d] = c.toBf16(x); + t.q[r * D + D / 2 + d] = c.toBf16(-x); + }; + for (0..blocks) |b| for (0..D / 2) |d| { + const x: f32 = @floatFromInt(128 + rng.uintLessThan(u32, 128)); + t.kb[b * D + d] = x; + t.kb[b * D + D / 2 + d] = x - @as(f32, if (d == 0) @floatFromInt(shift[b]) else 0); + }; + } else { + k.fillBf16(rng, t.q, 1); + for (t.kb) |*x| x.* = (rng.float(f32) * 2 - 1) * 0.5; + } + // mask 0 holds no block (its rows fall back to every remote block); the rest about a third each + t.masks = try t.a.alloc(u32, masks_n * t.words); + for (t.masks, 0..) |*w, i| w.* = if (i < t.words) 0 else rng.int(u32) & rng.int(u32) | rng.int(u32) & rng.int(u32) & rng.int(u32); + t.qmask = try t.a.alloc(i32, rows); + for (t.qmask) |*m| m.* = @as(i32, @intCast(rng.uintLessThan(u32, masks_n + 1))) - 1; + if (fill == .nonfinite) { + // row 0's query NaN; block 2 +Inf where every query weighs it up, block 3 NaN; both candidates for all + for (t.q[0..D]) |*x| x.* = c.toBf16(k.nan32); + for (1..rows) |r| t.q[r * D + 7] = c.toBf16(1); + if (blocks > 3) { + t.kb[2 * D + 7] = k.inf32; + t.kb[3 * D + 9] = k.nan32; + } + @memset(t.qmask, -1); + } + t.ins[0] = try t.rig.input(std.mem.sliceAsBytes(t.q)); + t.ins[1] = try t.rig.input(std.mem.sliceAsBytes(t.kb)); + t.ins[2] = try t.rig.input(std.mem.sliceAsBytes(t.masks)); + t.ins[3] = try t.rig.input(std.mem.sliceAsBytes(t.qmask)); + t.bias = try t.rig.output(rows * keep_n * 4); + t.sel = try t.rig.output(rows * keep_n * 4); + return true; + } + + pub fn run(t: *Route) !void { + const p = t.rig.begin(); + p.e.setPipeline(t.pipe); + for (t.ins, 0..) |r, i| p.e.setBuffer(r.buf, r.off, i); + p.e.setBuffer(t.sel.buf, t.sel.off, 4); + p.e.setBuffer(t.bias.buf, t.bias.off, 5); + p.e.setValue(extern struct { pos0: u32, words: u32 }{ .pos0 = @intCast(t.pos0()), .words = @intCast(t.words) }, 6); + p.e.dispatchGroups(mtl.Size.of(t.shape.rows, 1, 1), mtl.Size.of(256, 1, 1)); + try t.rig.finish(p); + } + + pub fn count(t: *Route) usize { + return t.shape.rows * keep_n; + } + + /// Row r's scores (dots in `acc`, `order`), their error bounds and candidates; returns the remote count. + fn scores(t: *Route, r: usize, acc: c.Accum, order: g.Order) usize { + const n = t.remote(r); + var terms: [D]f64 = undefined; + var own: usize = 0; + for (0..n) |b| { + var dot: f64 = 0; + var m: f64 = 0; + for (&terms, 0..) |*x, d| { + x.* = @as(f64, c.fromBf16(t.q[r * D + d])) * t.kb[b * D + d]; + dot += x.*; + m += @abs(x.*); + } + if (acc != .none) dot = contract.rows.sumIn(acc, order, &terms); + const z = clampNan(dot * k.inv_sqrt_hd); + t.v[b] = z * k.router_scale; + const chain = if (t.fill == .stress or !std.math.isFinite(m)) 0 else c.gamma(D, u) * m * k.inv_sqrt_hd; + t.e[b] = (chain + u * @abs(z)) * k.router_scale + u * @abs(t.v[b]); + const mk = t.qmask[r]; + t.cand[b] = mk < 0 or (t.masks[@as(usize, @intCast(mk)) * t.words + b / 32] >> @intCast(b % 32)) & 1 != 0; + if (t.cand[b]) own += 1; + } + if (own == 0) @memset(t.cand[0..n], true); + return n; + } + + /// The best `want` candidates by score not in `skip`, best first, ties to the lower block; NaN never. + fn rank(t: *Route, n: usize, skip: []const u32, out: []u32) usize { + var got: usize = 0; + while (got < out.len) : (got += 1) { + var best: ?usize = null; + for (0..n) |b| { + if (!t.cand[b] or std.math.isNan(t.v[b])) continue; + if (std.mem.indexOfScalar(u32, skip, @intCast(b)) != null or std.mem.indexOfScalar(u32, out[0..got], @intCast(b)) != null) continue; + if (best == null or t.v[b] > t.v[best.?]) best = b; + } + out[got] = @intCast(best orelse break); + } + return got; + } + + /// Exact biases for picks `sel` (the first `keep`) and ranked extras `more` (to 16 in all). + fn biases(t: *Route, sel: []const u32, more: []const u32, out: *[keep_n]f64) void { + var buf: [rank_n]f64 = undefined; + var tau: [rank_n]f64 = undefined; + const xs = buf[0 .. sel.len + more.len]; + const top = t.sorted(sel, more, xs); + const ts = tau[thresholds(xs, tau[0..xs.len])]; + var mu: f64 = 0; + @memset(out, 0); + for (sel, 0..) |b, i| { + const y = @max((t.v[b] - top) / 2 - ts, 0); + out[i] = @log(@max(y * y, floor)); + mu += out[i]; + } + mu /= @floatFromInt(@max(sel.len, 1)); + for (out[0..sel.len]) |*x| x.* -= mu; + } + + /// The picks' and extras' values sorted, less the largest, halved: the entmax's X. Returns the largest. + fn sorted(t: *Route, sel: []const u32, more: []const u32, xs: []f64) f64 { + for (sel, xs[0..sel.len]) |b, *x| x.* = t.v[b]; + for (more, xs[sel.len..]) |b, *x| x.* = t.v[b]; + std.mem.sort(f64, xs, {}, std.sort.desc(f64)); + const top = xs[0]; + for (xs) |*x| x.* = (x.* - top) / 2; + return top; + } + + /// Each pick's bias interval: scores off by their bounds, threshold errors, near-tie supports, logs, mean. + fn intervals(t: *Route, sel: []const u32, more: []const u32, out: *[keep_n]Range) void { + var buf: [rank_n]f64 = undefined; + var tau: [rank_n]f64 = undefined; + var err: [rank_n]f64 = undefined; + const n = sel.len + more.len; + const xs = buf[0..n]; + const top = t.sorted(sel, more, xs); + var worst: f64 = 0; + var big: f64 = 0; + for (sel) |b| worst = @max(worst, t.e[b]); + for (more) |b| worst = @max(worst, t.e[b]); + for (xs) |x| big = @max(big, @abs(x)); + const ex = 2 * worst + u * big; + const at = thresholds(xs, tau[0..n]); + thresholdErrors(xs, ex, err[0..n]); + var lo: usize = 0; + var hi: usize = 0; + for (xs, tau[0..n], err[0..n]) |x, tt, e| { + if (tt - x <= -(e + ex)) lo += 1; + if (tt - x <= e + ex) hi += 1; + } + var ets: f64 = 0; + for (@max(lo, 1)..@max(hi, 1) + 1) |s| ets = @max(ets, @abs(tau[s - 1] - tau[at]) + err[s - 1]); + const ts = tau[at]; + var mu = Range.point(0); + for (sel, 0..) |b, i| { + const x = (t.v[b] - top) / 2; + const ylo = @max(x - ex - ts - ets, 0) * (1 - 2 * u); + const yhi = @max(x + ex - ts + ets, 0) * (1 + 2 * u); + const l = Range{ .lo = @log(@max(ylo * (1 - u) * ylo, floor)), .hi = @log(@max(yhi * (1 + u) * yhi, floor)) }; + out[i] = l.widen(4 * u * @max(@abs(l.lo), @abs(l.hi)) + 0x1p-22); + mu = mu.add(out[i]); + } + const kn: f64 = @floatFromInt(@max(sel.len, 1)); + mu = (Range{ .lo = mu.lo / kn, .hi = mu.hi / kn }).fp32(3); + for (out[0..sel.len]) |*r| r.* = (Range{ .lo = r.lo - mu.hi, .hi = r.hi - mu.lo }).fp32(1); + } + + fn outputs(t: *Route, acc: c.Accum, order: g.Order, want: []f64) void { + var sel: [rank_n]u32 = undefined; + var out: [keep_n]f64 = undefined; + for (0..t.shape.rows) |r| { + const n = t.rank(t.scores(r, acc, order), &.{}, &sel); + const kept = @min(n, keep_n); + t.biases(sel[0..kept], sel[kept..n], &out); + @memcpy(want[r * keep_n ..][0..keep_n], &out); + } + } + + pub fn reference(t: *Route, want: []f64, mag: []f64) !void { + t.outputs(.none, .sequential, want); + for (mag, want) |*m, w| m.* = @abs(w); + } + + pub fn simulate(t: *Route, acc: c.Accum, order: g.Order, out: []f64) !void { + t.outputs(acc, order, out); + } + + /// Gate 4's allowance: the interval about the exact biases at the exact picks. + pub fn bounds(t: *Route, want: []const f64, _: []const f64, allow: []f64) !void { + var sel: [rank_n]u32 = undefined; + var r_: [keep_n]Range = undefined; + for (0..t.shape.rows) |r| { + const n = t.rank(t.scores(r, .none, .sequential), &.{}, &sel); + const kept = @min(n, keep_n); + t.intervals(sel[0..kept], sel[kept..n], &r_); + for (0..keep_n) |i| { + const j = r * keep_n + i; + allow[j] = if (i < kept) @max(k.spread(want[j], r_[i]), 0x1p-149) else 0x1p-149; + } + } + } + + fn say(t: *Route, comptime fmt: []const u8, args: anytype) []const u8 { + return std.fmt.bufPrint(&t.msg, fmt, args) catch "check failed (message too long)"; + } + + /// The kernel's picks and biases, row by row (gates 1 and 3). + pub fn check(t: *Route, _: g.Gate) !?[]const u8 { + const bias = t.rig.bytes(t.bias, t.count() * 4); + const picked = std.mem.bytesAsSlice(u32, t.rig.bytes(t.sel, t.count() * 4)); + var want: [rank_n]u32 = undefined; + var more: [rank_n]u32 = undefined; + var r_: [keep_n]Range = undefined; + for (0..t.shape.rows) |r| { + const n = t.scores(r, .none, .sequential); + const kept = @min(t.rank(n, &.{}, &want), keep_n); + const sel: []const u32 = @alignCast(picked[r * keep_n ..][0..keep_n]); + var got: usize = 0; + while (got < keep_n and sel[got] != none) got += 1; + if (got != kept) return t.say("row {d}: {d} blocks read where {d} candidates allow {d}", .{ r, got, n, kept }); + for (sel[got..], got..) |b, i| { + if (b != none) return t.say("row {d} slot {d}: block {d} after the last pick", .{ r, i, b }); + if (c.read(.f32, bias, r * keep_n + i) != 0) return t.say("row {d} slot {d}: an unused bias is not 0", .{ r, i }); + } + for (sel[0..got], 0..) |b, i| { + if (b >= n or !t.cand[b] or std.math.isNan(t.v[b])) return t.say("row {d} pick {d}: block {d} is no candidate", .{ r, i, b }); + if (std.mem.indexOfScalar(u32, sel[0..i], b) != null) return t.say("row {d} pick {d}: block {d} picked twice", .{ r, i, b }); + if (i > 0 and t.v[b] > t.v[sel[i - 1]] + t.e[b] + t.e[sel[i - 1]]) return t.say("row {d} pick {d}: block {d} ranks above the pick before it", .{ r, i, b }); + } + if (got == 0) continue; + const last = sel[got - 1]; + for (0..n) |b| if (t.cand[b] and !std.math.isNan(t.v[b]) and std.mem.indexOfScalar(u32, sel[0..got], @intCast(b)) == null) { + if (got == keep_n and t.v[b] > t.v[last] + t.e[b] + t.e[last]) return t.say("row {d}: block {d} beats the last pick {d} but is not read", .{ r, b, last }); + }; + const extra = t.rank(n, sel[0..got], more[0 .. rank_n - got]); + t.intervals(sel[0..got], more[0..extra], &r_); + for (r_[0..got], 0..) |iv, i| { + const x = c.read(.f32, bias, r * keep_n + i); + if (!(x >= iv.lo and x <= iv.hi)) return t.say("row {d} pick {d} (block {d}): bias {e:.6} outside [{e:.6}, {e:.6}]", .{ r, i, sel[i], x, iv.lo, iv.hi }); + } + } + return null; + } +}; + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + probes: std.ArrayList(*Route) = .empty, + + pub fn collect(s: *Suite, only: ?[]const u8) !void { + for ([_]Mutation{ .none, .route_no_mean }) |m| { + const x = try s.a.create(Route); + x.* = try Route.init(s.a, s.device, s.queue, m); + const kern = x.kernel(); + if (!k.wanted(only, kern.spec.name)) { + x.deinit(); + s.a.destroy(x); + continue; + } + try s.probes.append(s.a, x); + try s.kernels.append(s.a, kern); + } + } + + pub fn deinit(s: *Suite) void { + for (s.probes.items) |x| { + x.deinit(); + s.a.destroy(x); + } + s.probes.deinit(s.a); + } +}; + +/// Gate 5's texts for this group's launch. +pub fn limitsText(_: std.mem.Allocator, _: mtl.Device, name: []const u8) !?k.Texts { + return k.limitsText(name, &.{"ud_route"}); +} diff --git a/zig/tests/contract/metal_uocr_vision.zig b/zig/tests/contract/metal_uocr_vision.zig new file mode 100644 index 00000000000..8dd25a3447f --- /dev/null +++ b/zig/tests/contract/metal_uocr_vision.zig @@ -0,0 +1,178 @@ +//! Unlimited-OCR-2's image-encoder kernels (uv_*) under the contract: the shared source, controls and helpers. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const hub = @import("metal_uocr.zig"); +const glue = @import("metal_uocr_vision_glue.zig"); +const maps = @import("metal_uocr_vision_maps.zig"); +const attn = @import("metal_uocr_vision_attn.zig"); + +const c = contract.spec; +const g = contract.gates; + +/// A planted control: vision.metal with one fault, which one gate must report. +pub const Mutation = enum { + none, + add_subtracts, + add_writes_input, + bias_next_column, + norm_mean_over_threads, + gelu_wrong_scale, + quick_gelu_unrounded, + concat_left_twice, + embed_own_row, + cols_pad_down, + window_transposed, + unwindow_no_add, + rel_mirrored, + rel_half_sums, + attention_row_by_column, + attention_nan_skipped, + + pub fn name(m: Mutation) []const u8 { + return switch (m) { + .none => "", + .add_subtracts => "control: uocr vision uv_add, the rows are subtracted", + .add_writes_input => "control: uocr vision uv_add, each sum is also written over its first input", + .bias_next_column => "control: uocr vision uv_bias, each column takes the next column's bias", + .norm_mean_over_threads => "control: uocr vision uv_layer_norm, the mean divides by the threads, not the width", + .gelu_wrong_scale => "control: uocr vision uv_gelu, erf's argument is x times 0.75, not 1 / sqrt 2", + .quick_gelu_unrounded => "control: uocr vision uv_quick_gelu, the sigmoid is not rounded to bf16", + .concat_left_twice => "control: uocr vision uv_concat, the right half repeats the left rows", + .embed_own_row => "control: uocr vision uv_clip_embed, row r adds SAM's row r - 2, not r - 1", + .cols_pad_down => "control: uocr vision uv_im2col, the rows are offset by the padding the wrong way", + .window_transposed => "control: uocr vision uv_window, each window's rows and columns are swapped", + .unwindow_no_add => "control: uocr vision uv_unwindow_add, the window rows replace the map's", + .rel_mirrored => "control: uocr vision uv_rel_pos, the offsets are mirrored (key minus query)", + .rel_half_sums => "control: uocr vision uv_rel_pos, the dot summed in half", + .attention_row_by_column => "control: uocr vision uv_attention, the row term is read at the key's column", + .attention_nan_skipped => "control: uocr vision uv_attention, a NaN score weighs 0", + }; + } + + /// The gate that must go red. + pub fn gate(m: Mutation) ?g.Gate { + return switch (m) { + .none => null, + .add_writes_input => .repeat, + .rel_half_sums => .sums, + .attention_nan_skipped => .nonfinite, + else => .shapes, + }; + } + + const Edit = struct { from: []const u8, to: []const u8 }; + + fn edit(m: Mutation) Edit { + return switch (m) { + .none => unreachable, + .add_subtracts => .{ .from = "y[i] = bfloat(float(a[i]) + float(b[i]));", .to = "y[i] = bfloat(float(a[i]) - float(b[i]));" }, + .add_writes_input => .{ .from = "y[i] = bfloat(float(a[i]) + float(b[i]));", .to = "y[i] = bfloat(float(a[i]) + float(b[i])); const_cast(a)[i] = y[i];" }, + .bias_next_column => .{ .from = "y[i] = bfloat(c[i] + float(b[at.x]));", .to = "y[i] = bfloat(c[i] + float(b[(at.x + 1) % width]));" }, + .norm_mean_over_threads => .{ .from = "uv_sum(s, part, n, lane, sg) / float(p.width);", .to = "uv_sum(s, part, n, lane, sg) / float(n);" }, + .gelu_wrong_scale => .{ .from = "uv_erf(v * 0.70710678118654752f)", .to = "uv_erf(v * 0.75f)" }, + .quick_gelu_unrounded => .{ .from = "const float s = uv_bf(1.0f / (1.0f + metal::precise::exp(-z)));", .to = "const float s = 1.0f / (1.0f + metal::precise::exp(-z));" }, + .concat_left_twice => .{ .from = ": b[ulong(at.y) * p.right + at.x - p.left];", .to = ": a[ulong(at.y) * p.left + (at.x - p.left) % p.left];" }, + .embed_own_row => .{ .from = "float(sam[ulong(at.y - 1) * width + at.x]);", .to = "float(sam[ulong(at.y > 1 ? at.y - 2 : 0) * width + at.x]);" }, + .cols_pad_down => .{ .from = "const int iy = int((at.y / p.out_side) * p.stride + t / p.span) - int(p.pad);", .to = "const int iy = int((at.y / p.out_side) * p.stride + t / p.span) + int(p.pad);" }, + .window_transposed => .{ .from = "(w / across) * p.window + i / p.window, c = (w % across) * p.window + i % p.window;", .to = "(w / across) * p.window + i % p.window, c = (w % across) * p.window + i / p.window;" }, + .unwindow_no_add => .{ .from = "x[to] = bfloat(float(x[to]) + float(win[", .to = "x[to] = bfloat(float(win[" }, + .rel_mirrored => .{ .from = "const uint from = (across ? i % p.side : i / p.side) + p.side - 1 - j;", .to = "const uint from = j + p.side - 1 - (across ? i % p.side : i / p.side);" }, + .rel_half_sums => .{ .from = "s = fma(float(q[c]), float(r[c]), s);", .to = "s = float(half(fma(float(q[c]), float(r[c]), s)));" }, + .attention_row_by_column => .{ .from = "s += float(bfloat(float(rel_h[at + key / p.side])", .to = "s += float(bfloat(float(rel_h[at + key % p.side])" }, + .attention_nan_skipped => .{ .from = "const float w = key < p.len ? metal::precise::exp(", .to = "const float w = key < p.len && !isnan(stage[at]) ? metal::precise::exp(" }, + }; + } +}; + +/// vision.metal with the control's one edit (a copy either way); an edit that finds nothing errors. +pub fn source(a: std.mem.Allocator, m: Mutation) ![]u8 { + const text = hub.source(.vision); + if (m == .none) return a.dupe(u8, text); + const e = m.edit(); + if (std.mem.count(u8, text, e.from) != 1) return error.ControlEditMissing; + return std.mem.replaceOwned(u8, a, text, e.from, e.to); +} + +/// A vision kernel compiled as families/uocr/kernels.zig compiles it (MLX's options), with the control's edit. +pub fn pipeline(a: std.mem.Allocator, device: mtl.Device, name: []const u8, m: Mutation) !mtl.Pipeline { + if (m == .none) return hub.pipeline(device, .vision, name); + const src = try source(a, m); + defer a.free(src); + const lib = try mtl.Library.fromSource(device, src, mtl.CompileOptions.mlx()); + defer lib.deinit(); + return mtl.Pipeline.init(device, lib, name, false); +} + +/// A kernel's spec renamed and marked for a control built with `m`. +pub fn mark(k: g.Kernel, m: Mutation) g.Kernel { + var out = k; + if (m != .none) { + out.spec.name = m.name(); + out.control = m.gate(); + } + return out; +} + +/// A value's spread through fp32 steps and bf16 rounding points. +pub const Range = struct { + lo: f64, + hi: f64, + pub fn point(v: f64) Range { + return .{ .lo = v, .hi = v }; + } + /// Each end moved by `e` either way. + pub fn widen(r: Range, e: f64) Range { + return .{ .lo = r.lo - e, .hi = r.hi + e }; + } + /// Each end rounded to bf16, as the kernel rounds a value it stores. + pub fn bf16(r: Range) Range { + return .{ .lo = hub.bf(r.lo), .hi = hub.bf(r.hi) }; + } + /// Times an exact value of either sign. + pub fn times(r: Range, v: f64) Range { + return .{ .lo = @min(r.lo * v, r.hi * v), .hi = @max(r.lo * v, r.hi * v) }; + } +}; + +/// The allowance a range gives about `want`: the farther end. +pub fn spread(want: f64, r: Range) f64 { + return @max(@abs(want - r.lo), @abs(r.hi - want)); +} + +/// bf16 bits of random values in [lo, hi). +pub fn fill(rng: std.Random, out: []u16, lo: f32, hi: f32) void { + for (out) |*v| v.* = c.toBf16(lo + rng.float(f32) * (hi - lo)); +} + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + glue: glue.Suite = undefined, + maps: maps.Suite = undefined, + attn: attn.Suite = undefined, + + pub fn collect(s: *Suite, only: ?[]const u8) !void { + inline for (.{ "glue", "maps", "attn" }) |f| { + @field(s, f) = .{ .a = s.a, .device = s.device, .queue = s.queue, .kernels = s.kernels }; + try @field(s, f).collect(only); + } + } + pub fn deinit(s: *Suite) void { + inline for (.{ "glue", "maps", "attn" }) |f| @field(s, f).deinit(); + } +}; + +/// Gate 5's texts for this group's registrations (`uocr vision ...`): vision.metal as is, on every chip. +pub fn limitsText(_: std.mem.Allocator, _: mtl.Device, name: []const u8) !?hub.Texts { + if (!std.mem.startsWith(u8, name, "uocr vision ")) return null; + return .{ .here = hub.source(.vision), .pre_m5 = hub.source(.vision) }; +} + +/// Whether `only` (tf-kernel-contract's --only) selects a kernel named `name`. +pub fn wanted(only: ?[]const u8, name: []const u8) bool { + const o = only orelse return true; + return std.mem.indexOf(u8, name, o) != null; +} diff --git a/zig/tests/contract/metal_uocr_vision_attn.zig b/zig/tests/contract/metal_uocr_vision_attn.zig new file mode 100644 index 00000000000..1e5c83f099c --- /dev/null +++ b/zig/tests/contract/metal_uocr_vision_attn.zig @@ -0,0 +1,348 @@ +//! The image encoder's attention under the contract (SAM's blocks, CLIP's rows): bf16 outputs in float64's range. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); +const hub = @import("metal_uocr.zig"); +const v = @import("metal_uocr_vision.zig"); + +const c = contract.spec; +const g = contract.gates; +const rows = contract.rows; +const ar = contract.attention_range; +const Mutation = v.Mutation; + +const dh = 64; +/// Keys a softmax block: the kernel's running top score is per block. +const block = 512; +const u: f64 = 0x1p-24; +/// A score's dot: 64 terms summed in any order, at most 64 roundings of their magnitude. +const score_dot = 64; + +/// A simulated accumulator and its order (gate 4). +const Sum = struct { c.Accum, g.Order }; + +pub const Kind = enum { sam, clip }; + +/// A score's dot of 64 terms in any order (the 8 x 8 simdgroup products and their chain over the head). +fn depth(_: c.Shape) usize { + return dh; +} + +/// Rows: a group's rows; n: heads; k: groups. SAM's scores add terms by key row and column (side^2 >= rows). +pub fn spec(k: Kind) c.Spec { + return switch (k) { + // 1024 and tile windows, a tile's global blocks, the 1024 view's at 2 of 12 heads (float64's cost) + .sam => .{ .name = "uocr vision uv_attention SAM (relative positions)", .accum = .f32, .depth = depth, .out = .bf16, .served = &.{ .{ .rows = 196, .n = 12, .k = 25 }, .{ .rows = 196, .n = 12, .k = 9 }, .{ .rows = 1600, .n = 12, .k = 1 }, .{ .rows = 4096, .n = 2, .k = 1 } }, .sums = .{ .exact = true } }, + // CLIP-L's rows on the 1024 view and on a tile + .clip => .{ .name = "uocr vision uv_attention CLIP", .accum = .f32, .depth = depth, .out = .bf16, .served = &.{ .{ .rows = 257, .n = 16, .k = 1 }, .{ .rows = 101, .n = 16, .k = 1 } }, .sums = .{ .exact = true } }, + }; +} + +fn sideOf(n: usize) usize { + var s: usize = 1; + while (s * s < n) s += 1; + return s; +} + +const Params = extern struct { groups: u32, len: u32, heads: u32, width: u32, side: u32, scale: f32 }; + +pub const Attn = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + kind: Kind, + m: Mutation, + pipe: mtl.Pipeline, + p: Params = undefined, + stressed: bool = false, + qkv: []u16 = &.{}, + rel: [2][]u16 = .{ &.{}, &.{} }, + point: []f64 = &.{}, + half: []f64 = &.{}, + ins: [3]rig_.Ref = undefined, + out: rig_.Ref = undefined, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kind: Kind, m: Mutation) !Attn { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .kind = kind, .m = m, .pipe = try v.pipeline(a, device, "uv_attention", m) }; + } + pub fn deinit(t: *Attn) void { + t.free(); + t.rig.deinit(); + t.pipe.deinit(); + } + fn free(t: *Attn) void { + t.a.free(t.qkv); + for (&t.rel) |*r| t.a.free(r.*); + t.a.free(t.point); + t.a.free(t.half); + t.qkv = &.{}; + t.rel = .{ &.{}, &.{} }; + t.point = &.{}; + t.half = &.{}; + } + pub fn kernel(t: *Attn) g.Kernel { + return v.mark(.{ .spec = spec(t.kind), .ctx = t, .vt = &vt }, t.m); + } + const vt = g.hooks(Attn); + + fn rowsTotal(t: *const Attn) usize { + return t.p.groups * t.p.len; + } + + pub fn prepare(t: *Attn, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n == 0 or shape.k == 0) return false; + t.rig.reset(); + t.free(); + const side: usize = if (t.kind == .sam) sideOf(shape.rows) else 0; + t.p = .{ .groups = @intCast(shape.k), .len = @intCast(shape.rows), .heads = @intCast(shape.n), .width = @intCast(shape.n * dh), .side = @intCast(side), .scale = 0.125 }; + t.stressed = fill == .stress; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const n = t.rowsTotal(); + const w = t.p.width; + t.qkv = try t.a.alloc(u16, n * 3 * w); + for (0..n) |r| { + const row = t.qkv[r * 3 * w ..][0 .. 3 * w]; + v.fill(rng, row[0 .. 2 * w], -2, 2); + v.fill(rng, row[2 * w ..], -4, 4); + } + const nrel = if (side > 0) t.p.heads * n * side else 1; + for (&t.rel) |*r| { + r.* = try t.a.alloc(u16, nrel); + for (r.*) |*x| x.* = c.toBf16(if (t.stressed or side == 0) 0 else rng.float(f32) * 4 - 2); + } + if (t.stressed) t.stress(rng); + if (fill == .nonfinite) { + const P = hub.planted; + t.qkv[3] = c.toBf16(P[0]); // row 0's query, head 0: its row NaN + t.qkv[2 * 3 * w + w + 1] = c.toBf16(P[1]); // key 2, head 0: +inf or -inf scores by each query's sign + t.qkv[4 * 3 * w + w + 2] = c.toBf16(P[0]); // key 4, head 0: a NaN score in every row + t.qkv[5 * 3 * w + 2 * w + 7] = c.toBf16(P[2]); // value 5, head 0: -inf in column 7 + if (side > 0) t.rel[0][1 * side] = c.toBf16(P[0]); // row 1's term for key row 0 + } + t.ins[0] = try t.rig.input(std.mem.sliceAsBytes(t.qkv)); + t.ins[1] = try t.rig.input(std.mem.sliceAsBytes(t.rel[0])); + t.ins[2] = try t.rig.input(std.mem.sliceAsBytes(t.rel[1])); + t.out = try t.rig.output(n * w * 2); + try t.ranges(); + return true; + } + + /// Gate 4's q, k: integers 128-255 (partial dots to 2^21), k's halves negated mirrors (2 dims nudged). + fn stress(t: *Attn, rng: std.Random) void { + const w = t.p.width; + for (0..t.rowsTotal()) |r| for (0..t.p.heads) |h| { + const q = t.qkv[r * 3 * w + h * dh ..][0..dh]; + const k = t.qkv[r * 3 * w + w + h * dh ..][0..dh]; + for (0..dh / 2) |e| { + q[e] = c.toBf16(@floatFromInt(128 + rng.uintLessThan(u32, 128))); + q[dh - 1 - e] = q[e]; + const x: f32 = @floatFromInt(128 + rng.uintLessThan(u32, 128)); + const nudge: f32 = if (e < 2) @floatFromInt(@as(i32, @intCast(rng.uintLessThan(u32, 3))) - 1) else 0; + k[e] = c.toBf16(x); + k[dh - 1 - e] = c.toBf16(nudge - x); + } + }; + } + + pub fn run(t: *Attn) !void { + const p = t.rig.begin(); + const e = p.e; + e.setPipeline(t.pipe); + for (t.ins, 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setBuffer(t.out.buf, t.out.off, 3); + e.setValue(t.p, 4); + e.dispatchGroups(mtl.Size.of((t.p.len + 31) / 32, t.p.heads, t.p.groups), mtl.Size.of(128, 1, 1)); + try t.rig.finish(p); + } + + pub fn count(t: *Attn) usize { + return t.rowsTotal() * t.p.width; + } + + fn val(t: *const Attn, row: usize, part: usize, h: usize, e: usize) f64 { + const w = t.p.width; + return c.fromBf16(t.qkv[row * 3 * w + part * w + h * dh + e]); + } + + /// Row `row`'s score against key `key` of head h and its terms' magnitude; `sum` simulates the dot's accumulator. + fn score(t: *const Attn, row: usize, key: usize, h: usize, sum: ?Sum) [2]f64 { + var terms: [dh]f64 = undefined; + var mag: f64 = 0; + var dot: f64 = 0; + for (&terms, 0..) |*x, e| { + x.* = t.val(row, 0, h, e) * t.val(key, 1, h, e); + mag += @abs(x.*); + dot += x.*; + } + if (sum) |s| dot = rows.sumIn(s[0], s[1], &terms); + var s = t.p.scale * dot; + var bias: f64 = 0; + if (t.p.side > 0) { + const side = t.p.side; + const in = key % t.p.len; + const at = (h * t.rowsTotal() + row) * side; + // the two bf16 terms summed in fp32 and rounded to bf16, as the kernel adds them + const both: f32 = @floatCast(c.fromBf16(t.rel[0][at + in / side]) + c.fromBf16(t.rel[1][at + in % side])); + const term = c.fromBf16(c.toBf16(both)); + bias = @abs(term); + s += term; + } + return .{ s, t.p.scale * mag + bias }; + } + + const Job = struct { + t: *Attn, + first: usize, + stride: usize, + sum: ?Sum = null, + out: []f64, + err: ?anyerror = null, + + pub fn run(j: *Job) void { + j.work() catch |e| { + j.err = e; + }; + } + + fn work(j: *Job) !void { + const t = j.t; + const len = t.p.len; + const buf = try t.a.alloc(f64, 2 * len); + defer t.a.free(buf); + var item = j.first; + while (item < t.rowsTotal() * t.p.heads) : (item += j.stride) { + const h = item % t.p.heads; + const row = item / t.p.heads; + t.head(row, h, j.sum, buf[0..len], buf[len..], j.out); + } + } + }; + + /// A row of a head: float64's output (or simulated) and spread, as attention_range's, with rescales and bf16 P. + fn head(t: *Attn, row: usize, h: usize, sum: ?Sum, w: []f64, tau: []f64, sim: []f64) void { + const len = t.p.len; + const base = row - row % len; + const n: f64 = @floatFromInt(len); + var m: f64 = -std.math.inf(f64); + var dmax: f64 = 0; + const rescale = 9 * u * @as(f64, @floatFromInt((len - 1) / block)); + for (0..len) |j| { + const s = t.score(row, base + j, h, sum); + w[j] = s[0]; + // the dot's chain (none for gate 4's exact sums), then the scale and the two terms' adds + tau[j] = (if (t.stressed) 0 else score_dot * u * s[1]) + 3 * u * (@abs(s[0]) + s[1]) + rescale; + m = @max(m, w[j]); + if (std.math.isFinite(tau[j])) dmax = @max(dmax, tau[j]); + } + var l: f64 = 0; + var tmax: f64 = 0; + for (w, tau) |*p, *e| { + const x = (m - p.*) + 2 * dmax; + p.* = @exp(p.* - m); + l += p.*; + e.* = std.math.expm1(e.* + u * x + 4 * 0x1p-23); // precise::exp within 4 ulps, the subtraction's rounding + if (std.math.isFinite(e.*)) tmax = @max(tmax, e.*); + } + const big = tmax >= 0.5; + const kappa = (1 + tmax) / (1 - tmax); + const num = n + 8; // P x V: a chain over the keys, 8-term products + const den = n / 4 + 8; // a lane's 8 weights a step over the steps, two shuffles + for (0..dh) |e| { + var o: f64 = 0; + for (0..len) |j| o += w[j] * t.val(base + j, 2, h, e); + o /= l; + const at = row * t.p.width + h * dh + e; + if (sum != null) { + sim[at] = o; + continue; + } + t.point[at] = o; + if (!std.math.isFinite(o) or big) { + t.half[at] = if (big) std.math.inf(f64) else 0; + continue; + } + var r: f64 = 0; + var dv: f64 = 0; + for (0..len) |j| { + const x = t.val(base + j, 2, h, e); + r += w[j] * @abs(x); + dv += w[j] * tau[j] * @abs(x - o); + } + r /= l; + dv /= l; + const e1 = dv / (1 - tmax); + const en = gammaOf(num) * r * kappa; + const ep = 0x1p-9 * (1 + tmax) * r * kappa; // each weight's bf16 rounding, in the numerator alone + const all = @abs(o) + e1 + en + ep; + t.half[at] = (e1 + en + ep + (gammaOf(den) + u) * all) * (1 + 0x1p-20) + (n + 8) * 0x1p-120 * (1 + r); + } + } + + fn ranges(t: *Attn) !void { + t.point = try t.a.alloc(f64, t.count()); + t.half = try t.a.alloc(f64, t.count()); + try t.each(null, &.{}); + } + + fn each(t: *Attn, sum: ?Sum, sim: []f64) !void { + var jobs: [contract.reference_threads.maximum]Job = undefined; + const k = contract.reference_threads.count(contract.reference_threads.maximum, t.rowsTotal() * t.p.heads); + for (jobs[0..k], 0..) |*j, i| j.* = .{ .t = t, .first = i, .stride = k, .sum = sum, .out = sim }; + contract.reference_threads.run(Job, jobs[0..k], .normal); + for (jobs[0..k]) |j| if (j.err) |e| return e; + } + + pub fn reference(t: *Attn, want: []f64, mag: []f64) !void { + @memcpy(want, t.point); + @memset(mag, 0); + } + + pub fn bounds(t: *Attn, _: []const f64, _: []const f64, allow: []f64) !void { + for (allow, t.point, t.half) |*l, p, h| l.* = ar.allowBf16(p, h, 0, 0); + } + + pub fn intervals(t: *Attn, low: []f64, high: []f64) !void { + for (low, high, t.point, t.half) |*l, *h, p, hf| { + const e = ar.intervalBf16(p, hf, 0, 0); + l.* = e[0]; + h.* = e[1]; + } + } + + /// The outputs with every score's dot summed in `acc` in `order`, the rest exact (gate 4). + pub fn simulate(t: *Attn, acc: c.Accum, order: g.Order, out: []f64) !void { + try t.each(Sum{ acc, order }, out); + } +}; + +fn gammaOf(n: f64) f64 { + return n * u / (1 - n * u); +} + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + made: std.ArrayList(*Attn) = .empty, + + const controls = [_]struct { Kind, Mutation }{ .{ .sam, .attention_row_by_column }, .{ .clip, .attention_nan_skipped } }; + + fn one(s: *Suite, kind: Kind, m: Mutation, only: ?[]const u8) !void { + if (!v.wanted(only, if (m == .none) spec(kind).name else m.name())) return; + const x = try s.a.create(Attn); + x.* = try Attn.init(s.a, s.device, s.queue, kind, m); + try s.made.append(s.a, x); + try s.kernels.append(s.a, x.kernel()); + } + + pub fn collect(s: *Suite, only: ?[]const u8) !void { + for (std.enums.values(Kind)) |kind| try s.one(kind, .none, only); + for (controls) |ctl| try s.one(ctl[0], ctl[1], only); + } + pub fn deinit(s: *Suite) void { + for (s.made.items) |x| x.deinit(); + s.made.deinit(s.a); + } +}; diff --git a/zig/tests/contract/metal_uocr_vision_glue.zig b/zig/tests/contract/metal_uocr_vision_glue.zig new file mode 100644 index 00000000000..bd172811348 --- /dev/null +++ b/zig/tests/contract/metal_uocr_vision_glue.zig @@ -0,0 +1,323 @@ +//! The image encoder's glue under the contract: adds, biases, norms, GELUs and CLIP's embedding and concat rows. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); +const hub = @import("metal_uocr.zig"); +const v = @import("metal_uocr_vision.zig"); + +const c = contract.spec; +const g = contract.gates; +const rows = contract.rows; +const Mutation = v.Mutation; + +pub const Kind = enum { add, bias, concat, embed, gelu, quick_gelu, norm }; + +fn function(k: Kind) []const u8 { + return switch (k) { + .add => "uv_add", + .bias => "uv_bias", + .concat => "uv_concat", + .embed => "uv_clip_embed", + .gelu => "uv_gelu", + .quick_gelu => "uv_quick_gelu", + .norm => "uv_layer_norm", + }; +} + +/// Four inputs at most a thread in order (a 768- to 1,024-wide row over 256 threads), then two 32-way simd_sum trees. +fn normDepth(s: c.Shape) usize { + return (s.k + 255) / 256 + 10; +} + +const S = hub.sam_width; +const C = hub.clip_width; + +pub fn spec(k: Kind) c.Spec { + const flat: [3]c.Tile = .{ .{}, .{ .size = 256, .step = 1, .min = 1 }, .{} }; + return switch (k) { + // SAM's map (1024 view and tile) and CLIP's rows (1024 view and tile) + .add => .{ .name = "uocr vision uv_add", .accum = .none, .depth = hub.noSums, .ops = 1, .out = .bf16, .tiles = flat, .served = &.{ .{ .rows = 4096, .n = S, .k = 1 }, .{ .rows = 1600, .n = S, .k = 1 }, .{ .rows = 257, .n = C, .k = 1 }, .{ .rows = 101, .n = C, .k = 1 } } }, + // SAM's qkv over the padded windows, its MLP, CLIP's qkv and MLP, the projector + .bias => .{ .name = "uocr vision uv_bias", .accum = .none, .depth = hub.noSums, .ops = 1, .out = .bf16, .tiles = flat, .served = &.{ .{ .rows = 4900, .n = 3 * S, .k = 1 }, .{ .rows = 4096, .n = 4 * S, .k = 1 }, .{ .rows = 257, .n = 4 * C, .k = 1 }, .{ .rows = 100, .n = hub.hidden, .k = 1 } } }, + .concat => .{ .name = "uocr vision uv_concat", .accum = .none, .depth = hub.noSums, .out = .bf16, .served = &.{ .{ .rows = 256, .n = 2 * C, .k = 1 }, .{ .rows = 100, .n = 2 * C, .k = 1 } } }, + .embed => .{ .name = "uocr vision uv_clip_embed", .accum = .none, .depth = hub.noSums, .ops = 1, .out = .bf16, .served = &.{ .{ .rows = 257, .n = C, .k = 1 }, .{ .rows = 101, .n = C, .k = 1 } } }, + .gelu => .{ .name = "uocr vision uv_gelu (erf)", .accum = .none, .depth = hub.noSums, .ops = 6, .out = .bf16, .tiles = flat, .served = &.{ .{ .rows = 4096, .n = 4 * S, .k = 1 }, .{ .rows = 1600, .n = 4 * S, .k = 1 } } }, + .quick_gelu => .{ .name = "uocr vision uv_quick_gelu", .accum = .none, .depth = hub.noSums, .out = .bf16, .tiles = flat, .served = &.{ .{ .rows = 257, .n = 4 * C, .k = 1 }, .{ .rows = 101, .n = 4 * C, .k = 1 } } }, + // SAM's blocks (eps 1e-6), its neck's channel norms on rows of 256, CLIP's rows (eps 1e-5) + .norm => .{ .name = "uocr vision uv_layer_norm", .accum = .f32, .depth = normDepth, .ops = 8, .out = .bf16, .tiles = .{ .{}, .{}, .{ .size = 256, .step = 1, .min = 1 } }, .served = &.{ .{ .rows = 4096, .n = S, .k = S }, .{ .rows = 4096, .n = 256, .k = 256 }, .{ .rows = 257, .n = C, .k = C }, .{ .rows = 1600, .n = 256, .k = 256 } } }, + }; +} + +/// The served width a launch's eps belongs to: CLIP's 1,024-wide rows take 1e-5, SAM's 1e-6. +fn epsOf(width: usize) f32 { + return if (width == C) 1e-5 else 1e-6; +} + +pub const Glue = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + kind: Kind, + m: Mutation, + pipe: mtl.Pipeline, + shape: c.Shape = undefined, + /// Host inputs as bytes: up to three (bias: fp32 sums then bf16 bias; norm: x, w, b). + host: [3][]u8 = .{ &.{}, &.{}, &.{} }, + r: ?rows.Rows = null, + ins: [3]rig_.Ref = undefined, + out: rig_.Ref = undefined, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kind: Kind, m: Mutation) !Glue { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .kind = kind, .m = m, .pipe = try v.pipeline(a, device, function(kind), m) }; + } + pub fn deinit(t: *Glue) void { + t.free(); + t.rig.deinit(); + t.pipe.deinit(); + } + fn free(t: *Glue) void { + for (&t.host) |*h| { + t.a.free(h.*); + h.* = &.{}; + } + if (t.r) |r| r.deinit(); + t.r = null; + } + pub fn kernel(t: *Glue) g.Kernel { + return v.mark(.{ .spec = spec(t.kind), .ctx = t, .vt = &vt }, t.m); + } + const vt = g.hooks(Glue); + + fn halves(t: *Glue, i: usize) []u16 { + return @alignCast(std.mem.bytesAsSlice(u16, t.host[i])); + } + + fn bf16s(t: *Glue, i: usize, n: usize) ![]u16 { + t.host[i] = std.mem.sliceAsBytes(try t.a.alloc(u16, n)); + return t.halves(i); + } + + pub fn prepare(t: *Glue, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n == 0) return false; + if (t.kind == .concat and shape.n % 2 != 0) return false; + if (t.kind == .embed and shape.rows < 2) return false; + t.rig.reset(); + t.free(); + t.shape = shape; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const n = shape.rows * shape.n; + const nf = fill == .nonfinite; + const P = hub.planted; + switch (t.kind) { + .add => { + const x = try t.bf16s(0, n); + const y = try t.bf16s(1, n); + v.fill(rng, x, -4, 4); + v.fill(rng, y, -4, 4); + // a NaN, both infinities, and +inf meeting -inf (NaN) + if (nf and n > 4) { + x[1] = c.toBf16(P[0]); + x[2] = c.toBf16(P[1]); + y[3] = c.toBf16(P[2]); + x[4] = c.toBf16(P[1]); + y[4] = c.toBf16(P[2]); + } + }, + .bias => { + const cs = try t.a.alloc(f32, n); + for (cs) |*s| s.* = (rng.float(f32) * 2 - 1) * 8; + if (nf) for ([_]usize{ 1, 2 }, [_]f32{ P[0], P[1] }) |i, val| { + if (i < n) cs[i] = val; + }; + t.host[0] = std.mem.sliceAsBytes(cs); + const b = try t.bf16s(1, shape.n); + v.fill(rng, b, -2, 2); + if (nf) b[shape.n - 1] = c.toBf16(P[2]); + }, + .concat => { + for (0..2) |i| v.fill(rng, try t.bf16s(i, shape.rows * shape.n / 2), -4, 4); + if (nf) { + t.halves(0)[0] = c.toBf16(P[0]); + t.halves(1)[0] = c.toBf16(P[1]); + t.halves(1)[t.halves(1).len - 1] = c.toBf16(P[2]); + } + }, + .embed => { + v.fill(rng, try t.bf16s(0, shape.n), -1, 1); + v.fill(rng, try t.bf16s(1, (shape.rows - 1) * shape.n), -4, 4); + v.fill(rng, try t.bf16s(2, n), -1, 1); + if (nf) { + t.halves(0)[0] = c.toBf16(P[0]); + t.halves(1)[1] = c.toBf16(P[1]); + t.halves(2)[shape.n + 2] = c.toBf16(P[2]); + } + }, + .gelu, .quick_gelu => { + const x = try t.bf16s(0, n); + v.fill(rng, x, -8, 8); + if (nf) for (P, 0..) |val, i| { + if (i < n) x[i * 7 % n] = c.toBf16(val); + }; + }, + .norm => { + var r = try rows.Rows.init(t.a, .layer_norm, shape); + r.eps = epsOf(shape.k); + r.fill(fill, seed); + t.r = r; + t.ins[0] = try t.rig.input(std.mem.sliceAsBytes(r.x)); + t.ins[1] = try t.rig.input(std.mem.sliceAsBytes(r.w)); + t.ins[2] = try t.rig.input(std.mem.sliceAsBytes(r.b)); + t.out = try t.rig.output(r.outputs() * 2); + return true; + }, + } + for (t.host, 0..) |h, i| if (h.len > 0) { + t.ins[i] = try t.rig.input(h); + }; + t.out = try t.rig.output(t.count() * 2); + return true; + } + + pub fn run(t: *Glue) !void { + const s = t.shape; + const n: u32 = @intCast(s.rows * s.n); + const w: u32 = @intCast(s.n); + // the activations run in place: each launch starts from the prepared input copied into the output + if (t.kind == .gelu or t.kind == .quick_gelu) @memcpy(t.rig.bytes(t.out, n * 2), t.host[0]); + const p = t.rig.begin(); + const e = p.e; + e.setPipeline(t.pipe); + const tg = mtl.Size.of(256, 1, 1); + switch (t.kind) { + .add => { + for (t.ins[0..2], 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setBuffer(t.out.buf, t.out.off, 2); + e.setValue(n, 3); + e.dispatchThreads(mtl.Size.of(n, 1, 1), tg); + }, + .bias => { + for (t.ins[0..2], 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setBuffer(t.out.buf, t.out.off, 2); + e.setValue(w, 3); + e.dispatchThreads(mtl.Size.of(s.n, s.rows, 1), tg); + }, + .concat => { + for (t.ins[0..2], 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setBuffer(t.out.buf, t.out.off, 2); + e.setValue([3]u32{ @intCast(s.rows), w / 2, w / 2 }, 3); + e.dispatchThreads(mtl.Size.of(s.n, s.rows, 1), tg); + }, + .embed => { + for (t.ins, 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setBuffer(t.out.buf, t.out.off, 3); + e.setValue(w, 4); + e.dispatchThreads(mtl.Size.of(s.n, s.rows, 1), tg); + }, + .gelu, .quick_gelu => { + e.setBuffer(t.out.buf, t.out.off, 0); + e.setValue(n, 1); + e.dispatchThreads(mtl.Size.of(n, 1, 1), tg); + }, + .norm => { + for (t.ins, 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setBuffer(t.out.buf, t.out.off, 3); + e.setValue(extern struct { width: u32, eps: f32 }{ .width = @intCast(s.k), .eps = epsOf(s.k) }, 4); + e.dispatchGroups(mtl.Size.of(s.rows, 1, 1), tg); + }, + } + try t.rig.finish(p); + } + + pub fn count(t: *Glue) usize { + return if (t.kind == .norm) t.shape.rows * t.shape.k else t.shape.rows * t.shape.n; + } + + fn hv(t: *Glue, i: usize, at: usize) f64 { + return c.fromBf16(t.halves(i)[at]); + } + + /// quick_gelu's three bf16 points: z = bf16(fp32(1.702 x)), s = bf16(sigmoid z), bf16(x s). + fn quick(x: f64) [2]f64 { + const z = hub.bf(@as(f32, @floatCast(@as(f64, @as(f32, 1.702)) * x))); + return .{ z, hub.bf(1 / (1 + @exp(-z))) }; + } + + pub fn reference(t: *Glue, want: []f64, mag: []f64) !void { + if (t.r) |r| return r.reference(want, mag); + const w = t.shape.n; + for (want, mag, 0..) |*o, *m, i| { + m.* = 0; + o.* = switch (t.kind) { + .add => t.hv(0, i) + t.hv(1, i), + .bias => @as(f64, std.mem.bytesAsSlice(f32, t.host[0])[i]) + t.hv(1, i % w), + .concat => if (i % w < w / 2) t.hv(0, (i / w) * (w / 2) + i % w) else t.hv(1, (i / w) * (w / 2) + i % w - w / 2), + .embed => (if (i < w) t.hv(0, i) else t.hv(1, i - w)) + t.hv(2, i), + .gelu => rows.gelu(t.hv(0, i)), + .quick_gelu => blk: { + const x = t.hv(0, i); + break :blk hub.bf(x * quick(x)[1]); + }, + .norm => unreachable, + }; + } + } + + /// GELU's erf (under one ulp) and its fp32 steps: an absolute slack of x / 2 times 2^-22, where 1 + erf cancels. + pub fn bounds(t: *Glue, _: []const f64, _: []const f64, allow: []f64) !void { + if (t.kind != .gelu) return; + for (allow, 0..) |*l, i| l.* += rows.geluSlack(t.hv(0, i)); + } + + /// quick_gelu's range: the sigmoid's fp32 exp, add and divide (16 ulps), each bf16 point, the product's rounding. + pub fn intervals(t: *Glue, low: []f64, high: []f64) !void { + for (low, high, 0..) |*l, *hi, i| { + if (t.kind != .quick_gelu) { + l.* = -std.math.floatMax(f64); + hi.* = std.math.floatMax(f64); + continue; + } + const x = t.hv(0, i); + const z = quick(x)[0]; + const s = 1 / (1 + @exp(-z)); + const r = v.Range.point(s).widen(16 * 0x1p-24 * s).bf16().times(x).widen(0x1p-24 * @abs(x)).bf16(); + l.* = r.lo; + hi.* = r.hi; + } + } + + pub fn simulate(t: *Glue, acc: c.Accum, order: g.Order, out: []f64) !void { + return (t.r orelse return error.NoSums).simulate(acc, order, out); + } +}; + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + made: std.ArrayList(*Glue) = .empty, + + const controls = [_]struct { Kind, Mutation }{ + .{ .add, .add_subtracts }, .{ .add, .add_writes_input }, .{ .bias, .bias_next_column }, + .{ .norm, .norm_mean_over_threads }, .{ .gelu, .gelu_wrong_scale }, .{ .quick_gelu, .quick_gelu_unrounded }, + .{ .concat, .concat_left_twice }, .{ .embed, .embed_own_row }, + }; + + fn one(s: *Suite, kind: Kind, m: Mutation, only: ?[]const u8) !void { + if (!v.wanted(only, if (m == .none) spec(kind).name else m.name())) return; + const x = try s.a.create(Glue); + x.* = try Glue.init(s.a, s.device, s.queue, kind, m); + try s.made.append(s.a, x); + try s.kernels.append(s.a, x.kernel()); + } + + pub fn collect(s: *Suite, only: ?[]const u8) !void { + for (std.enums.values(Kind)) |kind| try s.one(kind, .none, only); + for (controls) |ctl| try s.one(ctl[0], ctl[1], only); + } + pub fn deinit(s: *Suite) void { + for (s.made.items) |x| x.deinit(); + s.made.deinit(s.a); + } +}; diff --git a/zig/tests/contract/metal_uocr_vision_maps.zig b/zig/tests/contract/metal_uocr_vision_maps.zig new file mode 100644 index 00000000000..ff51b4247e0 --- /dev/null +++ b/zig/tests/contract/metal_uocr_vision_maps.zig @@ -0,0 +1,345 @@ +//! The image encoder's map kernels under the contract: convolution rows, SAM's windows and its relative positions. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); +const hub = @import("metal_uocr.zig"); +const v = @import("metal_uocr_vision.zig"); + +const c = contract.spec; +const g = contract.gates; +const rows = contract.rows; +const Mutation = v.Mutation; + +const S = hub.sam_width; +const heads = 12; +const dh = 64; +const window = 14; + +/// Patches (16 x 16, planar pixels), the neck's 3 x 3 and stride-2 rows, the windows, the relative positions. +pub const Kind = enum { cols_patch, cols_neck, cols_down, window, unwindow, rel }; + +fn function(k: Kind) []const u8 { + return switch (k) { + .cols_patch, .cols_neck, .cols_down => "uv_im2col", + .window => "uv_window", + .unwindow => "uv_unwindow_add", + .rel => "uv_rel_pos", + }; +} + +/// A dot of 64 in one fma chain. +fn relDepth(_: c.Shape) usize { + return dh; +} + +/// Rows: output positions, map positions, or query rows (whole side^2 groups); n: a row's width or the side; k: head. +pub fn spec(k: Kind) c.Spec { + return switch (k) { + .cols_patch => .{ .name = "uocr vision uv_im2col 16 x 16 stride 16 (patches)", .accum = .none, .depth = hub.noSums, .out = .bf16, .served = &.{ .{ .rows = 4096, .n = 768, .k = 1 }, .{ .rows = 1600, .n = 768, .k = 1 } } }, + .cols_neck => .{ .name = "uocr vision uv_im2col 3 x 3 pad 1 (neck)", .accum = .none, .depth = hub.noSums, .out = .bf16, .served = &.{ .{ .rows = 4096, .n = 256 * 9, .k = 1 }, .{ .rows = 1600, .n = 256 * 9, .k = 1 } } }, + .cols_down => .{ .name = "uocr vision uv_im2col 3 x 3 stride 2 pad 1 (net_2, net_3)", .accum = .none, .depth = hub.noSums, .out = .bf16, .served = &.{ .{ .rows = 1024, .n = 256 * 9, .k = 1 }, .{ .rows = 256, .n = 512 * 9, .k = 1 }, .{ .rows = 400, .n = 256 * 9, .k = 1 }, .{ .rows = 100, .n = 512 * 9, .k = 1 } } }, + .window => .{ .name = "uocr vision uv_window 14", .accum = .none, .depth = hub.noSums, .out = .bf16, .served = &.{ .{ .rows = 4096, .n = S, .k = 1 }, .{ .rows = 1600, .n = S, .k = 1 } } }, + .unwindow => .{ .name = "uocr vision uv_unwindow_add 14", .accum = .none, .depth = hub.noSums, .ops = 1, .out = .bf16, .served = &.{ .{ .rows = 4096, .n = S, .k = 1 }, .{ .rows = 1600, .n = S, .k = 1 } } }, + // windows of the 1024 view and of a tile, the global blocks of each + .rel => .{ .name = "uocr vision uv_rel_pos (12 heads of 64)", .accum = .f32, .depth = relDepth, .out = .bf16, .served = &.{ .{ .rows = 25 * 196, .n = window, .k = dh }, .{ .rows = 9 * 196, .n = window, .k = dh }, .{ .rows = 4096, .n = 64, .k = dh }, .{ .rows = 1600, .n = 40, .k = dh } } }, + }; +} + +/// The least side whose square holds `n`. +fn sideOf(n: usize) usize { + var s: usize = 1; + while (s * s < n) s += 1; + return s; +} + +const Cols = extern struct { channels: u32, in_side: u32, out_side: u32, span: u32, stride: u32, pad: u32, cstride: u32, pstride: u32 }; +const Win = extern struct { side: u32, padded: u32, window: u32, channels: u32 }; +const Rel = extern struct { groups: u32, side: u32, heads: u32, width: u32 }; + +pub const Map = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + kind: Kind, + m: Mutation, + pipe: mtl.Pipeline, + shape: c.Shape = undefined, + cols: Cols = undefined, + win: Win = undefined, + rel: Rel = undefined, + host: [3][]u16 = .{ &.{}, &.{}, &.{} }, + ins: [3]rig_.Ref = undefined, + outs: [2]rig_.Ref = undefined, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kind: Kind, m: Mutation) !Map { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .kind = kind, .m = m, .pipe = try v.pipeline(a, device, function(kind), m) }; + } + pub fn deinit(t: *Map) void { + t.free(); + t.rig.deinit(); + t.pipe.deinit(); + } + fn free(t: *Map) void { + for (&t.host) |*h| { + t.a.free(h.*); + h.* = &.{}; + } + } + pub fn kernel(t: *Map) g.Kernel { + return v.mark(.{ .spec = spec(t.kind), .ctx = t, .vt = &vt }, t.m); + } + const vt = g.hooks(Map); + + fn input(t: *Map, i: usize, n: usize, rng: std.Random) ![]u16 { + t.host[i] = try t.a.alloc(u16, n); + v.fill(rng, t.host[i], -4, 4); + return t.host[i]; + } + + pub fn prepare(t: *Map, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n == 0) return false; + t.rig.reset(); + t.free(); + t.shape = shape; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const P = hub.planted; + const nf = fill == .nonfinite; + switch (t.kind) { + .cols_patch, .cols_neck, .cols_down => { + const out_side = sideOf(shape.rows); + const span: usize = if (t.kind == .cols_patch) 16 else 3; + const ch = shape.n / (span * span); + if (ch * span * span != shape.n) return false; + const stride: usize = switch (t.kind) { + .cols_patch => 16, + .cols_neck => 1, + else => 2, + }; + const in_side = out_side * stride; + const planar = t.kind == .cols_patch; + t.cols = .{ .channels = @intCast(ch), .in_side = @intCast(in_side), .out_side = @intCast(out_side), .span = @intCast(span), .stride = @intCast(stride), .pad = if (planar) 0 else 1, .cstride = @intCast(if (planar) in_side * in_side else 1), .pstride = @intCast(if (planar) 1 else ch) }; + const x = try t.input(0, ch * in_side * in_side, rng); + if (nf) for (P, 0..) |val, i| { + x[(i * 977) % x.len] = c.toBf16(val); + }; + }, + .window, .unwindow => { + const side = sideOf(shape.rows); + const padded = (side + window - 1) / window * window; + t.win = .{ .side = @intCast(side), .padded = @intCast(padded), .window = window, .channels = @intCast(shape.n) }; + const x = try t.input(0, side * side * shape.n, rng); + if (t.kind == .unwindow) _ = try t.input(1, padded * padded * shape.n, rng); + if (nf) for (P, 0..) |val, i| { + x[(i * 977) % x.len] = c.toBf16(val); + }; + if (nf and t.kind == .unwindow) t.host[1][0] = c.toBf16(P[1]); // with x's NaN at 0: NaN + }, + .rel => { + const side = shape.n; + const groups = @max(1, shape.rows / (side * side)); + t.rel = .{ .groups = @intCast(groups), .side = @intCast(side), .heads = heads, .width = S }; + const n = groups * side * side; + const qkv = try t.input(0, n * 3 * S, rng); + const rh = try t.input(1, (2 * side - 1) * dh, rng); + const rw = try t.input(2, (2 * side - 1) * dh, rng); + if (fill == .stress) stress(rng, qkv, rh, rw, n); + if (nf) { + qkv[5] = c.toBf16(P[0]); // row 0, head 0: every term of it NaN + rh[3] = c.toBf16(P[1]); // offset row 0: +inf where q's dim 3 is positive, -inf where negative + rw[dh + 1] = c.toBf16(P[2]); + } + }, + } + for (t.host, 0..) |h, i| if (h.len > 0) { + t.ins[i] = try t.rig.input(std.mem.sliceAsBytes(h)); + }; + if (t.kind == .rel) { + const each = t.count() / 2 * 2; + t.outs[0] = try t.rig.output(each); + t.outs[1] = try t.rig.output(each); + } else t.outs[0] = try t.rig.output(t.count() * 2); + return true; + } + + /// Gate 4's q, tables: integers 128-255 (partial sums to 2^21), rows' halves negated mirrors (2 dims nudged). + fn stress(rng: std.Random, qkv: []u16, rh: []u16, rw: []u16, n: usize) void { + for (0..n) |r| for (0..heads) |h| { + const q = qkv[r * 3 * S + h * dh ..][0..dh]; + for (0..dh / 2) |e| { + q[e] = c.toBf16(@floatFromInt(128 + rng.uintLessThan(u32, 128))); + q[dh - 1 - e] = q[e]; + } + }; + for ([2][]u16{ rh, rw }) |tab| for (0..tab.len / dh) |r| { + const row = tab[r * dh ..][0..dh]; + for (0..dh / 2) |e| { + const x: f32 = @floatFromInt(128 + rng.uintLessThan(u32, 128)); + const nudge: f32 = if (e < 2) @floatFromInt(@as(i32, @intCast(rng.uintLessThan(u32, 3))) - 1) else 0; + row[e] = c.toBf16(x); + row[dh - 1 - e] = c.toBf16(nudge - x); + } + }; + } + + pub fn run(t: *Map) !void { + // the return of the windows adds in place: each launch starts from the prepared map copied into the output + if (t.kind == .unwindow) @memcpy(t.rig.bytes(t.outs[0], t.host[0].len * 2), std.mem.sliceAsBytes(t.host[0])); + const p = t.rig.begin(); + const e = p.e; + e.setPipeline(t.pipe); + const tg = mtl.Size.of(256, 1, 1); + switch (t.kind) { + .cols_patch, .cols_neck, .cols_down => { + e.setBuffer(t.ins[0].buf, t.ins[0].off, 0); + e.setBuffer(t.outs[0].buf, t.outs[0].off, 1); + e.setValue(t.cols, 2); + const o = t.cols.out_side; + e.dispatchThreads(mtl.Size.of(t.shape.n, o * o, 1), tg); + }, + .window => { + e.setBuffer(t.ins[0].buf, t.ins[0].off, 0); + e.setBuffer(t.outs[0].buf, t.outs[0].off, 1); + e.setValue(t.win, 2); + e.dispatchThreads(mtl.Size.of(t.win.channels, t.win.padded * t.win.padded, 1), tg); + }, + .unwindow => { + e.setBuffer(t.outs[0].buf, t.outs[0].off, 0); + e.setBuffer(t.ins[1].buf, t.ins[1].off, 1); + e.setValue(t.win, 2); + e.dispatchThreads(mtl.Size.of(t.win.channels, t.win.side * t.win.side, 1), tg); + }, + .rel => { + for (t.ins, 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setBuffer(t.outs[0].buf, t.outs[0].off, 3); + e.setBuffer(t.outs[1].buf, t.outs[1].off, 4); + e.setValue(t.rel, 5); + const n = t.rel.groups * t.rel.side * t.rel.side; + e.dispatchThreads(mtl.Size.of(2 * t.rel.side, n, heads), mtl.Size.of(32, 8, 1)); + }, + } + try t.rig.finish(p); + } + + pub fn count(t: *Map) usize { + return switch (t.kind) { + .cols_patch, .cols_neck, .cols_down => t.cols.out_side * t.cols.out_side * t.shape.n, + .window => t.win.padded * t.win.padded * t.win.channels, + .unwindow => t.win.side * t.win.side * t.win.channels, + .rel => 2 * heads * t.rel.groups * t.rel.side * t.rel.side * t.rel.side, + }; + } + + fn at(t: *Map, i: usize, j: usize) f64 { + return c.fromBf16(t.host[i][j]); + } + + /// Output i of a relative-position launch: its terms q_e R_e (into `terms`); h's outputs, then w's. + fn relTerms(t: *Map, i: usize, terms: []f64) void { + const side = t.rel.side; + const n = t.rel.groups * side * side; + const half = heads * n * side; + const across = i >= half; + const o = i % half; + const h = o / (n * side); + const row = (o / side) % n; + const j = o % side; + const in = row % (side * side); + const from = (if (across) in % side else in / side) + side - 1 - j; + for (terms, 0..) |*x, e| x.* = t.at(0, row * 3 * S + h * dh + e) * t.at(if (across) 2 else 1, from * dh + e); + } + + pub fn reference(t: *Map, want: []f64, mag: []f64) !void { + @memset(mag, 0); + switch (t.kind) { + .cols_patch, .cols_neck, .cols_down => { + const p = t.cols; + const width = t.shape.n; + const taps = p.span * p.span; + for (want, 0..) |*o, i| { + const r = i / width; + const col = i % width; + const ch = col / taps; + const tap = col % taps; + const iy = @as(isize, @intCast((r / p.out_side) * p.stride + tap / p.span)) - p.pad; + const ix = @as(isize, @intCast((r % p.out_side) * p.stride + tap % p.span)) - p.pad; + const inside = iy >= 0 and ix >= 0 and iy < p.in_side and ix < p.in_side; + o.* = if (inside) t.at(0, ch * p.cstride + (@as(usize, @intCast(iy)) * p.in_side + @as(usize, @intCast(ix))) * p.pstride) else 0; + } + }, + .window => { + const w = t.win; + for (want, 0..) |*o, i| { + const r = i / w.channels; + const win = r / (window * window); + const in = r % (window * window); + const across = w.padded / window; + const y = (win / across) * window + in / window; + const x = (win % across) * window + in % window; + o.* = if (y < w.side and x < w.side) t.at(0, (y * w.side + x) * w.channels + i % w.channels) else 0; + } + }, + .unwindow => { + const w = t.win; + for (want, 0..) |*o, i| { + const r = i / w.channels; + const y = r / w.side; + const x = r % w.side; + const across = w.padded / window; + const from = ((y / window) * across + x / window) * window * window + (y % window) * window + x % window; + o.* = t.at(0, i) + t.at(1, from * w.channels + i % w.channels); + } + }, + .rel => { + var terms: [dh]f64 = undefined; + for (want, mag, 0..) |*o, *m, i| { + t.relTerms(i, &terms); + o.* = 0; + for (terms) |x| { + o.* += x; + m.* += @abs(x); + } + } + }, + } + } + + pub fn simulate(t: *Map, acc: c.Accum, order: g.Order, out: []f64) !void { + if (t.kind != .rel) return error.NoSums; + var terms: [dh]f64 = undefined; + for (out, 0..) |*o, i| { + t.relTerms(i, &terms); + o.* = rows.sumIn(acc, order, &terms); + } + } +}; + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + made: std.ArrayList(*Map) = .empty, + + const controls = [_]struct { Kind, Mutation }{ + .{ .cols_neck, .cols_pad_down }, .{ .window, .window_transposed }, .{ .unwindow, .unwindow_no_add }, + .{ .rel, .rel_mirrored }, .{ .rel, .rel_half_sums }, + }; + + fn one(s: *Suite, kind: Kind, m: Mutation, only: ?[]const u8) !void { + if (!v.wanted(only, if (m == .none) spec(kind).name else m.name())) return; + const x = try s.a.create(Map); + x.* = try Map.init(s.a, s.device, s.queue, kind, m); + try s.made.append(s.a, x); + try s.kernels.append(s.a, x.kernel()); + } + + pub fn collect(s: *Suite, only: ?[]const u8) !void { + for (std.enums.values(Kind)) |kind| try s.one(kind, .none, only); + for (controls) |ctl| try s.one(ctl[0], ctl[1], only); + } + pub fn deinit(s: *Suite) void { + for (s.made.items) |x| x.deinit(); + s.made.deinit(s.a); + } +}; diff --git a/zig/tests/uocr/blocks.zig b/zig/tests/uocr/blocks.zig new file mode 100644 index 00000000000..8c7b43cb080 --- /dev/null +++ b/zig/tests/uocr/blocks.zig @@ -0,0 +1,133 @@ +//! tf-uocr-blocks: Unlimited-OCR-2's image encoder step by step, each step alone against float32. +const std = @import("std"); +const mtl = @import("metal"); +const tf = @import("tensorfold"); +const uo = tf.uocr; +const gate = uo.gate; +const Encoder = uo.vision.Encoder; + +const usage = + \\tf-uocr-blocks MODEL_DIR BLOCKS + \\BLOCKS is `tools/zig/uocr_reference.py blocks` for one view: each step's float32 input rounded to bf16, its + \\float32 output and torch bf16's output on that same input, for every SAM block (sam_*), the neck and its + \\convolutions (neck_*), CLIP's embedding and pre-norm (front_*), every CLIP layer (clip_*) and the projector + \\(project_*). Each step runs alone here on its input and must be as close to float32 as twice torch bf16's (or + \\bf16 rounding's) cosine error and worst row; every step then runs again and must repeat byte for byte. +; + +fn halves(f: *const tf.safetensors.File, name: []const u8) ![]const u16 { + const t = f.get(name) orelse return error.MissingTensor; + if (t.dtype != .bf16) return error.BadBlocksTensor; + return @alignCast(std.mem.bytesAsSlice(u16, t.bytes)); +} + +fn floats(a: std.mem.Allocator, f: *const tf.safetensors.File, name: []const u8) ![]f32 { + const t = f.get(name) orelse return error.MissingTensor; + const out = try a.alloc(f32, t.numel()); + switch (t.dtype) { + .f32 => @memcpy(std.mem.sliceAsBytes(out), t.bytes), + .bf16 => for (out, std.mem.bytesAsSlice(u16, t.bytes)) |*o, h| { + o.* = uo.resize.widen(h); + }, + else => return error.BadBlocksTensor, + } + return out; +} + +/// One kind of step: its tensors' prefix, the rows it reads, the width of its output rows. +const Kind = struct { name: []const u8, width: usize, input: enum { x, m3, cx, both } }; + +const kinds = [_]Kind{ + .{ .name = "sam", .width = 768, .input = .x }, + .{ .name = "neck", .width = 1024, .input = .x }, + .{ .name = "front", .width = 1024, .input = .m3 }, + .{ .name = "clip", .width = 1024, .input = .cx }, + .{ .name = "project", .width = 1280, .input = .both }, +}; + +const Tally = struct { pass: bool = true, same: bool = true }; + +pub fn main(init: std.process.Init) !u8 { + const a = init.arena.allocator(); + const io = init.io; + const args = try init.minimal.args.toSlice(a); + if (args.len != 3) { + std.debug.print("{s}\n", .{usage}); + return 2; + } + var f = try tf.safetensors.File.open(a, io, args[2]); + defer f.close(io); + const pix = f.get("pixels") orelse return error.MissingTensor; + const size = pix.dim(3); + + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const device = try mtl.Device.init(); + if (!device.tensorUnits()) { + std.debug.print("{s} has no tensor units; this family runs on the M5's alone\n", .{device.name()}); + return 1; + } + const queue = try device.queue(); + defer queue.deinit(); + var w = try uo.weights.load(std.heap.smp_allocator, io, device, args[1]); + defer w.deinit(); + var k = try uo.kernels.Kernels.load(std.heap.smp_allocator, device); + defer k.deinit(); + var enc = try Encoder.init(std.heap.smp_allocator, device, queue, &k, &w); + defer enc.deinit(); + std.debug.print("{s}: a view of {d}\n", .{ device.name(), size }); + + var tally: Tally = .{}; + for (kinds) |kind| { + const exact = try floats(a, &f, try std.fmt.allocPrint(a, "{s}_f32", .{kind.name})); + const theirs = try floats(a, &f, try std.fmt.allocPrint(a, "{s}_bf16", .{kind.name})); + const ft = f.get(try std.fmt.allocPrint(a, "{s}_f32", .{kind.name})).?; + // the towers stack their blocks [blocks, rows, width]; the steps between are one [rows, width] + const count: usize = if (ft.rank == 3) ft.dim(0) else 1; + const n = exact.len / count; + const in_name = try std.fmt.allocPrint(a, "{s}_in", .{kind.name}); + const ins: ?[]const u16 = if (kind.input == .both) null else try halves(&f, in_name); + const outs = try a.alloc(u16, n); + const again = try a.alloc(u16, n); + const ours = try a.alloc(f32, n); + var passed: usize = 0; + var most: f64 = 0; + for (0..count) |i| { + var rows: Encoder.Rows = .{}; + switch (kind.input) { + .x => rows.x = ins.?[i * (ins.?.len / count) ..][0 .. ins.?.len / count], + .m3 => rows.m3 = ins.?, + .cx => rows.cx = ins.?[i * n ..][0..n], + .both => { + rows.cx = try halves(&f, "project_cx"); + rows.m3 = try halves(&f, "project_m3"); + }, + } + const st: Encoder.Step = if (std.mem.eql(u8, kind.name, "sam")) + .{ .sam = i } + else if (std.mem.eql(u8, kind.name, "neck")) + .neck + else if (std.mem.eql(u8, kind.name, "front")) + .front + else if (std.mem.eql(u8, kind.name, "clip")) + .{ .clip = i } + else + .project; + try enc.step(size, st, rows, outs); + try enc.step(size, st, rows, again); + tally.same = tally.same and std.mem.eql(u16, outs, again); + for (ours, outs) |*o, h| o.* = uo.resize.widen(h); + const ex = exact[i * n ..][0..n]; + const ref = gate.match(theirs[i * n ..][0..n], ex, kind.width); + const v = gate.verdict(gate.match(ours, ex, kind.width), ref, try gate.rounding(a, ex, kind.width)); + most = @max(most, @max(v.cosine_err / v.cosine_limit, v.row / v.row_limit)); + std.debug.print(" {s} {d}: 1-cosine {e:.2} of {e:.2}, worst row {d:.5} (row {d}) of {d:.5}, torch bf16 {d:.5}: {s}\n", .{ kind.name, i, v.cosine_err, v.cosine_limit, v.row, v.row_at, v.row_limit, ref.worst_row, if (v.pass) "pass" else "FAIL" }); + passed += @intFromBool(v.pass); + tally.pass = tally.pass and v.pass; + } + std.debug.print("{s}: {d} of {d} pass, at most {d:.2} of a limit\n", .{ kind.name, passed, count, most }); + } + const ok = tally.pass and tally.same; + std.debug.print("repeat byte for byte: {}\n{s}\n", .{ tally.same, if (ok) "PASS" else "FAIL" }); + return if (ok) 0 else 1; +} diff --git a/zig/tests/uocr/decode.zig b/zig/tests/uocr/decode.zig new file mode 100644 index 00000000000..cba0d5e947f --- /dev/null +++ b/zig/tests/uocr/decode.zig @@ -0,0 +1,300 @@ +//! tf-uocr-decode: a page end to end against a reference dump: ids, embeddings, every layer, logits, the greedy reply. +const std = @import("std"); +const mtl = @import("metal"); +const tf = @import("tensorfold"); +const uo = tf.uocr; +const cfg = uo.config; +const gate = uo.gate; +const H = cfg.hidden; + +const usage = + \\tf-uocr-decode MODEL_DIR PAGE[,PAGE...] DUMP_BF16 DUMP_F32 [--their-embeds] [--chunk ROWS] [--save-rows FILE] + \\ [--reply-reported] + \\The dumps are `tools/zig/uocr_reference.py dump`'s for the pages (DUMP.json beside each .safetensors holds the + \\prompt ids and the greedy reply). Each page is preprocessed and encoded here (gundam when the dump's pages + \\hold tiles), the prompt must match the dump's ids, every layer's prefill rows and the first logits are + \\measured against float32 within twice torch bf16's distance, and the reply is generated greedily for as many + \\tokens as the bf16 reference's, reporting where it first differs from each reference. --their-embeds feeds the + \\bf16 dump's embeddings to the decoder and runs no encoder, so the layers and the reply measure the decoder + \\alone: the layers and the first logits must then be within those limits (and each layer is also compared with + \\torch bf16's). From our own image rows they are reported, not gated, as tf-uocr-vision reports CLIP: they + \\carry the encoder's departures, which tf-uocr-blocks gates step by step. The prompt's text rows must equal + \\torch's bit for bit. Torch bf16's reply is then fed back a token a step: wherever our pick differs, the two + \\contenders must be torch's own two (the dump's `top2`), and both margins, ours and torch's, within one bf16 + \\step at the logits' size; any other departure fails. --reply-reported reports those departures instead of + \\gating them (the five-page document, which the recipe reports beside the single pages it claims). --chunk ROWS + \\prefills again in chunks of ROWS rows and requires the first logits and the whole reply to equal the one-pass + \\prefill's bit for bit. --save-rows writes the image-token rows the decoder takes (bf16, raw). +; + +fn floats(a: std.mem.Allocator, f: *const tf.safetensors.File, name: []const u8) ![]f32 { + const t = f.get(name) orelse return error.MissingTensor; + const out = try a.alloc(f32, t.numel()); + switch (t.dtype) { + .f32 => @memcpy(std.mem.sliceAsBytes(out), t.bytes), + .bf16 => for (out, std.mem.bytesAsSlice(u16, t.bytes)) |*o, h| { + o.* = uo.resize.widen(h); + }, + else => return error.BadDumpTensor, + } + return out; +} + +fn widen(a: std.mem.Allocator, h: []const u16) ![]f32 { + const out = try a.alloc(f32, h.len); + for (out, h) |*o, x| o.* = uo.resize.widen(x); + return out; +} + +/// A stage is gated from the reference's image rows (--their-embeds), reported from ours (see the usage). +fn verdict(pass: bool, gated: bool) []const u8 { + return if (pass) "pass" else if (gated) "FAIL" else "over (reported)"; +} + +const Top2 = gate.Top2; +const Ref = struct { prompt: []u32, gen: []u32, top2: []Top2 }; + +fn reference(a: std.mem.Allocator, io: std.Io, safetensors_path: []const u8) !Ref { + const json_path = try std.fmt.allocPrint(a, "{s}.json", .{safetensors_path[0 .. safetensors_path.len - ".safetensors".len]}); + const text = try std.Io.Dir.cwd().readFileAlloc(io, json_path, a, .limited(64 << 20)); + const v = try std.json.parseFromSliceLeaky(struct { prompt: []u32, gen: []u32, top2: []Top2 = &.{} }, a, text, .{ .ignore_unknown_fields = true }); + return .{ .prompt = v.prompt, .gen = v.gen, .top2 = v.top2 }; +} + +const departure = gate.departure; + +fn firstDiff(a: []const u32, b: []const u32) ?usize { + for (0..@min(a.len, b.len)) |i| if (a[i] != b[i]) return i; + return if (a.len == b.len) null else @min(a.len, b.len); +} + +fn noop(_: void, _: u32) void {} + +pub fn main(init: std.process.Init) !u8 { + const a = init.arena.allocator(); + const io = init.io; + const args = try init.minimal.args.toSlice(a); + var their = false; + var chunk: ?usize = null; + var save: ?[]const u8 = null; + var reply_reported = false; + var ai: usize = 5; + while (ai < args.len) : (ai += 1) { + if (std.mem.eql(u8, args[ai], "--their-embeds")) { + their = true; + } else if (std.mem.eql(u8, args[ai], "--reply-reported")) { + reply_reported = true; + } else if (std.mem.eql(u8, args[ai], "--chunk") and ai + 1 < args.len) { + ai += 1; + chunk = std.fmt.parseInt(usize, args[ai], 10) catch null; + if (chunk == null or chunk.? == 0) break; + } else if (std.mem.eql(u8, args[ai], "--save-rows") and ai + 1 < args.len) { + ai += 1; + save = args[ai]; + } else break; + } + if (args.len < 5 or ai < args.len) { + std.debug.print("{s}\n", .{usage}); + return 2; + } + var bf = try tf.safetensors.File.open(a, io, args[3]); + var ex = try tf.safetensors.File.open(a, io, args[4]); + const ref_bf = try reference(a, io, args[3]); + const ref_ex = try reference(a, io, args[4]); + if (ref_bf.top2.len != ref_bf.gen.len) { + std.debug.print("{s}: the dump's top2 has {d} steps for {d} tokens; rerun uocr_reference.py dump\n", .{ args[3], ref_bf.top2.len, ref_bf.gen.len }); + return 2; + } + + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const device = try mtl.Device.init(); + if (!device.tensorUnits()) { + std.debug.print("{s} has no tensor units; this family runs on the M5's alone\n", .{device.name()}); + return 1; + } + const queue = try device.queue(); + defer queue.deinit(); + const gpa = std.heap.smp_allocator; + var w = try uo.weights.load(gpa, io, device, args[1]); + defer w.deinit(); + var k = try uo.kernels.Kernels.load(gpa, device); + defer k.deinit(); + // each page's views, encoded, laid out as its image tokens; with --their-embeds the dump's rows instead + var page_tokens: std.ArrayList(usize) = .empty; + var all_rows: std.ArrayList(u16) = .empty; + var t_enc: f64 = 0; + if (their) { + const emb = bf.get("embeds") orelse return error.MissingTensor; + const all: []const u16 = @alignCast(std.mem.bytesAsSlice(u16, emb.bytes)); + for (ref_bf.prompt, 0..) |id, i| { + if (id == cfg.page_token) try page_tokens.append(a, 0); + if (id != cfg.image_token or page_tokens.items.len == 0) continue; + page_tokens.items[page_tokens.items.len - 1] += 1; + try all_rows.appendSlice(a, all[i * H ..][0..H]); + } + std.debug.print("{s}: the dump's {d} pages of image rows\n", .{ args[2], page_tokens.items.len }); + } else { + var enc = try uo.vision.Encoder.init(gpa, device, queue, &k, &w); + defer enc.deinit(); + var paths = std.mem.splitScalar(u8, args[2], ','); + // gundam when the dump's pages hold more image tokens than a base page's + var images: usize = 0; + for (ref_bf.prompt) |id| images += @intFromBool(id == cfg.image_token); + var pages: usize = 0; + for (ref_bf.prompt) |id| pages += @intFromBool(id == cfg.page_token); + const gundam = images > @max(pages, 1) * uo.serve.basePageTokens(); + while (paths.next()) |path| { + const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, a, .limited(64 << 20)); + var page = try uo.preprocess.decode(io, a, bytes); + const views = try uo.preprocess.views(a, page.rgb, page.width, page.height, gundam); + const t0 = mtl.clock.seconds(); + const g = cfg.side(cfg.base_size); + const t = cfg.side(cfg.tile_size); + const global = try a.alloc(u16, g * g * H); + try enc.encode(cfg.base_size, views.global, global, .{}); + const tiles = try a.alloc(u16, views.tileCount() * t * t * H); + for (0..views.tileCount()) |i| try enc.encode(cfg.tile_size, views.tile(i), tiles[i * t * t * H ..][0 .. t * t * H], .{}); + const page_rows = try all_rows.addManyAsSlice(a, views.tokens() * H); + uo.vision.layout(&w, global, tiles, views.across, views.down, page_rows); + t_enc += mtl.clock.seconds() - t0; + try page_tokens.append(a, views.tokens()); + std.debug.print("{s}: {d} x {d}, {s} {d} x {d}\n", .{ path, page.width, page.height, if (gundam) "gundam" else "base", views.across, views.down }); + page.deinit(a); + } + } + const rows = all_rows.items; + if (save) |path| try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = std.mem.sliceAsBytes(rows) }); + var p = try uo.prompt.build(a, page_tokens.items, &cfg.instruction); + const ids_same = std.mem.eql(u32, p.ids, ref_bf.prompt); + std.debug.print("prompt {d} tokens, ids {s}; encoded in {d:.2} s\n", .{ p.len(), if (ids_same) "match" else "DIFFER", t_enc }); + if (!ids_same) return 1; + + const n = p.len(); + const max_new = ref_bf.gen.len + 8; + var all_pass = true; + var dec = try uo.decoder.Decoder.init(gpa, device, queue, &k, &w, n + max_new + 1, n); + defer dec.deinit(); + const trace = try a.alloc([]u16, cfg.layers); + for (trace) |*s| s.* = try a.alloc(u16, n * H); + dec.trace = trace; + var parts: [2][][]u16 = undefined; + for (&parts) |*pt| { + pt.* = try a.alloc([]u16, cfg.layers); + for (pt.*) |*sl| sl.* = try a.alloc(u16, n * H); + } + dec.trace_parts = parts; + + // the spliced embeddings: text rows exact, image rows gated + { + const theirs = try floats(a, &bf, "embeds"); + const exact = try floats(a, &ex, "embeds"); + var text_differ: usize = 0; + var img: usize = 0; + const ours = try a.alloc(f32, n * H); + for (p.ids, 0..) |id, i| { + for (0..H) |c| ours[i * H + c] = if (id == cfg.image_token) uo.resize.widen(rows[(img * H) + c]) else uo.resize.widen(@as([*]const u16, @ptrCast(@alignCast(w.embed.addr())))[id * H + c]); + if (id == cfg.image_token) { + img += 1; + } else for (0..H) |c| { + text_differ += @intFromBool(ours[i * H + c] != theirs[i * H + c]); + } + } + const v = gate.verdict(gate.match(ours, exact, H), gate.match(theirs, exact, H), try gate.rounding(a, exact, H)); + std.debug.print("embeds: text values differing {d}: {s}; 1-cos {e:.2} of {e:.2}, worst row {d:.4} of {d:.4}: {s}\n", .{ text_differ, if (text_differ == 0) "pass" else "FAIL", v.cosine_err, v.cosine_limit, v.row, v.row_limit, verdict(v.pass, false) }); + all_pass = all_pass and text_differ == 0; + } + + const t1 = mtl.clock.seconds(); + try dec.prefill(p, rows); + const t_pre = mtl.clock.seconds() - t1; + dec.trace = null; + dec.trace_parts = null; + for (0..cfg.layers) |l| { + const name = try std.fmt.allocPrint(a, "layer{d}", .{l}); + const theirs = try floats(a, &bf, name); + const exact = try floats(a, &ex, name); + const v = gate.verdict(gate.match(try widen(a, trace[l]), exact, H), gate.match(theirs, exact, H), try gate.rounding(a, exact, H)); + std.debug.print(" layer {d:>2}: 1-cos {e:.2} of {e:.2}, worst row {d:.4} (row {d}) of {d:.4}: {s}\n", .{ l, v.cosine_err, v.cosine_limit, v.row, v.row_at, v.row_limit, verdict(v.pass, their) }); + if (their) { + const m = gate.match(try widen(a, trace[l]), theirs, H); + std.debug.print(" against torch bf16: 1-cos {e:.2}, worst row {d:.4} (row {d})\n", .{ 1 - m.cosine, m.worst_row, m.worst_at }); + for ([_][]const u8{ "attn", "mlp" }, 0..) |part, pi| { + const pt = floats(a, &bf, try std.fmt.allocPrint(a, "{s}{d}", .{ part, l })) catch continue; + const pm = gate.match(try widen(a, parts[pi][l]), pt, H); + std.debug.print(" {s}: 1-cos {e:.2}, worst row {d:.4} (row {d})\n", .{ part, 1 - pm.cosine, pm.worst_row, pm.worst_at }); + } + } + if (their) all_pass = all_pass and v.pass; + } + std.debug.print("prefill {d} tokens in {d:.3} s\n", .{ n, t_pre }); + + // the first logits, then the reply + { + const lg = try dec.logits(); + const theirs = (try floats(a, &bf, "logits"))[0..cfg.vocab]; + const exact = (try floats(a, &ex, "logits"))[0..cfg.vocab]; + const v = gate.verdict(gate.match(try widen(a, lg), exact, cfg.vocab), gate.match(theirs, exact, cfg.vocab), try gate.rounding(a, exact, cfg.vocab)); + std.debug.print("first logits: rel err {d:.4} of {d:.4}: {s}\n", .{ v.row, v.row_limit, verdict(v.pass, their) }); + if (their) all_pass = all_pass and v.pass; + } + const first_logits = try a.dupe(u16, try dec.logits()); + var gen: std.ArrayList(u32) = .empty; + const t2 = mtl.clock.seconds(); + try uo.generate.greedy(&dec, p, ref_bf.gen.len, &gen, a, {}, noop); + const t_gen = mtl.clock.seconds() - t2; + std.debug.print("reply: {d} tokens in {d:.2} s ({d:.1} tok/s)\n", .{ gen.items.len, t_gen, @as(f64, @floatFromInt(gen.items.len)) / t_gen }); + for ([_]struct { []const u8, []const u32 }{ .{ "torch bf16", ref_bf.gen }, .{ "torch fp32", ref_ex.gen } }) |r| { + if (firstDiff(gen.items, r[1][0..@min(r[1].len, gen.items.len)])) |at| + std.debug.print(" vs {s} ({d} tokens): first differs at token {d}\n", .{ r[0], r[1].len, at }) + else + std.debug.print(" vs {s} ({d} tokens): identical over {d}\n", .{ r[0], r[1].len, gen.items.len }); + } + const bf_fp = firstDiff(ref_bf.gen, ref_ex.gen[0..@min(ref_ex.gen.len, ref_bf.gen.len)]); + std.debug.print(" (torch bf16 vs fp32: first differs at {?d})\n", .{bf_fp}); + std.debug.print("ids {any}\n", .{gen.items}); + // torch bf16's reply fed back: at each step where our pick differs, both runs' two contenders and margins + { + var fed = try uo.decoder.Decoder.init(gpa, device, queue, &k, &w, n + max_new + 1, n); + defer fed.deinit(); + try fed.prefill(p, rows); + var guard = uo.generate.Guard.init(p); + var st = uo.prompt.Step.init(p); + var flips: usize = 0; + var ties: usize = 0; + for (ref_bf.gen, 0..) |want, i| { + const lg = try fed.logits(); + const ours = guard.pick(lg); + if (ours != want) { + const d = departure(lg, ours, want, ref_bf.top2[i]); + flips += 1; + ties += @intFromBool(d.tie()); + const t = ref_bf.top2[i]; + const other: u32 = @intFromFloat(if (@as(u32, @intFromFloat(t[0])) == want) t[2] else t[0]); + std.debug.print(" fed step {d}: torch bf16 {d} over {d} by {d:.2} steps, ours {d} over {d} by {d:.2}: {s}\n", .{ i, want, other, d.theirs, ours, want, d.ours, if (d.tie()) "a tie" else if (d.same_two) "the same two, but not within a step" else "NOT the same two" }); + } + guard.take(want); + if (i + 1 == ref_bf.gen.len) break; + try fed.step(want, st.next(want)); + } + const all_ties = ties == flips; + std.debug.print("fed torch bf16's reply: {d} of {d} steps pick otherwise, {d} of them ties (the same two contenders, both margins within one bf16 step): {s}\n", .{ flips, ref_bf.gen.len, ties, if (all_ties) "pass" else if (reply_reported) "over (reported)" else "FAIL" }); + if (!reply_reported) all_pass = all_pass and all_ties; + } + if (chunk) |c| { + dec.deinit(); + dec = try uo.decoder.Decoder.init(gpa, device, queue, &k, &w, n + max_new + 1, @min(c, n)); + const t3 = mtl.clock.seconds(); + try dec.prefill(p, rows); + const lg = try dec.logits(); + const t_chunked = mtl.clock.seconds() - t3; + const same_logits = std.mem.eql(u16, lg, first_logits); + var again: std.ArrayList(u32) = .empty; + try uo.generate.greedy(&dec, p, ref_bf.gen.len, &again, a, {}, noop); + const same_reply = std.mem.eql(u32, again.items, gen.items); + std.debug.print("chunks of {d} rows ({d:.3} s): first logits {s}, reply {s}\n", .{ c, t_chunked, if (same_logits) "bit-identical" else "DIFFER", if (same_reply) "identical" else "DIFFERS" }); + all_pass = all_pass and same_logits and same_reply; + } + std.debug.print("{s}\n", .{if (all_pass) "PASS" else "FAIL"}); + return if (all_pass) 0 else 1; +} diff --git a/zig/tests/uocr/vision.zig b/zig/tests/uocr/vision.zig new file mode 100644 index 00000000000..f2b431eaa90 --- /dev/null +++ b/zig/tests/uocr/vision.zig @@ -0,0 +1,156 @@ +//! tf-uocr-vision: Unlimited-OCR-2's image encoder on a reference dump's own pixels, each stage against float32. +const std = @import("std"); +const mtl = @import("metal"); +const tf = @import("tensorfold"); +const uo = tf.uocr; +const cfg = uo.config; +const gate = uo.gate; + +const usage = + \\tf-uocr-vision MODEL_DIR DUMP_BF16 DUMP_F32 [PAGE] + \\MODEL_DIR is the baidu/Unlimited-OCR-2 folder. The dumps (`tools/zig/uocr_reference.py dump`) hold, for every + \\encoder call i, its pixels pixels{i} [views, 3, size, size] and the reference's SAM (sam{i}), CLIP (clip{i}) and + \\projector (projector{i}) outputs, from torch bf16 and from float32 on the same bf16 pixels. Each view is encoded + \\here from the bf16 dump's pixels; SAM's output must be as close to float32 as twice torch bf16's (or bf16 + \\rounding's) cosine error and worst row. CLIP's and the projector's are reported against the same limits but not + \\gated: CLIP's input is SAM's output, and a few of its rows magnify bf16 rounding there by more than twice, on + \\torch's devices as on ours; tf-uocr-blocks gates each CLIP layer and the projector alone. The views are then + \\encoded again and must repeat byte for byte. With PAGE (the image the dump was made from), the views are made + \\here from it instead, and must equal the dump's pixels bit for bit first. +; + +fn floats(a: std.mem.Allocator, f: *const tf.safetensors.File, name: []const u8) ![]f32 { + const t = f.get(name) orelse return error.MissingTensor; + const out = try a.alloc(f32, t.numel()); + switch (t.dtype) { + .f32 => @memcpy(std.mem.sliceAsBytes(out), t.bytes), + .bf16 => for (out, std.mem.bytesAsSlice(u16, t.bytes)) |*o, h| { + o.* = uo.resize.widen(h); + }, + else => return error.BadDumpTensor, + } + return out; +} + +fn widen(a: std.mem.Allocator, h: []const u16) ![]f32 { + const out = try a.alloc(f32, h.len); + for (out, h) |*o, x| o.* = uo.resize.widen(x); + return out; +} + +/// SAM's [channels, side, side] as rows [side^2, channels]. +fn rowsOf(a: std.mem.Allocator, chw: []const f32, channels: usize, positions: usize) ![]f32 { + const out = try a.alloc(f32, chw.len); + for (0..channels) |c| for (0..positions) |p| { + out[p * channels + c] = chw[c * positions + p]; + }; + return out; +} + +fn report(label: []const u8, view: usize, theirs: gate.Match, v: gate.Verdict, gated: bool) void { + const verdict = if (v.pass) "within" else if (gated) "FAIL" else "over (reported)"; + std.debug.print(" {s} view {d}: 1-cosine {e:.2} of {e:.2}, worst row {d:.5} (row {d}) of {d:.5}, torch bf16 {d:.5}: {s}\n", .{ label, view, v.cosine_err, v.cosine_limit, v.row, v.row_at, v.row_limit, theirs.worst_row, verdict }); +} + +pub fn main(init: std.process.Init) !u8 { + const a = init.arena.allocator(); + const io = init.io; + const args = try init.minimal.args.toSlice(a); + if (args.len != 4 and args.len != 5) { + std.debug.print("{s}\n", .{usage}); + return 2; + } + var bf = try tf.safetensors.File.open(a, io, args[2]); + defer bf.close(io); + var ex = try tf.safetensors.File.open(a, io, args[3]); + defer ex.close(io); + + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const device = try mtl.Device.init(); + if (!device.tensorUnits()) { + std.debug.print("{s} has no tensor units; this family runs on the M5's alone\n", .{device.name()}); + return 1; + } + const queue = try device.queue(); + defer queue.deinit(); + const t0 = mtl.clock.seconds(); + var w = try uo.weights.load(std.heap.smp_allocator, io, device, args[1]); + defer w.deinit(); + var k = try uo.kernels.Kernels.load(std.heap.smp_allocator, device); + defer k.deinit(); + var enc = try uo.vision.Encoder.init(std.heap.smp_allocator, device, queue, &k, &w); + defer enc.deinit(); + std.debug.print("{s}: loaded in {d:.1} s\n", .{ device.name(), mtl.clock.seconds() - t0 }); + + var mine: ?uo.preprocess.Views = null; + if (args.len == 5) { + const bytes = try std.Io.Dir.cwd().readFileAlloc(io, args[4], a, .limited(64 << 20)); + var page = try uo.preprocess.decode(io, a, bytes); + const gundam = bf.get("pixels1") != null; + mine = try uo.preprocess.views(a, page.rgb, page.width, page.height, gundam); + page.deinit(a); + std.debug.print("page {s}: {d} x {d}, {s}, tiles {d} x {d}\n", .{ args[4], page.width, page.height, if (gundam) "gundam" else "base", mine.?.across, mine.?.down }); + } + + var all_pass = true; + var repeat_same = true; + var call: usize = 0; + while (true) : (call += 1) { + var name_buf: [32]u8 = undefined; + const pix_name = try std.fmt.bufPrint(&name_buf, "pixels{d}", .{call}); + const pix = bf.get(pix_name) orelse break; + if (pix.dtype != .bf16) return error.BadDumpTensor; + const views = pix.dim(0); + const size = pix.dim(2); + const side = cfg.side(size); + const n = side * side; + const sam_bf = try floats(a, &bf, try std.fmt.allocPrint(a, "sam{d}", .{call})); + const sam_ex = try floats(a, &ex, try std.fmt.allocPrint(a, "sam{d}", .{call})); + const clip_bf = try floats(a, &bf, try std.fmt.allocPrint(a, "clip{d}", .{call})); + const clip_ex = try floats(a, &ex, try std.fmt.allocPrint(a, "clip{d}", .{call})); + const proj_bf = try floats(a, &bf, try std.fmt.allocPrint(a, "projector{d}", .{call})); + const proj_ex = try floats(a, &ex, try std.fmt.allocPrint(a, "projector{d}", .{call})); + std.debug.print("call {d}: {d} view(s) of {d}\n", .{ call, views, size }); + const out = try a.alloc(u16, n * cfg.hidden); + const again = try a.alloc(u16, n * cfg.hidden); + const sam = try a.alloc(u16, n * cfg.net3_width); + const clip = try a.alloc(u16, (n + 1) * cfg.clip_width); + for (0..views) |vi| { + const dumped: []const u16 = @alignCast(std.mem.bytesAsSlice(u16, pix.bytes)[vi * 3 * size * size ..][0 .. 3 * size * size]); + const px = if (mine) |m| (if (size == cfg.base_size) m.global else m.tile(vi)) else dumped; + if (mine != null) { + var differ: usize = 0; + for (px, dumped) |x, y| differ += @intFromBool(x != y); + std.debug.print(" view {d}: pixels {d} of {d} differ from the dump's\n", .{ vi, differ, px.len }); + all_pass = all_pass and differ == 0; + } + const t = mtl.clock.seconds(); + try enc.encode(size, @alignCast(px), out, .{ .sam = sam, .clip = clip }); + const dt = mtl.clock.seconds() - t; + try enc.encode(size, @alignCast(px), again, .{}); + repeat_same = repeat_same and std.mem.eql(u16, out, again); + const sam_off = vi * n * cfg.net3_width; + const s_bf = try rowsOf(a, sam_bf[sam_off..][0 .. n * cfg.net3_width], cfg.net3_width, n); + const s_ex = try rowsOf(a, sam_ex[sam_off..][0 .. n * cfg.net3_width], cfg.net3_width, n); + const stages = .{ + .{ "sam", try widen(a, sam), s_bf, s_ex, cfg.net3_width, true }, + .{ "clip", try widen(a, clip), clip_bf[vi * (n + 1) * cfg.clip_width ..][0 .. (n + 1) * cfg.clip_width], clip_ex[vi * (n + 1) * cfg.clip_width ..][0 .. (n + 1) * cfg.clip_width], cfg.clip_width, false }, + .{ "projector", try widen(a, out), proj_bf[vi * n * cfg.hidden ..][0 .. n * cfg.hidden], proj_ex[vi * n * cfg.hidden ..][0 .. n * cfg.hidden], cfg.hidden, false }, + }; + std.debug.print(" view {d}: encoded in {d:.3} s\n", .{ vi, dt }); + inline for (stages) |s| { + const theirs = gate.match(s[2], s[3], s[4]); + const v = gate.verdict(gate.match(s[1], s[3], s[4]), theirs, try gate.rounding(a, s[3], s[4])); + report(s[0], vi, theirs, v, s[5]); + if (s[5]) all_pass = all_pass and v.pass; + } + } + } + if (call == 0) { + std.debug.print("the dump has no pixels0\n", .{}); + return 1; + } + std.debug.print("repeat byte for byte: {}\n{s}\n", .{ repeat_same, if (all_pass and repeat_same) "PASS" else "FAIL" }); + return if (all_pass and repeat_same) 0 else 1; +} From 6d55bd2664996b65132991d68a528210223ce075 Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Fri, 6 Nov 2026 09:58:08 -0600 Subject: [PATCH 04/14] changelog: Unlimited-OCR-2 on native Metal under Unreleased --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4a722153d10..87ecfecea4b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -34,6 +34,11 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Server: an Ollama-compatible API serves `/api/chat`, `/api/generate`, `/api/embed`, `/api/tags`, `/api/show`, `/api/ps` and `/api/version` through the same chat, completions and embeddings paths as the OpenAI routes, with NDJSON streaming and named refusals for unsupported options (#3342, fixes #3117). - Server: each `/v1/models` entry now ends with `input_types`, the content parts the model takes: `["text"]`, plus `"image"` with `--vision`, plus `"video"` when the checkpoint reads video and the server loads `libtfvideo`. A `video_url` part sent to a model without video now gets HTTP 400 (`invalid_request_error`) instead of a 500, decided by the same startup check, so the listing and the refusal agree; a server whose model reads video loads `libtfvideo` at startup and says once in its log when it is missing. The other keys are unchanged (#3019, fixes #3004). Thanks to @WebReflection for the design. +- Unlimited-OCR-2 on native Metal (M5 GPUs): Baidu's BF16 release as published serves page images through + `tensorfold-native serve --vision`; one stream, greedy, up to 131,072 tokens. On the recipe's single pages its text + is identical to the release's own `infer` in torch bf16, or departs from it only where two candidate tokens lie + within one bf16 step of each other, the same two torch's float32 run weighs. The five-page document is served the + same way; its departures are listed in the recipe beside float32's (#2074). Thanks to @BobClawblaw. - Server: with thinking off, the reasoning effort a request names reaches the chat template (GLM's head follows it), and the reply reports it; a server's own `--reasoning-effort` no longer changes a thinking-off prompt (#3017, fixes #1911). Thanks to @ss-cong for the report. From a6350ce2f47ed38439b19a5de48443de5ff0b2c1 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sun, 15 Nov 2026 01:23:56 +0000 Subject: [PATCH 05/14] changelog: #2074's line from lines/2074.txt in place of its own --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 87ecfecea4b..c4bdfe7e73e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- Metal: Baidu's Unlimited-OCR-2 is served natively from its BF16 release on M5-class Macs: page images through `serve --vision`, the family's chat template built in, its SAM and CLIP image encoders and decoder under the kernel contract; on five reference pages every departure from the release's own reply is a one-step tie (#2074). Thanks to @BobClawblaw. + ## 1.2.9 - Flash Next on CUDA: a lone stream draws on its own path again; the batched draws #2927 added now run only when two or more streams share a step, so one sampled stream no longer pays the group's whole-buffer download each step. Tokens are unchanged (#3391, after #2927). From 1f486d76036a86065fa33601a9ed305b74680574 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sun, 15 Nov 2026 02:53:32 +0000 Subject: [PATCH 06/14] changelog: back under Unreleased --- CHANGELOG.md | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c4bdfe7e73e..f85517a0ce0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,11 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased - Metal: Baidu's Unlimited-OCR-2 is served natively from its BF16 release on M5-class Macs: page images through `serve --vision`, the family's chat template built in, its SAM and CLIP image encoders and decoder under the kernel contract; on five reference pages every departure from the release's own reply is a one-step tie (#2074). Thanks to @BobClawblaw. - +- Unlimited-OCR-2 on native Metal (M5 GPUs): Baidu's BF16 release as published serves page images through + `tensorfold-native serve --vision`; one stream, greedy, up to 131,072 tokens. On the recipe's single pages its text + is identical to the release's own `infer` in torch bf16, or departs from it only where two candidate tokens lie + within one bf16 step of each other, the same two torch's float32 run weighs. The five-page document is served the + same way; its departures are listed in the recipe beside float32's (#2074). Thanks to @BobClawblaw. ## 1.2.9 - Flash Next on CUDA: a lone stream draws on its own path again; the batched draws #2927 added now run only when two or more streams share a step, so one sampled stream no longer pays the group's whole-buffer download each step. Tokens are unchanged (#3391, after #2927). @@ -36,11 +40,6 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Server: an Ollama-compatible API serves `/api/chat`, `/api/generate`, `/api/embed`, `/api/tags`, `/api/show`, `/api/ps` and `/api/version` through the same chat, completions and embeddings paths as the OpenAI routes, with NDJSON streaming and named refusals for unsupported options (#3342, fixes #3117). - Server: each `/v1/models` entry now ends with `input_types`, the content parts the model takes: `["text"]`, plus `"image"` with `--vision`, plus `"video"` when the checkpoint reads video and the server loads `libtfvideo`. A `video_url` part sent to a model without video now gets HTTP 400 (`invalid_request_error`) instead of a 500, decided by the same startup check, so the listing and the refusal agree; a server whose model reads video loads `libtfvideo` at startup and says once in its log when it is missing. The other keys are unchanged (#3019, fixes #3004). Thanks to @WebReflection for the design. -- Unlimited-OCR-2 on native Metal (M5 GPUs): Baidu's BF16 release as published serves page images through - `tensorfold-native serve --vision`; one stream, greedy, up to 131,072 tokens. On the recipe's single pages its text - is identical to the release's own `infer` in torch bf16, or departs from it only where two candidate tokens lie - within one bf16 step of each other, the same two torch's float32 run weighs. The five-page document is served the - same way; its departures are listed in the recipe beside float32's (#2074). Thanks to @BobClawblaw. - Server: with thinking off, the reasoning effort a request names reaches the chat template (GLM's head follows it), and the reply reports it; a server's own `--reasoning-effort` no longer changes a thinking-off prompt (#3017, fixes #1911). Thanks to @ss-cong for the report. From 9f43a6500757ccc8234470d24e918f2ea50e4939 Mon Sep 17 00:00:00 2001 From: Bizuayeu <30091157+Bizuayeu@users.noreply.github.com> Date: Thu, 12 Nov 2026 23:03:57 +0900 Subject: [PATCH 07/14] kv pool: a named TF_KV_SHARE's slots come where an asked cache goes Under slots_only without --prompt-cache-gib, plan sets aside the slots that fit past the engine's own window and each other stream's fixed part and page, TF_KV_SHARE at most, before windows and held count the rest. The rest of the default cache still becomes pages after the windows. Plans that already kept all n are unchanged, so is every plan without slots_only or with an asked cache. GLM's advice under 4 states a stream names TF_KV_SHARE alone where its slots now fit, and --prompt-cache-gib only beside a named cache too small for them. --- docs/recipes/glm-5.3-flash-cuda.md | 11 ++-- zig/src/core/kv_pool.zig | 10 ++-- zig/src/core/kv_pool_band_test.zig | 84 ++++++++++++++++++++++++++-- zig/src/families/glm/cuda_native.zig | 2 +- zig/src/families/glm/cuda_share.zig | 30 ++++++++-- zig/src/native/cuda_streams.zig | 30 ++++++++++ 6 files changed, 146 insertions(+), 21 deletions(-) diff --git a/docs/recipes/glm-5.3-flash-cuda.md b/docs/recipes/glm-5.3-flash-cuda.md index 4aba406ae16..3c7b1fd2a89 100644 --- a/docs/recipes/glm-5.3-flash-cuda.md +++ b/docs/recipes/glm-5.3-flash-cuda.md @@ -58,7 +58,8 @@ left after a 12.2 GiB reserve` and a 5.8 GiB prompt cache prompt's rows as the pool's pages instead of copying them into the cache, and that log line names it. - With KV pages (the default at two or more ranks), the pool sets the windows the room holds aside before the prompt cache, which gets what they leave of its 16 GiB. `--prompt-cache-gib N` sets N GiB aside first, after the engine's - own window and a fixed part and page for each other stream, and the pool takes the rest. + own window and a fixed part and page for each other stream, and the pool takes the rest. `TF_KV_SHARE=n` sets its n + kept states' slots aside in the same place. - `TF_GLM_PROMPT_TAIL=1` keeps a prompt that names no history, as a `/v1/completions` request's, at its last prompt chunk start, as a chat keeps its history's, so the same prompt or a longer one resumes there. Those states share the prompt cache's budget with chat states, least recently used out first, so long raw prompts between two chat turns can @@ -78,9 +79,11 @@ left after a 12.2 GiB reserve` and a 5.8 GiB prompt cache `TF_GLM_KV_HOST_GIB` sizes the host pages (one full window unasked); `TF_GLM_KV_HOST_SHARED=1` gives the ranks of one host a single copy in `/dev/shm`. Checked on two RTX PRO 6000 Blackwell cards at TP=2. - `TF_KV_SHARE=n` (with KV pages, 64 at most) keeps prompts' rows as the pool's pages, and the startup plan sets aside - a slot for each of the n kept states' other parts in the prompt cache, as many as the cache holds; the rest of the - cache goes to the pool's pages. `--prompt-cache-gib N` bounds them: the startup line names the slots, and when the - cache holds fewer than n, how many it holds and the `--prompt-cache-gib` that holds all n. + a slot for each of the n kept states' other parts first, where an asked cache goes, as many as fit there; the rest of + the prompt cache goes to the pool's pages after the windows. Where the room would hold one more whole window, the + slots come out of it, so the pool holds fewer pages than it would without them. A named `--prompt-cache-gib N` + bounds the slots too: the startup line names them, and when fewer than n fit, how many, and the + `--prompt-cache-gib` that holds all n where one does. - `TF_GLM_CHUNK_SOLO=4096` on every rank (opt-in) lets a prompt pass take 4,096 rows while no other stream is decoding. Unset or `2048`, every pass takes 2,048 rows and nothing extra is held. See [Prompt chunk size](#prompt-chunk-size). - `TF_GLM_REQUEST_STARTS=1` on rank 0 (opt-in, off by default) cuts each prompt pass at the request's message starts diff --git a/zig/src/core/kv_pool.zig b/zig/src/core/kv_pool.zig index a8941b77ffe..bdaa5c1cd64 100644 --- a/zig/src/core/kv_pool.zig +++ b/zig/src/core/kv_pool.zig @@ -98,7 +98,7 @@ pub const Budget = struct { engine_paged: bool = false, /// Parts per million of the cache that kept states hold as pool pages (TF_KV_SHARE): made pages past the windows. kept_ppm: u32 = 0, - /// TF_KV_SHARE with a slot a state (GLM): the cache is its slots, `snaps` at most, and the rest is made pages. + /// TF_KV_SHARE with a slot a state (GLM): `snaps` slots at most, where an asked cache goes; the rest made pages. slots_only: bool = false, /// --prompt-cache-gib named the cache: it comes before every window but the engine's own, which take the rest. asked: bool = false, @@ -131,8 +131,10 @@ pub fn plan(l: Layout, b: Budget) error{ NoStream, TooMany }!Plan { const fit = @min(extra, left / each); if (fit < extra and b.fixed) return error.TooMany; left -= fit * l.fixed_bytes; - const cache = @min(b.cache, left -| held(l, b, fit, windows(l, b, left) - 1)); - const taken = @min(b.cache, left -| held(l, b, fit, 0)) - cache; // what the windows past the engine's own took + const first: u64 = if (b.slots_only and !b.asked) split(@min(b.cache, left -| held(l, b, fit, 0)), l.snap_bytes, b.snaps).snaps * l.snap_bytes else 0; // TF_KV_SHARE's slots, where an asked cache goes + const rest = left - first; // what the windows past the engine's own and the rest of the cache share + const cache = first + @min(b.cache - first, rest -| held(l, b, fit, windows(l, b, rest) - 1)); + const taken = first + @min(b.cache - first, rest -| held(l, b, fit, 0)) - cache; // what the windows past the engine's own took const kept = if (b.slots_only) cache - split(cache, l.snap_bytes, b.snaps).snaps * l.snap_bytes else cache / 1_000_000 * b.kept_ppm + cache % 1_000_000 * b.kept_ppm / 1_000_000; // the cache's share as pages const c = split(cache - kept, l.snap_bytes, b.snaps); left -= c.snaps * l.snap_bytes + c.copied; @@ -174,7 +176,7 @@ fn windows(l: Layout, b: Budget, rest: u64) u64 { if (!b.engine_paged or b.window == 0 or b.asked) return 1; // an asked cache comes before all but the engine's own const own = ownPages(l, b); const room = @min(b.lanes, 1 + (b.room - own) / (own + l.fixed_bytes)); // a window and a fixed part each - return if (own == 0) room else @min(room, 1 + rest / own); // `rest`: past the engine's own window and every fixed part + return if (own == 0) room else @min(room, 1 + rest / own); // `rest`: past the engine's own window, every fixed part and TF_KV_SHARE's slots } /// The bytes of the engine's own window as pages, set aside first when its rows are pages (0 when it has a window). diff --git a/zig/src/core/kv_pool_band_test.zig b/zig/src/core/kv_pool_band_test.zig index 5c8c7c3a5de..57e7162ae27 100644 --- a/zig/src/core/kv_pool_band_test.zig +++ b/zig/src/core/kv_pool_band_test.zig @@ -53,8 +53,6 @@ test "outside that band the room's count of windows stands: GLM at TP=3 and TP=2 .{ .room = 37 * g, .plan = .{ .lanes = 8, .snaps = 32, .copied = 0, .pages = 5046, .kept = 6339952640, .taken = 6981156864 } }, .{ .room = 38 * g, .plan = .{ .lanes = 8, .snaps = 32, .copied = 0, .pages = 5207, .kept = 7413694464, .taken = 5907415040 } }, .{ .room = 38 * g + 3 * g / 4, .plan = .{ .lanes = 8, .snaps = 32, .copied = 0, .pages = 5327, .kept = 8219000832, .taken = 5102108672 } }, - .{ .room = 40 * g + 3 * g / 8, .plan = .{ .lanes = 8, .snaps = 1, .copied = 0, .pages = 6147, .kept = 5111808, .taken = 17054171136 } }, - .{ .room = 41 * g + g / 8, .plan = .{ .lanes = 8, .snaps = 7, .copied = 0, .pages = 6160, .kept = 86900736, .taken = 16248864768 } }, .{ .room = 44 * g, .plan = .{ .lanes = 8, .snaps = 32, .copied = 0, .pages = 6170, .kept = 159252480, .taken = 13161857024 } }, }); var copies3 = tp3; @@ -71,8 +69,6 @@ test "outside that band the room's count of windows stands: GLM at TP=3 and TP=2 .{ .room = 15 * g, .plan = .{ .lanes = 4, .snaps = 16, .copied = 0, .pages = 1797, .kept = 3767795712, .taken = 0 } }, .{ .room = 15 * g + 2 * g / 5, .plan = .{ .lanes = 4, .snaps = 16, .copied = 0, .pages = 1861, .kept = 4197292441, .taken = 0 } }, .{ .room = 15 * g + 3 * g / 5, .plan = .{ .lanes = 4, .snaps = 16, .copied = 0, .pages = 1894, .kept = 4412040806, .taken = 0 } }, - .{ .room = 16 * g + 2 * g / 5, .plan = .{ .lanes = 4, .snaps = 0, .copied = 0, .pages = 2474, .kept = 82155929, .taken = 8208777216 } }, - .{ .room = 17 * g + g / 5, .plan = .{ .lanes = 4, .snaps = 4, .copied = 0, .pages = 2489, .kept = 186174668, .taken = 8208777216 } }, .{ .room = 20 * g, .plan = .{ .lanes = 4, .snaps = 16, .copied = 0, .pages = 2600, .kept = 927727616, .taken = 8208777216 } }, }); var wide2 = share2; // a 1,048,576-token window: only the engine's own comes before the cache in these rooms @@ -114,11 +110,87 @@ test "a --prompt-cache-gib is named for n slots only where asking it keeps them try expect(!kv.holds(tp2, three)); try expectEqual(@as(usize, 16), (try kv.plan(tp2, three)).snaps); // clipped to the rest, 3 asked keeps all 16 try expectEqual(@as(?u64, 3), kv.holding(tp2, strip, 16).gib); - // TP=3, eight streams, just past where the rest holds a third window: under a slot of cache; 4 GiB asked holds 32 + // TP=3, eight streams, just past where the rest holds a third window: 4 GiB asked holds all 32 const tp3: kv.Layout = .{ .fixed_bytes = 291 * mib, .token_bytes = 13_056, .page_tokens = 512, .snap_bytes = 115 * mib }; const edge: kv.Budget = .{ .room = 40 * g + 5 * g / 16, .engine = 0, .lanes = 8, .fixed = true, .cache = 16 * g, .snaps = 32, .window = 1_048_576 + 8, .engine_paged = true, .slots_only = true }; - try expectEqual(@as(usize, 0), (try kv.plan(tp3, edge)).snaps); const e = kv.holding(tp3, edge, 32); try expectEqual(@as(?u64, 4), e.gib); try expectEqual(@as(usize, 32), e.most); } + +// GLM-5.3-Flash at TP=3 today, as its startup line rounds it: 327 MiB fixed, a 168 MiB slot, a 6.38 MiB page +const now3: kv.Layout = .{ .fixed_bytes = 327 * mib, .token_bytes = 13_056, .page_tokens = 512, .snap_bytes = 168 * mib }; +const share8: kv.Budget = .{ .room = 0, .engine = 0, .lanes = 8, .fixed = true, .cache = 16 << 30, .snaps = 32, .window = 1_048_576 + 8, .engine_paged = true, .slots_only = true }; + +test "a named TF_KV_SHARE's slots come where an asked cache goes, before the windows past the engine's own (#2987)" { + const g: u64 = 1 << 30; + // Jammed XSFP4's 42.0 GiB at TP=3, --parallel 8, TF_KV_SHARE=32: all 32 and 5,538 pages, not 8 after a third window + try pinned(now3, share8, &.{.{ .room = 41 * g + 992 * mib, .plan = .{ .lanes = 8, .snaps = 32, .copied = 0, .pages = 5538, .kept = 9632481280, .taken = 1910243328 } }}); + var asked = share8; // the pages --prompt-cache-gib 6 leaves beside the same 32 + asked.room = 41 * g + 992 * mib; + asked.asked = true; + asked.cache = 6 * g; + try expectEqual(@as(usize, 5538), (try kv.plan(now3, asked)).pages); + // #2568's TP=2 receipt (340 MiB fixed, 180 MiB a slot, --parallel 4, a 630,000-token window): all 16, not 4 + const tp2: kv.Layout = .{ .fixed_bytes = 340 * mib, .token_bytes = 13_056, .page_tokens = 512, .snap_bytes = 180 * mib }; + const share4: kv.Budget = .{ .room = 0, .engine = 0, .lanes = 4, .fixed = true, .cache = 16 * g, .snaps = 16, .window = 630_000 + 8, .engine_paged = true, .slots_only = true }; + try pinned(tp2, share4, &.{ + .{ .room = 16 * g + 2 * g / 5, .plan = .{ .lanes = 4, .snaps = 16, .copied = 0, .pages = 2022, .kept = 5271034265, .taken = 0 } }, + .{ .room = 17 * g + g / 20, .plan = .{ .lanes = 4, .snaps = 16, .copied = 0, .pages = 2126, .kept = 5968966451, .taken = 0 } }, + .{ .room = 17 * g + g / 10, .plan = .{ .lanes = 4, .snaps = 16, .copied = 0, .pages = 2134, .kept = 6022653542, .taken = 0 } }, + .{ .room = 17 * g + g / 5, .plan = .{ .lanes = 4, .snaps = 16, .copied = 0, .pages = 2151, .kept = 6130027724, .taken = 0 } }, + }); + // #2568's TP=3 layout (291 MiB fixed, 115 MiB a state) just past the third window's edge: all 32, not 0, 1 or 7 + const tp3: kv.Layout = .{ .fixed_bytes = 291 * mib, .token_bytes = 13_056, .page_tokens = 512, .snap_bytes = 115 * mib }; + try pinned(tp3, share8, &.{ + .{ .room = 40 * g + 5 * g / 16, .plan = .{ .lanes = 8, .snaps = 32, .copied = 0, .pages = 5578, .kept = 9896722432, .taken = 3424387072 } }, + .{ .room = 40 * g + 3 * g / 8, .plan = .{ .lanes = 8, .snaps = 32, .copied = 0, .pages = 5588, .kept = 9963831296, .taken = 3357278208 } }, + .{ .room = 41 * g + g / 8, .plan = .{ .lanes = 8, .snaps = 32, .copied = 0, .pages = 5709, .kept = 10769137664, .taken = 2551971840 } }, + }); +} + +test "plans stand where today's keeps all n, without TF_KV_SHARE, beside --prompt-cache-gib and at kept_ppm" { + const g: u64 = 1 << 30; + // XSFP4's 37.2 GiB at TP=3: 4,780 pages and all 32 after two windows + try pinned(now3, share8, &.{.{ .room = 37 * g + 252 * mib, .plan = .{ .lanes = 8, .snaps = 32, .copied = 0, .pages = 4780, .kept = 4561567744, .taken = 6981156864 } }}); + var asked = share8; // --prompt-cache-gib 6 beside TF_KV_SHARE=32 at Jammed's room + asked.asked = true; + asked.cache = 6 * g; + try pinned(now3, asked, &.{.{ .room = 41 * g + 992 * mib, .plan = .{ .lanes = 8, .snaps = 32, .copied = 0, .pages = 5538, .kept = 805306368, .taken = 0 } }}); + var copies = now3; // TF_KV_SHARE unset (or empty: kv_prompts.sharing): GLM's copies, no slot + copies.snap_bytes = 0; + try pinned(copies, .{ .room = 0, .engine = 0, .lanes = 8, .fixed = true, .cache = 16 * g, .window = 1_048_576 + 8, .engine_paged = true }, &.{ + .{ .room = 37 * g + 252 * mib, .plan = .{ .lanes = 8, .snaps = 0, .copied = 10198712320, .pages = 4098, .kept = 0, .taken = 6981156864 } }, + .{ .room = 41 * g + 992 * mib, .plan = .{ .lanes = 8, .snaps = 0, .copied = 1572732928, .pages = 6147, .kept = 0, .taken = 15607136256 } }, + }); + // a family whose kept states are pool pages (kept_ppm, no slot) under TF_KV_SHARE: Gemma 4's layout as above + const gemma: kv.Layout = .{ .fixed_bytes = 7_864_384, .token_bytes = 2_048, .page_tokens = 256, .snap_bytes = 0 }; + try pinned(gemma, .{ .room = 0, .engine = 0, .lanes = 8, .cache = 16 * mib, .window = 4096, .engine_paged = true, .kept_ppm = 1_000_000 }, &.{ + .{ .room = 24 * mib, .plan = .{ .lanes = 2, .snaps = 0, .copied = 0, .pages = 32, .kept = 524224, .taken = 7864320 } }, + .{ .room = 64 * mib, .plan = .{ .lanes = 7, .snaps = 0, .copied = 0, .pages = 37, .kept = 3145344, .taken = 5242880 } }, + .{ .room = 112 * mib, .plan = .{ .lanes = 8, .snaps = 0, .copied = 0, .pages = 118, .kept = 3669568, .taken = 13107648 } }, + .{ .room = 160 * mib, .plan = .{ .lanes = 8, .snaps = 0, .copied = 0, .pages = 160, .kept = 16777216, .taken = 0 } }, + }); +} + +test "with --parallel named, TF_KV_SHARE's kept states never fall as the room grows: no band, no window's edge" { + const g: u64 = 1 << 30; + const tp2: kv.Layout = .{ .fixed_bytes = 340 * mib, .token_bytes = 13_056, .page_tokens = 512, .snap_bytes = 180 * mib }; + const Case = struct { l: kv.Layout, lanes: u32, snaps: usize, window: u64 }; + const cases = [_]Case{ + .{ .l = .{ .fixed_bytes = 291 * mib, .token_bytes = 13_056, .page_tokens = 512, .snap_bytes = 115 * mib }, .lanes = 8, .snaps = 32, .window = 1_048_576 + 8 }, + .{ .l = now3, .lanes = 8, .snaps = 32, .window = 1_048_576 + 8 }, + .{ .l = tp2, .lanes = 4, .snaps = 16, .window = 630_000 + 8 }, + .{ .l = tp2, .lanes = 4, .snaps = 16, .window = 1_048_576 + 8 }, + }; + for (cases) |c| { + var last: usize = 0; + var room: u64 = 8 * g; + while (room <= 64 * g) : (room += 64 * mib) { + const p = kv.plan(c.l, .{ .room = room, .engine = 0, .lanes = c.lanes, .fixed = true, .cache = 16 * g, .snaps = c.snaps, .window = c.window, .engine_paged = true, .slots_only = true }) catch continue; // the streams don't fit yet + try expect(p.snaps >= last); + last = p.snaps; + } + try expectEqual(c.snaps, last); + } +} diff --git a/zig/src/families/glm/cuda_native.zig b/zig/src/families/glm/cuda_native.zig index 97f13ae1dd8..0aef928c1d5 100644 --- a/zig/src/families/glm/cuda_native.zig +++ b/zig/src/families/glm/cuda_native.zig @@ -106,7 +106,7 @@ pub fn share_states(p: *anyopaque, snaps: usize, parallel: u32, planned: ?kv.Bud if (n > 0) try readySnapshots(own, n * slot); const want = share_mod.advice(n, parallel, l, if (host) null else planned) orelse return; const why = "TF_KV_SHARE={d} keeps {d} states in the prompt cache's slots, under 4 a GLM stream at --parallel {d}: live streams evict each other's before a resume; "; - if (want.gib) |gib| std.log.warn(why ++ "{d} take TF_KV_SHARE={d} and --prompt-cache-gib {d}", .{ own.share, n, parallel, want.states, want.states, gib }) else std.log.warn(why ++ "the room holds {d} at any --prompt-cache-gib", .{ own.share, n, parallel, want.most }); + if (want.gib) |gib| std.log.warn(why ++ "{d} take TF_KV_SHARE={d} and --prompt-cache-gib {d}", .{ own.share, n, parallel, want.states, want.states, gib }) else if (want.most >= want.states) std.log.warn(why ++ "{d} take TF_KV_SHARE={d}", .{ own.share, n, parallel, want.states, want.states }) else std.log.warn(why ++ "the room holds {d} at any --prompt-cache-gib", .{ own.share, n, parallel, want.most }); } /// Rank 0, its pool attached: choose the expert form and publish MTP's window prices, timed or kept. diff --git a/zig/src/families/glm/cuda_share.zig b/zig/src/families/glm/cuda_share.zig index 75ee6b282a8..2eabbe11bdf 100644 --- a/zig/src/families/glm/cuda_share.zig +++ b/zig/src/families/glm/cuda_share.zig @@ -16,11 +16,15 @@ pub fn cacheable(s: *const Stream) bool { return s.prompt_logprobs == null and !s.untaught and s.embedding == null and cacheKey(s) != null; } -/// Below 4 states a stream: that many, and their slots' --prompt-cache-gib where asking it keeps all, else the most. +/// Below 4 states a stream: that many, the --prompt-cache-gib they need beside TF_KV_SHARE (null: none), and the most. pub fn advice(states: usize, parallel: usize, l: kv.Layout, planned: ?kv.Budget) ?struct { states: usize, gib: ?u64, most: usize } { const want = 4 * parallel; if (states >= want) return null; const b = planned orelse return .{ .states = want, .gib = kv.holdingGib(want, l.snap_bytes), .most = want }; + var named = b; // TF_KV_SHARE=want: its slots come before the windows past the engine's own (kv_pool.plan) + named.snaps = want; + if (!b.asked) named.cache = std.math.maxInt(u64); // and an unasked cache is sized after them (budgetOf) + if (if (kv.plan(l, named)) |p| p.snaps >= want else |_| false) return .{ .states = want, .gib = null, .most = want }; const h = kv.holding(l, b, want); return .{ .states = want, .gib = h.gib, .most = h.most }; } @@ -30,7 +34,7 @@ pub fn tooMany(states: usize) bool { return states > @import("core").kv_pool.most_snaps; } -test "TF_KV_SHARE: under 4 planned states a GLM stream, the advice names 4 a stream and, where it holds them, their cache" { +test "TF_KV_SHARE: under 4 planned states a GLM stream, the advice names 4 a stream, and a cache only if they need it" { const mib: u64 = 1 << 20; const g: u64 = 1 << 30; const l: kv.Layout = .{ .fixed_bytes = 340 * mib, .token_bytes = 13_056, .page_tokens = 512, .snap_bytes = 180 * mib }; @@ -44,11 +48,25 @@ test "TF_KV_SHARE: under 4 planned states a GLM stream, the advice names 4 a str try std.testing.expectEqual(@as(?u64, null), t.gib); // 3 GiB keeps no more there try std.testing.expectEqual(@as(usize, 15), t.most); var wide = tight; - wide.room = 24 * g; - try std.testing.expectEqual(@as(?u64, 3), advice(15, 4, l, wide).?.gib); + wide.room = 24 * g; // TF_KV_SHARE=16 alone keeps all 16 there: no --prompt-cache-gib is named + const w = advice(15, 4, l, wide).?; + try std.testing.expectEqual(@as(?u64, null), w.gib); + try std.testing.expectEqual(@as(usize, 16), w.most); var strip = tight; - strip.room = 16 * g + 11 * g / 16; // the 16 slots fit and 3 GiB doesn't: an asked 3 keeps all 16, so it is named - try std.testing.expectEqual(@as(?u64, 3), advice(15, 4, l, strip).?.gib); + strip.room = 16 * g + 11 * g / 16; // the 16 slots fit past the engine's own window, where TF_KV_SHARE's slots go + try std.testing.expectEqual(@as(?u64, null), advice(15, 4, l, strip).?.gib); + // TP=3 at Jammed XSFP4's 42.0 GiB, --parallel 8 (327 MiB fixed, a 168 MiB slot): TF_KV_SHARE=8 keeps its 8 + const now3: kv.Layout = .{ .fixed_bytes = 327 * mib, .token_bytes = 13_056, .page_tokens = 512, .snap_bytes = 168 * mib }; + const eight: kv.Budget = .{ .room = 41 * g + 992 * mib, .engine = 0, .lanes = 8, .fixed = true, .cache = 3 * g / 2, .snaps = 8, .window = 1_048_576 + 8, .engine_paged = true, .slots_only = true }; + const j = advice(8, 8, now3, eight).?; // 32 take TF_KV_SHARE=32 alone, though the cache sized for 8 holds 9 slots + try std.testing.expectEqual(@as(?u64, null), j.gib); + try std.testing.expectEqual(@as(usize, 32), j.most); + var small = eight; // --prompt-cache-gib 2 beside TF_KV_SHARE=32 keeps 12: the advice names both settings + small.snaps = 32; + small.asked = true; + small.cache = 2 * g; + try std.testing.expectEqual(@as(usize, 12), (try kv.plan(now3, small)).snaps); + try std.testing.expectEqual(@as(?u64, 6), advice(12, 8, now3, small).?.gib); } test "TF_KV_SHARE: up to 64 states is a plan's, 65 is refused" { diff --git a/zig/src/native/cuda_streams.zig b/zig/src/native/cuda_streams.zig index 53f38f2d063..303354eb1a2 100644 --- a/zig/src/native/cuda_streams.zig +++ b/zig/src/native/cuda_streams.zig @@ -121,6 +121,36 @@ test "TF_KV_SHARE's states take slots only with share on, a layout slot and the try std.testing.expect(try shareSlots(true, 1, true) == null); } +test "TF_KV_SHARE unset or empty plans as before: no slot, and GLM's copies take what the windows leave" { + if (comptime @import("builtin").os.tag == .windows) return error.SkipZigTest; + const env = @import("sys").env; + const name = "TF_KV_SHARE"; + const before = if (std.c.getenv(name)) |v| try std.testing.allocator.dupeSentinel(u8, std.mem.span(v), 0) else null; + defer { + if (before) |v| { + _ = env.setenv(name, v, 1); + std.testing.allocator.free(v); + } else _ = env.unsetenv(name); + } + const Glm = struct { + pub const share_kept_ppm: u32 = 0; + pub const window_rows = 8; + }; + const mib: u64 = 1 << 20; + // GLM at TP=3 without the share (327 MiB fixed, no slot), --parallel 8, a 1M window, Jammed XSFP4's 42.0 GiB + const l: kv_pool.Layout = .{ .fixed_bytes = 327 * mib, .token_bytes = 13_056, .page_tokens = 512, .snap_bytes = 0 }; + const o: api.Open = .{ .dir = "", .model_type = "g", .lanes = 8, .lanes_fixed = true }; + for ([_]?[:0]const u8{ null, "", " " }) |v| { + _ = if (v) |s| env.setenv(name, s, 1) else env.unsetenv(name); + const share = try @import("core").kv_prompts.sharing() > 0; + const slots = try shareSlots(share, l.snap_bytes, false); + try std.testing.expectEqual(@as(?usize, null), slots); + const b = kv_pages.budgetOf(Glm, l, (41 << 30) + 992 * mib, o, 1_048_576, false, true, keptPpm(Glm, share), slots); + try std.testing.expect(!b.slots_only); + try std.testing.expectEqual(kv_pool.Plan{ .lanes = 8, .snaps = 0, .copied = 1572732928, .pages = 6147 }, try kv_pool.plan(l, b)); + } +} + test "CUDA cache default uses the declared request ledger windows and scratch" { const GiB: u64 = 1 << 30; var counted: Count = .{ .streams = 8, .paged = null, .layout = null }; From b48d62a6202ed3f9fb4aebd1e5301bc950a8f305 Mon Sep 17 00:00:00 2001 From: Bizuayeu <30091157+Bizuayeu@users.noreply.github.com> Date: Fri, 13 Nov 2026 21:14:09 +0900 Subject: [PATCH 08/14] docs: the memory plan sets a named TF_KV_SHARE's slots where a named cache goes --- docs/api.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/api.md b/docs/api.md index f62e7151f9b..f74d829fbeb 100644 --- a/docs/api.md +++ b/docs/api.md @@ -879,9 +879,11 @@ one from 0.5 GiB up. With pages, the plan takes the engine's own window first, then each other stream's fixed part, then the prompt cache: a named `--prompt-cache-gib` comes before every window but the engine's own, and an unnamed one after the whole -windows the budget holds, half of what they leave but at least 16 GiB and at most all of it (#2987 shows what that -does to `TF_KV_SHARE`'s states). The cache then holds the kept states (on GLM with `TF_KV_SHARE`, a slot a state, the -rest of it made pages), and the rest of the budget becomes pages, up to the streams' windows plus the cache's pages. +windows the budget holds, half of what they leave but at least 16 GiB and at most all of it. On GLM with +`TF_KV_SHARE` named and the cache unnamed, the kept states' slots, `TF_KV_SHARE` at most, come where a named cache +goes, and the rest of the cache after the windows. The cache then holds the kept states (on GLM with `TF_KV_SHARE`, +a slot a state, the rest of it made pages), and the rest of the budget becomes pages, up to the streams' windows plus +the cache's pages. The settings that decide each part: | Setting | Kind | Scope | Unset | What it decides | Read in | From 8a5fdddbc2beff258a06232b17c6d0ffbf97740b Mon Sep 17 00:00:00 2001 From: Bizuayeu <30091157+Bizuayeu@users.noreply.github.com> Date: Fri, 13 Nov 2026 11:18:16 +0900 Subject: [PATCH 09/14] changelog: #3125 under Unreleased --- CHANGELOG.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index f85517a0ce0..f1024bf3380 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -40,6 +40,13 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Server: an Ollama-compatible API serves `/api/chat`, `/api/generate`, `/api/embed`, `/api/tags`, `/api/show`, `/api/ps` and `/api/version` through the same chat, completions and embeddings paths as the OpenAI routes, with NDJSON streaming and named refusals for unsupported options (#3342, fixes #3117). - Server: each `/v1/models` entry now ends with `input_types`, the content parts the model takes: `["text"]`, plus `"image"` with `--vision`, plus `"video"` when the checkpoint reads video and the server loads `libtfvideo`. A `video_url` part sent to a model without video now gets HTTP 400 (`invalid_request_error`) instead of a 500, decided by the same startup check, so the listing and the refusal agree; a server whose model reads video loads `libtfvideo` at startup and says once in its log when it is missing. The other keys are unchanged (#3019, fixes #3004). Thanks to @WebReflection for the design. +- Unlimited-OCR-2 on native Metal (M5 GPUs): Baidu's BF16 release as published serves page images through + `tensorfold-native serve --vision`; one stream, greedy, up to 131,072 tokens. On the recipe's single pages its text + is identical to the release's own `infer` in torch bf16, or departs from it only where two candidate tokens lie + within one bf16 step of each other, the same two torch's float32 run weighs. The five-page document is served the + same way; its departures are listed in the recipe beside float32's (#2074). Thanks to @BobClawblaw. +- GLM-5.3-Flash on CUDA with `TF_KV_SHARE` and no `--prompt-cache-gib`: the kept states' slots, `TF_KV_SHARE` at most, now come where an asked cache goes, before the windows past the engine's own, so a room that holds one more whole window no longer keeps fewer states; Jammed XSFP4 at TP=3 on three GB10s keeps all 32 at `TF_KV_SHARE=32` instead of 8, with the same tokens (#3125). Thanks to @Bizuayeu. + - Server: with thinking off, the reasoning effort a request names reaches the chat template (GLM's head follows it), and the reply reports it; a server's own `--reasoning-effort` no longer changes a thinking-off prompt (#3017, fixes #1911). Thanks to @ss-cong for the report. From af2cce4e082c0f0344d1979f296e301c6cb479ef Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sun, 15 Nov 2026 02:54:06 +0000 Subject: [PATCH 10/14] changelog: back under Unreleased --- CHANGELOG.md | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f1024bf3380..a07f48c16a9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- GLM-5.3-Flash on CUDA with `TF_KV_SHARE` and no `--prompt-cache-gib`: the kept states' slots, `TF_KV_SHARE` at most, now come where an asked cache goes, before the windows past the engine's own, so a room that holds one more whole window no longer keeps fewer states; Jammed XSFP4 at TP=3 on three GB10s keeps all 32 at `TF_KV_SHARE=32` instead of 8, with the same tokens (#3125). Thanks to @Bizuayeu. - Metal: Baidu's Unlimited-OCR-2 is served natively from its BF16 release on M5-class Macs: page images through `serve --vision`, the family's chat template built in, its SAM and CLIP image encoders and decoder under the kernel contract; on five reference pages every departure from the release's own reply is a one-step tie (#2074). Thanks to @BobClawblaw. - Unlimited-OCR-2 on native Metal (M5 GPUs): Baidu's BF16 release as published serves page images through `tensorfold-native serve --vision`; one stream, greedy, up to 131,072 tokens. On the recipe's single pages its text @@ -40,13 +41,6 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Server: an Ollama-compatible API serves `/api/chat`, `/api/generate`, `/api/embed`, `/api/tags`, `/api/show`, `/api/ps` and `/api/version` through the same chat, completions and embeddings paths as the OpenAI routes, with NDJSON streaming and named refusals for unsupported options (#3342, fixes #3117). - Server: each `/v1/models` entry now ends with `input_types`, the content parts the model takes: `["text"]`, plus `"image"` with `--vision`, plus `"video"` when the checkpoint reads video and the server loads `libtfvideo`. A `video_url` part sent to a model without video now gets HTTP 400 (`invalid_request_error`) instead of a 500, decided by the same startup check, so the listing and the refusal agree; a server whose model reads video loads `libtfvideo` at startup and says once in its log when it is missing. The other keys are unchanged (#3019, fixes #3004). Thanks to @WebReflection for the design. -- Unlimited-OCR-2 on native Metal (M5 GPUs): Baidu's BF16 release as published serves page images through - `tensorfold-native serve --vision`; one stream, greedy, up to 131,072 tokens. On the recipe's single pages its text - is identical to the release's own `infer` in torch bf16, or departs from it only where two candidate tokens lie - within one bf16 step of each other, the same two torch's float32 run weighs. The five-page document is served the - same way; its departures are listed in the recipe beside float32's (#2074). Thanks to @BobClawblaw. -- GLM-5.3-Flash on CUDA with `TF_KV_SHARE` and no `--prompt-cache-gib`: the kept states' slots, `TF_KV_SHARE` at most, now come where an asked cache goes, before the windows past the engine's own, so a room that holds one more whole window no longer keeps fewer states; Jammed XSFP4 at TP=3 on three GB10s keeps all 32 at `TF_KV_SHARE=32` instead of 8, with the same tokens (#3125). Thanks to @Bizuayeu. - - Server: with thinking off, the reasoning effort a request names reaches the chat template (GLM's head follows it), and the reply reports it; a server's own `--reasoning-effort` no longer changes a thinking-off prompt (#3017, fixes #1911). Thanks to @ss-cong for the report. From 49b76e06d0df06a85fd226f65eebb1494a4b049e Mon Sep 17 00:00:00 2001 From: Bizuayeu <30091157+Bizuayeu@users.noreply.github.com> Date: Fri, 13 Nov 2026 11:18:16 +0900 Subject: [PATCH 11/14] changelog: #3125 under Unreleased --- CHANGELOG.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index a07f48c16a9..ddf21230922 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,6 +41,13 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Server: an Ollama-compatible API serves `/api/chat`, `/api/generate`, `/api/embed`, `/api/tags`, `/api/show`, `/api/ps` and `/api/version` through the same chat, completions and embeddings paths as the OpenAI routes, with NDJSON streaming and named refusals for unsupported options (#3342, fixes #3117). - Server: each `/v1/models` entry now ends with `input_types`, the content parts the model takes: `["text"]`, plus `"image"` with `--vision`, plus `"video"` when the checkpoint reads video and the server loads `libtfvideo`. A `video_url` part sent to a model without video now gets HTTP 400 (`invalid_request_error`) instead of a 500, decided by the same startup check, so the listing and the refusal agree; a server whose model reads video loads `libtfvideo` at startup and says once in its log when it is missing. The other keys are unchanged (#3019, fixes #3004). Thanks to @WebReflection for the design. +- Unlimited-OCR-2 on native Metal (M5 GPUs): Baidu's BF16 release as published serves page images through + `tensorfold-native serve --vision`; one stream, greedy, up to 131,072 tokens. On the recipe's single pages its text + is identical to the release's own `infer` in torch bf16, or departs from it only where two candidate tokens lie + within one bf16 step of each other, the same two torch's float32 run weighs. The five-page document is served the + same way; its departures are listed in the recipe beside float32's (#2074). Thanks to @BobClawblaw. +- GLM-5.3-Flash on CUDA with `TF_KV_SHARE` and no `--prompt-cache-gib`: the kept states' slots, `TF_KV_SHARE` at most, now come where an asked cache goes, before the windows past the engine's own, so a room that holds one more whole window no longer keeps fewer states; Jammed XSFP4 at TP=3 on three GB10s keeps all 32 at `TF_KV_SHARE=32` instead of 8, with the same tokens (#3125). Thanks to @Bizuayeu. + - Server: with thinking off, the reasoning effort a request names reaches the chat template (GLM's head follows it), and the reply reports it; a server's own `--reasoning-effort` no longer changes a thinking-off prompt (#3017, fixes #1911). Thanks to @ss-cong for the report. From db064529bc718d7c0fe961cf02525eb1805801a9 Mon Sep 17 00:00:00 2001 From: Abraham <119352736+AbrahamCete@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:14:31 +0100 Subject: [PATCH 12/14] feat(hip): a tuning row can bound the width of the codes it takes A row said which products its entry takes by rows, items and pairs, and nothing about the weights' width. Timings on gfx1151 show a choice that turns with it: of the two K-parallel tiles a plain prompt of 1 row can run on, one is ahead on 2-bit and 3-bit codes and the other from 4-bit up. `max_bits` is the most bits a weight code holds for the row to take a product (0, the default: any). The registry's cost check refuses wider codes for plain products and plans alike. A bound that does not parse refuses its row instead of being ignored: - a bound that is no code width (2, 3, 4, 5, 6 or 8) stops the build of the table that writes it, naming the entry and the bound, where 7 or 9 would have read as "up to 6" or "any"; a row made by hand with such a bound takes no product. The registry and the kernel cases read the widths from one list, beside the row type; - `tuning.build` copies an entry's fields by name and dropped the ones the row type lacks, so a misspelled bound left its row taking every product. Such a field now stops the build, naming the entry and the field. Every field the four tables carry is the row type's. `hip-affine-tune` prints the bound with a row it proposes. No table sets the bound yet, so no choice changes. Refs #2923 --- zig/src/core/registry.zig | 38 +++++++++++++++++++++- zig/src/core/tuning.zig | 41 ++++++++++++++++++++++++ zig/src/hip/kernel_tests/affine/tune.zig | 1 + zig/src/hip/tuning/gfx1030.zon | 1 + zig/src/hip/tuning/gfx1100.zon | 1 + zig/src/hip/tuning/gfx1151.zon | 1 + zig/src/hip/tuning/gfx1201.zon | 1 + zig/src/hip/tuning/tuning.zig | 7 ++++ 8 files changed, 90 insertions(+), 1 deletion(-) diff --git a/zig/src/core/registry.zig b/zig/src/core/registry.zig index e0ea439046e..2a44764e638 100644 --- a/zig/src/core/registry.zig +++ b/zig/src/core/registry.zig @@ -91,6 +91,9 @@ pub fn Entry(comptime Launch: type) type { /// Room for the entries' tuned rows: a Registry sits in a backend's kernel table, so its size is fixed. pub const max_entries = 64; +/// The widths a format's codes come in: the list a tuning row's bound is checked against. +pub const widths = tuning.widths; + /// The most rows the family rule is checked at. pub const rule_rows = 256; @@ -129,6 +132,8 @@ pub fn Registry(comptime Launch: type) type { if (t.items != 0 and plan and shape.items > t.items) return null; if (t.pairs_per_item > 0 and plan and shape.plan_pairs != 0 and @as(f64, @floatFromInt(shape.plan_pairs)) > @as(f64, t.pairs_per_item) * @as(f64, @floatFromInt(shape.items))) return null; + // wider codes than the bound are refused; so is a row made by hand whose bound is no code width + if (!tuning.widthBound(t.max_bits) or (t.max_bits != 0 and shape.bits > t.max_bits)) return null; // a routed prompt's kernel ignores the rows one item holds (`m`): its items and pairs bound it if (!plan or e.path == .decode) { const limit = if (t.rows_matrix != 0 and env.matrix_on and env.matrix) t.rows_matrix else t.rows; @@ -173,7 +178,7 @@ pub fn Registry(comptime Launch: type) type { pub fn verify(r: *const Self, env: Env, format: quant.Format) error{FamilyChanges}!void { // the reference decode tiles and the reference GEMM tile are the Python engine's rules, by row count if (!env.stream_on or !env.gemm_on) return; - for ([_]u8{ 2, 3, 4, 5, 6, 8 }) |bits| for ([_]u16{ 32, 64, 128 }) |group| { + for (widths) |bits| for ([_]u16{ 32, 64, 128 }) |group| { var base: Shape = .{ .m = 1, .n = 4096, .k = 4096, .bits = bits, .group = group, .fp16 = !env.bf16, .tables = if (env.bf16) .bf16 else .f16 }; base.round = true; try r.rule(env, format, .project, .decode, base, false); @@ -361,6 +366,37 @@ test "a plan past its entry's pairs per item takes the next entry" { try std.testing.expect(std.mem.endsWith(u8, h.select(toy_env, .mlx, .project, .prefill, shape).?.id, "k1")); } +test "an entry bounded by the codes' width takes no wider product, and none when its bound is no code width" { + const entries = [_]ToyEntry{ + toy("a.prefill.narrow", .prefill, .gemm, false), + toy("a.prefill.any", .prefill, .gemm, false), + }; + const rows = [_]tuning.Row{ + .{ .id = "a.prefill.narrow", .cost = 1, .max_bits = 3 }, + .{ .id = "a.prefill.any", .cost = 2 }, + }; + const r = Toy.init(&.{ .gfx = "toy", .rows = &rows }, &entries); + var shape = toy_shape; + const want = [_]struct { u8, []const u8 }{ .{ 2, "narrow" }, .{ 3, "narrow" }, .{ 4, "any" }, .{ 5, "any" }, .{ 6, "any" }, .{ 8, "any" } }; + for ([_]u32{ 0, 100 }) |items| for (want) |w| { + // a plan is bounded as a plain product is + shape.items = items; + shape.bits = w[0]; + try std.testing.expect(std.mem.endsWith(u8, r.select(toy_env, .mlx, .project, .prefill, shape).?.id, w[1])); + }; + // a bound that is no code width is a table error: its row takes nothing, where 7 or 9 would have taken 3-bit codes + shape.items = 0; + for ([_]u8{ 1, 7, 9, 255 }) |bound| { + var wrong = rows; + wrong[0].max_bits = bound; + const w = Toy.init(&.{ .gfx = "toy", .rows = &wrong }, &entries); + for (widths) |bits| { + shape.bits = bits; + try std.testing.expect(std.mem.endsWith(u8, w.select(toy_env, .mlx, .project, .prefill, shape).?.id, "any")); + } + } +} + test "the family rule refuses a path whose family changes with the rows" { const entries = [_]ToyEntry{ toy("a.decode.small", .decode, .stream, false), diff --git a/zig/src/core/tuning.zig b/zig/src/core/tuning.zig index 45a8a169483..d7a527b0d1a 100644 --- a/zig/src/core/tuning.zig +++ b/zig/src/core/tuning.zig @@ -14,12 +14,17 @@ pub const Row = struct { pairs_per_item: f32 = 0, /// A routed prompt item of at most this many rows takes its kernel's K-parallel passes (0: none does). few_rows: u32 = 0, + /// The most bits a weight code holds (0: any); a bound that is no code width takes no product. + max_bits: u8 = 0, plain: bool = true, routed: bool = true, }; pub const Table = struct { gfx: []const u8, rows: []const Row }; +/// The widths a format's codes come in. +pub const widths = [_]u8{ 2, 3, 4, 5, 6, 8 }; + /// The table a .zon document of `gfx` and `entries` describes. pub fn build(comptime zon: anytype) Table { const rows = comptime blk: { @@ -27,11 +32,15 @@ pub fn build(comptime zon: anytype) Table { @setEvalBranchQuota(1000 + 100 * zon.entries.len * @typeInfo(Row).@"struct".field_names.len); var out: [zon.entries.len]Row = undefined; for (zon.entries, 0..) |e, i| { + // a field read by name is dropped when misspelled, and a dropped bound takes every product + if (stray(e)) |name| @compileError("tuning: " ++ e.id ++ " has a field no row has: " ++ name); var row: Row = .{ .id = e.id, .cost = e.cost }; for (@typeInfo(Row).@"struct".field_names) |name| { if (std.mem.eql(u8, name, "id") or std.mem.eql(u8, name, "cost")) continue; if (@hasField(@TypeOf(e), name)) @field(row, name) = @field(e, name); } + // a bound that is no code width would take no product at all: it is reported here, where it is written + if (!widthBound(row.max_bits)) @compileError(std.fmt.comptimePrint("tuning: {s} bounds its codes at {d} bits, which is no width they come in", .{ e.id, row.max_bits })); out[i] = row; } break :blk out; @@ -39,6 +48,19 @@ pub fn build(comptime zon: anytype) Table { return .{ .gfx = zon.gfx, .rows = &rows }; } +/// The first field of a table entry that the row type lacks, or null. +pub fn stray(comptime e: anytype) ?[]const u8 { + for (@typeInfo(@TypeOf(e)).@"struct".field_names) |name| { + if (!@hasField(Row, name)) return name; + } + return null; +} + +/// Whether `max_bits` is a bound a row may carry: 0 for any width, or a width the codes come in. +pub fn widthBound(max_bits: u8) bool { + return max_bits == 0 or std.mem.indexOfScalar(u8, &widths, max_bits) != null; +} + pub fn find(t: *const Table, id: []const u8) ?Row { for (t.rows) |r| if (std.mem.eql(u8, r.id, id)) return r; return null; @@ -50,3 +72,22 @@ test "a table is found by an entry's id" { try std.testing.expectEqual(@as(u32, 8), find(&t, "b").?.rows); try std.testing.expect(find(&t, "c") == null); } + +test "a field the row type lacks is found in an entry, so a misspelled bound stops the build instead of being dropped" { + try std.testing.expect(comptime stray(.{ .id = "a", .cost = 1, .rows = 8, .max_bits = 3 }) == null); + const misspelled = comptime stray(.{ .id = "a", .cost = 1, .max_bit = 3 }); + try std.testing.expectEqualStrings("max_bit", misspelled orelse ""); + const t = comptime build(.{ .gfx = "toy", .entries = .{.{ .id = "a", .cost = 1, .max_bits = 3 }} }); + try std.testing.expectEqual(@as(u8, 3), find(&t, "a").?.max_bits); +} + +test "a width bound that is no code width is told apart, so a table that writes one stops the build instead of taking nothing" { + try std.testing.expect(widthBound(0)); + for (widths) |bits| try std.testing.expect(widthBound(bits)); + for ([_]u8{ 1, 7, 9, 255 }) |bits| try std.testing.expect(!widthBound(bits)); + // every width is a bound a table may write + inline for (widths) |bits| { + const t = comptime build(.{ .gfx = "toy", .entries = .{.{ .id = "a", .cost = 1, .max_bits = bits }} }); + try std.testing.expectEqual(@as(u8, bits), find(&t, "a").?.max_bits); + } +} diff --git a/zig/src/hip/kernel_tests/affine/tune.zig b/zig/src/hip/kernel_tests/affine/tune.zig index 3004f3abb35..bf6e274b1fb 100644 --- a/zig/src/hip/kernel_tests/affine/tune.zig +++ b/zig/src/hip/kernel_tests/affine/tune.zig @@ -145,6 +145,7 @@ fn printRow(r: tuning.Row) void { if (r.min_rows != 0) std.debug.print(", .min_rows = {d}", .{r.min_rows}); if (r.items != 0) std.debug.print(", .items = {d}", .{r.items}); if (r.pairs_per_item != 0) std.debug.print(", .pairs_per_item = {d}", .{r.pairs_per_item}); + if (r.max_bits != 0) std.debug.print(", .max_bits = {d}", .{r.max_bits}); if (!r.plain) std.debug.print(", .plain = false", .{}); if (!r.routed) std.debug.print(", .routed = false", .{}); std.debug.print(" }},\n", .{}); diff --git a/zig/src/hip/tuning/gfx1030.zon b/zig/src/hip/tuning/gfx1030.zon index a420e64cb4b..e08a2d9d2dd 100644 --- a/zig/src/hip/tuning/gfx1030.zon +++ b/zig/src/hip/tuning/gfx1030.zon @@ -5,6 +5,7 @@ // rows the most rows of a plain product (0: any), and rows_matrix the most when the matrix cores take the rows above it // min_rows the fewest rows // items the most items of a routed plan (0: any) +// max_bits the most bits a weight code holds (0: any) // plain, routed whether it takes plain products, routed plans (both by default) // The numbers are the thresholds the launches kept before the registry; a measured table replaces them. .{ diff --git a/zig/src/hip/tuning/gfx1100.zon b/zig/src/hip/tuning/gfx1100.zon index 462330a8b18..cec269ef7e1 100644 --- a/zig/src/hip/tuning/gfx1100.zon +++ b/zig/src/hip/tuning/gfx1100.zon @@ -5,6 +5,7 @@ // rows the most rows of a plain product (0: any), and rows_matrix the most when the matrix cores take the rows above it // min_rows the fewest rows // items the most items of a routed plan (0: any) +// max_bits the most bits a weight code holds (0: any) // plain, routed whether it takes plain products, routed plans (both by default) // The numbers are the thresholds the launches kept before the registry; a measured table replaces them. .{ diff --git a/zig/src/hip/tuning/gfx1151.zon b/zig/src/hip/tuning/gfx1151.zon index cdecfe82346..919a2110dc2 100644 --- a/zig/src/hip/tuning/gfx1151.zon +++ b/zig/src/hip/tuning/gfx1151.zon @@ -8,6 +8,7 @@ // items the most items of a routed plan (0: any) // pairs_per_item the most pairs a routed plan holds per item (0: any) // few_rows a routed prompt item of at most this many rows takes the kernel's K-parallel passes (0: none) +// max_bits the most bits a weight code holds (0: any) // plain, routed whether it takes plain products, routed plans (both by default) // gfx1100's rows, plus the 64-row routed matrix-core tile below 12 pairs an item (measured on gfx1151), // and the skewed-row matrix tile (three blocks a WGP) ahead of the padded one where it takes a product. diff --git a/zig/src/hip/tuning/gfx1201.zon b/zig/src/hip/tuning/gfx1201.zon index a7c6052812b..ea0fafb19e8 100644 --- a/zig/src/hip/tuning/gfx1201.zon +++ b/zig/src/hip/tuning/gfx1201.zon @@ -6,6 +6,7 @@ // min_rows the fewest rows // items the most items of a routed plan (0: any) // pairs_per_item the most pairs a routed plan holds per item (0: any) +// max_bits the most bits a weight code holds (0: any) // plain, routed whether it takes plain products, routed plans (both by default) // The decode rows are gfx1100's, so decode choices are the same; the matrix rows are gfx1100's too, and never run here. // The prompt rows keep gfx1100's bounds, which `zig build hip-affine-tune` measures against on a gfx1201 card, but diff --git a/zig/src/hip/tuning/tuning.zig b/zig/src/hip/tuning/tuning.zig index b294625a2ba..90c4c2fa979 100644 --- a/zig/src/hip/tuning/tuning.zig +++ b/zig/src/hip/tuning/tuning.zig @@ -2,6 +2,7 @@ const std = @import("std"); const tuning = @import("core").tuning; +const registry = @import("core").registry; pub const Row = tuning.Row; pub const Table = tuning.Table; @@ -29,6 +30,12 @@ test "only the routed prompt's item tile cuts at few rows, at no more than its K try std.testing.expect(find(&gfx1151, "mlx.routed.prefill.item64").?.few_rows != 0); } +test "a row's width bound is a width the codes come in" { + for ([_]*const Table{ &gfx1030, &gfx1100, &gfx1151, &gfx1201 }) |t| for (t.rows) |r| { + if (r.max_bits != 0) try std.testing.expect(std.mem.indexOfScalar(u8, ®istry.widths, r.max_bits) != null); + }; +} + test "the tables name each entry once" { for ([_]*const Table{ &gfx1030, &gfx1100, &gfx1151, &gfx1201 }) |t| { for (t.rows, 0..) |r, i| { From 1587dee1f9ff2365938c6da697abfc439e8a4888 Mon Sep 17 00:00:00 2001 From: Abraham <119352736+AbrahamCete@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:15:24 +0100 Subject: [PATCH 13/14] perf(hip): on gfx1151 a plain prompt of 1 or 2 rows takes the 2-row K-parallel tile A plain prompt product of 1 or 2 rows ran on `kp0` (8 columns a lane set, 1 row a pass) on every card. On gfx1151 `kp3` (4 columns, 2 rows a pass) is ahead at 2 rows at every width, and at 1 row from 4-bit codes up; at 1 row of 2-bit or 3-bit codes `kp0` stays ahead. A resumed prompt ends in such a piece whenever 1 or 2 tokens follow the kept state. gfx1151's table now gives `kp0` one row of codes of at most 3 bits and `kp3` the other plain products of up to 2 rows. Costs stay as they were, so `kp0` keeps the products its row still takes and no row is shadowed. Nothing else is chosen differently: products of 3 rows and more, routed plans, decode and the other three tables keep their tiles. Both tiles are one template and write the 128-row tile's bytes. Tests: - launches: at every width gfx1151 picks `kp3` at 2 rows and, at 1 row, `kp0` for 2-bit and 3-bit codes and `kp3` from 4-bit up, with the matrix cores on or off; it keeps `kp1` and `kp2` past 2 rows and the reference tile with the dot2 GEMM tiles off; gfx1030, gfx1100 and gfx1201 still pick `kp0`. - tuning: gfx1151's bound is set, so a table that lost it fails. - kernel suite: `kp0`, `kp3` and the 128-row dot2 tile, launched by id whatever the card's table picks, write the same bytes at 1 and 2 rows, every width and group, fp32 and rounded into out16; an output left unwritten fails too. Refs #2923 --- zig/src/hip/kernel_tests/affine/cases.zig | 3 +- zig/src/hip/kernel_tests/affine/rows.zig | 58 +++++++++++++++++++++++ zig/src/hip/launches/mlx_entries.zig | 27 +++++++++++ zig/src/hip/tuning/gfx1151.zon | 6 ++- zig/src/hip/tuning/tuning.zig | 2 + 5 files changed, 93 insertions(+), 3 deletions(-) diff --git a/zig/src/hip/kernel_tests/affine/cases.zig b/zig/src/hip/kernel_tests/affine/cases.zig index cf68a09ced8..c645ffa4b02 100644 --- a/zig/src/hip/kernel_tests/affine/cases.zig +++ b/zig/src/hip/kernel_tests/affine/cases.zig @@ -119,7 +119,8 @@ pub const prefill = [_]Case{ .{ .name = "flash next served gate_up", .path = .prefill, .rows = 42, .n = 1280, .k = 2560, .group = 32, .experts = 512, .slots = 11, .shared = true, .served = true, .exact = true }, }; -pub const widths = [_]u8{ 2, 3, 4, 5, 6, 8 }; +/// The registry's own list: the kernel cases and the selection tests walk the same widths. +pub const widths = registry.widths; pub const groups = [_]u16{ 32, 64, 128 }; /// A short prompt's few rows, for the timings of each tile on dense and routed products. diff --git a/zig/src/hip/kernel_tests/affine/rows.zig b/zig/src/hip/kernel_tests/affine/rows.zig index 171f7fb55e9..595938441a5 100644 --- a/zig/src/hip/kernel_tests/affine/rows.zig +++ b/zig/src/hip/kernel_tests/affine/rows.zig @@ -394,6 +394,55 @@ fn tiers(t: *Rig) !usize { return ran; } +/// The tiles a table may give a plain prompt of 1 or 2 rows, and the 128-row dot2 tile whose bytes they keep. +const few_row_tiles = [_][]const u8{ "mlx.project.prefill.kp0", "mlx.project.prefill.kp3", "mlx.project.prefill.gemm" }; + +fn named(p: *const prod.Product, id: []const u8) ?*const Entry { + for (p.rig.kernels.reg.entries) |*e| if (std.mem.eql(u8, e.id, id) and prod.takes(p, e)) return e; + return null; +} + +/// One plain product through each of `few_row_tiles` by id, whatever the GPU's table picks: launches unlike the first. +fn fewRowProduct(t: *Rig, c: shapes.Case) !usize { + var p = try prod.Product.init(t, c); + defer p.deinit(); + var out = try Buffer.alloc(t.base, p.outBytes(false)); + defer out.free(); + var bad: usize = 0; + for ([_]bool{ false, true }) |rounded| { + const len = p.outBytes(rounded); + try out.fill8(0xA5, null); + const unwritten = try prod.digestOf(out, len); + var want: u64 = 0; + for (few_row_tiles, 0..) |id, i| { + const e = named(&p, id) orelse return error.NoTile; + try out.fill8(0xA5, null); + try prod.launchEntry(&p, e, out, rounded, 0, 0); + try t.base.stream.synchronize(); + const got = try prod.digestOf(out, len); + if (i == 0) want = got; + if (got == want and got != unwritten) continue; + std.debug.print(" {s} rounded {}: {x:0>16}, {s} wrote {x:0>16}, an unwritten output is {x:0>16}\n", .{ id, rounded, got, few_row_tiles[0], want, unwritten }); + bad += 1; + } + } + return bad; +} + +/// Every width and group at 1 and 2 rows, on the shapes `tiers` runs: n off every block width, k short or long. +fn fewRowTiers(t: *Rig) !usize { + var ran: usize = 0; + for (shapes.widths) |bits| for (shapes.groups) |group| for ([_]usize{ 1, 2 }) |m| { + const ks = [_]usize{ 3 * @as(usize, group), if (group == 32) 2080 else 1024 }; + for (ks, [_]usize{ 97, 288 }) |k, n| { + const bad = try fewRowProduct(t, .{ .name = "few rows", .path = .prefill, .rows = m, .n = n, .k = k, .bits = bits, .group = group }); + try base.expect(bad == 0, "few rows m{d} n{d} k{d} b{d} g{d}: {d} launches write other bytes than the 1-row tile, or none", .{ m, n, k, bits, group, bad }); + ran += 1; + } + }; + return ran; +} + /// Decode: the rows of a lane round's launch against each row alone, plain products and routed plans. pub fn decode(t: *Rig) !void { var rng: data.Rng = .{ .state = 0x9E3779B97F4A7C15 }; @@ -425,3 +474,12 @@ test "a prompt row writes the same bytes in every tile, dense and routed, every var rig = Rig.open(b); try prefill(&rig); } + +test "a plain prompt of 1 or 2 rows writes the same bytes on the 1-row and 2-row K-parallel tiles and the 128-row tile, fp32 and rounded" { + const b = try base.Rig.open(1 << 20); + defer b.close(); + var rig = Rig.open(b); + const ran = try fewRowTiers(&rig); + std.debug.print("FEW ROWS {d} products on {d} tiles each, fp32 and out16\n", .{ ran, few_row_tiles.len }); + try base.expect(ran == 2 * 2 * shapes.widths.len * shapes.groups.len, "few rows: only {d} products ran", .{ran}); +} diff --git a/zig/src/hip/launches/mlx_entries.zig b/zig/src/hip/launches/mlx_entries.zig index 02e8a51b863..7f23a48e310 100644 --- a/zig/src/hip/launches/mlx_entries.zig +++ b/zig/src/hip/launches/mlx_entries.zig @@ -439,6 +439,33 @@ test "a prompt takes the K-parallel tiles by rows and by items, then the 128-row try std.testing.expect(std.mem.endsWith(u8, v.select(envOn("gfx1030", true, true, false), .mlx, .routed, .prefill, shape).?.id, "kp1")); } +test "gfx1151 takes the 2-row K-parallel tile for a plain prompt of 1 or 2 rows, the 1-row tile for 1 row of 2-bit or 3-bit codes" { + const r = kernelsOn("gfx1151"); + var shape: Shape = .{ .m = 1, .n = 4096, .k = 4096, .bits = 4, .group = 64, .fp16 = false }; + // from 2 rows up every width takes the same tiles, with the matrix cores on or off + const plain = [_]struct { u32, []const u8 }{ .{ 2, "kp3" }, .{ 3, "kp1" }, .{ 4, "kp1" }, .{ 5, "kp2" }, .{ 32, "kp2" } }; + for ([_]bool{ true, false }) |matrix_on| for (registry.widths) |bits| { + const env = envOn("gfx1151", true, true, matrix_on); + shape.bits = bits; + // one row: the 1-row tile is ahead on 2-bit and 3-bit codes, the 2-row tile from 4-bit up (measured on gfx1151) + shape.m = 1; + try std.testing.expect(std.mem.endsWith(u8, r.select(env, .mlx, .project, .prefill, shape).?.id, if (bits <= 3) "kp0" else "kp3")); + for (plain) |p| { + shape.m = p[0]; + try std.testing.expect(std.mem.endsWith(u8, r.select(env, .mlx, .project, .prefill, shape).?.id, p[1])); + } + }; + // with the dot2 GEMM tiles switched off the reference tile still runs + shape.bits = 4; + shape.m = 2; + try std.testing.expect(std.mem.endsWith(u8, r.select(envOn("gfx1151", true, false, false), .mlx, .project, .prefill, shape).?.id, "block")); + // the other GPUs' tables keep the 1-row tile at 1 and 2 rows, whatever the width + for ([_][]const u8{ "gfx1030", "gfx1100", "gfx1201" }) |gfx| for (registry.widths) |bits| for ([_]u32{ 1, 2 }) |m| { + shape = .{ .m = m, .n = 4096, .k = 4096, .bits = bits, .group = 64, .fp16 = Caps.of(gfx).?.act != .bf16 }; + try std.testing.expect(std.mem.endsWith(u8, kernelsOn(gfx).select(envOn(gfx, true, true, false), .mlx, .project, .prefill, shape).?.id, "kp0")); + }; +} + test "a routed prompt past its pairs per item leaves the K-parallel tiles for the 128-row tile" { const tuning = @import("../tuning/tuning.zig"); const bounded = comptime blk: { diff --git a/zig/src/hip/tuning/gfx1151.zon b/zig/src/hip/tuning/gfx1151.zon index 919a2110dc2..a4941e41a04 100644 --- a/zig/src/hip/tuning/gfx1151.zon +++ b/zig/src/hip/tuning/gfx1151.zon @@ -13,6 +13,8 @@ // gfx1100's rows, plus the 64-row routed matrix-core tile below 12 pairs an item (measured on gfx1151), // and the skewed-row matrix tile (three blocks a WGP) ahead of the padded one where it takes a product. // The 64-row routed tile's items of 8 rows or fewer take its K-parallel passes (measured on gfx1151). +// A plain prompt of 1 or 2 rows takes the 2-row K-parallel tile (measured on gfx1151), +// but 1 row of 2-bit or 3-bit codes keeps the 1-row tile, which is ahead there. .{ .gfx = "gfx1151", .entries = .{ @@ -34,8 +36,8 @@ .{ .id = "mlx.routed_act.decode.stream", .cost = 1, .rows = 16, .rows_matrix = 15 }, // a prompt: the K-parallel tiles for a few rows or a short plan, the 128-row tile past them - .{ .id = "mlx.project.prefill.kp0", .cost = 1, .rows = 2, .routed = false }, - .{ .id = "mlx.project.prefill.kp3", .cost = 2, .items = 300, .plain = false }, + .{ .id = "mlx.project.prefill.kp0", .cost = 1, .rows = 1, .max_bits = 3, .routed = false }, + .{ .id = "mlx.project.prefill.kp3", .cost = 2, .rows = 2, .items = 300 }, .{ .id = "mlx.project.prefill.kp1", .cost = 3, .rows = 4, .items = 300 }, .{ .id = "mlx.project.prefill.kp2", .cost = 4, .rows = 32, .routed = false }, .{ .id = "mlx.project.prefill.skew", .cost = 9.5 }, diff --git a/zig/src/hip/tuning/tuning.zig b/zig/src/hip/tuning/tuning.zig index 90c4c2fa979..f39e4f27518 100644 --- a/zig/src/hip/tuning/tuning.zig +++ b/zig/src/hip/tuning/tuning.zig @@ -34,6 +34,8 @@ test "a row's width bound is a width the codes come in" { for ([_]*const Table{ &gfx1030, &gfx1100, &gfx1151, &gfx1201 }) |t| for (t.rows) |r| { if (r.max_bits != 0) try std.testing.expect(std.mem.indexOfScalar(u8, ®istry.widths, r.max_bits) != null); }; + // the bound is live where it was measured: a table that lost it would pass the loop above + try std.testing.expectEqual(@as(u8, 3), find(&gfx1151, "mlx.project.prefill.kp0").?.max_bits); } test "the tables name each entry once" { From 41a72fd2578dfbdd73b25663da78d5fc0047bd95 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sun, 15 Nov 2026 01:23:59 +0000 Subject: [PATCH 14/14] changelog: #3273 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index ddf21230922..e7d549dfe68 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- HIP on gfx1151: a plain prompt of 1 or 2 rows takes the 2-row K-parallel tile, with byte-identical output (#3273). Thanks to @AbrahamCete. + - GLM-5.3-Flash on CUDA with `TF_KV_SHARE` and no `--prompt-cache-gib`: the kept states' slots, `TF_KV_SHARE` at most, now come where an asked cache goes, before the windows past the engine's own, so a room that holds one more whole window no longer keeps fewer states; Jammed XSFP4 at TP=3 on three GB10s keeps all 32 at `TF_KV_SHARE=32` instead of 8, with the same tokens (#3125). Thanks to @Bizuayeu. - Metal: Baidu's Unlimited-OCR-2 is served natively from its BF16 release on M5-class Macs: page images through `serve --vision`, the family's chat template built in, its SAM and CLIP image encoders and decoder under the kernel contract; on five reference pages every departure from the release's own reply is a one-step tie (#2074). Thanks to @BobClawblaw. - Unlimited-OCR-2 on native Metal (M5 GPUs): Baidu's BF16 release as published serves page images through