[PR #3783] [Engine] Batch slots on Metal: --batch N rows decode together #4780

Open
opened 2026-11-07 15:39:00 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/Niko1221/Strata/pull/3783
Author: @catalinb13
Created: 10/23/2026
Status: 🔄 Open

Base: main ← Head: metal-batch


📝 Commits (10+)

  • b158818 metal: the request's sampling (the CUDA sampler's chain, on the CPU over the window's head logits)
  • 0d6e5ba tests: tools/metal_sampling_test.py (the request's sampling through --serve: reproducible seeds, picks draw for draw against a reference sampler on the dumped logits, penalties, logit_bias) and metal/tests/engine/host_sampler_parity.cpp
  • 3a49b02 docs: Mac sampling (MAC.md Sampling: the keys, the order, seeds, the host pick's cost, greedy vs sampled decode)
  • 093ed30 metal: release prompt scratch buffers before workspace growth
  • 02e9f27 fix(serve): stop reporting stale cache occupancy after refused parking
  • b9252ed Merge current main and exercise prompt growth without caller autorelease pools
  • 9844762 conversation cache: --conversation-cache-min-tokens WRITE[,READ] gates parked reads
  • 1be9c7d metal: opt-in fp16-slab expert path (mpp) for streaming prompt chunks
  • 1d7f1b5 gap harness + attribution rounds 1-4; kprof gate reverted to baseline
  • a9b951b metal: M1 Max A/B hooks (STRATA_METAL_GEMV_TILE/MOE_TILE/GDN_SCAN); decode copy-overlap on by default on Metal

📊 Changes

341 files changed (+53789 additions, -1723 deletions)

View changed files

📝 .gitignore (+3 -0)
📝 docs/BATCHING.md (+77 -2)
➕ docs/DECODE_2X_PLAN.md (+179 -0)
📝 docs/DETAILS.md (+2414 -1196)
📝 docs/MAC.md (+257 -238)
➕ gap/arms-base.txt (+13 -0)
➕ gap/arms-final.txt (+7 -0)
➕ gap/arms-kprof.txt (+2 -0)
➕ gap/arms-needle.txt (+5 -0)
➕ gap/arms-needle2.txt (+7 -0)
➕ gap/arms-needle3.txt (+2 -0)
➕ gap/arms-profile.txt (+9 -0)
➕ gap/arms-round10.txt (+9 -0)
➕ gap/arms-round11.txt (+9 -0)
➕ gap/arms-round12.txt (+7 -0)
➕ gap/arms-round13.txt (+15 -0)
➕ gap/arms-round14.txt (+13 -0)
➕ gap/arms-round15.txt (+13 -0)
➕ gap/arms-round16.txt (+17 -0)
➕ gap/arms-round17.txt (+15 -0)

...and 80 more files

📄 Description

Closes #3284. This repo's rules ask a feature's scope to be agreed in an issue first; there has been no comment there, so treat this as that proposal — the feature is opt-in, measured, and the whole record is in docs/BATCHING.md. Happy to discuss scope before merge.

Problem

On a Mac the engine answers one request at a time and every other client queues (docs/MAC.md: "--parallel (batch slots) is not ported"). One person plus their coding agents — a small office — leave the machine between requests at ~2 GB/s of weight reads when the bandwidth is several times that, while the same model on a PC gains multiples by decoding waiting requests together.

Result

--batch N on the Metal engine runs N conversations in one window. Measured on an M1 Max (64 GB, Qwen3.8-Flash-Next IQ3_XXS), 21–23 Oct 2026:

Run Aggregate Same prompts alone Replies vs solo
2 slots, greedy, 128 tok 37.5 tok/s 23 / 25 tok/s both byte-identical
2 slots, sampled (temp 0.7, seed 7), 64 tok 42.7 tok/s 23 / 25 tok/s both byte-identical
4 slots, greedy, 128 tok 34.7 tok/s 23–32 tok/s 2 of 4 byte-identical; the other 2 answered their own question fluently and chose a different word at one near tie (tokens 88 and 13)

The interleave cases hold too: a 4888-token prompt reads in while slots decode (126 slot tokens during the read); a read that gives way at a chunk boundary (YIELDED 2 1024) goes on in its slot; a request stopped part-way in a slot hands back to the solo path and reproduces its solo reply; a next turn reads from its slot's parked state; a prompt chunk cancelled mid-read resumes from its checkpoint (1024 reused + 3866 read). With STRATA_BATCH_VERIFY=1 the engine byte-compares each slot region's GDN states, QSA cells, tails, dead and pooled rows and PLE history against the window that made them, and reported all match for every region; the per-step kernel captures show each row's folds up to the batched PLE block bit-exact against its solo run.

The default path is unchanged: without --batch the window builds and runs exactly the commands it did before, and every unit gate passes both ways.

Approach

  • The arena carves a region per slot — each reply's full state in the solo window's own layout (about 3.8 GB with these settings, so the batch count is a memory choice, not a speed choice; the engine prints the cost at start, and refuses with a clear line when the regions do not fit). Parking already kept this state per conversation, so --batch combines with --conversation-cache-mib: a prompt reads through the main window and is copied into its slot's region before its rows first run.
  • The batch window builds the solo one-token dispatch list once per row. Every kernel that touches state takes the row index and reads and writes only its own region, and every GEMV keeps the plain tile — no CUDA grouped tiles, no doorbell kernels, no graph capture. What a window saves per step is the fixed cost the rows share: the device-flag cut handshake (each segment gated by a ~90 us flag spin, not an event pair), the sampler round trip, the launch gaps.
  • One binding fix the captures found, worth naming: a batch row's GDN step binds the prepared activation at its own slice, and the per-16 sums it writes for the quantized-input GEMVs landed at that bound base — rows after the first wrote sums nobody read and past the buffer, into the arena's next allocation. The sums have their own binding now; the solo window and the first row address them bit-identically to before, and gdn_parity's new plane-row check pins it (it fails with the pre-fix address and passes after).
  • Where a batched row can differ from solo is measured, not guessed: a 315-probe per-step trajectory for every row shows the first difference is the fold leaving the batched PLE block — a few kernels batch the rows in one dispatch and round differently than the per-token solo sequence, at fractions of a percent, amplified by fold cancellations. (Which kernel exactly rounds differently is unconfirmed static analysis.)

Validation

Revisions and environment. The measurements were made on this fork's Mac line at 783a55fc (the batch commits 2d50ea42..783a55fc), M1 Max, 64 GB, macOS 27, Qwen3.8-Flash-Next IQ3_XXS. upstream/main was merged into the branch after the runs (merge commit 1ff3a385, main at 5c8dd322); the post-merge tree rebuilds on this machine, and the merge touches none of the batch code.

Passed:

  • metal/tests host gates on 783a55fc (M1 Max, macOS 27): gdn_parity (incl. the new plane-row check and its negative control), gdn_prompt_parity, window_cells_test, host_sampler_parity, runtime_hello, moe_mm_parity, gemv_parity, qsa_parity, buffer_free_test — all green.
  • tools/batch_interleave_test.py run twice — prompt reads interleaving with slot decoding, the yield at a chunk boundary, the stop-into-slot hand-back, the parked-state next turn, the mid-read checkpoint resume.
  • STRATA_BATCH_VERIFY=1 on the 2- and 4-slot runs — per-slot state byte-compare all match, per-step 315-probe trajectories printed for every row.
  • tools/token_chain.py / tools/prompt_chain.py on the 47 GB shard (30.5 tok/s, 147 tok/s; the 2-chunk wrap past maxBufferLength).
  • Solo rates with --batch absent match this branch's pre-batch measurements (23–33 tok/s) — the solo path did not regress.

Failed:

  • The harnesses' byte-identity gate — 2 of 4 slots at --batch 4, and three interleave slots across two runs. At every miss both continuations answer their own prompt and the window's logits differ from solo's by the PLE-block noise above, so argmax breaks the tie the other way (the interleave runs print both texts: a colon against a comma, one period, static int against int). docs/BATCHING.md's Metal section carries the same doctrine CUDA already ships: token identity of a batched row is luck, coherence and no cross-talk are the contract. With serialized admissions the flips repeat exactly (4 slots: 88 and 13 across independent runs); when prompt reads interleave with decoding, arrival timing changes what each row shares its dispatches with and which slot flips can move between runs.

Not run:

  • The CUDA, HIP and SYCL builds (this is a macOS host without an NVIDIA or AMD card). The shared src/core and src/program hunks sit inside #if defined(STRATA_GPU_METAL) and the non-Metal bodies are unchanged text, but I cannot certify a build I did not run — CI must.
  • Other Apple Silicon shapes (only this M1 Max: no M3/M4/M5, no Studio or Ultra), --batch-groups pipelining on Metal, layer split with batch, batch counts past 4 (the regions would not fit 64 GB with the model), multi-day serving under real user load, and vision towers with batch.

What is in this branch, honestly

The seven batch commits (2d50ea42..783a55fc) sit on this fork's Mac line, which upstream has not taken: conversation parking on macOS, the device-flag cut handshake, M1/M2 GEMV speedups, the purge/hash fix, and merges of the still-open #3301, #3527, #3615 and #3333 plus my open #3287 and #2645. That is why the commit list is longer than the feature; upstream/main is merged into the branch (1ff3a385), so the diff applies cleanly, and the batch changes are marked in the commit subjects. I am happy to rebase onto whichever pieces land first, or to split.

Limits

Opt-in and experimental on Macs. No layer split or pipelined groups in a batch window. Each extra slot costs a full per-conversation region in RAM (15.4 GB for four here). The gain is real on this box (up to ~1.7x at two slots) and falls as rows grow; nobody has measured more than four.

How to try it

tools/metal_batch_try.sh 2 2 128

It starts the engine with --batch, runs the same prompts alone and together, byte-compares every reply, and refuses to run while another big server holds the memory (see the script's header). For sampled rows add --keys "temperature=0.7 seed=7".


🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/Niko1221/Strata/pull/3783 **Author:** [@catalinb13](https://github.com/catalinb13) **Created:** 10/23/2026 **Status:** 🔄 Open **Base:** `main` ← **Head:** `metal-batch` --- ### 📝 Commits (10+) - [`b158818`](https://github.com/Niko1221/Strata/commit/b158818c33d010eca4c933a10ffbe4414620438e) metal: the request's sampling (the CUDA sampler's chain, on the CPU over the window's head logits) - [`0d6e5ba`](https://github.com/Niko1221/Strata/commit/0d6e5ba3413da4a82a18d2807c99e0897bd701de) tests: tools/metal_sampling_test.py (the request's sampling through --serve: reproducible seeds, picks draw for draw against a reference sampler on the dumped logits, penalties, logit_bias) and metal/tests/engine/host_sampler_parity.cpp - [`3a49b02`](https://github.com/Niko1221/Strata/commit/3a49b029e80aa5d63eae8752c47198bf096483f5) docs: Mac sampling (MAC.md Sampling: the keys, the order, seeds, the host pick's cost, greedy vs sampled decode) - [`093ed30`](https://github.com/Niko1221/Strata/commit/093ed3077e8f03ae54ffc302ac0b1af37592b38e) metal: release prompt scratch buffers before workspace growth - [`02e9f27`](https://github.com/Niko1221/Strata/commit/02e9f272264b8df363ddc9f3eb177d945d5d84fb) fix(serve): stop reporting stale cache occupancy after refused parking - [`b9252ed`](https://github.com/Niko1221/Strata/commit/b9252edc5368b452a530b32d017e30f8a19e107a) Merge current main and exercise prompt growth without caller autorelease pools - [`9844762`](https://github.com/Niko1221/Strata/commit/9844762a97fb326bc3338624ff2ba512c5108bad) conversation cache: --conversation-cache-min-tokens WRITE[,READ] gates parked reads - [`1be9c7d`](https://github.com/Niko1221/Strata/commit/1be9c7deb2e8114e3c658e6d8505b905e8ddd38c) metal: opt-in fp16-slab expert path (mpp) for streaming prompt chunks - [`1d7f1b5`](https://github.com/Niko1221/Strata/commit/1d7f1b5bc348678edd117b8acd6fcb885ff0598e) gap harness + attribution rounds 1-4; kprof gate reverted to baseline - [`a9b951b`](https://github.com/Niko1221/Strata/commit/a9b951bc7806a4d6712a9fe9febce04a7bb31b83) metal: M1 Max A/B hooks (STRATA_METAL_GEMV_TILE/MOE_TILE/GDN_SCAN); decode copy-overlap on by default on Metal ### 📊 Changes **341 files changed** (+53789 additions, -1723 deletions) <details> <summary>View changed files</summary> 📝 `.gitignore` (+3 -0) 📝 `docs/BATCHING.md` (+77 -2) ➕ `docs/DECODE_2X_PLAN.md` (+179 -0) 📝 `docs/DETAILS.md` (+2414 -1196) 📝 `docs/MAC.md` (+257 -238) ➕ `gap/arms-base.txt` (+13 -0) ➕ `gap/arms-final.txt` (+7 -0) ➕ `gap/arms-kprof.txt` (+2 -0) ➕ `gap/arms-needle.txt` (+5 -0) ➕ `gap/arms-needle2.txt` (+7 -0) ➕ `gap/arms-needle3.txt` (+2 -0) ➕ `gap/arms-profile.txt` (+9 -0) ➕ `gap/arms-round10.txt` (+9 -0) ➕ `gap/arms-round11.txt` (+9 -0) ➕ `gap/arms-round12.txt` (+7 -0) ➕ `gap/arms-round13.txt` (+15 -0) ➕ `gap/arms-round14.txt` (+13 -0) ➕ `gap/arms-round15.txt` (+13 -0) ➕ `gap/arms-round16.txt` (+17 -0) ➕ `gap/arms-round17.txt` (+15 -0) _...and 80 more files_ </details> ### 📄 Description Closes #3284. This repo's rules ask a feature's scope to be agreed in an issue first; there has been no comment there, so treat this as that proposal — the feature is opt-in, measured, and the whole record is in `docs/BATCHING.md`. Happy to discuss scope before merge. ## Problem On a Mac the engine answers one request at a time and every other client queues (`docs/MAC.md`: "--parallel (batch slots) is not ported"). One person plus their coding agents — a small office — leave the machine between requests at ~2 GB/s of weight reads when the bandwidth is several times that, while the same model on a PC gains multiples by decoding waiting requests together. ## Result `--batch N` on the Metal engine runs N conversations in one window. Measured on an M1 Max (64 GB, Qwen3.8-Flash-Next IQ3_XXS), 21–23 Oct 2026: | Run | Aggregate | Same prompts alone | Replies vs solo | | --- | --- | --- | --- | | 2 slots, greedy, 128 tok | 37.5 tok/s | 23 / 25 tok/s | both byte-identical | | 2 slots, sampled (temp 0.7, seed 7), 64 tok | 42.7 tok/s | 23 / 25 tok/s | both byte-identical | | 4 slots, greedy, 128 tok | 34.7 tok/s | 23–32 tok/s | 2 of 4 byte-identical; the other 2 answered their own question fluently and chose a different word at one near tie (tokens 88 and 13) | The interleave cases hold too: a 4888-token prompt reads in while slots decode (126 slot tokens during the read); a read that gives way at a chunk boundary (`YIELDED 2 1024`) goes on in its slot; a request stopped part-way in a slot hands back to the solo path and reproduces its solo reply; a next turn reads from its slot's parked state; a prompt chunk cancelled mid-read resumes from its checkpoint (`1024 reused + 3866 read`). With `STRATA_BATCH_VERIFY=1` the engine byte-compares each slot region's GDN states, QSA cells, tails, dead and pooled rows and PLE history against the window that made them, and reported all match for every region; the per-step kernel captures show each row's folds up to the batched PLE block bit-exact against its solo run. The default path is unchanged: without `--batch` the window builds and runs exactly the commands it did before, and every unit gate passes both ways. ## Approach - The arena carves a region per slot — each reply's full state in the solo window's own layout (about 3.8 GB with these settings, so the batch count is a memory choice, not a speed choice; the engine prints the cost at start, and refuses with a clear line when the regions do not fit). Parking already kept this state per conversation, so `--batch` combines with `--conversation-cache-mib`: a prompt reads through the main window and is copied into its slot's region before its rows first run. - The batch window builds the solo one-token dispatch list once per row. Every kernel that touches state takes the row index and reads and writes only its own region, and every GEMV keeps the plain tile — no CUDA grouped tiles, no doorbell kernels, no graph capture. What a window saves per step is the fixed cost the rows share: the device-flag cut handshake (each segment gated by a ~90 us flag spin, not an event pair), the sampler round trip, the launch gaps. - One binding fix the captures found, worth naming: a batch row's GDN step binds the prepared activation at its own slice, and the per-16 sums it writes for the quantized-input GEMVs landed at that bound base — rows after the first wrote sums nobody read and past the buffer, into the arena's next allocation. The sums have their own binding now; the solo window and the first row address them bit-identically to before, and `gdn_parity`'s new plane-row check pins it (it fails with the pre-fix address and passes after). - Where a batched row can differ from solo is measured, not guessed: a 315-probe per-step trajectory for every row shows the first difference is the fold leaving the batched PLE block — a few kernels batch the rows in one dispatch and round differently than the per-token solo sequence, at fractions of a percent, amplified by fold cancellations. (Which kernel exactly rounds differently is unconfirmed static analysis.) ## Validation Revisions and environment. The measurements were made on this fork's Mac line at `783a55fc` (the batch commits `2d50ea42..783a55fc`), M1 Max, 64 GB, macOS 27, Qwen3.8-Flash-Next IQ3_XXS. `upstream/main` was merged into the branch after the runs (merge commit `1ff3a385`, main at `5c8dd322`); the post-merge tree rebuilds on this machine, and the merge touches none of the batch code. **Passed:** - `metal/tests` host gates on `783a55fc` (M1 Max, macOS 27): `gdn_parity` (incl. the new plane-row check and its negative control), `gdn_prompt_parity`, `window_cells_test`, `host_sampler_parity`, `runtime_hello`, `moe_mm_parity`, `gemv_parity`, `qsa_parity`, `buffer_free_test` — all green. - `tools/batch_interleave_test.py` run twice — prompt reads interleaving with slot decoding, the yield at a chunk boundary, the stop-into-slot hand-back, the parked-state next turn, the mid-read checkpoint resume. - `STRATA_BATCH_VERIFY=1` on the 2- and 4-slot runs — per-slot state byte-compare all match, per-step 315-probe trajectories printed for every row. - `tools/token_chain.py` / `tools/prompt_chain.py` on the 47 GB shard (30.5 tok/s, 147 tok/s; the 2-chunk wrap past `maxBufferLength`). - Solo rates with `--batch` absent match this branch's pre-batch measurements (23–33 tok/s) — the solo path did not regress. **Failed:** - The harnesses' byte-identity gate — 2 of 4 slots at `--batch 4`, and three interleave slots across two runs. At every miss both continuations answer their own prompt and the window's logits differ from solo's by the PLE-block noise above, so argmax breaks the tie the other way (the interleave runs print both texts: a colon against a comma, one period, `static int` against `int`). `docs/BATCHING.md`'s Metal section carries the same doctrine CUDA already ships: token identity of a batched row is luck, coherence and no cross-talk are the contract. With serialized admissions the flips repeat exactly (4 slots: 88 and 13 across independent runs); when prompt reads interleave with decoding, arrival timing changes what each row shares its dispatches with and which slot flips can move between runs. **Not run:** - The CUDA, HIP and SYCL builds (this is a macOS host without an NVIDIA or AMD card). The shared `src/core` and `src/program` hunks sit inside `#if defined(STRATA_GPU_METAL)` and the non-Metal bodies are unchanged text, but I cannot certify a build I did not run — CI must. - Other Apple Silicon shapes (only this M1 Max: no M3/M4/M5, no Studio or Ultra), `--batch-groups` pipelining on Metal, layer split with batch, batch counts past 4 (the regions would not fit 64 GB with the model), multi-day serving under real user load, and vision towers with batch. ## What is in this branch, honestly The seven batch commits (`2d50ea42..783a55fc`) sit on this fork's Mac line, which upstream has not taken: conversation parking on macOS, the device-flag cut handshake, M1/M2 GEMV speedups, the purge/hash fix, and merges of the still-open #3301, #3527, #3615 and #3333 plus my open #3287 and #2645. That is why the commit list is longer than the feature; `upstream/main` is merged into the branch (`1ff3a385`), so the diff applies cleanly, and the batch changes are marked in the commit subjects. I am happy to rebase onto whichever pieces land first, or to split. ## Limits Opt-in and experimental on Macs. No layer split or pipelined groups in a batch window. Each extra slot costs a full per-conversation region in RAM (15.4 GB for four here). The gain is real on this box (up to ~1.7x at two slots) and falls as rows grow; nobody has measured more than four. ## How to try it ``` tools/metal_batch_try.sh 2 2 128 ``` It starts the engine with `--batch`, runs the same prompts alone and together, byte-compares every reply, and refuses to run while another big server holds the memory (see the script's header). For sampled rows add `--keys "temperature=0.7 seed=7"`. --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
Niko1221/Strata#4780
No description provided.