nnterp · encyclopedia gemma · nnterp.families.gemma

family gemma

GemmaPaliGemma

Llama's pre-norm block with a GeGLU MLP: the embeddings are multiplied by √hidden_size before block 0, every RMSNorm multiplies by 1 + weight, and the head is the embedding matrix.

The block

01 · the residual stream

One block of the stack. Hover any part for its nnterp name; click to pin the card.

embed_tokenstoken_embeddings
→
layers× 18
→
normfinal_norm_output
→
lm_headlm_head_output
→
logitsthe output
i = 0

identity layers[i].input + self_attn.attention_output + mlp.mlp_output == layer_output

The API

02 · support()

Values, by host

⚠︎ marks a value this checkpoint has only under some load: hover it for the condition.

model GemmaForCausalLMlayoutwhat it isread at
logits Logits [batch seq vocab_size] The logits the model returns, after anything it does past lm_head (a softcap, a scale)

the module's own output

token_embeddings Residual [batch seq hidden_size] The embedding module's output; layers[0].input is what enters the first block

the child module embed_tokens's output

final_norm_output Residual [batch seq hidden_size] The residual stream after the final norm, what lm_head reads

the child module norm's output

lm_head_output Logits [batch seq vocab_size] The head's logits before anything the model does past lm_head (a softcap, a scale)

the child module lm_head's output

next_token_probs NextTokenProbs [batch vocab_size] The next-token distribution at the last position; derived, read-only

the module's own output

input_ids Tokens [batch seq] The token ids the model was called with

the module's own input

attention_mask Tokens [batch seq] The attention mask the model was called with; zeros are padding

the module's own input

input_size scalar [batch, seq] of the current call; read-only

the module's own input

model.layers[i] GemmaDecoderLayerlayoutwhat it isread at
layer_input Residual [batch seq hidden_size] The residual stream entering the block

the module's own input

attention_norm_output Residual [batch seq hidden_size] The normed stream entering the attention

the child module input_layernorm's output

layer_mid Residual [batch seq hidden_size] The residual stream after the attention add

the child module post_attention_layernorm's input

mlp_norm_output Residual [batch seq hidden_size] The normed stream entering the MLP

the child module post_attention_layernorm's output

mlp_input Residual [batch seq hidden_size] What the MLP is called with

the child module mlp's input

layer_output Residual [batch seq hidden_size] The residual stream leaving the block, a tensor even when the block returns a tuple

the module's own output

model.layers[i].self_attn GemmaAttentionlayoutwhat it isread at
⚠︎attention_queries Queries [batch num_heads seq qk_head_dim] The queries entering attention

inside the forward: the arguments of attention_interface_1, element 1

⚠︎attention_keys Keys [batch num_kv_heads seq qk_head_dim] The keys entering attention

inside the forward: the arguments of attention_interface_1, element 2

⚠︎attention_values Values [batch num_kv_heads seq head_dim] The values entering attention

inside the forward: the arguments of attention_interface_1, element 3

⚠︎attention_scores Pattern [batch num_heads query key] The attention scores entering the softmax, masked

inside the forward: the input of nn_functional_softmax_0 inside attention_interface_1

attention_premix HeadOutputs [batch seq num_heads head_dim] Every head's output side by side, as the output projection takes it

the child module o_proj's input

attention_output Residual [batch seq hidden_size] What the attention adds to the residual stream

the module's own output

⚠︎attention_probabilities Pattern [batch num_heads query key] The attention pattern the values are mixed with

inside the forward: the output of nn_functional_dropout_0 inside attention_interface_1

⚠︎attention_head_outputs HeadOutputs [batch seq num_heads head_dim] The per-head outputs before the output projection

inside the forward: the output of attention_interface_1, element 0

model.layers[i].mlp GemmaMLPlayoutwhat it isread at
mlp_activation Neurons [batch seq intermediate_size] The activation function's output

the child module act_fn's output

mlp_neurons Neurons [batch seq intermediate_size] What the down projection receives: act(gate)·up on a gated MLP, the activation itself otherwise

the child module down_proj's input

mlp_output Residual [batch seq hidden_size] What the MLP adds to the residual stream

the module's own output

Printout

What print(model) shows on google/gemma-2b: the native modules, standard names and every standard value with its layout.

