Last updated: 2026-11-17

Inference Runtime

Forward Cuda Gemma

All API Sections

Shared ROCm/CUDA forward pass for Gemma and Muse Glimmer transformers.

Separate from forward_cuda.zig's Qwen execution path. The selected native C shim supplies AMD HIP or NVIDIA CUDA kernels; dense and MoE Gemma use this module. Gemma 4 31B has the following per-layer geometry: sliding attention on a period-6 pattern (5 SWA + 1 full), per-layer head dims (256 SWA / 512 full) and KV-head counts (16 SWA / 4 full), per-head Q/K RMS norm + per-head V RMS normalize, four norms per layer (pre/post attn + pre/post ffn), GeGLU FFN, a learned per-layer output scale, scaled token embeddings, and a tied LM head.

Norm convention: the gemma RMSNorm `(1 + weight)` offset is baked into the GGUF weights at conversion (confirmed: attn_q_norm ≈ 1.0234), so every gemma norm reuses the standard `rms_norm` kernel; V uses `rms_norm_noweight`.

Attention scale: gemma4 sets f_attention_scale = 1.0 (no 1/sqrt(d) scaling). Final-logit soft-cap is monotonic, so it does not change the greedy argmax and is intentionally skipped here (correctness-first bring-up).

2 exports shown

struct

ForwardGemma

#
pub const ForwardGemma = struct

No public doc comment yet.

src/compute/forward_cuda_gemma.zig:458

Methods

16

method

ForwardGemma.decodeStep

#
pub fn decodeStep(self: *ForwardGemma, token: u32, pos: u32, run_layers: bool) !u32

One greedy decode step for `token` at sequence position `pos`.

src/compute/forward_cuda_gemma.zig:1081

method

ForwardGemma.prefillStep

#
pub fn prefillStep(self: *ForwardGemma, token: u32, pos: u32) !void

Prefill helper (mirrors ForwardCuda.prefillStep): run every layer to build the KV cache, but SKIP the tail rms_norm + LM head + argmax — a prompt-internal token's logits are never read.

Saves the vocab-sized head matvec on T-1 of the T prompt tokens; the MoE gemma model (small active forward, full head) benefits most. Async layer ops drained here; bit-identical generation.

src/compute/forward_cuda_gemma.zig:1146

method

ForwardGemma.prefillBatched

#
pub fn prefillBatched(self: *ForwardGemma, tokens: []const u32) !u32

Batched dense-gemma prefill: process ALL T prompt tokens at once, reading each weight ONCE for all tokens via the gemm_*_tiled_v2 register-blocked GEMMs (5.9× over the per-token matvec). Returns the last token's argmax (= the first generated token), exactly like running prefillStep on tokens [0..T-1] then decodeStep on the last. ADDITIVE: builds its own token-major scratch and never touches the single-token decode path.

Dense and MoE Gemma share batched attention. MoE then runs its shared expert, F32 router, grouped routed experts and residual combination over the prompt rows. The serial-expert override isolates that FFN while retaining batched attention; the ROCm serial-prefill override replaces the whole path. Neither diagnostic reuses the other's norm scratch.

src/compute/forward_cuda_gemma.zig:1178

method

ForwardGemma.prefillBatchedSlot

#
pub fn prefillBatchedSlot(self: *ForwardGemma, tokens: []const u32, slot: u32) !u32

Server-mode batched prefill.

Run the normal token-major prefill directly against one sequence's region of the slot KV cache, so the first decode step can continue at `tokens.len` without copying or replaying the prompt.

src/compute/forward_cuda_gemma.zig:1526

method

ForwardGemma.decodeBatch

#
pub fn decodeBatch(self: *ForwardGemma, tokens: []const u32, positions: []const u32, slots: []const u32, out_tokens: []u32) !void

Batched DECODE step: advance B independent sequences by ONE token each in a SINGLE B-row forward. The projections + FFN reuse the batched-prefill GEMM path — `gemmDispatch`/`ffnBlockBatched` read each weight ONCE for all B rows (the launch / weight-bandwidth amortization that makes batching a throughput win). The attention inner (per-head V/Q/K norm + RoPE + KV-write + causal softmax) LOOPS per row through the proven single-token kernels (`rms_norm_rope_qkv` / `gemma_attention`) against each sequence's OWN KV slot at its OWN position — so row b attends over slot `slots[b]`'s history [0..positions[b]] only. Fusing that per-row loop into one batched-seq attention kernel is sub-step 1c (a perf step; the looped form here is already correct for mixed positions). ADDITIVE — the production `decodeStep` / `prefillBatched` paths are untouched.

Requires `allocSlotKv(n_slots, slot_ctx)` first, with n_slots > max(slots) and slot_ctx > max(positions). Each sequence b's slot must already hold its KV history for [0..positions[b]-1] (written by prior `decodeBatch` calls — e.g. a per-token B=1 prefill into the slot). Writes b's new K/V at its slot.

tokens[b] input token for sequence b this step positions[b] sequence b's current position (slot holds [0..pos-1]) slots[b] sequence b's KV slot index out_tokens[b] greedy argmax for sequence b (caller advances pos + feeds back)

src/compute/forward_cuda_gemma.zig:2078

method

ForwardGemma.allocSlotKv

#
pub fn allocSlotKv(self: *ForwardGemma, n_slots: u32, slot_ctx: u32) !void

Allocate slot-based KV for `n_slots` concurrent sequences of up to `slot_ctx` positions each.

A single slot reuses the existing cache through lightweight views; multiple slots retain independent allocations. Idempotent, including cleanup after a partial allocation failure.

src/compute/forward_cuda_gemma.zig:2936

method

ForwardGemma.slotKvOffsetBytes

#
pub fn slotKvOffsetBytes(self: *const ForwardGemma, L: u32, slot: u32, pos: u32) usize

Byte offset of sequence-slot `slot`'s K/V for position `pos` in layer `L`'s slot KV buffer: (slot*slot_ctx + pos)*kv_dim(L)*sizeof(f32).

This is the exact indexing the 1c per-sequence kv-write + slot attention kernels use.

src/compute/forward_cuda_gemma.zig:3045

method

ForwardGemma.slotKvSmoke

#
pub fn slotKvSmoke(self: *ForwardGemma) !bool

Sub-step 1a plumbing smoke: prove the slot-KV offset arithmetic round-trips and that distinct (slot,pos) pairs map to NON-overlapping device regions.

Writes a sentinel into (slot 0, pos 0) and a distinct pattern into the LAST (slot, pos) of layer 0's K cache, reads both back, and checks neither write clobbered the other. Returns true on success. Requires allocSlotKv first.

src/compute/forward_cuda_gemma.zig:3054

method

ForwardGemma.ffnLayerPub

#
pub fn ffnLayerPub(self: *ForwardGemma, L: u32) !void

FFN block dispatched exactly as decodeStep: routed MoE when this layer carries a router, dense GeGLU otherwise.

src/compute/forward_cuda_gemma.zig:4222

function

quantizeActivationGrid

#
pub fn quantizeActivationGrid(K: u32, rows: u32) [3]u32

Shared with the dedicated GPU packing regression.

Keep the full row stride in QuantActPush; the kernel folds only its launch coordinates, not its data.

src/compute/forward_cuda_gemma.zig:4357