By Sagi Shaier · 6 November 2026 · 8 min read
Generalization vs memorization in language models
How to tell whether a language model learned patterns or stored its training text, what pushes it toward each, and why it changes how far you can trust an evaluation score.
A language model memorizes when it reproduces exact sequences from its training text, and it generalizes when it produces sensible output for text it never saw during training. A trained model usually does some of both. The balance decides how the model handles new text and whether it can leak private data it was trained on.
A language model is trained to predict the next token in a piece of text, where a token is a whole word or a piece of a word. The examples below use whole words to keep things simple.
What a model can learn from next-token prediction
When a model predicts the next token well, it could have learned either of two things. It could have learned patterns of language that carry over to new text, such as which words tend to follow a country name in a sentence about capitals. Or it could have stored specific strings it saw, such as one exact question and its answer.
One way to tell them apart is to change the wording. A pattern still works on new wording. A stored string works only on the exact text that was stored.
Take a model that gives "Paris" a probability of 0.82 after "The capital of France is" and 0.76 after "What is the capital of France?". Rewording the input barely moved the prediction, so the model learned something about France and capitals that carries over. Now take a model that gives "4" a probability of 0.98 after "Q: What is 2+2? A:", and only 0.21 after "What is two plus two? Answer:". The first prompt matched a string it had seen. The reworded prompt asks the same thing and left it guessing.

The two definitions
Memorization is reproducing exact sequences from the training data, word for word. The model replays a string it saw instead of composing a new one.
Generalization is producing sensible output for inputs the model did not see during training. The model has learned patterns that transfer to new cases.
Some memorization is useful. A model that answers "Paris" has stored a fact. The risky kind is verbatim recall of rare or sensitive strings, such as a phone number that appeared once in the training data.

N-gram models make memorization easy to see
An n-gram model is one of the simplest language models. It predicts the next token by counting what followed the previous $n - 1$ tokens in the training text. A bigram model ($n = 2$) looks at one previous token. A 5-gram model looks at four.
As $n$ grows, the context becomes more specific. Suppose the training text contains "the old clock struck twelve" once. In a bigram model the context "the" is followed by many different words. In a 5-gram model the context "the old clock struck" may have exactly one continuation in the counts, which is "twelve". The model is following a lookup table from a long context to the one continuation it saw, so it copies the training text instead of applying a flexible rule.

The code below counts continuations in a tiny made-up corpus:
1from collections import Counter, defaultdict
2
3corpus = (
4 "the old clock struck twelve . "
5 "the cat sat on the mat . "
6 "the old man sat by the fire . "
7 "the cat ran to the door . "
8 "the old dog slept by the door . "
9 "the city was quiet at night ."
10).split()
11
12def continuations(tokens, n):
13 """Map each context of n - 1 tokens to a count of the tokens that followed it."""
14 table = defaultdict(Counter)
15 for i in range(len(tokens) - n + 1):
16 context = tuple(tokens[i : i + n - 1])
17 table[context][tokens[i + n - 1]] += 1
18 return table
19
20bigram = continuations(corpus, 2)
21fivegram = continuations(corpus, 5)
22print("bigram, after 'the':", dict(bigram[("the",)]))
23print("5-gram, after 'the old clock struck':", dict(fivegram[("the", "old", "clock", "struck")]))
24
25for n in [2, 3, 4, 5]:
26 table = continuations(corpus, n)
27 most_choices = max(len(c) for c in table.values())
28 print(f"n={n}: {len(table)} contexts, the most varied one has {most_choices} different next tokens")1bigram, after 'the': {'old': 3, 'cat': 2, 'mat': 1, 'fire': 1, 'door': 2, 'city': 1}
25-gram, after 'the old clock struck': {'twelve': 1}
3n=2: 23 contexts, the most varied one has 6 different next tokens
4n=3: 31 contexts, the most varied one has 3 different next tokens
5n=4: 36 contexts, the most varied one has 2 different next tokens
6n=5: 38 contexts, the most varied one has 2 different next tokensAfter "the", the bigram model has six different next words to spread its probability over. After "the old clock struck", the 5-gram model has one, so it will always produce "twelve". With longer contexts, the most varied context drops from 6 choices to 2, and more of the model's predictions replay the corpus word for word.
Generalization depends on the training data
A model generalizes within the kind of text it was trained on and often does worse outside it. A model trained on formal news articles has seen sentences like "The minister declined to comment" and rarely anything like "ngl that update kinda slaps fr". It will predict casual social media text poorly. The same happens when a model trained on one dialect or one subject area meets another.
One way to measure this is perplexity, a score for how well a language model predicts a piece of text. Lower perplexity means the model gave the actual next tokens higher probabilities. The news-trained model gets a much lower perplexity on held-out news than on social media posts.