GemmaForCausalLM(
  (lm_head): Linear(in_features=2048, out_features=256000, bias=False)
  (generator): Generator(
    (streamer): Streamer()
  )
  (embed_tokens): GemmaTextScaledWordEmbedding(256000, 2048, padding_idx=0)
  (layers): ModuleList(
    (0-17): 18 x GemmaDecoderLayer(
      (self_attn): GemmaAttention(
        (q_proj): Linear(in_features=2048, out_features=2048, bias=False)
        (k_proj): Linear(in_features=2048, out_features=256, bias=False)
        (v_proj): Linear(in_features=2048, out_features=256, bias=False)
        (o_proj): Linear(in_features=2048, out_features=2048, bias=False)
        (attention_queries) -> Queries [batch num_heads seq qk_head_dim]: The queries entering attention
        (attention_keys) -> Keys [batch num_kv_heads seq qk_head_dim]: The keys entering attention
        (attention_values) -> Values [batch num_kv_heads seq head_dim]: The values entering attention
        (attention_scores) -> Pattern [batch num_heads query key]: The attention scores entering the softmax, masked
        (attention_premix) -> HeadOutputs [batch seq num_heads head_dim]: Every head's output side by side, as the output projection takes it
        (attention_output) -> Residual [batch seq hidden_size]: What the attention adds to the residual stream
        (attention_probabilities) -> Pattern [batch num_heads query key]: The attention pattern the values are mixed with
        (attention_head_outputs) -> HeadOutputs [batch seq num_heads head_dim]: The per-head outputs before the output projection
      )
      (mlp): GemmaMLP(
        (gate_proj): Linear(in_features=2048, out_features=16384, bias=False)
        (up_proj): Linear(in_features=2048, out_features=16384, bias=False)
        (down_proj): Linear(in_features=16384, out_features=2048, bias=False)
        (act_fn): GELUTanh()
        (mlp_activation) -> Neurons [batch seq intermediate_size]: The activation function's output
        (mlp_neurons) -> Neurons [batch seq intermediate_size]: What the down projection receives: act(gate)·up on a gated MLP, the activation itself otherwise
        (mlp_output) -> Residual [batch seq hidden_size]: What the MLP adds to the residual stream
      )
      (input_layernorm): GemmaRMSNorm((2048,), eps=1e-06)
      (post_attention_layernorm): GemmaRMSNorm((2048,), eps=1e-06)
      (layer_input) -> Residual [batch seq hidden_size]: The residual stream entering the block
      (attention_norm_output) -> Residual [batch seq hidden_size]: The normed stream entering the attention
      (layer_mid) -> Residual [batch seq hidden_size]: The residual stream after the attention add
      (mlp_norm_output) -> Residual [batch seq hidden_size]: The normed stream entering the MLP
      (mlp_input) -> Residual [batch seq hidden_size]: What the MLP is called with
      (layer_output) -> Residual [batch seq hidden_size]: The residual stream leaving the block, a tensor even when the block returns a tuple
    )
  )
  (norm): GemmaRMSNorm((2048,), eps=1e-06)
  (logits) -> Logits [batch seq vocab_size]: The logits the model returns, after anything it does past lm_head (a softcap, a scale)
  (token_embeddings) -> Residual [batch seq hidden_size]: The embedding module's output; layers[0].input is what enters the first block
  (final_norm_output) -> Residual [batch seq hidden_size]: The residual stream after the final norm, what lm_head reads
  (lm_head_output) -> Logits [batch seq vocab_size]: The head's logits before anything the model does past lm_head (a softcap, a scale)
  (next_token_probs) -> NextTokenProbs [batch vocab_size]: The next-token distribution at the last position; derived, read-only
  (input_ids) -> Tokens [batch seq]: The token ids the model was called with
  (attention_mask) -> Tokens [batch seq]: The attention mask the model was called with; zeros are padding
  (input_size): [batch, seq] of the current call; read-only
)

Config

model.num_layers18
model.hidden_size2048
model.num_heads8
model.num_kv_heads1
model.head_dim256
model.qk_head_dim256
model.vocab_size256000
model.intermediate_size16384
architecturesGemmaForCausalLM
num_hidden_layers18
hidden_size2048
intermediate_size16384
num_attention_heads8
num_key_value_heads1
head_dim256
vocab_size256000
max_position_embeddings8192
hidden_actgelu_pytorch_tanh
rms_norm_eps1e-06
tie_word_embeddingsTrue
dtypebfloat16
attention_biasFalse

