Skip to content

Gemma3 4b optimization - #1126

Open
michyu-amd wants to merge 18 commits into
mainfrom
gemma3-4b-optimization
Open

michyu-amd wants to merge 18 commits into
mainfrom
gemma3-4b-optimization

Conversation

@michyu-amd

Copy link
Copy Markdown
Collaborator

Decode speed work for gemma3:4b, medgemma:4b, medgemma1.5:4b and translategemma:4b on NPU2.
All four now use one kernel, Gemma3/gemma_npu_lm_bin -> layer_lm.xclbin.

Changes

  • lm_head runs inside the layer xclbin (new lm_head mode), so decode has no hw_context switch.
    The old layer.xclbin / lm_head.xclbin units and their kernel folders are removed.
  • Sliding-window KV is read in whole 16-row chunks past 1,024 tokens.
  • KV cache keeps a bfp16 copy (packed on the host as chunks finish); attention uses native bfp16 mmul.
  • restore() zeroes the global KV rows above the checkpoint (replay after restore is now byte-identical).
  • lm_head: the rms core sends x one round ahead, so the weight stream no longer stalls each round.
  • P.V core skips the y *= c correction when c == 1.
  • Engine syncs only the bytes it writes/reads for x, logits and rope tables (BOs are padded to 1 MB).
  • Probe builds (PROBE=...) and test_lm_head / test_layer_time for timing splits.

Results (gemma3:4b, Strix Halo, Performance mode, median of 3 alternating rounds, 128 tokens)

  • Decode per token: 1K 57.38 -> 50.13 ms (+14.5%), 4K 59.17 -> 50.81 ms (+16.5%).

Accuracy

  • Most steps are byte-identical vs the step before (six engine scenarios: 1K/4K, second prefill,
    checkpoint/restore, read/write_state).
  • Not bit-identical:
    • the chunked ring read order (median cos ~0.99985, the same spread as any other read order);
    • the correction skip (same forced tokens: top-1 equal 99.6% at 1K / 97.3% at 4K, cos >= 0.99965).
  • Details are in the kernel and engine READMEs.

To do

  • CI build + NPU tests for all four models; layer_lm.xclbin arrives in the dev-kit swap commit.

michyu-amd and others added 17 commits November 23, 2026 11:35
Pure copy of the 30 tracked files, no changes. The shared folder
Gemma3/gemma_npu_bin also feeds medgemma:4b, medgemma1.5:4b and
translategemma:4b; the next commits change only this copy (lm_head
inside the layer xclbin, no context switch per decode token).
Not yet in build_units.json / kernel_assignment.json.

Co-Authored-By: Claude <noreply@anthropic.com>
Kernel copy Gemma3/gemma3_4b_npu_bin (gemma3:4b only):
- rms_residual: IS_ATTN 2 = lm_head with x already normalized on the host
  (copy instead of RMS norm), so the logits keep today's bits.
- proj: FLM_STUB skips the math (make STUB=1, data floor).
- bitstream.mk: output layer_lm.xclbin; writes rtp_addresses.txt and fails
  if one of the 25 RTPs moves or a core program is over 16 KB; make txn
  builds the design with --aie-generate-txn.
- host/test_lm_head.cpp + makefiles/test.mk: same x to lm_head.xclbin and
  layer_lm.xclbin, compares every logit bit, CPU Q4_1 reference, timing.

FLM_DLL gemma_npu_sequence: gen_lm_head_in_layer_seq() and
get_lm_head_in_layer_rows(); not called by the engine yet.

Strix Halo: 28 x vectors (24 real decode x at 1K/4K + 4 random) give
bit-identical logits; cos vs CPU >= 0.999987. lm_head in the layer design
takes 9.84 ms (stub 9.59) vs 7.56 ms for lm_head.xclbin.

Co-Authored-By: Claude <noreply@anthropic.com>
The engine registers layer_lm.xclbin instead of layer.xclbin and no longer
uses lm_head.xclbin: lm_head is a second app on the layer xclbin
(gen_lm_head_in_layer_seq, mode RTPs proj 0 / rms 2), weights in the layer
layout (reorder_cpy(..., 2)), logits padded to 263,680 rows. The run order
is unchanged, so the next token's run rebuild still hides behind lm_head.
gen_lm_head_seq() is removed; the kernel test keeps a copy as its reference.

