Gemma 4 31B-it Architecture

A source-grounded visual guide to the Gemma 4 31B-it text path.

From token to logit

Gemma 4 31B-it Text Architecture

Gemma 4 31B-it is packaged as a multimodal conditional-generation checkpoint, but the text backbone is a decoder-only transformer. This page follows the language path only: token embeddings, 60 decoder layers, local and global attention, gated MLPs, final normalization, a tied language-model head, and the final logit softcap.

60 Decoder layers
5376 Hidden width
262144 Vocabulary size
5 + 1 Local then full attention

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.

Token IDs [B, T] integers
Scaled embedding sqrt(D) * E[x]
60 decoder layers 5 sliding, 1 full, repeated
Final RMSNorm normalize each token vector
Tied LM head H * E^T
Softcapped logits 30 * tanh(L / 30)
The text path is a decoder-only causal LM. The top-level checkpoint can include vision tokens before the text model sees the sequence, but this diagram starts at the text decoder input.
Width stays fixed.

Embeddings, residual stream, decoder outputs, and final norm all live at D = 5376.

Context alternates by layer.

Most layers do local work; every sixth layer reconnects the token to the full causal history.

The head is tied.

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.

Weights 0 GiB
KV cache 0 GiB
Total estimate 0 GiB
KV elements 0B
Weights
0%
Sliding KV
0%
Full KV
0%

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.

Linear MACs 0
Attention MACs 0
Total MACs 0
Approx FLOPs 0
Linear
0%
Attention
0%

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.

123456 789101112 131415161718 192021222324 252627282930 313233343536 373839404142 434445464748 495051525354 555657585960
Sliding window attention Full causal attention
The pattern is not a training trick outside the model; it is encoded in the checkpoint configuration's 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.

Sliding Full Selected
6

Full Attention Layer

Full

Every sixth layer uses full causal attention and can read the entire previous context.

Mask Full causal
Head dim 512
KV heads 4
GQA group 8 query heads per KV head

Projection Shapes

Q projection 5376 -> 16384
K projection 5376 -> 2048
V projection Raw K tensor, then V norm
Output projection 16384 -> 5376

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

Token
x_t
Embed
5376
L1
local
L2-5
local
L6
global
L60
global
Logits
262K
The residual width stays 5376 throughout. Only the internal attention head geometry changes between sliding and full layers.

Grouped-Query Attention

Queries Q0Q1Q2Q3 Q4Q5Q6Q7
Sliding KV KV0KV0KV1KV1 KV2KV2KV3KV3
Full KV KV0KV0KV0KV0 KV0KV0KV0KV0
This shows the first 8 query heads. Sliding layers share one KV head across 2 query heads; full layers share one KV head across 8 query heads.

Residual Stream Update

H_l Norm Attention Post-norm Add
Y Norm Gated MLP Post-norm H_(l+1)
The architecture is not just pre-norm. It also normalizes each sublayer output before adding it back to the residual stream.

KV Cache Shape at Long Context

S
S
S
S
S
F
S
S
S
S
S
F
For generation, sliding layers need only the latest window. Full layers keep growing with context length, so they dominate KV cache at long contexts.

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.

H_l residual stream
RMSNorm input norm
Self Attention sliding or full
RMSNorm post-attn norm
Residual Add Y = H_l + attn
RMSNorm pre-FFN norm
Gated MLP GELU(gate) * up, then down
RMSNorm post-FFN norm
Residual Add H_(l+1) = Y + ffn
The registered 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.

Q
8192
K
4096
V
4096
O
8192 -> D

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.

Q
16384
K
2048
V
K raw
O
16384 -> D

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.

The grids show a toy 12-position sequence. Full attention keeps the entire causal lower triangle; sliding attention keeps only a diagonal band of recent keys.

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.

Z RMSNormed residual
Gate and Up D -> D_ff twice
Multiply GELU(gate) * up
Down D_ff -> D
The MLP is a SwiGLU-like gated structure, but with gelu_pytorch_tanh as the gate activation.

MLP formula

gate = Z * W_gate
up = Z * W_up
F = (GELU_tanh(gate) * up) * W_down

One 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.

MLP linears
20.81B
Attention linears
8.48B
Tied embedding
1.41B
Computed from the public dimensions: 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^T
L_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.

+30 -30 30 * tanh(L / 30)
The output is bounded near -30 and +30 while the center remains almost linear.
Softcapped 27.15

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.