The Notes

03 · what to know before you run

The block, in order

h   = x + self_attn(input_layernorm(x))
out = h + mlp(post_attention_layernorm(h))

Two RMSNorms per block, each before its sublayer, none after: Llama's layout and Llama's names. post_attention_layernorm is the MLP's input norm. The Gemma 2, 3 and 4 blocks add a norm after each sublayer and give this name to the norm after the attention, so a hook ported by name from those families lands on a different tensor here.

The contributions are the modules' outputs

attention_output is self_attn.output[0] and mlp_output is mlp.output, added to the stream with nothing in between. On the pinned checkpoint, in float32:

with model.trace(prompt):
    x = model.layers[1].input.save()
    attn = model.layers[1].self_attn.attention_output.save()
    mlp = model.layers[1].mlp.mlp_output.save()
    out = model.layers[1].layer_output.save()

torch.testing.assert_close(x + attn + mlp, out)

Scaling a module's output scales its contribution: mlp.output[:] *= 0.5 and mlp.mlp_output[:] *= 0.5 are the same edit.

Embeddings are scaled before block 0

embed_tokens multiplies its lookup by √hidden_size, cast to the weight's dtype first: 45.25 on 2B and 55.5 on 7B in bfloat16, where the exact roots are 45.25 and 55.43. token_embeddings is the scaled tensor and equals layers[0].input on text. The stored embedding weight is also the unembedding (tie_word_embeddings), so a row of embed_tokens.weight is a token's unembedding direction unscaled, and an edit to it changes the readout too.

The norm gain is 1 + weight

GemmaRMSNorm normalizes in float32 and multiplies by 1 + weight, then casts back. Folding a norm into the next projection, or reading its gain, uses 1 + model.norm._module.weight; the stored weight is initialized at zero.

Attention: multi-query on 2B, 256-wide heads

2B has 8 query heads over a single key/value head; 7B has 16 of each. attention_keys and attention_values are read before repeat_kv, so on 2B they are [batch, 1, seq, 256] and an edit to them reaches every query head. head_dim is 256 on both sizes, so 7B's 16 heads are 4096 wide against a hidden_size of 3072, and the query scale is head_dim ** -0.5. There is no score softcap, window or sink: the default sdpa load and attn_implementation="eager" run the same attention, and eager serves the interior values.

Every checkpoint runs the tanh GELU

The MLP is down_proj(act(gate_proj(x)) * up_proj(x)) with the config's hidden_act. The gemma-2b and gemma-7b configs (with their -it versions and codegemma-2b) say gelu, a legacy value meant as the tanh approximation of GELU. GemmaConfig rewrites it to gelu_pytorch_tanh when it loads, with a warning, so model.config.hidden_act reads gelu_pytorch_tanh and the MLP runs the tanh approximation, not the exact erf GELU. The other configs set no hidden_act and take GemmaConfig's default, the same gelu_pytorch_tanh: Gemma 1.1 and codegemma-7b write it under hidden_activation, a key GemmaConfig does not read, and PaliGemma's text config names no activation.

The readout

model.logits is model.lm_head.output: no cap and no scale, so project_on_vocab is lm_head(norm(hidden)) with the 1 + weight gain inside norm, and a logit lens at the last block equals logits.

What this family module covers

Every checkpoint whose config says model_type gemma: Gemma 2B and 7B with their instruction-tuned -it and 1.1 releases, CodeGemma 2B and 7B, and the text model inside PaliGemma 1. PaliGemma 2 wraps a Gemma 2 text model (its text_config.model_type is gemma2), so it is not this family's.

From the family module

04 · nnterp/families/gemma.py

Gemma 1 (GemmaForCausalLM).

Llama's tree and Llama's block: model.{embed_tokens, layers[i].{input_layernorm, self_attn, post_attention_layernorm, mlp}, norm} and lm_head, the residual added in the block, attention through the shared eager forward.

PaliGemma puts a SigLIP tower at model.vision_tower, which is vision (its post_layernorm over the patches is vision.norm), and a linear projector model.multi_modal_projector, which is projector; vision.image_features is read at the scatter (ImageScatter). Its processor refuses a prompt without an image: a text-only trace takes the tokenizer's encoding.