01 — Wikitext Perplexity
Introduction
Wikitext Perplexity is one of the most fundamental and widely-reported evaluation metrics for autoregressive language models. It measures how well a language model predicts the next token in a sequence of curated, long-form Wikipedia text. A model that assigns high probability to the correct next token at each step achieves low perplexity; a model that is frequently “surprised” by the actual next token achieves high perplexity.
Source lab: Salesforce Research — Stephen Merity, Caiming Xiong, James Bradbury, and Richard Socher.
Paper: “Pointer Sentinel Mixture Models” (2016) — introduced the WikiText-2 and WikiText-103 benchmark datasets as replacements for the aging Penn Treebank.
Primary metric: Perplexity (PPL) — lower is better.
What Perplexity means: Perplexity is the exponentiated average negative log-likelihood of the test set tokens. Intuitively, a perplexity of $X$ means the model is, on average, as uncertain as if it were choosing uniformly among $X$ tokens at every step.
- When $\text{PPL} = 1$, the model is perfectly confident and always correct — it assigns probability 1.0 to every actual next token.
- When $\text{PPL} = V$ (the vocabulary size), the model is no better than random guessing.
- For WikiText-2, typical state-of-the-art values range from roughly 3 to 30 depending on model size:
- GPT-2 Small (124M): ~29.4 PPL
- LLaMA-3-8B: ~6.1 PPL
- LLaMA-3-70B: ~3.1 PPL
Formula & Intuition
The Core Formula
Given a sequence of $N$ tokens $x_1, x_2, \ldots, x_N$, the perplexity of a language model is:
\[\text{PPL} = \exp\!\left( -\frac{1}{N} \sum_{i=1}^{N} \log p(x_i \mid x_{<i}) \right)\]where $p(x_i \mid x_{<i})$ is the probability the model assigns to token $x_i$ given all preceding tokens $x_1, \ldots, x_{i-1}$.
Step-by-Step Breakdown
-
For each token $x_i$, the model outputs a probability distribution over the entire vocabulary $V$. This distribution is obtained by applying softmax to the raw logits: $p(\cdot \mid x_{<i}) = \text{softmax}(\mathbf{z}_i)$ where $\mathbf{z}_i \in \mathbb{R}^{ V }$. -
We look up the probability assigned to the actual next token $x_i$ in that distribution. This gives us a single scalar $p(x_i \mid x_{<i}) \in (0, 1]$.
-
Take the logarithm of that probability. Since $p(x_i \mid x_{<i}) \leq 1$, we have $\log p(x_i \mid x_{<i}) \leq 0$ — it is always non-positive. The negative sign in the formula flips this to a positive quantity (the negative log-likelihood, or NLL).
-
Average over all $N$ tokens. This gives the mean NLL (or equivalently, the cross-entropy loss):
\[\bar{H} = -\frac{1}{N} \sum_{i=1}^{N} \log p(x_i \mid x_{<i})\] -
Exponentiate to get back to a “branching factor” interpretation. The exponentiation converts from log-space back to a multiplicative scale, giving us the effective number of equally-likely choices:
\[\text{PPL} = \exp(\bar{H}) = e^{\bar{H}}\]
Cross-Entropy Equivalence
Perplexity is directly related to the cross-entropy $H(p, q)$ between the true data distribution $p$ and the model distribution $q$:
\[\text{PPL} = \exp\!\big(H(p, q)\big) \quad \text{(using natural log)}\] \[\text{PPL} = 2^{H(p, q)} \quad \text{(using log base 2)}\]Both formulations are equivalent — the choice of log base only changes the numeric value of $H$, not the final PPL:
\[\exp(H_{\text{nat}}) = 2^{H_{\text{bit}}} = b^{H_{\log_b}}\]Bits-per-Character (BPC) vs. Bits-per-Word vs. Nats-per-Token
These are all different ways to express the same underlying quantity — the average information content of a prediction:
| Measure | Log Base | Unit | Conversion |
|---|---|---|---|
| Nats-per-token | $e$ (natural log) | nats | This is $\bar{H}$ as defined above. $\text{PPL} = \exp(\bar{H})$ |
| Bits-per-token (or bits-per-word) | $2$ | bits | $\bar{H}{\text{bits}} = \bar{H}{\text{nats}} / \ln 2$. $\text{PPL} = 2^{\bar{H}_{\text{bits}}}$ |
| Bits-per-character (BPC) | $2$ | bits/char | Bits-per-token divided by average characters per token. Used for character-level models. |
Key insight: When comparing models, nats-per-token or bits-per-token are additive and comparable; perplexity is multiplicative. A drop from 10 PPL to 5 PPL is much more significant than a drop from 100 PPL to 95 PPL, even though the absolute difference is larger in the second case.
Tensor Shapes at the Formula Level
For a concrete model like LLaMA-3-8B (vocab size 128,256):
- Logits:
(batch_size, seq_len, vocab_size)— e.g.,(1, 2048, 128256) - Log-probabilities =
log_softmax(logits): same shape(1, 2048, 128256) - Per-token log-prob: for each position $i$, we index
log_probs[0, i, target_token_id]to extract a single scalar $\log p(x_i \mid x_{<i})$ - Sum of $N$ scalars → single scalar (total NLL)
- Mean → single scalar (average NLL)
- Exponentiate → single scalar (PPL)
Dataset Details
Quantitative Overview
| Variant | Train Tokens | Valid Tokens | Test Tokens | Articles | Vocab Size |
|---|---|---|---|---|---|
| WikiText-2 | 2.09M | 217K | 245K | 720 | 33K |
| WikiText-103 | 103.2M | 217K | 245K | 28,595 | 267K |
Note: WikiText-2 and WikiText-103 share the same validation and test sets. WikiText-103 simply has a much larger training set (more Wikipedia articles). For evaluation purposes, both give the same PPL when using the test split.
Dataset Variants
There are four configurations available on Hugging Face:
| Config Name | Type | Description |
|---|---|---|
wikitext-2-raw-v1 |
Raw (untokenized) | Preserves original case, punctuation, and formatting. Recommended for modern LLMs. |
wikitext-103-raw-v1 |
Raw (untokenized) | Same as above, larger training set. |
wikitext-2-v1 |
Word-level tokenized | Pre-tokenized with <unk> for rare words. Not recommended for modern models. |
wikitext-103-v1 |
Word-level tokenized | Same as above, larger training set. |
Always use the “raw” versions (wikitext-2-raw-v1 or wikitext-103-raw-v1) for modern subword tokenizers (BPE, SentencePiece, Unigram). The word-level “v1” versions replace rare tokens with <unk>, which modern BPE tokenizers do not produce — leading to artificially deflated perplexity because the model never has to predict rare words.
Qualitative Characteristics
WikiText articles are long-form Wikipedia articles that preserve:
- Paragraph structure: full paragraphs with natural sentence boundaries
- Section headers: marked with
=signs (e.g.,= = Section Title = =) - Lists and formatting: bulleted lists, numbered items
- Rare words and entities: proper nouns, technical terms, foreign words — a major advantage over Penn Treebank which was limited to Wall Street Journal text
- Natural language: more diverse and representative of general English than PTB
Loading the Dataset
1
2
3
4
5
6
7
8
from datasets import load_dataset
# Recommended: raw version for modern tokenizers
dataset = load_dataset("wikitext", "wikitext-2-raw-v1", split="test")
# Each example is a text string (a line from the articles)
print(dataset[0]) # {'text': ''}
print(dataset[1]) # {'text': ' = Valkyria Chronicles III = \n'}
Hugging Face dataset identifier:
wikitextwith configswikitext-2-raw-v1,wikitext-103-raw-v1,wikitext-2-v1,wikitext-103-v1.
Tensor Shapes at Every Stage
This section walks through the complete evaluation pipeline with concrete tensor shapes at every step. Understanding these shapes is essential for implementing and debugging perplexity evaluation correctly.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
Step 1: Load text
raw_text: str # e.g., len = 287,646 characters for WikiText-2 test
Step 2: Tokenize
input_ids: (1, total_tokens) # e.g., (1, 245000) — but too long for one forward pass
Step 3: Chunk into windows
For stride-based evaluation with max_length=2048, stride=2048:
chunk_0: input_ids[:, 0:2048] → (1, 2048)
chunk_1: input_ids[:, 2048:4096] → (1, 2048)
...
chunk_k: input_ids[:, k*2048:(k+1)*2048] → (1, 2048) or smaller for last chunk
Step 4: Forward pass (per chunk)
Input: input_ids → (1, seq_len) e.g., (1, 2048)
Embedding layer:
token_embeds: (1, 2048, hidden_dim) e.g., (1, 2048, 4096) for LLaMA-3-8B
Through transformer layers:
hidden_states: (1, 2048, 4096) — same shape through all 32 layers
LM head (linear projection to vocabulary):
logits: (1, 2048, vocab_size) e.g., (1, 2048, 128256)
Step 5: Compute loss
Shift logits and labels (causal LM convention):
shift_logits: (1, 2047, 128256) # positions 0..2046 predict tokens at 1..2047
shift_labels: (1, 2047) # ground truth tokens at positions 1..2047
Cross-entropy per token:
token_losses: (2047,) # one loss value per predicted token
Mean loss for this chunk:
chunk_loss: scalar (float) # mean of the 2047 per-token losses
Step 6: Aggregate across all chunks
total_nll: scalar = sum of all (chunk_loss × num_tokens_in_chunk)
total_tokens: int = total number of tokens evaluated across all chunks
avg_nll: scalar = total_nll / total_tokens
PPL = exp(avg_nll): scalar (float)
Shape Transformation Walkthrough
Step 1 → 2 (Tokenization): The raw text string is converted to integer token IDs via the model’s tokenizer. A string of ~288K characters becomes ~245K token IDs (the ratio depends on the tokenizer — LLaMA-3’s BPE averages ~1.17 characters per token for English Wikipedia text). The result is a 1D tensor of shape (1, T) where T ≈ 245,000.
Step 2 → 3 (Chunking): The full sequence is too long for a single forward pass (most models have a max context of 2048–8192 tokens, and even if they support longer contexts, memory is a constraint). We split the sequence into overlapping or non-overlapping windows of size max_length. Each chunk has shape (1, max_length) except possibly the last chunk which may be shorter.
Step 3 → 4 (Forward pass): Each chunk goes through the full transformer. The embedding layer maps each token ID to a dense vector of dimension hidden_dim (4096 for LLaMA-3-8B). This shape is maintained through all transformer layers (attention + FFN). Finally, the LM head projects from hidden_dim back to vocab_size, producing logits of shape (1, seq_len, vocab_size).
Step 4 → 5 (Loss computation): For causal language modeling, position $i$ predicts position $i+1$. We “shift” the logits and labels: shift_logits = logits[:, :-1, :] and shift_labels = labels[:, 1:]. This removes one position, giving shapes (1, 2047, 128256) and (1, 2047). Cross-entropy loss is computed per token, yielding a vector of 2047 loss values, which is then averaged to a scalar.
Step 5 → 6 (Aggregation): We weight each chunk’s mean loss by the number of tokens it evaluated (to handle stride overlap masking and the last shorter chunk correctly), then divide by total tokens to get the overall mean NLL. A single exp() call converts to PPL.
Figure 2 — Tensor shape transformations through the full PPL forward pass. Note: the entire operation is a single prefill pass — no autoregressive decoding occurs.
Evaluation Procedure (Pseudocode)
The following pseudocode details the standard sliding-window perplexity evaluation procedure. This is the approach used by HuggingFace Transformers and most evaluation frameworks.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
function compute_wikitext_perplexity(model, tokenizer, dataset, max_length, stride):
# Step 1: Concatenate all test examples into a single string.
# WikiText test set contains ~4,358 lines (some empty). Joining them
# produces a single long document for evaluation.
text = concatenate all test examples (joining with "\n\n")
# Step 2: Tokenize the full text into a single long sequence.
input_ids = tokenizer.encode(text) # shape: (1, T)
T = input_ids.shape[1]
total_nll = 0.0
total_tokens = 0
prev_end_loc = 0
# Step 3: Slide a window of size max_length across the token sequence.
for begin_loc in range(0, T, stride):
end_loc = min(begin_loc + max_length, T)
# The number of NEW tokens to evaluate in this window.
# For the first window, trg_len = end_loc (all tokens are new).
# For subsequent windows with overlap, trg_len = stride.
trg_len = end_loc - prev_end_loc
input_chunk = input_ids[:, begin_loc:end_loc] # (1, chunk_len)
target_chunk = input_chunk.clone()
# Mask tokens in the overlap region that were already evaluated
# in the previous window. Setting to -100 tells CrossEntropyLoss
# to ignore these positions.
target_chunk[:, :-trg_len] = -100 # ignore already-evaluated tokens
with no_grad():
outputs = model(input_chunk, labels=target_chunk)
# outputs.loss: scalar — mean NLL over non-masked tokens
# outputs.logits: (1, chunk_len, vocab_size)
neg_log_likelihood = outputs.loss
# Accumulate: loss × number of valid (non-masked) tokens
num_valid = (target_chunk != -100).sum()
total_nll += neg_log_likelihood * num_valid
total_tokens += num_valid
prev_end_loc = end_loc
if end_loc == T:
break
# Step 4: Compute final perplexity
avg_nll = total_nll / total_tokens
ppl = exp(avg_nll)
return ppl
Why the overlap masking matters: When
stride < max_length, the beginning of each window overlaps with the end of the previous window. Without masking, those overlapping tokens would be counted twice — once with less context (at the start of the previous window) and once with more context (at the start of the current window). The masking ensures each token is evaluated exactly once, and specifically with the maximum available context.
Figure 1 — Sliding window evaluation: stride controls overlap between windows. Only new (non-overlapping) tokens contribute to the NLL sum. The orange window is Window 1; cyan is Window 2 showing the overlap region (context only) and new evaluated tokens.
Reference Implementation
HuggingFace Transformers — Sliding Window Perplexity
This implementation is based on the official HuggingFace perplexity guide:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from datasets import load_dataset
def compute_perplexity(
model_id: str = "meta-llama/Llama-3.1-8B",
dataset_name: str = "wikitext",
dataset_config: str = "wikitext-2-raw-v1",
split: str = "test",
max_length: int = 2048,
stride: int = 512,
device: str = "cuda",
dtype: torch.dtype = torch.bfloat16,
) -> float:
"""
Compute perplexity on WikiText using sliding window evaluation.
Based on HuggingFace's perplexity evaluation guide:
https://huggingface.co/docs/transformers/perplexity
"""
# Load model and tokenizer
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
model_id, torch_dtype=dtype, device_map=device
)
model.eval()
# Load and concatenate dataset
dataset = load_dataset(dataset_name, dataset_config, split=split)
text = "\n\n".join(dataset["text"])
encodings = tokenizer(text, return_tensors="pt")
input_ids = encodings.input_ids.to(device) # (1, total_tokens)
seq_len = input_ids.size(1)
print(f"Total tokens: {seq_len}")
nlls = []
prev_end_loc = 0
for begin_loc in range(0, seq_len, stride):
end_loc = min(begin_loc + max_length, seq_len)
trg_len = end_loc - prev_end_loc # number of new tokens to evaluate
input_chunk = input_ids[:, begin_loc:end_loc] # (1, chunk_len)
target_ids = input_chunk.clone()
target_ids[:, :-trg_len] = -100 # mask already-evaluated tokens
with torch.no_grad():
outputs = model(input_chunk, labels=target_ids)
# outputs.loss: scalar — mean NLL over non-masked tokens
# outputs.logits: (1, chunk_len, vocab_size)
neg_log_likelihood = outputs.loss
nlls.append(neg_log_likelihood * trg_len)
prev_end_loc = end_loc
if end_loc == seq_len:
break
ppl = torch.exp(torch.stack(nlls).sum() / end_loc)
return ppl.item()
if __name__ == "__main__":
ppl = compute_perplexity()
print(f"Perplexity: {ppl:.2f}")
lm-eval-harness (EleutherAI) — CLI
The lm-evaluation-harness is the most widely-used standardized framework. Running WikiText perplexity is a single command:
1
2
3
4
5
6
# Using lm-eval-harness
lm_eval --model hf \
--model_args pretrained=meta-llama/Llama-3.1-8B,dtype=bfloat16 \
--tasks wikitext \
--batch_size 1 \
--output_path results/
This runs the wikitext task group, which evaluates word-level and byte-level perplexity on WikiText. The output includes word_perplexity and byte_perplexity metrics.
Tip: For reproducible comparisons, always pin the
lm-evalversion and report the exact command used. Different versions may use slightly different stride or preprocessing settings.
Caveats & Pitfalls
This is the most critical section for understanding perplexity evaluation. Subtle implementation choices can swing PPL by 0.5–2.0 points — enough to completely change model rankings.
1. Token-by-Token vs. Chunked (Strided) Evaluation
Quantitative Impact: Using stride = max_length gives PPL approximately 0.5–1.0 higher than stride = 1 on WikiText-2 for 7B-class models. A stride of 512 with max_length = 2048 is a widely used practical compromise.
| Strategy | Stride | Forward Passes (T=100K, max_len=2048) | PPL Accuracy | Speed |
|---|---|---|---|---|
| Full context | 1 | ~100,000 | Best (gold standard) | Extremely slow |
| Overlapping | 512 | ~195 | Very good | Moderate |
| Non-overlapping | 2048 | ~49 | Good (slightly inflated) | Fast |
2. Prefill vs. Decode — Is It Applicable?
- PPL evaluation is entirely prefill — you are NOT doing autoregressive decoding or text generation.
- The model processes each chunk in a single forward pass (prefill mode), computing logits for all positions simultaneously via parallelized self-attention.
- This means PPL benchmarks do not use the KV-cache. There is no sequential token-by-token generation happening.
- PPL evaluation is therefore much faster per-token than autoregressive generation, because all positions in a chunk are computed in parallel.
- Implication: Perplexity does not measure “generation quality.” A model with excellent PPL could still generate poorly if the sampling strategy (temperature, top-k, top-p) is misconfigured. PPL measures the model’s probability assignments, not its generated outputs.
3. Sequence Length (seq_len / max_length)
- The
max_lengthparameter must be ≤ the model’s maximum context length (positional encoding range). - Using
max_length> model’s trained context → positional encoding errors, producing garbage results (nonsensical logits). - Using
max_length< model’s context → the model cannot leverage its full context window, which will inflate PPL because predictions have less conditioning information. - Common choices: 1024 (GPT-2), 2048, 4096, 8192 (modern models).
- Critical for fair comparisons: always use the same
max_lengthandstridewhen comparing models. Usingmax_length=4096for one model andmax_length=2048for another is an apples-to-oranges comparison. - LLaMA-3 supports 8192 (base) and up to 128K (extended); evaluating it with
max_length=2048disadvantages it relative to shorter-context models that were specifically optimized for that window size.
4. Speed of Execution
- WikiText-2 test set: ~245K tokens — a relatively small dataset by modern standards.
- With
max_length=2048, stride=2048: approximately 120 forward passes. Takes 30–60 seconds on a single A100 for a 7B model. - With
max_length=2048, stride=512: approximately 480 forward passes. Takes 2–4 minutes on a single A100 for a 7B model. - WikiText-103 test set is the same as WikiText-2 test set (~245K tokens), so evaluation speed is identical.
- This is one of the fastest evals to run — considerably faster than MMLU (~14K questions requiring few-shot prompts), HumanEval (164 code generation problems), or MMMU (multimodal reasoning).
- Bottleneck: purely GPU compute in prefill mode. No generation overhead, no sampling, no multi-turn interaction.
5. Common Time Taken
| Model Size | Device | max_len=2048, stride=2048 | max_len=2048, stride=512 |
|---|---|---|---|
| 1–3B | A100 80GB | ~15–30s | ~1–2 min |
| 7–8B | A100 80GB | ~30–60s | ~2–4 min |
| 13B | A100 80GB | ~1–2 min | ~4–8 min |
| 70B | 2×A100 80GB | ~3–5 min | ~10–20 min |
6. Other Important Caveats
Tokenizer dependence in detail: Consider two models — Model A with a 32K BPE vocabulary and Model B with a 128K BPE vocabulary. For the same WikiText-2 test text, Model A might tokenize it into 260K tokens while Model B produces 230K tokens. Even if both models achieve the same bits-per-character, their per-token PPL values will differ because they are averaging over a different number of (differently-sized) tokens. To make a truly fair comparison, use bits-per-byte or bits-per-character instead of raw PPL.
Empty lines: The WikiText dataset contains many empty lines (separating sections and articles). These tokenize to just a newline character. Whether you join examples with "\n\n" or "" or strip empty lines can shift the token count by several hundred, leading to small but measurable PPL differences.
BOS token: LLaMA tokenizers prepend <s> (token ID 1) by default. GPT-2 tokenizers do not add a BOS token. This single-token difference changes the denominator of the PPL calculation and slightly alters the conditioning for the first real token.
Float precision: The softmax operation is numerically sensitive. BF16 has less mantissa precision than FP32, which can cause slight differences in the probability distribution and therefore in the log-likelihood computation. For rigorous comparisons, use the same dtype across all models.
7. labels = input_ids Shortcut — How It Works
A common pattern in HuggingFace code is outputs = model(input_ids, labels=input_ids). This seems circular — why pass the inputs as labels? Here’s what’s happening internally:
- HuggingFace’s
CausalLMmodels automatically shift the labels:labels[i]is used as the target for positioni-1 - So
labels[i] = input_ids[i]means “token at position i is the target for the prediction made at position i-1” - This is equivalent to:
logits[:, :-1, :]predictinginput_ids[:, 1:] - The model internally computes:
loss = CrossEntropy(logits[:, :-1, :].reshape(-1, V), input_ids[:, 1:].reshape(-1))
Pitfall: If you manually implement the loss without understanding this shift, you’ll compute loss over the wrong (off-by-one) position pairs, producing slightly wrong PPL values.
8. The “Last Chunk” Truncation Problem
When the total sequence length T is not a multiple of stride, the final chunk is shorter than max_length. Implementations that don’t handle this correctly may:
- Pad the last chunk to
max_lengthwithout properly masking the padding → inflated loss - Skip the last chunk if it’s shorter than
max_length→ slightly lower reported token count → marginally deflated PPL - Evaluate it as-is (correct approach) → the last chunk simply has a smaller
chunk_lenand contributes proportionally
Always verify that your implementation handles the final partial chunk correctly and that total_tokens accounts for all tokens including the final chunk.
9. Vocabulary-Normalized Comparison: Bits-Per-Byte (BPB)
Raw PPL is tokenizer-dependent. Two models with identical quality but different tokenizers (e.g., 32K BPE vs 128K BPE) will produce different PPL values because they tokenize the same text into different numbers of tokens.
Solution: Normalize by the average number of bits per byte of text:
\[\text{BPB} = \frac{\log_2 e \cdot \text{NLL (nats per token)} \cdot \text{num tokens}}{\text{num bytes of text}}\]This converts from “nats per token” to “bits per byte of raw text”, which is comparable across tokenizers. Some papers and frameworks report BPB instead of (or in addition to) PPL.
When to use BPB: Any time you’re comparing models with different tokenizers. When comparing models with the same tokenizer family, raw PPL is fine.
10. Chat Template Applying to Eval Text
Some evaluation scripts incorrectly wrap the WikiText evaluation text in a chat template (e.g., <|begin_of_text|><|start_header_id|>user<|end_header_id|>...). This:
- Adds extra tokens (template tokens) that the model wasn’t optimized to predict on raw Wikipedia text
- Drastically inflates PPL because the model sees an unusual context format
- Is wrong — PPL on WikiText should be evaluated on raw continuation text, not chat-formatted text
Rule: For PPL evaluation on WikiText, never apply a chat template. Always evaluate raw text directly.
11. Model in Training vs. Eval Mode
PyTorch models have model.train() and model.eval() modes. The key difference for PPL:
- Train mode: Dropout is active — some activations are randomly zeroed. This makes the model “appear worse” because its predictions are stochastic.
- Eval mode: Dropout is disabled — the full model capacity is used. This is correct for evaluation.
Always call model.eval() before running PPL evaluation. Forgetting this can inflate PPL by 0.3–2.0 points depending on the model’s dropout rate (most modern LLMs have dropout=0, so this is a legacy concern, but some fine-tuned models still use it).
Leaderboard Reference
The following tables provide representative WikiText-2 perplexity scores from published results and community benchmarks. All values are approximate and depend on exact evaluation settings (stride, max_length, dataset version, float precision, tokenizer).
Small Models (<7B)
| Model | Params | WikiText-2 PPL | max_len | Notes |
|---|---|---|---|---|
| GPT-2 Small | 124M | 29.41 | 1024 | Original paper |
| GPT-2 Medium | 355M | 22.76 | 1024 | Original paper |
| GPT-2 Large | 774M | 19.93 | 1024 | Original paper |
| GPT-2 XL | 1.5B | 18.34 | 1024 | Original paper |
| Phi-2 | 2.7B | ~9.7 | 2048 | Microsoft |
| Gemma-2-2B | 2.6B | ~10.1 | 2048 | |
| LLaMA-2-7B | 7B | ~5.5 | 4096 | Meta |
| LLaMA-3-8B | 8B | ~6.1 | 2048 | Meta (reported) |
| Mistral-7B | 7.2B | ~5.3 | 2048 | Mistral AI |
Medium Models (<30B)
| Model | Params | WikiText-2 PPL | max_len | Notes |
|---|---|---|---|---|
| LLaMA-2-13B | 13B | ~5.0 | 4096 | Meta |
| Mistral-Small (22B) | 22B | ~4.2 | 2048 | Mistral AI |
Large Models (30B+)
| Model | Params | WikiText-2 PPL | max_len | Notes |
|---|---|---|---|---|
| LLaMA-2-70B | 70B | ~3.3 | 4096 | Meta |
| LLaMA-3-70B | 70B | ~3.1 | 2048 | Meta |
| Qwen-2.5-72B | 72B | ~3.4 | 2048 | Alibaba |
Important: These values should not be compared directly across rows if the
max_lenor stride differ. The GPT-2 results usemax_len=1024(the model’s maximum), while LLaMA results use 2048 or 4096. Re-running all models with identical settings is necessary for apples-to-apples comparison.
Parameters: Deep Dive
This section explains every configurable parameter in PPL evaluation: why it exists, what values it can take, how it affects accuracy and speed, and what pitfalls to avoid.
max_length (Window Size)
Why it exists: Language models have a fixed positional encoding range — they can only attend to a limited number of prior tokens. max_length sets the size of each evaluation chunk to stay within this range.
Values: Any positive integer ≤ the model’s maximum context length.
| Value | Effect on PPL | Effect on Speed | When to Use |
|---|---|---|---|
| 512 | Higher PPL (less context) | Fastest | Legacy GPT-2 style comparisons |
| 1024 | Moderate | Fast | GPT-2 max (1024 is its limit) |
| 2048 | Good | Standard | Most 7B–13B models, published comparisons |
| 4096 | Better | Slower per chunk | LLaMA-2, Mistral (4096 trained context) |
| 8192 | Best (if model supports) | Slowest per chunk | LLaMA-3 (8192 base context) |
Critical rule: max_length must never exceed the model’s trained context length. Exceeding it causes positional encoding to produce meaningless embeddings, resulting in garbage logits and inflated PPL.
Why context matters: With more tokens as context, the model can better predict each next token. Moving from 512→2048 typically improves PPL by 1–3 points for 7B models. Beyond 4096, improvements are marginal (~0.1–0.3 PPL) because most predictive signal is in the recent few hundred tokens.
Pitfall: When comparing models, using different max_length values (e.g., 4096 for LLaMA-2 but 1024 for GPT-2) is an unfair comparison. Always normalize to the same max_length for apples-to-apples results.
stride
Why it exists: stride controls by how many tokens the window advances at each step. Without striding, tokens at the start of each chunk have almost no context, inflating their loss. Overlapping windows give boundary tokens more context.
Values: Any integer from 1 to max_length.
| stride | Overlap | Forward Passes (100K tokens, max_len=2048) | PPL Accuracy | Speed |
|---|---|---|---|---|
| 1 | 2047 tokens | ~100,000 | Gold standard | Extremely slow |
| 256 | 1792 tokens | ~390 | Near-perfect | Slow |
| 512 | 1536 tokens | ~195 | Very good | Moderate (standard) |
| 1024 | 1024 tokens | ~98 | Good | Fast |
| 2048 (= max_length) | 0 (none) | ~49 | Slightly inflated | Fastest |
Quantitative impact: The PPL difference between stride=2048 and stride=512 is typically 0.3–0.8 points for 7B models on WikiText-2. Between stride=512 and stride=1, less than 0.1 points.
Pitfall: Many older papers and blog posts report results with stride=max_length (non-overlapping) without disclosing this. If you compare your stride=512 result against a published stride=2048 result, your model will appear to score lower — not because it’s worse, but because you gave it more context.
Recommendation: Use stride=512 with max_length=2048 for standard published results. Match whatever setting your comparison baseline used.
dtype (Floating-Point Precision)
Why it exists: Controls the numerical precision used for model weights and activations during forward passes.
Values: torch.float32, torch.float16, torch.bfloat16
| dtype | PPL Impact | Memory | Speed | Recommended |
|---|---|---|---|---|
| float32 | Baseline (most precise) | 4× fp16 | Slowest | Reference runs, small models |
| float16 | ±0.01–0.05 vs fp32 | 2× fp16 (baseline) | ~2× faster | Legacy; NaN risk on some ops |
| bfloat16 | ±0.01–0.05 vs fp32 | Same as fp16 | ~2× faster | Recommended for modern GPUs |
Why dtype affects PPL: The softmax and log operations are numerically sensitive. Lower precision can cause slight differences in which tokens have the highest probability, especially when multiple tokens have very similar logits. The effect is small but measurable (~0.01–0.05 PPL).
Pitfall: Mixing dtypes between models being compared (float32 for one, bfloat16 for another) introduces a confound. Always use the same dtype. For published results, bfloat16 is standard on modern hardware.
batch_size
Why it exists: GPU throughput increases with larger batches; however, PPL evaluation is inherently sequential per-document.
Values: 1 (strongly recommended), or 2+ if padding is handled correctly.
| batch_size | Accuracy | Speed | Notes |
|---|---|---|---|
| 1 | Exact | Baseline | Standard; no padding needed |
| >1 | Requires care | Faster | Must mask padding tokens in both inputs AND targets |
Why batch_size=1 is standard: PPL is computed as the average NLL over a single long sequence. With batch_size > 1, you’d need to pad sequences to equal length, and those padding tokens must be excluded from the loss. If padding is accidentally included, you’re computing loss on padding-token predictions, which inflates (worsens) PPL. Getting this right is non-trivial, and the speed gain is marginal for PPL.
Pitfall: Using batch_size > 1 with incorrect padding mask implementation is a common source of silently wrong (inflated) PPL values.
dataset_config (WikiText Variant)
Why it exists: WikiText has multiple variants: word-level (older) and raw (newer), in WikiText-2 and WikiText-103 sizes.
Values:
wikitext-2-v1— word-level tokenized, 33K vocabulary,<unk>for rare wordswikitext-2-raw-v1— raw untokenized text, preserving case and punctuationwikitext-103-v1— word-level, larger training set (103M tokens)wikitext-103-raw-v1— raw, larger training set
Impact: Word-level versions tokenize text with a 33K word vocabulary and insert <unk> tokens for rare words. Modern BPE/SentencePiece tokenizers never produce <unk> (every sequence of bytes is representable). This means word-level configs introduce artificial unknowns that modern models have never seen in training, inflating PPL.
Rule: Always use wikitext-2-raw-v1 or wikitext-103-raw-v1 for modern models (LLaMA, Mistral, GPT-NeoX, etc.).
Note: The test split of WikiText-2 and WikiText-103 is the same (~245K tokens). Training sets differ dramatically (2M vs 103M), but for evaluation purposes, both variants test on identical text.
add_special_tokens (Tokenizer Setting)
Why it exists: Tokenizers optionally prepend BOS (beginning-of-sequence) and append EOS tokens. For PPL evaluation over continuous text, adding BOS at every chunk boundary is incorrect.
Values: True (adds BOS/EOS), False (no special tokens)
Impact on PPL:
- With BOS prepended to every chunk: the model’s first prediction in each window is conditioned on
<bos>, giving it an artificial “fresh start” signal. This slightly deflates per-window PPL but is inconsistent with the sliding-window intent. - Without BOS: the model treats each chunk as a continuation of text, which is the correct interpretation for PPL evaluation.
Recommendation: Set add_special_tokens=False when encoding chunks. Only add BOS to the very first chunk if desired. This is what HuggingFace’s official PPL evaluation guide does.
Summary: Parameter Impact Matrix
| Parameter | Increasing value → | PPL | Speed |
|---|---|---|---|
max_length ↑ |
More context | Lower (better) | Fewer chunks (faster) |
stride ↑ |
Less overlap | Higher (worse) | Fewer passes (faster) |
dtype fp32→bf16 |
Lower precision | ±0.05 | Faster |
batch_size ↑ |
More parallelism | Same (if correct) | Faster |
Applicability
When to Use Wikitext Perplexity
When NOT to Use Wikitext Perplexity
Common Eval Sources
- lm-eval-harness (EleutherAI):
lm_eval --tasks wikitext— the most widely adopted standardized evaluation framework. Supports word-level and byte-level perplexity. Used by the Open LLM Leaderboard. - HuggingFace evaluate:
evaluate.load("perplexity")— a simpler, more Pythonic API for quick perplexity measurement. Wraps the same sliding-window logic. - Custom scripts: Using HuggingFace Transformers directly (as shown in the Reference Implementation section above). Offers the most control over stride, max_length, and preprocessing.
- Open LLM Leaderboard: The original v1 leaderboard included perplexity-based metrics. The v2 leaderboard dropped perplexity in favor of harder reasoning benchmarks (MMLU-Pro, GPQA, etc.), but many model cards still report WikiText PPL from v1.
Links & References
Papers
- Pointer Sentinel Mixture Models — Merity, Xiong, Bradbury, Socher (2016). The paper that introduced the WikiText-2 and WikiText-103 datasets.
- Language Models are Unsupervised Multitask Learners — Radford et al. (2019). The GPT-2 paper that established WikiText PPL baselines still widely cited today.
Dataset
- WikiText on Hugging Face — all four configurations available for direct download.
- Original WikiText page — Salesforce Research’s official dataset page.
Evaluation Frameworks
- lm-eval-harness — EleutherAI’s comprehensive LLM evaluation framework.
- HuggingFace Perplexity Guide — official tutorial on computing perplexity with sliding windows.
Leaderboards
- Open LLM Leaderboard — HuggingFace’s community leaderboard for open-source LLMs.
← Back to Table of Contents · Next: 02 — MMLU →
Last updated: April 2026