Skip to content

Give a KV layout a second head shape and compile Gemma 4's attention - #823

Open
kevinzhao-dev wants to merge 1 commit into
incoai:mainfrom
kevinzhao-dev:exp/gemma4-kv-attention
Open

kevinzhao-dev wants to merge 1 commit into
incoai:mainfrom
kevinzhao-dev:exp/gemma4-kv-attention

Conversation

@kevinzhao-dev

@kevinzhao-dev kevinzhao-dev commented Nov 24, 2026 •

Copy link
Copy Markdown

Refs #8.

Gemma 4 31B has two kinds of attention layers, and a Splash KV layout holds one head shape. This PR lets a layout hold a second shape and compiles Gemma 4's two attention geometries. No target uses them yet. The engine target is the next PR.

From google/gemma-4-31B-it's config.json:

  • 50 sliding layers: 16 KV heads of 256. A row sees itself and the 1,023 keys before it (sliding_window: 1024, so windowTokens = 1023).
  • 10 global layers: 4 KV heads of 512 over the whole history. The keys are reused as values (attention_k_eq_v), and the values are RMS-normalized without a weight.
  • Scale: both kinds score with a scale of 1.

26B-A4B has the same layer pattern, window and K-as-V, with half the heads: 16 query heads, 8 × 256 on sliding layers and 2 × 512 on global ones. It can use this layout and these template switches, but needs two geometry rows of its own.

What changes

  • Layout: kv::Layout gains windowKvHeads and windowHeadDimension, a second head shape for the windowed regions. In each extent, their bytes follow the whole-history regions.
    • layerLayout(layer) gives each layer its own shape.
    • kvBytesBeforeRegion(count) gives the bytes of a page's first count regions. PageStorage, the page sizes and the extent alignment now use it.
    • Without a second shape, each returns what it did before.
  • Geometries: two BF16 geometries are added.
    • _kv4_g8_d512 for the global layers: shared K/V and normalized values.
    • _kv16_g2 with a 1,023-key window for the sliding layers.
    • The QKV prepare gains NormalizeValue and SharedKv, and the attention tile gains UnitScale. Each defaults to what the existing geometries compile.
  • Compiled table: kCompiledAttention gains bf16Only, wholeHistory and sharedKv, and commitSuffix becomes optional.

What changes for existing users

Nothing.

  • All 2,309 existing kernels compile to the same AIR as on main.
  • storesLayout refuses a layout with a second shape, so no existing model can select the new rows.
  • The metallib grows by 126 KB, from 74.63 MB to 74.76 MB, with 8 new kernels.

Testing

MacBook Pro, M5 Pro (18-core CPU, 20-core GPU), 64 GB, macOS 26.6.2, on main at d40c250.

  • attention-variants, under MTL_SHADER_VALIDATION=1. One sequence runs 1,064 tokens through both layers, which share a page table. The run crosses a Page32 boundary and a Slim relocation.
    • Every row's stored K and V are within a bf16 step of FP64 computed from the raw projection.
    • Outputs at the window edges match FP64: max abs error 0.00063 on sliding layers and 0.0020 on global ones.
    • At 1024 and 1055, the key that leaves the window changes the output.
    • The test fails with NormalizeValue off, and when the global layer reads its values from a V slot instead of its keys. I checked both by breaking the kernel locally.
  • q8-paged-kv: both page shapes, in both formats.
  • engine-cache: a 1,024-key window trims a page only after every row has passed it, and the global layers keep their history.
  • Make targets: make check-source and make check-native-engine pass: the architecture check, the CPU and Metal suites (Metal under MTL_SHADER_VALIDATION=1), and the Metal suites again under ThreadSanitizer.
  • Kernel identity: python3 dev/tools/kernel_identity.py MAIN.metallib build/splash.metallib, with MAIN.metallib built from d40c250, reports 2,309 of 2,317 kernels identical. The other 8 exist only in this PR.
make check-native-engine

Known limitations

  • BF16 KV only. The new geometries have no INT8 rows.
  • No KV path commit. The new geometries have no KV path commit kernels, so a draft tree's accepted path cannot be committed to these pages yet. Gemma 4's DFlash v1 draft verifies one block a step and does not need them.
  • One GPU family. Tested only on Apple10 (M5 Pro), not on Apple9 or an M5 Max.
  • No real-model rerun of existing models. Their outputs are covered by the kernel identity check above.

What comes next

The whole port runs on my fork (kevinzhao-dev#1). It sits on this PR's previous version, which was on 1.7.2. On the same GGUF, greedy output matches llama.cpp on three prompts, and one of them goes past the window. The numbers are in #8. To reproduce them, the fork has dev/tools/gemma4_parity.py and dev/benchmarks/gemma4_benchmark.mm.

Next I'd send the engine target: Gemma 4 as a layout that the Qwen target runs, as it runs Flint. DFlash v1 in the runtime would come after that. If you'd rather this took a different shape, I'm happy to change it.

🤖 Generated with Claude Code

Gemma 4 31B has two kinds of attention layers. Its 50 sliding layers
attend the 1,023 keys before each row with 16 KV heads of 256; its 10
global layers attend the whole history with 4 KV heads of 512, use each
key head as its value head and RMS-normalize the values without a
weight. Both score with a scale of 1. One page layout now holds both
shapes and the kernels compile both geometries; no target uses them yet,
and every existing kernel compiles as before.

- kv::Layout gains windowKvHeads and windowHeadDimension, a second head
  shape for its windowed regions, whose bytes follow the whole-history
  regions in each extent. layerLayout(layer) gives a layer its own shape
  and kvBytesBeforeRegion(count) the bytes of a page's first regions,
  which PageStorage, the page sizes and the extent alignment use.
  Without a second shape each is what it was.
- kCompiledAttention gains bf16Only, wholeHistory and sharedKv, and its
  commitSuffix becomes optional for pages that never leave their extent.
  Its new rows are _kv4_g8_d512 (shared K/V, normalized values) and
  _kv16_g2_w1023 (the window alone), both BF16. No compiled geometry
  matches a layout with a second shape: a target selects each layer's
  by layerLayout(layer).
- The QKV prepare takes NormalizeValue and SharedKv and the attention
  tile UnitScale, each defaulting to what the existing geometries
  compile.
- attention-variants runs both geometries in one sequence against FP64
  across a Page32 boundary and a Slim relocation, and checks every row's
  stored K and V against FP64 from the raw projection, so the shared K/V
  and the value norm are checked too; q8-paged-kv checks the
  two page shapes in both formats; engine-cache checks that a 1,024-key
  window trims a page only once every row has passed it and keeps the
  global layers' history.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@kevinzhao-dev
kevinzhao-dev force-pushed the exp/gemma4-kv-attention branch from a011362 to b4f007c Compare November 25, 2026 09:24
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.

1 participant