Serves gemma3:4b, medgemma:4b, medgemma1.5:4b, translategemma:4b; their
kernel assignment moves to layer_lm.xclbin in the next commit.

Strix Halo, gemma3:4b vs the engine at 995203b: logits byte-identical for
1,001 steps at 1K and 257 at 4K, same tokens; decode 57.38 -> 54.54 ms
(+5.2%) at 1K, 59.17 -> 56.40 ms (+4.9%) at 4K.

Co-Authored-By: Claude <noreply@anthropic.com>
gemma3:4b, medgemma:4b, medgemma1.5:4b and translategemma:4b (one engine,
gemma_npu, same shape and vocab) now use one decode kernel,
layer_lm.xclbin = xclbins-Gemma3_gemma_npu_lm_bin:
- rename FLM_Xclbin/Gemma3/gemma3_4b_npu_bin to Gemma3/gemma_npu_lm_bin;
- remove Gemma3/gemma_npu_bin and Gemma3/gemma_lm_head_npu_bin (no model
  uses them now; in git history);
- build_units.json, kernel_assignment.json/.md, RTP lock stanza for the
  new unit (25 RTPs, the addresses gemma_npu_sequence_detail.hpp writes);
- delete the 8 layer.xclbin / lm_head.xclbin files of the four models in
  src/xclbins (no longer assigned); layer_lm.xclbin comes from the CI swap.

Co-Authored-By: Claude <noreply@anthropic.com>
…kens

Past the window, _move_kv_cache now starts at the chunk after the newest
row's instead of at L % 1024, so the attention cores' 16-key groups are ring
chunks (needed for a bfp16 copy packed once per chunk). Unchanged up to
1,024 tokens and whenever L % 16 == 0.

gemma3:4b, Strix Halo: <= 1,024 tokens byte-identical (515 steps). Past
1,024, with forced tokens, the old order, this one and a row-0 order differ
pairwise alike (median cos ~0.99985, top-1 same 95-99%): bf16 rounding of
the online softmax, not a loss of accuracy.

Co-Authored-By: Claude <noreply@anthropic.com>
make bitstream KV_BFP16=1 builds a layer_lm.xclbin whose decode attention
reads every finished 16-key chunk of K and V from a host-packed bfp16 copy
(44% fewer bytes) and runs the native mac_8x8_8x8T_conf on it, instead of
the emulated bf16 mmul; the newest chunk still comes as bf16 and is packed
on the core. Same blocks as the emulation, so the same bits.

- attn_qk.cc / attn_kv.cc: KV_BFP16 paths (packed K / V^T, Q per block,
  P once per chunk, tail packing), FLM_STUB skips the math; floor rounding.
- iron: kvb option (4,608 B core buffers, 9,216 B mem tile units split by
  one fixed pattern, tail buffers, 8-argument kernels).
- bitstream.mk: per-build RTP checks (kvb: L_attn_qk 20992, L_attn_kv 50176).
- FLM_DLL gemma_npu: gemma_bfp16_pack.hpp (host packer, copy of MiniCPM-OCR's
  with a slice layout) and gen_layer_seq(..., kv_bfp16) + the packed read;
  the engine still uses the bf16 path until the next step.
- host/test_layer_kv.cpp: one layer on both builds, same random inputs.

Strix Halo: test_layer_kv PASSED (x and the written K/V row byte-identical
at 20 global and 17 sliding lengths, 1 to 8,192). One layer: global L 4,160
1.72-1.83 -> 1.62-1.66 ms, ring-full sliding 1.35 -> 1.32 ms. The default
build's MLIR and program sizes are unchanged.

Co-Authored-By: Claude <noreply@anthropic.com>
The engine keeps a bfp16 copy of every finished 16-row K/V chunk behind the
bf16 regions of each layer's kv buffer and the decode layer reads it with the
native bfp16 multiply (kernel from the previous commit). Same bits as the
bf16 attention.

