Gemma is a family of open language models with 2 billion (2B) and 7 billion (7B) parameters, built from Google's Gemini research and technology. Google DeepMind's Gemma Team introduced it in 2024 in the technical report "Gemma: Open Models Based on Gemini Research and Technology," releasing weights for both the pretrained models and models fine-tuned for dialogue and instruction following.
In 2023, open-weight language models such as LLaMA, Llama 2, and Mistral 7B appeared one after another. Gemma brings the architecture, data, and training methods that Google developed for its large Gemini models down to a size that runs on local hardware. Each of the two sizes targets a different use.
7B: Runs efficiently on GPUs and TPUs, for development.
2B: Runs on devices such as CPUs and smartphones.
Gemma 7B was trained on 6 trillion tokens, mainly of English web text, mathematics, and code. According to the technical report, Gemma outperformed open models of similar size on 11 of 18 text tasks. Its MMLU score is 64.3%, higher than Llama 2 13B (54.8%). It is especially strong at math and code, beating other models by more than 10 points on GSM8K and MATH.
Architecture: Changes from LLaMA
Gemma is a language model that stacks only Transformer decoders. Its basic form matches the LLaMA family: the input of each sublayer is normalized with RMSNorm, and position information is injected in every layer with RoPE. In the figure at the top of the article, the left side shows the overall flow and the right side shows the inside of one decoder layer.
It differs from the LLaMA family in four ways (Model Architecture section of the technical report).
GeGLU activation: The feed-forward gate uses an approximate GELU instead of SiLU.
Shared input and output embeddings: The matrix used to embed tokens is also used as the weight of the final linear layer that predicts the next token, to keep the model small.
A vocabulary as large as Gemini's: It uses a subset of Gemini's SentencePiece tokenizer, with a vocabulary of about 256k (256,128) tokens, 8 times LLaMA's 32k.
The GeGLU feed-forward in point 1 follows Shazeer (2020) (without biases):
FFNGEGLU(x)=(GELU(xW)⊗xV)W2
⊗ denotes the element-wise product. This is LLaMA's SwiGLU with SiLU replaced by GELU: the GELU-activated xW acts as a gate that decides how much of each component of xV passes through. The official implementation uses the tanh approximation of GELU.
The sizes of the two models are as follows (Tables 1 and 2 of the technical report).
Item
Gemma 2B
Gemma 7B
Model dimension d
2048
3072
Layers
18
28
Query heads
8
16
Key/value heads
1 (multi-query)
16 (multi-head)
Head dimension
256
256
Feed-forward hidden size
16,384
24,576
Embedding parameters
524M
786M
Non-embedding parameters
1.98B
7.75B
Training tokens
3T
6T
Both models have a context length of 8192 tokens. Table 1 of the technical report lists feed-forward widths of 32,768 and 49,152, but these are the combined widths of GeGLU's two linear layers W and V; each hidden size is the value in the table above (confirmed against the official implementation's configuration).
The 7B model has 16 heads × 256 dimensions, which multiplies to 4096, larger than the model dimension d=3072. In the LLaMA family, "number of heads × head dimension = d" is the norm, but Gemma does not keep them equal. The attention output is projected back to d by the final linear layer.
The official implementation also has a few smaller differences.
The embedding vectors are multiplied by d before entering the first layer.
The RMSNorm gain is applied as (1+w) rather than w (w is learned starting from 0).
Training: Data and Instruction Tuning
The pretraining data consists mainly of English web documents, mathematics, and code (3 trillion tokens for 2B, 6 trillion for 7B). Unlike Gemini, Gemma is not a multimodal model that handles images, and it is not trained for state-of-the-art performance on multilingual tasks.
The data goes through the following processing (Pretraining section of the technical report).
Filtering: Rules and classifiers remove harmful content, low-quality content, personal information, and so on.
Removing evaluation data: Data used for evaluation is removed from the training data, and the data is checked for contamination.
Staged mixing: The data mixture changes during training, increasing the share of relevant, high-quality data toward the end.
Tokenization uses a subset of Gemini's SentencePiece tokenizer. It splits digits individually, preserves extra whitespace, and falls back to bytes for characters outside the vocabulary.
The training infrastructure is TPUv5e. The 7B model was trained on 16 pods (4,096 chips) and the 2B model on 2 pods (512 chips), with optimizer state sharded using a technique similar to ZeRO-3.
Instruction tuning has two stages.
SFT (supervised fine-tuning): Fine-tuning on English-only text pairs of synthetic and human-written prompts and responses. The data mixture is chosen with evaluations in which a separate, larger model compares the responses of two models.
RLHF (reinforcement learning from human feedback): A reward model based on the Bradley-Terry model is trained on data where humans indicate which of two responses they prefer, and the policy is then tuned with reinforcement learning to increase that reward.
The tuned models are trained on a format with dedicated markers for conversation roles and turn boundaries (<start_of_turn>, <end_of_turn>, and user, model).
Design Rationale: Allocating Capacity in Small Models
Gemma's architectural choices share a common idea: where to spend limited parameters and memory in a small model.
The large vocabulary is inherited from Gemini and is designed to handle many languages. The trade-off is a large embedding matrix, which accounts for about 20% of all parameters (524M) in the 2B model. Table 2 of the technical report explains that this is why the embedding parameter count is higher than in models that handle only one or a few languages.
Sharing the input and output embeddings avoids keeping two copies of this large matrix. With separate input and output matrices as in LLaMA, the embeddings alone in Gemma 2B would exceed 1 billion parameters. Sharing cuts that in half.
According to the technical report, only the 2B model uses multi-query attention because ablation experiments showed that multi-query attention works well at small scales. Inference requires storing the keys and values of past tokens (the KV cache), and multi-query attention reduces that storage by a factor equal to the number of heads. For the 2B model, which runs on CPUs and devices, this memory saving matters a lot.
To use a packing analogy: the smaller the suitcase (2B), the more it pays to wear the same clothes in several outfits (shared embeddings) and to bundle bulky items together (shared keys and values).
Multi-query attention reduces expressiveness because it uses only one set of keys and values. Gemma itself goes back to multi-head attention for the larger 7B model. When scaling a model up, an intermediate degree of sharing such as grouped-query attention (GQA) is also an option.
Experimental Results
Academic benchmarks (excerpt from Table 6 of the technical report; Llama 2 values come from the Llama 2 paper, and the others include values measured by the Gemma team)
On MMLU, Gemma 7B outperformed every open model of the same size or smaller, as well as the larger Llama 2 13B. It beat other open models by more than 10 points on math (GSM8K, MATH) and by more than 6 points on code (HumanEval), and on MBPP it scored higher (44.4%) than even the code-specialized CodeLLaMA-7B (41.4%).
On knowledge-heavy tasks such as TriviaQA, however, it falls short of Llama 2 13B.
Independent evaluation by Hugging Face (Table 7 of the technical report; a check with a separate implementation, since small models are sensitive to minor prompt differences)
Benchmark
ARC-c
HellaSwag
MMLU
TruthfulQA
Winogrande
GSM8K
Average
Mistral 7B
60.0
83.3
64.2
42.2
78.4
37.8
61.0
Gemma 7B
61.9
82.2
64.6
44.8
79.0
50.9
63.8
In human evaluation (Table 5 of the technical report), on about 1,000 instruction-following prompts (creative writing, code, and more), the Gemma 1.1 instruction-tuned 7B model had a 61.2% win rate against Mistral v0.2 7B Instruct (ties counted as half), and the 2B model had 45%. On about 400 prompts testing basic safety, the 7B model scored 63.5% and the 2B model 60.1%.
Practical Considerations
Keep the following points in mind when using Gemma.
Use the dedicated format for dialogue: The instruction-tuned models were trained with markers such as <start_of_turn>user. They can generate text without the format, but the technical report notes that output tends to degrade because the input falls outside the training distribution.
Mainly English: The training data is mainly English, and multilingual performance was not a goal. Despite the large vocabulary, verify performance before using it in other languages.
Weaker than larger models on knowledge tasks: On TriviaQA and NaturalQuestions, it scores lower than Llama 2 13B.
Users also need to check safety: The technical report states that not every use case can be tested in advance and asks users to run safety tests suited to their application before deployment.
Open-weight models cannot prevent malicious actors from removing safety tuning through fine-tuning. Gemma is released under terms of use and a prohibited use policy. Check the distributor's terms before using it.
Comparison with Other Models
Comparing Gemma with open models of around 7B from the same period on the same criteria gives the following (MMLU and GSM8K values are from Table 6 of the Gemma technical report).
Note: The architectures and training token counts of Llama 2 and Mistral 7B are from their respective papers. Gemma's parameter counts are the sums of embedding and non-embedding parameters in Table 2 of the technical report.
Note that although Gemma 7B is named "7B," it has 8.5 billion parameters once the large-vocabulary embeddings are included, making it somewhat larger than other 7B models. Even so, its non-embedding parameters total 7.75 billion, and its lead in math and code is too wide to explain by size alone.
Rough guidelines for choosing:
Running on a CPU or smartphone: Gemma 2B has a small KV cache thanks to multi-query attention and is designed to run on devices.
Solving tasks involving math or code at the 7B scale: Gemma 7B is particularly strong at math and code among open models of this size.
Handling long contexts cheaply: Mistral 7B, which lightens inference with sliding-window attention, is a candidate.
Getting reasoning ability from an even smaller model: Phi-3, which concentrates reasoning ability into 3.8 billion parameters with high-quality data, and the 1.1B TinyLlama are also worth comparing.
PyTorch example
▶Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F
"""
A small version of Gemma's decoder layer, following the Model Architecture section of the technical report and the official implementation (google/gemma_pytorch)
- RMSNorm on the input side (gain is 1 + w), RoPE on Q and K, GeGLU feed-forward (GELU uses the tanh approximation), no biases
- n_kv_heads = 1 gives multi-query (2B); n_kv_heads equal to n_heads gives multi-head (7B)
- Embeddings are multiplied by √d, and the output linear layer shares weights with the embedding
No dropout is used, so model.train() and model.eval() compute the same thing
"""
class GemmaRMSNorm(nn.Module):
def __init__(self, dim, eps=1e-6):
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.zeros(dim)) # learned from 0; multiply by (1 + w)
def forward(self, x):
x = x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
return x * (1 + self.weight)
def rope_angles(head_dim, max_len, theta=10000.0):
freqs = 1.0 / (theta ** (torch.arange(0, head_dim, 2).float() / head_dim))
angles = torch.outer(torch.arange(max_len).float(), freqs)
angles = torch.cat((angles, angles), dim=-1)
return torch.cos(angles), torch.sin(angles)
def apply_rope(x, cos, sin):
x1, x2 = x.chunk(2, dim=-1)
return x * cos + torch.cat((-x2, x1), dim=-1) * sin
class GemmaDecoderLayer(nn.Module):
def __init__(self, dim, n_heads, n_kv_heads, head_dim, hidden):
super().__init__()
self.n_heads, self.n_kv_heads, self.head_dim = n_heads, n_kv_heads, head_dim
self.attn_norm = GemmaRMSNorm(dim)
self.q_proj = nn.Linear(dim, n_heads * head_dim, bias=False) # 7B: 16 × 256 = 4096 (differs from d = 3072)
self.k_proj = nn.Linear(dim, n_kv_heads * head_dim, bias=False)
self.v_proj = nn.Linear(dim, n_kv_heads * head_dim, bias=False)
self.o_proj = nn.Linear(n_heads * head_dim, dim, bias=False)
self.ffn_norm = GemmaRMSNorm(dim)
self.gate_proj = nn.Linear(dim, hidden, bias=False) # W (the side passed through GELU)
self.up_proj = nn.Linear(dim, hidden, bias=False) # V
self.down_proj = nn.Linear(hidden, dim, bias=False) # W2
def attention(self, h, cos, sin):
b, n, _ = h.shape
q = self.q_proj(h).view(b, n, self.n_heads, self.head_dim).transpose(1, 2)
k = self.k_proj(h).view(b, n, self.n_kv_heads, self.head_dim).transpose(1, 2)
v = self.v_proj(h).view(b, n, self.n_kv_heads, self.head_dim).transpose(1, 2)
q, k = apply_rope(q, cos[:n], sin[:n]), apply_rope(k, cos[:n], sin[:n])
rep = self.n_heads // self.n_kv_heads # with multi-query, all heads use the same K and V
k, v = k.repeat_interleave(rep, dim=1), v.repeat_interleave(rep, dim=1)
out = F.scaled_dot_product_attention(q, k, v, is_causal=True)
return self.o_proj(out.transpose(1, 2).reshape(b, n, -1))
def ffn(self, h):
return self.down_proj(F.gelu(self.gate_proj(h), approximate="tanh") * self.up_proj(h)) # GeGLU
def forward(self, x, cos, sin):
x = x + self.attention(self.attn_norm(x), cos, sin)
return x + self.ffn(self.ffn_norm(x))
class TinyGemma(nn.Module):
# 2B: dim=2048, n_layers=18, n_heads=8, n_kv_heads=1, head_dim=256, hidden=16384
# 7B: dim=3072, n_layers=28, n_heads=16, n_kv_heads=16, head_dim=256, hidden=24576
def __init__(self, vocab=256128, dim=2048, n_layers=18, n_heads=8, n_kv_heads=1, head_dim=256, hidden=16384, max_len=8192):
super().__init__()
self.dim = dim
self.embed = nn.Embedding(vocab, dim)
self.layers = nn.ModuleList(GemmaDecoderLayer(dim, n_heads, n_kv_heads, head_dim, hidden) for _ in range(n_layers))
self.norm = GemmaRMSNorm(dim)
cos, sin = rope_angles(head_dim, max_len)
self.register_buffer("cos", cos, persistent=False)
self.register_buffer("sin", sin, persistent=False)
def forward(self, tokens):
x = self.embed(tokens) * self.dim ** 0.5 # scale by √d before the first layer
for layer in self.layers:
x = layer(x, self.cos, self.sin)
return self.norm(x) @ self.embed.weight.T # output reuses the embedding weights
# Sanity check (small configuration, multi-query)
model = TinyGemma(vocab=1000, dim=128, n_layers=2, n_heads=4, n_kv_heads=1, head_dim=32, hidden=256, max_len=64).eval()
with torch.no_grad():
print(model(torch.randint(0, 1000, (2, 16))).shape) # torch.Size([2, 16, 1000])
FAQ
Q. How is Gemma different from Gemini?
A.
Gemma is a family of small, open-weight models built from Gemini's research and technology (architecture, data, and training methods). Unlike Gemini, it is a text-only model that does not handle images, and it is not trained for state-of-the-art performance on multilingual tasks.
Q. Why does Gemma 7B have 8.5 billion parameters despite being called "7B"?
A.
Because its vocabulary is large, about 256k tokens, and the embedding matrix alone has 786 million parameters. The non-embedding parameters total 7.75 billion. Keep this difference in mind when comparing it with models such as Llama 2 7B, which has a 32k vocabulary.
Q. How should I choose between Gemma 2B and 7B?
A.
2B targets devices such as CPUs and smartphones and reduces inference memory with multi-query attention. 7B targets development on GPUs and TPUs and delivers strong performance, with 64.3% on MMLU and high scores on math and code as well.