Figure 1
The Forward Pass at a Glance
The language model consumes a sequence of token IDs with shape
[batch, time]. After lookup, every token is represented as a
5376-dimensional vector. The decoder preserves that width all the way
through the stack, then maps each final hidden vector back to 262,144
vocabulary logits.
[B, T] integers
sqrt(D) * E[x]
H * E^T
30 * tanh(L / 30)
Embeddings, residual stream, decoder outputs, and final norm all live at D = 5376.
Most layers do local work; every sixth layer reconnects the token to the full causal history.
The final vocabulary projection reuses the input embedding table, then softcaps logits at 30.
Model constants
The Numbers That Shape the Model
Most of the architecture can be understood by tracking a few dimensions:
the model width D = 5376, the feed-forward width
D_ff = 21504, 32 query heads, and two different attention
geometries.
| Item | Value | Why it matters |
|---|---|---|
| Hidden size | 5376 |
Every residual stream vector has this width. |
| Layers | 60 |
The same high-level block is repeated 60 times. |
| Vocabulary | 262144 |
The final output is one logit per token in this vocabulary. |
| Attention heads | 32 query heads |
Queries are many; keys and values are grouped and shared. |
| Sliding attention | head_dim = 256, 16 KV heads |
Most layers see a 1024-token causal window. |
| Full attention | global_head_dim = 512, 4 KV heads |
Every sixth layer can see all previous positions. |
| MLP width | 21504 |
The gated feed-forward block is the largest parameter consumer. |
| RMSNorm epsilon | 1e-6 |
Used throughout the residual stream and per-head attention paths. |
| Final logit softcap | 30 |
Raw logits are squashed to keep extreme scores bounded. |
What the checkpoint is
Scope: Dense Text Decoder Inside a Multimodal Model
The public model card describes Gemma 4 31B as the dense 31B member of the Gemma 4 family, with 60 layers, a 1024-token sliding window on local layers, 256K context length, a 262K vocabulary, and text+image input support. It also lists a roughly 550M-parameter vision encoder and no audio encoder for the 31B dense model.
This page focuses on
The language backbone: scaled token embeddings, decoder layers, attention, MLPs, final norm, tied LM head, logits, generation cache, and text-path memory/compute estimates.
Outside the layer math
Vision preprocessing, variable image resolution, chat templates, system-role formatting, function-calling protocols, and serving engines such as vLLM or SGLang wrap the decoder but are not decoder-layer equations.
Separate acceleration path
Gemma 4 also has Multi-Token Prediction assistant checkpoints for speculative decoding. They can share KV cache with the target model, but they are separate models, not extra layers inside this 31B decoder.
Why this distinction matters
Deployment docs may discuss reasoning mode, native system prompts, image input, tool use, and speculative decoding. Those are real Gemma 4 capabilities, but the tensor diagrams here describe the dense text decoder forward pass after any multimodal tokens have already been placed into the sequence.
Interactive tools
Memory and Compute Estimators
These calculators are architecture-level estimates for the Gemma 4 31B-it text path. They account for the tied text weights and the K/V cache implied by the layer pattern. They do not include framework overhead, allocator fragmentation, vision-model memory, temporary activations, or hardware throughput limits.
Memory by Quantization and Context
Estimate text weights plus generation KV cache. Sliding layers can be capped at the 1024-token window; full layers keep the whole causal history.
Google's public memory table gives approximate load-memory planning numbers for Gemma 4 31B at BF16, 8-bit, and Q4_0. This calculator uses the released text dimensions, reports binary GiB, and adds KV cache separately, so treat it as a transparent planning estimate rather than an exact allocator measurement.
Forward-Pass Compute
Estimate multiply-accumulate operations for either a prompt prefill
or one decode step at a chosen context length. FLOPs are shown as
approximately 2 * MACs.
Figure 2
The 5-Sliding / 1-Full Layer Rhythm
Gemma 4 31B-it uses 50 sliding-window attention layers and 10 full-attention layers. If layers are counted from 1, the full layers are 6, 12, 18, 24, 30, 36, 42, 48, 54, and 60. This creates a practical long-context pattern: most computation is local, but information periodically passes through a global layer.
layer_types list.
Interactive figure
Layer Explorer
Move through the 60 layers to see how the attention geometry changes. The repeated pattern is easy to miss in code because the same module class covers both layer types; this explorer makes the active dimensions visible.
Full Attention Layer
Every sixth layer uses full causal attention and can read the entire previous context.
Projection Shapes
Full layers use proportional RoPE: 128 of 512 head dimensions are rotated.
More diagrams
How the Pieces Work Together
The architecture is easiest to understand as a set of conserved shapes and repeated transformations. These diagrams emphasize the flow of one token, how grouped-query attention shares KV heads, how the residual stream is updated, and why long-context cache memory is uneven across layer types.
One Token's Journey
x_t5376local
local
global
global
262KGrouped-Query Attention
Residual Stream Update
KV Cache Shape at Long Context
Decoder layer
One Layer: Norm, Attention, Norm, Residual, MLP
A Gemma 4 text decoder layer has two residual sublayers. The attention output is normalized before it is added back to the residual stream; the MLP output is also normalized before its residual add. That gives four residual-stream RMSNorms per layer.
layer_scalar is initialized to 1, so it does
not change the active equations for this checkpoint.
Layer equations
U = RMSNorm_in(H_l)A = Attention_l(U, mask_l, positions)Y = H_l + RMSNorm_post_attn(A)Z = RMSNorm_pre_ffn(Y)F = MLP_l(Z)H_(l+1) = Y + RMSNorm_post_ffn(F)Attention anatomy
Two Attention Geometries, One Grouped-Query Idea
Every layer has 32 query heads. The key/value head count is smaller, so several query heads share each key/value head. This is grouped-query attention: it keeps the query side expressive while reducing the cache and projection cost for keys and values.
Sliding layers
50 layers, local causal mask, 1024-token window.
32 Q heads x 256 dims. 16 KV heads, so each KV head serves 2 query heads.
Full layers
10 layers, full causal mask, wider heads.
32 Q heads x 512 dims. 4 KV heads, so each KV head serves 8 query heads.
Raw projections
Sliding layers use separate Q, K, and V projections. Full layers use
attention_k_eq_v = true, so the raw V tensor is the raw K
projection output before K and V are normalized differently.
Per-head norms
Q and K receive scaled RMSNorm over the head dimension. V receives an unscaled RMSNorm. RoPE is applied to Q and K only, not to V.
Attention score detail
In the Hugging Face Gemma 4 text attention module, the score scaling
passed to the attention function is 1.0. So the reference
path is scores = QK^T + mask, not an explicit
QK^T / sqrt(head_dim) expression.
Grouped-query mapping
kv_head = floor(query_head / group_size)
Sliding layers use group size 2; full layers use group
size 8.
Cache consequence
Fewer KV heads means fewer cached key/value vectors per token. The full layers widen each head to 512 dimensions but reduce KV heads to 4.
Full causal mask
Position t can attend to every key position s <= t.
Sliding causal mask
Same causal triangle, intersected with a local window. The real window is 1024 tokens.
Position information
RoPE: Local Heads Rotate Fully, Global Heads Rotate Partly
Rotary position embeddings are applied to Q and K after their per-head
RMSNorms. Sliding layers use the ordinary RoPE setup with
rope_theta = 10000 over 256-dimensional heads. Full layers use
proportional RoPE with rope_theta = 1000000 and
partial_rotary_factor = 0.25.
Sliding attention RoPE
head_dim = 256. The full head is position-rotated.
Full attention RoPE
head_dim = 512. Only 128 dimensions are rotated; the rest pass through unchanged.
RoPE(z, p) = z * cos(p) + rotate_half(z) * sin(p)
The full-layer proportional design gives the global layers larger head
vectors while limiting how much of each vector is explicitly position
rotated. In implementation terms, the non-rotated dimensions receive zero
inverse frequency, so cos(0) = 1 and sin(0) = 0.
Feed-forward network
The Gated MLP Carries Most of the Parameters
Each layer has a bias-free gated MLP with three matrices: gate, up, and down. The gate and up streams both expand from 5376 to 21504, then the down projection returns to the residual width. The activation is PyTorch's tanh-approximate GELU.
D -> D_ff twice
GELU(gate) * up
D_ff -> D
gelu_pytorch_tanh as the gate activation.
MLP formula
gate = Z * W_gateup = Z * W_upF = (GELU_tanh(gate) * up) * W_downOne layer's MLP linears contain about 347M weights. Across 60 layers, that is about 20.8B weights before attention and embeddings.
Parameter budget
Where the Text-Path Weights Live
The checkpoint is called 31B because the large dense matrices in the text path add up to roughly that scale. This figure is approximate and ignores small norm vectors, but it gives the right intuition: the dense gated MLPs dominate.
60 * 3 * 5376 * 21504
for MLP matrices, sliding/full attention projection shapes from the
layer pattern, and 262144 * 5376 for the tied embedding table.
Normalization
RMSNorm Is the Stabilizer Everywhere
RMSNorm divides a vector by its root mean square and, when enabled, applies
a learned scale. Gemma 4 uses the scale directly. It is not the older
Gemma-style 1 + weight parameterization.
rms(x) = sqrt(mean(x^2) + 1e-6)RMSNorm(x) = weight * x / rms(x)Residual stream
Input, post-attention, pre-FFN, post-FFN, and final model norm use learned scales.
Q and K
Scaled per-head RMSNorm is applied before RoPE.
V
Value vectors use unscaled RMSNorm and do not receive RoPE.
Output head
Final RMSNorm, Tied Embeddings, and Softcapped Logits
After layer 60, Gemma 4 applies a final RMSNorm. The LM head projects each hidden vector to the vocabulary. Because word embeddings are tied, the LM head uses the same weight table as the input token embedding matrix.
H_final = RMSNorm_final(H_60)L = H_final * E^TL_soft = 30 * tanh(L / 30)The softcap is not attention-logit softcapping. It is applied at the very end, after the vocabulary projection. It preserves sign and order for moderate logits but smoothly limits extreme values.
Inference behavior
Prefill, Cache, and Long Context
During prefill, the model computes Q, K, and V for all prompt positions. During generation, the new query positions attend to cached K/V tensors from previous tokens. The same masks still apply: sliding layers are limited to the latest 1024 causal positions, while full layers can see all previous positions.
Sliding cache effect
Even if more tokens exist in the cache, the attention mask limits a sliding layer to recent keys. This keeps most layers cheaper for long sequences.
Full layer effect
Every sixth layer reconnects the current token to the whole causal history, which lets information travel farther than one local window.
What is not active here
Useful Non-Features in This Checkpoint
The implementation supports optional components that are not active in the 31B-it text configuration. Calling these out matters because otherwise the code can look more complicated than the checkpoint's actual forward pass.
No MoE block
enable_moe_block = false, so the dense MLP path is the active path.
No per-layer embeddings
hidden_size_per_layer_input = 0, so auxiliary per-layer embedding injection is disabled.
No separate full V projection
Full layers use K as raw V, then apply separate K and V processing.
Compact form
The Whole Text Forward Pass
# Text-only input IDs path. If inputs_embeds are supplied, start with those instead.
H = embedding_table[input_ids] * sqrt(5376)
positions = past_seen_tokens + arange(T_current)
full_mask = causal_mask # keys s <= query t
sliding_mask = causal_mask & last_1024 # keys t - 1024 < s <= t
# Supplied padding or packed-sequence masks further restrict these masks.
for layer_index in 0..59:
kind = "full" if (layer_index + 1) % 6 == 0 else "sliding"
head_dim = 512 if kind == "full" else 256
kv_heads = 4 if kind == "full" else 16
group_size = 32 // kv_heads
mask = full_mask if kind == "full" else sliding_mask
U = input_rmsnorm[layer_index](H)
Q = reshape_heads(q_proj(U), heads=32, dim=head_dim)
K_raw = reshape_heads(k_proj(U), heads=kv_heads, dim=head_dim)
V_raw = reshape_heads(v_proj(U), heads=kv_heads, dim=head_dim) if kind == "sliding" else K_raw
Q = to_attention_layout(rope_kind(q_norm(Q), positions))
K = k_norm(K_raw)
K = to_attention_layout(rope_kind(K, positions))
V = to_attention_layout(v_norm_without_scale(V_raw))
# In cached generation, append the new layer K/V before attention.
if use_cache:
K, V = cache[layer_index].append_and_return(K, V)
# Shown explicitly; the eager backend performs this repeat internally.
K = repeat_kv_to_32_query_heads(K, repeats=group_size)
V = repeat_kv_to_32_query_heads(V, repeats=group_size)
scores = (Q @ K.transpose(-1, -2)) * 1.0 + mask
P = softmax(scores, dtype=float32)
A = o_proj(concat_heads(P @ V))
Y = H + post_attention_rmsnorm[layer_index](A)
Z = pre_ffn_rmsnorm[layer_index](Y)
F = down_proj(gelu_tanh(gate_proj(Z)) * up_proj(Z))
H = Y + post_ffn_rmsnorm[layer_index](F)
H = final_rmsnorm(H)
logits = H @ embedding_table.T # tied LM head
logits = 30 * tanh(logits / 30)
next_token_probs = softmax(logits[:, -1, :])
if labels are supplied:
loss = cross_entropy(logits[:, :-1, :], labels[:, 1:], ignore_masked_labels=True)
Primary references
Sources Used
The page is based on public model metadata and the Hugging Face reference implementation. Links are intentionally direct so the exact config and code paths can be inspected.
gelu_pytorch_tanh activation mapping.
Hugging Face Gemma 4 launch guide
Multi-Token Prediction drafter explanation and deployment ecosystem notes.