- gemma_npu.cpp: _kv_bfp16_ensure() in set_context_length packs stale
  chunks (exact ranged syncs, OpenMP), hidden under lm_head in decode;
  prefill, clear_context, restore, write_state(_kv), update_max_length mark
  chunks stale; states, checkpoints and prefill syncs use the bf16 part only.
- sequence: the bf16 KV read and the kv_bfp16 flag are gone; L_attn_qk 20992,
  L_attn_kv 50176 (RTP lock updated).
- kernel folder: the bfp16 attention is the only build (KV_BFP16 option,
  the emulated attention and test_layer_kv removed; MLIR and program sizes
  identical to the KV_BFP16 build).

gemma3:4b, Strix Halo, vs the engine at eded76e: logits byte-identical in
six scenarios (short, 1K, 4K, second prefill, checkpoint/restore,
read/write_state); decode 54.60 -> 53.75 ms at 1K, 56.39 -> 55.20 ms at 4K.

Co-Authored-By: Claude <noreply@anthropic.com>
restore() put back only the sliding rings, so the global layers' rows
above the checkpoint kept what was decoded after it; the attention's
unmasked max over the newest chunk saw them, and the decode after restore
did not replay the decode after checkpoint (cos 0.99983, tokens differed
from step 9; also before the bfp16 KV change). Zero them as write_state
does (kv_rows_zero up to dirty_rows) and mark their bfp16 chunks stale.

gemma3:4b, Strix Halo: the decode after restore is now byte-identical to
the one after checkpoint (40/40 steps); the other five engine scenarios
are byte-identical to before.

