mirror of
https://github.com/Niko1221/Strata.git
synced 2026-12-03 19:03:30 +07:00
[PR #2533] [CLOSED] metal: q4_0 KV cache on the Mac engine (--kv q4_0, opt-in; the non-q4 path byte-identical when off) #4103
Labels
No labels
needs-format
pull-request
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set.
Reference
Niko1221/Strata#4103
Loading…
Add table
Add a link
Reference in a new issue
No description provided.
Delete branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
📋 Pull Request Information
Original PR: https://github.com/Niko1221/Strata/pull/2533
Author: @afanty2021
Created: 10/15/2026
Status: ❌ Closed
Base:
main← Head:metal-kv-q4📝 Commits (10+)
22e0e61metal: the kv_q4 standalone kernels and their bit-level parity test (M0-p)d115063metal: the kv_q4.hpp entry points dispatch the new kernels; stubs regeneratedd2f8294metal: kv_q4 review hardening - offset-pinned mirrors, a permuted gather table, a page-crossing batchcbc98d5metal: kv_q4 review minors - the MSL block size pinned by static_assert, a fast-math note on the divisions, the kernels-dir env override on the engine pathcbe74c8metal: kv_q4 parity - all-zero and amplitude-class fixtures, a permuted composite table, a failure locator, the reference factored into kv_q4_ref.ha069e15metal: an in-tree engine-path kv_q4 test - the five kv_q4.hpp entry points over strata_gpu_metald313904metal: kv_q4.metal's prelude marked shared, the FWHT butterfly step factored out4fc0833metal: qsa.metal's q4 fused specialization behind function constant 2505c9e92metal: qsa_q4_parity - the fc 25 chain against the PC semantics, the V pool bit-level410e60cmetal: the engine's qsa compile lists prepend kv_q4.metal; two review wording fixes📊 Changes
54 files changed (+19137 additions, -99 deletions)
View changed files
➕
bench/results/2026-10-15-mac-kv-q4/README.md(+214 -0)➕
bench/results/2026-10-15-mac-kv-q4/data/kvmem-runs.txt(+24 -0)➕
bench/results/2026-10-15-mac-kv-q4/data/long-prompt-2200.ids(+1 -0)➕
bench/results/2026-10-15-mac-kv-q4/data/post-merge-checks.txt(+38 -0)➕
bench/results/2026-10-15-mac-kv-q4/data/prompt-path/p-fp16.index.json(+116 -0)➕
bench/results/2026-10-15-mac-kv-q4/data/prompt-path/p-fp16.run.txt(+2 -0)➕
bench/results/2026-10-15-mac-kv-q4/data/prompt-path/p-fp16.stderr.txt(+81 -0)➕
bench/results/2026-10-15-mac-kv-q4/data/prompt-path/p-q4.index.json(+116 -0)➕
bench/results/2026-10-15-mac-kv-q4/data/prompt-path/p-q4.run.txt(+2 -0)➕
bench/results/2026-10-15-mac-kv-q4/data/prompt-path/p-q4.stderr.txt(+81 -0)➕
bench/results/2026-10-15-mac-kv-q4/data/prompt-path/pcompare.txt(+2 -0)➕
bench/results/2026-10-15-mac-kv-q4/data/prompt-path/per-prompt.tsv(+22 -0)➕
bench/results/2026-10-15-mac-kv-q4/data/speed-runs.txt(+15 -0)➕
bench/results/2026-10-15-mac-kv-q4/data/teacher-forced/compare.json(+92 -0)➕
bench/results/2026-10-15-mac-kv-q4/data/teacher-forced/compare.txt(+14 -0)➕
bench/results/2026-10-15-mac-kv-q4/data/teacher-forced/fp16.run.txt(+6 -0)➕
bench/results/2026-10-15-mac-kv-q4/data/teacher-forced/fp16.tsv(+4995 -0)➕
bench/results/2026-10-15-mac-kv-q4/data/teacher-forced/fp16.tsv.seg.json(+67 -0)➕
bench/results/2026-10-15-mac-kv-q4/data/teacher-forced/fp16.tsv.stderr.txt(+51 -0)➕
bench/results/2026-10-15-mac-kv-q4/data/teacher-forced/q-int8.run.txt(+6 -0)...and 34 more files
📄 Description
What it changes
The PC engine's q4_0 K/V format (PR #21's FWHT-256 Hadamard rotation) brought to the Metal backend, opt-in
through the engine's existing
--kv q4_0flag:metal/kernels/kv_q4.metal(new): the FWHT-256 rotation, quantize and dequantize kernels, and the poollayout (576 B per cell per QSA layer against the non-q4 path's 1,056).
metal/kernels/qsa.metal,qsa_prompt.metal: the decode and prompt chains made format-aware — the fiveQSA dispatch sites carry function constant 25 in both the pipeline key and the Constants, so a q4 run gets
its own specializations instead of silently reusing the cached int8 ones over q4 pools.
metal/src/engine/:kv_format.h(new, the single source for pool sizes / keys / the format choice),kv_q4_host.cpp(new, the host side),window.cppandprompt_chain.incwired: q4 pools at init, the MTPdrafter swaps pools in the same format,
--kv k8v4refused at startup.fallback that read q4 prompts through decode windows is gone,
STRATA_METAL_PROMPT=windowstill forces it.metal/setup_mac.py: opt-in--kv q4_0that lands in the generated engine config'sargs(
tools/test_setup_mac.pyextended).tools/quant_quality.py: opt-in--kvonrun/prompt(replaces the harness's fixed fp16 pin only whenpassed).
docs/MAC.md: the option, the quality/speed numbers, the KV-memory numbers, the not-testeds.bench/results/2026-10-15-mac-kv-q4/(new): the whole Mac measurement round — scripts, raw TSVs, distilledrun lines, README.
What it leaves alone
src/orinclude/is touched, so no CUDA/HIP/SYCL build is affected (the Metal engine'shost code is the PC's, compiled for macOS as before).
byte for byte (pinned by tests, below). Defaults everywhere: setup writes no
--kvunless asked, theengine's default is the same non-q4 path as the last release.
refused by the shared code, as before).
Opt-in, and how the default path was checked byte-identical
Three independent gates:
metal/tests/kv_format_test.cpppins the five-key reduction (everyconstant set an engine site now binds is compiled as its own specialization) and a stale-key
counterfactual;
qsa_q4_parity.cppandqsa_prompt_parity.cppassert the fc-off outputs againstdouble-precision references — with q4 off every key, Constants set and binding order is the current int8
one, byte for byte.
output byte-identical to the pre-branch baseline run (
bd1f3153), zero stub lines — the engine's int8 pathdoes not move.
tools/quant_quality.py'sengine_args()output was diffed before vsafter the opt-in
--kvchange over the three gpu_experts modes: identical without the flag. For setup,metal/setup_mac.py'sengine_args()was compared against HEAD over a 48-cell matrix(stream x ram x context x shard shapes; 0 diffs) plus the full generated config on three of those cells:
identical without
--kv, and with it the pair--kv q4_0is appended at the end and nothing else moves(pinned by
tools/test_setup_mac.py).Measured (Apple M4 Pro, 20 cores, 48 GB unified memory, macOS 27.0.1; Qwen3.8-Flash-Next Q2_0, experts
streamed from the SSD; engine built from this branch; every number same-day 2026-10-15, nothing extrapolated)
The framing fact for the reference column: on Metal,
--kv fp16and--kv int8are one path — thewindow's pools are the int8 ones either way (
kv_format.h; the fp16-flagged run's own log printsKV int8), and the two teacher-forced TSVs of the round are byte-identical(md5
4e942a7375715ac014956fbdbf6110f6). So the reference below is that shared non-q4 path, q4_0 is theonly smaller K/V format on Mac, and no fp16-vs-int8 delta exists on this backend.
fp16-vs-int8 pair (one path on Metal) measured −1.3% decode, bounding noise near 1%. Single runs per cell.
to repeat it (a behavior miss, not a garbled retrieval; all 8 retrievals were the exact codeword).
Disclosures, as recorded in the bench README: the question ends with "The access code is" — a completion cue
all arms share, so the comparison is internally fair but the 8/9 is under an easier phrasing than a neutral
QA form; the miss has no int8 control at 90% depth (controls ran at 50%), so a shared-path refusal there
cannot be excluded; and its reply was cut mid-sentence at the 64-token budget — the injection-suspicion
reasoning is explicit, a final refusal sentence is not.
Disclosures (from the final segment review)
plans 576 stand-by slots for the prompt-GEMM chain (64 without it). Escape hatches:
STRATA_METAL_PROMPT_GEMM=0(prompts off the matrix-unit GEMM chain; the arena is then planned without thestand-by slots) and
STRATA_METAL_PROMPT=window(prompts through decode windows — the slow, exactfallback).
coop_k4=false), so the prompt fast path behindevery prompt-path and prefill number above is the matrix-unit GEMM chain over the v1 layout — the flash chain is off
by default on !k4 hardware and never dispatched here (same hardware fact as the k4 arm below).
chunk (the matrix units), so its numerics are a different floating-point order from the decode window's
(fp32 fused) — outputs can differ on near-ties, the same class as any reordering. Measured under q4_0 on
the 20-prompt set: argmax never flipped (top-1 100%), full-vocab KL as in the table.
this M4 Pro is !k4 hardware and never dispatches them (see Not tested).
--kv k8v4: the only statement is the explicit startup refusal — "metal window: --kv k8v4 is notimplemented on Metal (use fp16, int8 or q4_0)". No partial implementation exists.
STRATA_KV_ROT=1(the PC's rotated int8 K/V env): refused at startup next to--kv int8, like k8v4 — therethe PC rotates the pools and the shared conversation-snapshot tag adds +16 for the rotation, so a Metal session
would save a tag claiming a rotation its pools do not have (the env is parsed in kv_format_check as
generate.cpp does; the int8 flag comes through the existing qsa_kv_int8 getter). Next to fp16 (and no
--kv)the env is a no-op on both engines — the rotation is gated on the int8 flag (layer.cpp:
kv_rot = kv_q4 || (kv_int8 && env), and generate.cpp sets kv_int8 only for--kv int8), so nothing rotates and the tag addsnothing; allowed, matching the PC's silent no-op. Next to
--kv q4_0the rotation is intrinsic and the tagnever adds it, so the env there is a harmless no-op too.
Not tested
The M5 k4-layout q4 numeric arm (fc-7 right-input layouts): compiled but never dispatched on this !k4 host.
MTP + q4_0 end to end: every measured run used the template's
--spec 2 --suffix-draft 0; the drafter'ssame-format pool swap is structurally validated by tests, not exercised end to end.
PC consistency: no PC run this round; the 2026-09-27 PC table (
bench/results/2026-09-27-kv-q4/) is adifferent backend and a
--kv-residentstreaming configuration, so its numbers are not comparable and arenot cited.
Speed repeats (one run per cell; the same-code pair bounds noise near 1%) and needle breadth (one codeword,
one filler corpus, one run per case, no distractors, int8 controls at 50% depth only).
Other Macs: every number above is from one M4 Pro, 48 GB.
Long-context quality: every quality segment is 1,000 tokens. The PC round measured the q4_0 perplexity
cost growing with context (+8% at 1K to +12% at 8K on a document), so the +1.7% here is a short-context
number and must not be read as the format's cost at 32K.
Known follow-ups, none in this PR: the flash q4 epilogue is barrier-dense (a perf item only k4 hardware would
feel, and this !k4 host never dispatched it), the flash
vsdead array is still to be removed,prompt_chain's pre-existing argv bounds pattern and kv_format_test's pre-existing non-q4 flash constant sets
predate the branch and stay as found, and the Task-1-era nits stand (the
pipe()per-call cache lookup, theidentity-page gather case, the offsetof asserts).
Reproducing
bench/results/2026-10-15-mac-kv-q4/README.mdis the entry point: the exact commands for theteacher-forced round (
tools/quant_quality.py run/compare), the prompt-path round (prompt/pcompare), thespeed pairs (
speed.sh), the KV/arena numbers (kvmem.sh) and the needle matrix (needle.py), all with thecommitted raw TSVs and distilled run lines beside them (
data/speed-runs.txt,data/kvmem-runs.txt,needle-results.tsv, the stderr summaries); the full engine logs stay out per the repo'slogs/ignore andregenerate from the committed scripts. The in-tree test gates:
ninja -C build-metalthen the binaries inmetal/tests/(kv_q4_parity,kv_q4_engine,kv_format_test,qsa_q4_parity,qsa_prompt_parity).Setup's default-identity is
python3 -m unittest tools.test_setup_mac(no GPU, no downloads).note:
data/prompt-path/pcompare.txt's reference line was edited by hand to point at the committedper-prompt.tsv (the regeneration commands are in the README); the aggregates were never hand-touched.
Prior art searched (issues and PRs)
Re-checked read-only at packaging time (
gh search issues/gh pr viewagainst the upstream repo, terms: metal kv,kv q4, k8v4, mac backend, apple silicon, metal PRs): no issue or PR covers KV quantization on the Mac/Metal
backend — this PR opens that ground, and the PC lineage below is the prior art.
rotation, closed) are the format's siblings; PR #452/#904 are the PC prompt/append follow-ups.
--kv q4_0faults on a PC (HIP) when the KV itself streams (--kv-resident) with MTPdrafts. Different code path — the Metal engine has no
--kv-residentKV streaming (a Mac streams experts,not KV) — noted here so nobody reads the PC issue as covering this backend. The k8v4 PC streaming bugs
(#1135, #1188, #1169, all closed) are the same story:
--kv-resident-path-specific, not applicable here.moe_mm_parity's default tile does not exist in the v1 kernel set. Pre-existing onmain, reproduced byte-identically on a clean tree, untouched by this branch (that test, its kernels and the
failure are outside this diff; the branch's test sweeps treat it as the known exception).
🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.