The practical lesson is to train on data that looks like the text the model will meet in use. If the text in use looks different from the training text, expect worse results, and the fix is to add training data that matches.
Capacity, data size and dropout
Whether a model memorizes or generalizes depends on the balance between its capacity, which grows with its number of parameters, and the amount of training data. A large model given too little data has room to store the training set, so it can reach a very low training loss by memorizing. That is overfitting: low error on the training data and much higher error on new data.
More data pushes the other way. When there is far more text than the model can store, learning the general pattern is the cheaper way to lower the loss.
Dropout is a regularizer, a training technique that discourages overfitting. During training it sets a random fraction of a layer's outputs to zero at each step, a different set each time. The model cannot rely on any single exact path through the network to reproduce a training string, which pushes it toward patterns that hold up when some units are missing. In PyTorch, F.dropout(h, p=0.2, training=self.training) zeros each value of h with probability 0.2 during training and returns h unchanged at evaluation time.
In the plot below, model size grows to the right. Training error keeps falling as the model gets larger. Error on held-out data falls at first, then rises again once the model has more capacity than the data can pin down, because the extra capacity goes into storing the training set.

Memorization and privacy
Large models have the capacity to generalize broadly and to store specific rare strings at the same time. If the training data contained a phone number, an address or a block of private text, a large model can sometimes reproduce it word for word when given the right prompt.
That makes verbatim memorization a privacy and security problem. It is one reason teams that train models filter personal data out of the training text and test whether the finished model reproduces sensitive strings.

Why evaluation needs held-out data
To measure generalization, a model has to be scored on held-out data, text that was kept out of training. If some of the test text also appeared in the training data, the model can score well by recalling it, and the reported number overstates how well the model does on new text.
Test text leaking into training is called data contamination. Training sets scraped from the web are large enough that benchmark examples published online can end up in them by accident. Before trusting a score, check that the test set was really unseen. Two practical questions help: was the test set published before the training data was collected, and does any test string appear word for word in the training text?

The second question can be answered with a simple overlap count. The code below splits text into 8-grams, runs of 8 consecutive words, and measures what fraction of a test sentence's 8-grams also appear in the training text:
1def ngrams(text, n=8):
2 tokens = text.lower().split()
3 return {tuple(tokens[i : i + n]) for i in range(len(tokens) - n + 1)}
4
5def overlap(test_text, train_ngrams, n=8):
6 test = ngrams(test_text, n)
7 return len(test & train_ngrams) / max(len(test), 1)
8
9train_text = (
10 "The committee announced its decision. Officials confirmed the report. "
11 "The measure passed on Tuesday. Energy prices rose again this morning, "
12 "according to figures released by the ministry."
13)
14train_ngrams = ngrams(train_text)
15
16clean = "The minister declined to comment. Markets reacted to the announcement."
17leaked = "Energy prices rose again this morning, according to figures released by the ministry."
18print(f"clean test sentence: {overlap(clean, train_ngrams):.0%} of its 8-grams appear in training")
19print(f"leaked test sentence: {overlap(leaked, train_ngrams):.0%} of its 8-grams appear in training")1clean test sentence: 0% of its 8-grams appear in training
2leaked test sentence: 100% of its 8-grams appear in trainingA test example with high overlap is a candidate for contamination, and it is worth removing before the score is reported. The same check works on model outputs: a generated passage whose long n-grams all appear in the training text is likely being recalled rather than composed.
Common mistakes
- Reading low training loss as success. A model can reach a very low training loss by storing the training set. Compare it with the loss on held-out text, and a large gap between the two is the usual sign of memorization.
- Testing on text that overlaps the training data. Duplicates and near-duplicates between the two sets inflate the score. Remove them before splitting, or check the overlap after.
- Assuming a model trained on one kind of text works on another. A model trained on news, legal documents or one dialect can do much worse on other text. Evaluate it on samples of the text it will actually meet.
- Training on raw scraped data without filtering personal information. A large model can reproduce rare strings from its training data word for word.
Related concepts
Perplexity is a common score for comparing how well language models predict held-out text. What a language model is covers n-gram models and the move to neural models. Teacher forcing and exposure bias is another case of a model behaving differently on the text it trained on and the text it meets at inference.
QuiddityML teaches generalization vs memorization as its own concept in the language models unit of its NLP track. Its questions ask why long n-gram contexts lead to copying, what a large gap between training and held-out loss points to and why verbatim recall of rare strings is a privacy risk (QuiddityML).