Co-Authored-By: Claude <noreply@anthropic.com>
Timing-only builds (make bitstream STUB=1 PROBE=NO_X|NO_W|NO_Y) that drop
the x re-send, the weights or the logits from the lm_head mode, and a
matching probe sequence in test_lm_head (--probe). The normal build is
unchanged (only #ifdefs; program sizes identical).

Strix Halo, no-math lm_head inside the layer design: 9.64 ms; without the
x re-send 7.67 ms, without the logits 7.76 ms, without the weights 2.75 ms.
The rms core runs each 512-row round in lockstep (send x, collect logits,
then the next x), so the proj cores and the weight stream wait between
rounds. One weight descriptor per channel (no per-round waits) changed
nothing (9.77 / 9.57 ms) and was not kept.

Co-Authored-By: Claude <noreply@anthropic.com>
In lm_head mode the rms core sent each round's x, collected the round's
logits and only then sent the next x, so the 16 proj cores and the weight
stream waited between rounds. x is the same for every round: queue round
i + 1's x sends before collecting round i's logits (at most 10
outstanding, 515 in total as before). Same data and order per stream.

Strix Halo: logits bit-identical to lm_head.xclbin (28 x vectors); lm_head
in the layer design 9.84 -> 7.81 ms. gemma3:4b engine, old vs new
layer_lm.xclbin: logits byte-identical in six scenarios; decode 53.74 ->
51.61 ms at 1K, 55.19 -> 53.06 ms at 4K.

Co-Authored-By: Claude <noreply@anthropic.com>
host/test_layer_time.cpp (make test_layer_time): one decode layer run at
L = 16 / 1,088 / 4,160 on one xclbin, random inputs, timing only.

Strix Halo: weights alone (L 16) take 1.24 ms for 59 MB with or without
the math (~85% of the DDR limit); K/V adds 0.04-0.19 ms, attention math
~0.05 ms (1K) to ~0.2 ms (global, 4K). The weight stream stops between
the layer's 4 matrices while the proj cores wait for the previous step;
each weight mem tile keeps only 2 x 20 KB of read-ahead (41 of 512 KB).

Co-Authored-By: Claude <noreply@anthropic.com>
More weight buffering in the weight mem tiles was tried: 4 buffers of one
k-step gave no gain (one layer 1.242 vs 1.246 ms, lm_head 7.91 vs 7.99 ms,
logits bit-identical); buffers of 5 k-steps deadlock, because each weight
half's two readers are chained and all proj cores take x from one
broadcast stream. The design's lockstep, not the read-ahead depth, costs
the ~0.18 ms per layer. Code not kept.

Co-Authored-By: Claude <noreply@anthropic.com>
PROBE=NO_QK_MATH / NO_KV_MATH (timing only) skip the Q.K / P.V math;
test_layer_time also times the global layer at L 8,192. Normal build
unchanged (program sizes identical).

Strix Halo: Q.K math costs at most 0.02 ms per layer; P.V math ~0.19 ms
per global layer at 4K, ~0.40 ms at 8K, ~0.05 ms per sliding layer.

Co-Authored-By: Claude <noreply@anthropic.com>
PROBE=NO_KV_L / NO_KV_CORR / NO_KV_MAC (timing only) skip calculate_l,
the correction pass y *= c or the multiply pass. Normal build unchanged.

Strix Halo: the correction pass alone costs as much as all P.V math
(global layer 1.621 -> 1.437 ms at 4K, 2.031 -> 1.640 ms at 8K): the
float x float vector multiply is emulated on this core, 512 per chunk.

Co-Authored-By: Claude <noreply@anthropic.com>
The P.V core leaves y as it is when both heads' correction is exactly 1.0
(the running max did not move, nearly every chunk at long context)
instead of y *= c, an emulated fp32 multiply on this core. Not
bit-identical: a probe showed the multiply by 1.0 moves ~0.23% of negative
y by 1 ulp with no cheap rule; the skip keeps y exact.

gemma3:4b, Strix Halo: decode 51.58 -> 50.17 ms at 1K, 53.05 -> 50.87 ms
at 4K; same forced tokens: identical logits for the first 221 / 109
steps, then cos >= 0.99965, top-1 same at 99.6% / 97.3%.

Co-Authored-By: Claude <noreply@anthropic.com>
Every BO is padded to 1 MB and a plain sync flushes all of it. forward,
get_logits and _set_rope_rms_weights now sync only the elements the host
writes or reads (x: D, logits: rows, rope: the DH cos/sin values), ~38 MB
of cache flushes less per token.

Byte-identical logits and tokens in the six engine scenarios vs 454442f;
decode 1K 50.15 -> 50.13 ms, 4K 50.86 -> 50.81 ms (Strix Halo,
Performance mode; the rope syncs were already hidden behind lm_head).

Co-Authored-By: Claude <noreply@anthropic.com>
@github-actions

github-actions Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Security scan found no critical or high findings on lines changed by this pull request

View the security scan run for complete reports.

“New” means the finding is located in a changed file on an added or modified line; it is not a base-versus-head findings delta.

@github-actions

Copy link
Copy Markdown

Dev-kit bench

Results of the dev-kit benches in Build and Test run 45301001729 for 4c6e240e9e, as that run reported them (its artifacts hold the per-model reports).

Summary
## Dev-kit bench (pr) on `4c6e240e9e`

the pull request's staged packages: this run's numbers only, no comparison (to be designed later)

✅ No hard-gate failure and no soft-gate warning.

### Linux XRT

#### Perf (tok/s; dev-kit against the base package on the same runner)

| Model | Machine | Context | Decode base → dev-kit | Δ | Prefill base → dev-kit | Δ | Decode Δ vs nightly (same kind) |
|---|---|---|---|---|---|---|---|
| gemma3:4b | strix | 1k | — → 20.1 | — | — → 548.2 | — | no baseline for this kind |
| gemma3:4b | strix | 2k | — → 19.8 | — | — → 671.4 | — | no baseline for this kind |
| gemma3:4b | strix | 4k | — → 19.9 | — | — → 766.4 | — | no baseline for this kind |
| gemma3:4b | strix | 8k | — → 19.6 | — | — → 838.6 | — | no baseline for this kind |
| medgemma1.5:4b | ryzenai-npu4 | 1k | — → 19.9 | — | — → 562.6 | — | no baseline for this kind |
| medgemma1.5:4b | ryzenai-npu4 | 2k | — → 19.9 | — | — → 679.5 | — | no baseline for this kind |
| medgemma1.5:4b | ryzenai-npu4 | 4k | — → 19.7 | — | — → 766.6 | — | no baseline for this kind |
| medgemma1.5:4b | ryzenai-npu4 | 8k | — → 19.4 | — | — → 857.0 | — | no baseline for this kind |
| medgemma:4b | ryzenai-npu5 | 1k | — → 20.6 | — | — → 585.4 | — | no baseline for this kind |
| medgemma:4b | ryzenai-npu5 | 2k | — → 20.5 | — | — → 704.6 | — | no baseline for this kind |
| medgemma:4b | ryzenai-npu5 | 4k | — → 20.2 | — | — → 796.2 | — | no baseline for this kind |
| medgemma:4b | ryzenai-npu5 | 8k | — → 19.9 | — | — → 873.9 | — | no baseline for this kind |
| translategemma:4b | ryzenai-npu6 | 1k | — → 23.6 | — | — → 551.0 | — | no baseline for this kind |
| translategemma:4b | ryzenai-npu6 | 2k | — → 23.5 | — | — → 680.7 | — | no baseline for this kind |
| translategemma:4b | ryzenai-npu6 | 4k | — → 23.2 | — | — → 776.5 | — | no baseline for this kind |
| translategemma:4b | ryzenai-npu6 | 8k | — → 23.0 | — | — → 841.7 | — | no baseline for this kind |

#### GSM8K accuracy (%)

| Model | Nightly baseline | This run | Δ (points) | Notes |
|---|---|---|---|---|
| gemma3:4b | — | 74.0 | — | 5 hit max_tokens |
| medgemma1.5:4b | — | 54.0 | — | 9 hit max_tokens |
| medgemma:4b | — | 54.0 | — | 9 hit max_tokens |
| translategemma:4b | — | 46.0 | — | 9 hit max_tokens |

### Linux HRX

#### Perf (tok/s; dev-kit against the base package on the same runner)

| Model | Machine | Context | Decode base → dev-kit | Δ | Prefill base → dev-kit | Δ | Decode Δ vs nightly (same kind) |
|---|---|---|---|---|---|---|---|
| gemma3:4b | ryzenai-npu4 | 1k | — → 7.3 | — | — → 299.1 | — | no baseline for this kind |
| gemma3:4b | ryzenai-npu4 | 2k | — → 7.3 | — | — → 351.1 | — | no baseline for this kind |
| gemma3:4b | ryzenai-npu4 | 4k | — → 7.3 | — | — → 380.2 | — | no baseline for this kind |
| gemma3:4b | ryzenai-npu4 | 8k | — → 7.2 | — | — → 405.8 | — | no baseline for this kind |
| medgemma1.5:4b | ryzenai-npu4 | 1k | — → 20.6 | — | — → 597.2 | — | no baseline for this kind |
| medgemma1.5:4b | ryzenai-npu4 | 2k | — → 20.5 | — | — → 745.7 | — | no baseline for this kind |
| medgemma1.5:4b | ryzenai-npu4 | 4k | — → 20.4 | — | — → 848.3 | — | no baseline for this kind |
| medgemma1.5:4b | ryzenai-npu4 | 8k | — → 20.2 | — | — → 922.4 | — | no baseline for this kind |
| medgemma:4b | ryzenai-npu4 | 1k | — → 19.2 | — | — → 588.0 | — | no baseline for this kind |
| medgemma:4b | ryzenai-npu4 | 2k | — → 18.9 | — | — → 693.4 | — | no baseline for this kind |
| medgemma:4b | ryzenai-npu4 | 4k | — → 18.9 | — | — → 786.0 | — | no baseline for this kind |
| medgemma:4b | ryzenai-npu4 | 8k | — → 18.9 | — | — → 851.2 | — | no baseline for this kind |
| translategemma:4b | ryzenai-npu6 | 1k | — → 22.3 | — | — → 597.7 | — | no baseline for this kind |
| translategemma:4b | ryzenai-npu6 | 2k | — → 22.1 | — | — → 709.1 | — | no baseline for this kind |
| translategemma:4b | ryzenai-npu6 | 4k | — → 21.9 | — | — → 795.8 | — | no baseline for this kind |
| translategemma:4b | ryzenai-npu6 | 8k | — → 21.5 | — | — → 853.4 | — | no baseline for this kind |

#### GSM8K accuracy (%)

| Model | Nightly baseline | This run | Δ (points) | Notes |
|---|---|---|---|---|
| gemma3:4b | — | 73.3 | — | 5 hit max_tokens; time budget spent: 45 of 50 questions asked |
| medgemma1.5:4b | — | 54.0 | — | 9 hit max_tokens |
| medgemma:4b | — | 54.0 | — | 9 hit max_tokens |
| translategemma:4b | — | 46.0 | — | 9 hit max_tokens |

_Perf: flm bench, decode and prefill average tok/s per context. A/B is the one perf signal that judges a change; the runners differ by machine kind, so the nightly comparison is informational and only made for the same kind. Accuracy: GSM8K (first 50 questions) and DocVQA (when enabled), greedy; unanswered questions count as wrong. Per-question reports, server logs and CSVs: the devkit-bench-result-* artifacts._

The dev-kit engine libraries and kernels that run 45301001729 built from
4c6e240, staged into its product builds and tested on the NPU
(devkit_swap.py fetch): 6 engine file(s), 24 kernel(s).
CI checks these bytes against the run's staging manifests.

  src/lib/hrx/gemma_npu.dll
  src/lib/hrx/gemma_npu.lib
  src/lib/hrx/libgemma_npu.so
  src/lib/xrt/gemma_npu.dll
  src/lib/xrt/gemma_npu.lib
  src/lib/xrt/libgemma_npu.so
  src/xclbins/Gemma3-4B-NPU2/attn.xclbin
  src/xclbins/Gemma3-4B-NPU2/dequant.xclbin
  src/xclbins/Gemma3-4B-NPU2/layer_lm.xclbin
  src/xclbins/Gemma3-4B-NPU2/mm.xclbin
  src/xclbins/Gemma3-4B-NPU2/vision_attn.xclbin
  src/xclbins/Gemma3-4B-NPU2/vision_mm.xclbin
  src/xclbins/Medgemma-1.5-4B-NPU2/attn.xclbin
  src/xclbins/Medgemma-1.5-4B-NPU2/dequant.xclbin
  src/xclbins/Medgemma-1.5-4B-NPU2/layer_lm.xclbin
  src/xclbins/Medgemma-1.5-4B-NPU2/mm.xclbin
  src/xclbins/Medgemma-1.5-4B-NPU2/vision_attn.xclbin
  src/xclbins/Medgemma-1.5-4B-NPU2/vision_mm.xclbin
  src/xclbins/Medgemma-4B-NPU2/attn.xclbin
  src/xclbins/Medgemma-4B-NPU2/dequant.xclbin
  src/xclbins/Medgemma-4B-NPU2/layer_lm.xclbin
  src/xclbins/Medgemma-4B-NPU2/mm.xclbin
  src/xclbins/Medgemma-4B-NPU2/vision_attn.xclbin
  src/xclbins/Medgemma-4B-NPU2/vision_mm.xclbin
  src/xclbins/Translategemma-4B-Instruct-NPU2/attn.xclbin
  src/xclbins/Translategemma-4B-Instruct-NPU2/dequant.xclbin
  src/xclbins/Translategemma-4B-Instruct-NPU2/layer_lm.xclbin
  src/xclbins/Translategemma-4B-Instruct-NPU2/mm.xclbin
  src/xclbins/Translategemma-4B-Instruct-NPU2/vision_attn.xclbin
  src/xclbins/Translategemma-4B-Instruct-NPU2/vision_mm.xclbin

Devkit-Swap-Run: 45301001729
Devkit-Swap-Tested: 4c6e240
@tawei-amd

Copy link
Copy Markdown
Collaborator

@michyu-amd all CI checks are green on 9a7e3ae (dev-kit swap from Build and Test run 45301001729 committed; Build and Test, CPU Tests and Security scan all pass). Ready for your review.

🤖 Generated with Claude Code

This branch has not been deployed

No deployments
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.

2 participants