Skip to content

Make v3 attention exact under exact_attention (#81) - #92

Open
pythongiant wants to merge 1 commit into
lithos-ai:mainfrom
pythongiant:fix/exact-attention-v3
Open

pythongiant wants to merge 1 commit into
lithos-ai:mainfrom
pythongiant:fix/exact-attention-v3

Conversation

@pythongiant

@pythongiant pythongiant commented Oct 21, 2026 •

Copy link
Copy Markdown

Fixes #81.

What happens

exact_attention re-roots v1's chunked attention (EXACT_SUB) so a large prompt pass reproduces 128-row passes bit for bit, but it skipped gqa_decode_v3. v3 has no chunks; its cached-key loop pairs keys while key + NSG3 < position and folds the rest singly, so a row's result depends on where its pass starts. Under attention auto, exact prompt programs that select v3 (models without q/k norms, head dims outside 128/256, accelerator off) missed the 128-row results — breaking serve's default auto-exact guarantee and warm-prefix/cold interchangeability.

Fix

Preferred option from the issue: make v3 exact, keeping its prefill speed.

  • kernels/common/gqa_decode_v3.metal: under EXACT_SUB, each row computes
    pos_r = position + (t / EXACT_SUB) * EXACT_SUB and uses it for the cached
    pair/single boundaries. Keys in [position, pos_r) are this dispatch's
    earlier sub-pass keys, so they are read from the projection (the values those
    sub-passes appended) and folded with the cached prefix using the sub-pass's
    pairing; keys from pos_r on keep the single new-key fold. Causal mask and
    the r == 0 cache appends are unchanged.
  • monolith/compiler/prefill.py: exact_attention marks gqa_decode_v3 with
    EXACT_SUB too (v3 is core and merge in one dispatch and has no partial
    workspace). Non-exact v3 compiles the helpers out.

Verification

  • New GPU test test_v3_exact_sub_reproduces_shorter_passes: a 256-row v3 pass
    is bit-equal to the S-row passes in both outputs and appended caches, for
    D=128/NSG3=32 (S=128) and D=32/NSG3=8 (S=64). It fails on the unpatched
    kernel and passes with this change.
  • New contract test asserts exact_attention marks the v3 core.
  • Compiled the synthetic hybrid checkpoint (head dim 32) with
    attention='auto', accelerator='off', t=512, prefill=True: auto selects
    gqa_decode_v3, and the exact graph carries EXACT_SUB=128u.
  • tests/kernels/test_gqa_decode.py, tests/contract/test_prefill.py,
    tests/contract/test_prefill_exact.py pass (207 tests).

@pythongiant pythongiant reopened this Oct 21, 2026
@pythongiant pythongiant changed the title Make v3 attention exact under exact_attention (#31) Make v3 attention exact under exact_attention (#81) Oct 21, 2026

@woodsonl woodsonl left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I ran this on the Apple M3 Max where #81 was found (40-core GPU, 48 GB, macOS 27.0.1), against 5485ad6 with and without the PR. With the PR, exact prompt passes on v3 match 128-row passes bit for bit. Every GPU run below is under MTL_SHADER_VALIDATION=1 except the timing runs, and the PR adds no validation reports.

#81's reproduction

Same setup as #81: the synthetic hybrid checkpoint (_checkpoint in tests/contract/test_nn_lowering.py: head dim 32, 8 heads, 2 KV heads) with accelerator='off', autotune=False and eos=-1. One Session runs 128-row prompt passes (prefill_chunk_size=128), the other 512-row exact passes (prefill_chunk_size=512, prefill_exact=True). Each cell counts the last prompt row's differing scores, then the differing rows among the 128-row session's final pass. The 1000-token prompt takes two exact passes.

attention prompt 5485ad6 with the PR
v1 300, 260, 400, 1000 bit-equal bit-equal
auto 300 23 of 50 scores, 43 of 44 rows bit-equal
auto 260 24 of 50, 4 of 4 rows bit-equal
auto 400 28 of 50, 16 of 16 rows bit-equal
auto 1000 14 of 50, 63 of 104 rows bit-equal
v3 300, 260, 400, 1000 same as auto bit-equal

The 12 greedy tokens matched in every run. Without the PR, auto gives exactly #81's counts (23, 24 and 28 of 50). With it, the exact program carries EXACT_SUB=128u on gqa_decode_v3. Main registers no 40-core M3 Max, so the scripts below give both sessions the 30-core M3 Max fallback's engine block with 40 cores, on the common backend.

Warm prefix cache

The exact session, with the prefix cache on, stores a checkpoint at 256 tokens and resumes three prompts from it. The 128-row session runs each prompt cold.

attention tokens after the checkpoint 5485ad6 with the PR
v1 300, 130, 520 bit-equal bit-equal
auto, v3 300 24 of 50 scores, 39 of 44 rows bit-equal
auto, v3 130 23 of 50, 2 of 2 rows bit-equal
auto, v3 520 bit-equal bit-equal

The 520-token tail's final pass is 8 rows starting at 768 in both sessions, so it matches without the PR too. Greedy tokens matched throughout.

Kernel and test tiers

  • The PR's three test files (tests/kernels/test_gqa_decode.py, tests/contract/test_prefill.py, tests/contract/test_prefill_exact.py): all 207 pass, counting the three torch layer-oracle tests (v1, v2 and v3 against the GQAAttention oracle), run with torch 2.14.1. With gqa_decode_v3.metal and prefill.py back at 5485ad6, the three new tests fail.
  • A wider sweep on the PR's harness, 144 cases: head dims 32, 64, 128 and 256 (NSG3 8, 16, 32 and 16), pass starts 0, 77 and 600, (T, S) of (300, 128), (512, 128) and (256, 64), query and key norms on and off, SINGLE_BLOCK 0 and 1. With the PR, all 144 are bit-equal in outputs and appended caches. With the 5485ad6 kernel, all 144 differ.
  • The contract, kernel and runtime tiers run 2,907 tests on 5485ad6 and 2,910 with the PR; the extra three are its new tests, and they pass. Both runs fail the same 10 tests, and no other test changes status. A small pytest plugin gives sessions the same fallback profile as the scripts, so two of the 10 are backend-registry tests that expect this chip to have no profile. The other eight are test_large_prefill cases with accelerator='on' and an LM or DSpark drafter, which pin attention to v1. The only test that logs validation reports is test_steal_variant_is_exactly_once_and_identical (invalid stores in the STEAL variant of v1's gqa_decode), and it logs them on 5485ad6 too.

Speed

8000-token prompt, 512-row passes, attention auto, median of 9 runs, two rounds alternating 5485ad6 and the PR:

passes 5485ad6 with the PR
plain 1,329 and 1,332 ms 1,337 and 1,329 ms
exact 1,333 and 1,335 ms 1,352 and 1,366 ms

Plain passes compile with EXACT_SUB at 0, so they run the code they ran before, and their times match. Exact passes take 1.4 to 2.3 percent longer on this two-layer checkpoint (hidden size 256). Exact passes on v1, the smaller fix #81 mentioned, take 1,545 ms, 16 percent over 5485ad6's exact passes.

The core filter in exact_attention

The PR narrows it from startswith('gqa_decode') to == 'gqa_decode'. I compiled 36 exact prompt programs (no drafter, an LM drafter and a DSpark drafter; attention v1, v2, v3, auto, mma and mma-direct; accelerator off and on) and ran both filters on each. They mark the same ops in all 36. The DSpark programs under v3, auto, mma and mma-direct hold the drafter's v1 core beside the target's v3 dispatch, and both filters mark only the v3 dispatch there.

Why it's exact

Keys in [position, pos_r) re-derived from the projection carry the same bits a 128-row pass reads from the cache. norm_rope ends in round_bf16, so store_dl stores that value unchanged, and V reaches the cache through copy_dl, a straight copy of the projection. Each row's pair and single loops stop at its own sub-pass start, so every SIMD-group folds the same keys, in the same pairs, as the 128-row pass holding that row. Keys past position + t score -INFINITY and skip the fold, so the longer new-key loop changes nothing.

On current main

Main is at 6653b7d now. The PR merges into it cleanly, and on the merge the PR's three test files, the 144-case sweep and #81's reproduction give the same results as above.

The commit subject says "(issue #31)"; this PR is for #81.

Scripts

Each runs from the repository root of an editable install (pip install -e '.[dev]'), saved there.

repro_issue81.py: #81's reproduction (attention v1, auto and v3; prompts of 300, 260, 400 and 1000 tokens).

"""Issue #81's reproduction: plain 128-row prompt passes vs 512-row exact passes on the synthetic hybrid checkpoint
(head dim 32, 8 heads, 2 KV heads), accelerator off, no autotune, eos -1. Compares the prompt rows both sessions'
final passes score (the last prompt row first) and 12 greedy tokens, per attention setting."""
import json
import os
import sys
import tempfile
from pathlib import Path

import numpy as np

REPO = Path(os.environ.get("LITHOS_REPO", ".")).resolve()
sys.path.insert(0, str(REPO / "tests"))
sys.path.insert(0, str(REPO / "tests" / "contract"))
from test_nn_lowering import _checkpoint  # noqa: E402

from monolith.formats import PackLayout  # noqa: E402
from monolith.formats.fp import bf16_to_f32  # noqa: E402
from monolith.generate import Session  # noqa: E402
from monolith.models.qwen3_5 import Qwen3_5Model  # noqa: E402
from monolith.nn.pack_plan import pack_model  # noqa: E402

VOCAB = 50
PROMPTS = [int(n) for n in os.environ.get("PROMPTS", "300,260,400,1000").split(",")]
ATTENTION = os.environ.get("ATTENTION", "v1,auto,v3").split(",")


def final_rows(session, p, n_final):
    """The scores of the final pass's rows (that pass's lm_head covers each of its rows)."""
    raw = session.prefill_engine(p).buffers["logits"].read(0, n_final * VOCAB * 2)
    return bf16_to_f32(np.frombuffer(raw, dtype=np.uint16)).reshape(n_final, VOCAB)


def final_pass(p, rows):
    return p - rows * ((p - 1) // rows)


def profile_for_this_device():
    """main registers no 40-core M3 Max: the 30-core M3 Max fallback's engine block with this device's core count, on
    the common backend (the chip backends pin their core counts)."""
    from monolith.backends.metal import config_for_device
    from monolith.backends.metal.config import ChipConfig
    from monolith.runtime import _native as nt
    info = nt.Device().info()
    found = config_for_device(info.gpu_cores, info.apple_family, info.name)
    if found is not None:
        return found
    doc = json.loads((REPO / "monolith/backends/metal/m3_max_30c/config.json").read_text())
    doc.update(name=f"apple-m3-max-{info.gpu_cores}c-check", gpu_cores=info.gpu_cores, backend="common")
    return ChipConfig.from_dict(doc["name"], doc)


def main():
    work = Path(tempfile.mkdtemp(dir=os.environ.get("WORK_DIR")))
    _checkpoint(work)
    model = lambda: Qwen3_5Model.from_checkpoint(str(work), max_context=2048)  # noqa: E731
    pack_model(model(), str(work), str(work / "pack"), PackLayout(rows=16))
    common = dict(eos=-1, autotune=False, accelerator="off", profile=profile_for_this_device())
    for attention in ATTENTION:
        plain = Session(model(), str(work / "pack"), prefill_chunk_size=128, attention=attention, **common)
        exact = Session(model(), str(work / "pack"), prefill_chunk_size=512, prefill_exact=True, attention=attention, **common)
        for p in PROMPTS:
            ids = np.random.default_rng(p).integers(0, VOCAB, p).tolist()
            a_tok = plain.generate(ids, 1).tokens
            n_a = final_pass(p, 128)
            a = final_rows(plain, p, n_a)
            b_tok = exact.generate(ids, 1).tokens
            n_b = final_pass(p, 512)
            b = final_rows(exact, p, n_b)[n_b - n_a:]          # the same prompt positions as the plain pass's rows
            assert int(np.argmax(a[-1])) == a_tok[0] and int(np.argmax(b[-1])) == b_tok[0], "row mapping"
            last = int(np.sum(a[-1] != b[-1]))
            rows = int(np.sum(np.any(a != b, axis=1)))
            g_a, g_b = plain.generate(ids, 12).tokens, exact.generate(ids, 12).tokens
            used = [exact.prefill_engine(p).program.kernels[op.kernel] for op in exact.prefill_engine(p).program.ops]
            kernels = sorted({k.function for k in used if k.function.startswith("gqa_")})
            exact_sub = sorted({k.macros.get("EXACT_SUB", "-") for k in used if k.function.startswith("gqa_decode")})
            print(f"attention={attention:5s} prompt={p:4d} kernels={'+'.join(kernels)} EXACT_SUB={','.join(exact_sub)} "
                  f"last-row scores differing={last}/{VOCAB} rows differing={rows}/{n_a} "
                  f"greedy12 {'equal' if g_a == g_b else 'DIFFER'}", flush=True)


if __name__ == "__main__":
    main()

warm_issue81.py: a prompt resumed from a prefix-cache checkpoint against the same prompt run cold.

"""Issue #81's impact: a prompt resumed from a prefix-cache checkpoint in an exact session must score like the same
prompt run cold in 128-row passes."""
import os
import sys
import tempfile
from pathlib import Path

import numpy as np

sys.path.insert(0, str(Path(__file__).resolve().parent))
from repro_issue81 import (ATTENTION, VOCAB, PackLayout, Qwen3_5Model, Session, _checkpoint, final_pass,  # noqa: E402
                           final_rows, pack_model, profile_for_this_device)

CHECKPOINT = 256


def main():
    work = Path(tempfile.mkdtemp(dir=os.environ.get("WORK_DIR")))
    _checkpoint(work)
    model = lambda: Qwen3_5Model.from_checkpoint(str(work), max_context=2048)  # noqa: E731
    pack_model(model(), str(work), str(work / "pack"), PackLayout(rows=16))
    common = dict(eos=-1, autotune=False, accelerator="off", profile=profile_for_this_device())
    for attention in ATTENTION:
        cold = Session(model(), str(work / "pack"), prefill_chunk_size=128, attention=attention, **common)
        warm = Session(model(), str(work / "pack"), prefill_chunk_size=512, prefill_exact=True, prefix_cache=True,
                       attention=attention, **common)
        rng = np.random.default_rng(81)
        prefix = rng.integers(0, VOCAB, CHECKPOINT).tolist()
        warm.generate(prefix + rng.integers(0, VOCAB, 40).tolist(), 1, cache_prefix_tokens=CHECKPOINT)
        for tail in (300, 130, 520):
            ids = prefix + rng.integers(0, VOCAB, tail).tolist()
            p = len(ids)
            g = warm.generate(ids, 1, cache_prefix_tokens=CHECKPOINT)
            n_w, n_c = final_pass(p - CHECKPOINT, 512), final_pass(p, 128)
            w = final_rows(warm, p, n_w)[n_w - n_c:]
            c_tok = cold.generate(ids, 1).tokens
            c = final_rows(cold, p, n_c)
            assert int(np.argmax(w[-1])) == g.tokens[0] and int(np.argmax(c[-1])) == c_tok[0], "row mapping"
            last = int(np.sum(w[-1] != c[-1]))
            rows = int(np.sum(np.any(w != c, axis=1)))
            g12_w = warm.generate(ids, 12, cache_prefix_tokens=CHECKPOINT)
            g12_c = cold.generate(ids, 12).tokens
            print(f"attention={attention:5s} warm from {g.cached_prompt_tokens} (then {g12_w.cached_prompt_tokens}), "
                  f"prompt={p:4d}: last-row scores differing={last}/{VOCAB} rows differing={rows}/{n_c} "
                  f"greedy12 {'equal' if g12_w.tokens == g12_c else 'DIFFER'}", flush=True)


if __name__ == "__main__":
    main()

test_v3_exact_edges.py: the 144-case kernel sweep (python -m pytest test_v3_exact_edges.py).

"""v3 EXACT_SUB = S: a T-row pass equals the S-row passes bit for bit (outputs and appended caches), across head dims,
pass starts, pass lengths, query/key norms and SINGLE_BLOCK. Reuses tests/kernels/test_gqa_decode.py's harness; run
from the repository root."""
import itertools
import os
import sys

import numpy as np
import pytest

sys.path.insert(0, os.path.join(os.environ.get("LITHOS_REPO", "."), "tests", "kernels"))
from test_gqa_decode import Cfg, Harness, _norms, _random_proj, rbf  # noqa: E402

from monolith import kernels  # noqa: E402
from monolith.runtime import _native as nt  # noqa: E402

CASES = list(itertools.product(
    [32, 64, 128, 256],          # head dim: v3 geometry NSG3 = 8, 16, 32, 16
    [0, 77, 600],                # cold prompt, a start off every NSG3 multiple, the PR's warm start
    [(300, 128), (512, 128), (256, 64)],   # (T, S): short last sub-pass, four 128-row sub-passes, the PR's S = 64
    [True, False],               # query/key RMSNorm (False: Llama-style)
    [False, True],               # SINGLE_BLOCK (the emitter's v3 form is 1)
))


@pytest.fixture(scope="module")
def dev():
    return nt.Device()


@pytest.mark.parametrize("d,position,ts,qk_norm,single_block", CASES)
def test_v3_exact_sub_matches_sub_passes(dev, d, position, ts, qk_norm, single_block):
    t, s = ts
    heads, kv = 8, 2
    ctx_max = position + t + 64
    common = dict(heads=heads, kv=kv, d=d, rot=d // 2, ctx_max=ctx_max, t_max=t, v3=True,
                  nsg3=kernels.gqa_v3_simdgroups(d), qk_norm=qk_norm, single_block=single_block)
    rng = np.random.default_rng(d * 1000 + position + t)
    qn, kn = _norms(rng, d)
    sub, whole = Harness(dev, Cfg(**common), qn, kn), Harness(dev, Cfg(**common, exact_sub=s), qn, kn)
    k = rbf(rng.standard_normal((ctx_max, kv, d)) * 0.5)
    v = rbf(rng.standard_normal((ctx_max, kv, d)))
    k[position:], v[position:] = 0, 0
    proj = _random_proj(rng, sub.cfg, t)
    sub.set_caches(k, v)
    ref = np.concatenate([sub.step(proj[s0:s0 + s], position + s0) for s0 in range(0, t, s)])
    whole.set_caches(k, v)
    got = whole.step(proj, position)
    assert np.array_equal(got, ref)
    for a, b in zip(whole.caches(), sub.caches()):
        assert np.array_equal(a, b)

collect_variants.py: both core filters on the 36 compiled exact prompt programs.

"""PR #92 changes exact_attention's core filter from startswith('gqa_decode') to == 'gqa_decode'. Compile the exact
prompt programs sessions build today and check both filters mark the same ops."""
import copy
import inspect
import os
import sys
import tempfile
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
from repro_issue81 import REPO, PackLayout, Qwen3_5Model, Session, _checkpoint, pack_model, profile_for_this_device  # noqa: E402

import monolith.compiler.prefill as prefill  # noqa: E402

sys.path.insert(0, str(REPO / "tests"))
from dspark_synth import build, write_checkpoint as write_dspark  # noqa: E402
from lm_synth import write_checkpoint as write_lm  # noqa: E402
from monolith.spec.lm import LMDrafter  # noqa: E402

source = inspect.getsource(prefill.exact_attention)
assert "elif k.function == 'gqa_decode':" in source
namespace = dict(vars(prefill))
exec(source.replace("elif k.function == 'gqa_decode':", "elif k.function.startswith('gqa_decode'):")
     .replace("def exact_attention(", "def exact_attention_startswith("), namespace)
pr_version, startswith_version = prefill.exact_attention, namespace["exact_attention_startswith"]
results = []


def compare(program, rows):
    a, b = pr_version(copy.deepcopy(program), rows), startswith_version(copy.deepcopy(program), rows)
    functions = sorted({program.kernels[op.kernel].function for op in program.ops
                        if program.kernels[op.kernel].function.startswith("gqa_")})
    marked = sorted({a.kernels[op.kernel].function for op in a.ops if "EXACT_SUB" in a.kernels[op.kernel].macros})
    results.append((functions, marked, a.to_json() == b.to_json()))
    return pr_version(program, rows)


prefill.exact_attention = compare


def main():
    work = Path(tempfile.mkdtemp(dir=os.environ.get("WORK_DIR")))
    target, draft = work / "target", work / "draft"
    target.mkdir(); draft.mkdir()
    _checkpoint(target)
    model = lambda: Qwen3_5Model.from_checkpoint(str(target), max_context=1024)  # noqa: E731
    pack_model(model(), str(target), str(target / "pack"), PackLayout(rows=16))
    profile = profile_for_this_device()
    for drafter in (None, "lm", "dspark"):
        for attention in ("v1", "v2", "v3", "auto", "mma", "mma-direct"):
            for accelerator in ("off", "on"):
                m, options = model(), {}
                if drafter == "lm":
                    write_lm(draft, vocab_size=50)
                    d = LMDrafter.from_checkpoint(str(draft), target_lm_head=m.lm_head, max_context=1024, gamma=3)
                elif drafter == "dspark":
                    write_dspark(draft, with_head=False, vocab_size=50, target_hidden_size=256, target_layer_ids=[-1, 1])
                    d, _, _, _ = build(draft, target_lm_head=m.lm_head, max_context=1024)
                if drafter:
                    pack_model(d, str(draft), str(draft / "pack"), PackLayout(rows=16))
                    options = dict(drafter=d, drafter_pack=str(draft / "pack"), verify="fixed", verify_length=3)
                before = len(results)
                try:
                    Session(m, str(target / "pack"), eos=-1, autotune=False, attention=attention, accelerator=accelerator,
                            profile=profile, prefill_chunk_size=512, prefill_exact=True, **options).prepare()
                except Exception as e:  # a configuration this chip or model cannot compile
                    print(f"drafter={drafter} attention={attention} accelerator={accelerator}: not compiled ({type(e).__name__}: {e})")
                    continue
                for functions, marked, same in results[before:]:
                    print(f"drafter={drafter} attention={attention} accelerator={accelerator}: "
                          f"attention kernels={'+'.join(functions)} marked={'+'.join(marked) or '-'} "
                          f"filters agree={same}", flush=True)
    agree = sum(same for _, _, same in results)
    print(f"programs compared: {len(results)}, filters agree on {agree}")


if __name__ == "__main__":
    main()

speed_issue81.py: the timing (EXACT=0 for plain passes, ATTENTION=v1 for exact passes on v1).

"""Prefill time of 512-row passes on an 8000-token prompt (ATTENTION, default auto: v3; EXACT=1 exact passes, 0 plain),
to compare the kernel with and without the fix."""
import os
import sys
import tempfile
from pathlib import Path

import numpy as np

sys.path.insert(0, str(Path(__file__).resolve().parent))
from repro_issue81 import VOCAB, PackLayout, Qwen3_5Model, Session, _checkpoint, pack_model, profile_for_this_device  # noqa: E402

CONTEXT, PROMPT, RUNS = 8192, 8000, int(os.environ.get("RUNS", "9"))
ATTENTION, EXACT = os.environ.get("ATTENTION", "auto"), os.environ.get("EXACT", "1") == "1"


def main():
    work = Path(tempfile.mkdtemp(dir=os.environ.get("WORK_DIR")))
    _checkpoint(work)
    model = lambda: Qwen3_5Model.from_checkpoint(str(work), max_context=CONTEXT)  # noqa: E731
    pack_model(model(), str(work), str(work / "pack"), PackLayout(rows=16))
    session = Session(model(), str(work / "pack"), eos=-1, autotune=False, accelerator="off", attention=ATTENTION,
                      profile=profile_for_this_device(), prefill_chunk_size=512, prefill_exact=EXACT)
    ids = np.random.default_rng(8000).integers(0, VOCAB, PROMPT).tolist()
    session.generate(ids, 1)                                   # compile and warm up
    times = [session.generate(ids, 1).prefill_ms for _ in range(RUNS)]
    print(f"attention={ATTENTION} exact={EXACT} prompt={PROMPT} prefill_ms median={np.median(times):.2f} "
          f"min={min(times):.2f} max={max(times):.2f} runs={RUNS}", flush=True)


if __name__ == "__main__":
    main()

m3max40_profile.py: the pytest plugin for the tiers (PYTHONPATH=. python -m pytest -p m3max40_profile tests/contract tests/kernels tests/runtime).

"""pytest plugin (-p m3max40_profile): main registers no 40-core M3 Max, so sessions on this machine get the 30-core
M3 Max fallback's engine block with this device's core count, on the common backend. Other devices are unaffected."""
import json
from pathlib import Path

import monolith.backends.metal as metal
import monolith.backends.metal.registry as registry
import monolith.bench as bench
import monolith.generate as generate
import monolith.serving.setup as serving_setup
from monolith.backends.metal.config import ChipConfig

_registered = registry.config_for_device


def config_for_device(gpu_cores, apple_family, chip=None):
    found = _registered(gpu_cores, apple_family, chip)
    if found is not None or chip is None or chip.strip().casefold() != "apple m3 max":
        return found
    doc = json.loads((Path(registry.__file__).parent / "m3_max_30c" / "config.json").read_text())
    doc.update(name=f"apple-m3-max-{gpu_cores}c-check", gpu_cores=gpu_cores, backend="common")
    return ChipConfig.from_dict(doc["name"], doc)


for module in (registry, metal, generate, bench, serving_setup):
    if hasattr(module, "config_for_device"):
        module.config_for_device = config_for_device

v3 pairs cached keys while key + NSG3 < position and folds the rest
singly, so a row's result depended on where its pass started. Under
attention auto, exact prompt passes that select v3 therefore missed the
128-row results, breaking serve's bit-for-bit promise for models
without query/key norms, head dims other than 128/256, and accelerator
off.

With EXACT_SUB, each row re-roots that boundary at its own sub-pass
start (position + (t / EXACT_SUB) * EXACT_SUB). Keys between the pass
start and that boundary are this dispatch's earlier sub-pass keys: read
them from the projection (the values those passes appended) and fold
them with the cached prefix in the sub-pass's pairing. exact_attention
now marks gqa_decode_v3 as well as the v1 core/merge pair; v3 has no
partial workspace.

A 256-row v3 pass is now bit-equal to the S-row passes in outputs and
appended caches for D=128/NSG3=32 and D=32/NSG3=8. Non-exact v3 is
unchanged (the helpers compile out).
@pythongiant
pythongiant force-pushed the fix/exact-attention-v3 branch from 0cc5526 to 7df40b7 Compare October 22, 2026 16:00
@pythongiant

Copy link
Copy Markdown
Author

@woodsonl fixed the message

@pythongiant

Copy link
Copy Markdown
Author

@yzhou442 could u merge?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Compiler: exact prompt passes are not bit-exact where attention auto picks v3

2 participants