Memorization & the Long Tail
Why fitting rare examples can be necessary, and what networks memorize.
Most training images of a class look alike, but many are one of a kind: an unusual breed, an odd angle, a rare way of writing a digit. From a single example a network cannot tell a mislabeled outlier from the only representative of a real subpopulation that test images will also come from. Feldman's theory says that on long-tailed data, memorizing such examples is necessary for near-optimal accuracy. This lesson proves the key bound, measures what image networks actually memorize, follows memorization into language models, and shows why privacy, which forbids memorization, costs most on the tail.
What you’ll learn
- State Feldman's long-tail model and his lower bound on the cost of not fitting examples seen once, and compute it for a Zipf distribution.
- Define memorization and influence scores, estimate them by subsampling, and summarize what high-memorization examples look like in image datasets.
- Describe how verbatim memorization in language models grows with scale, duplication and context, and how counterfactual memorization separates rare text from common text.
- Derive the limit differential privacy puts on memorization, and explain why its accuracy cost falls on the tail.
A model of the long tail
Real datasets are mixtures of subpopulations whose frequencies form a long tail: a few are common, and very many are individually rare. Feldman (2020) made the consequence precise with a deliberately bare model. The input space has points, each standing for a subpopulation; their frequencies are drawn at random from a prior and normalized; and the labels come from a rich class, so the label of a point the learner has not seen is unpredictable from the rest of the data. The learner sees examples. Some points appear many times, some never, and some exactly once: the singletons. What does an algorithm lose by not fitting the singletons?
A point of frequency appears exactly once in draws with probability . By Bayes' rule, the frequency of a point given that it appeared exactly once has density proportional to that likelihood times the prior:
Its expected frequency is therefore exactly :
A singleton's label cannot be inferred from the rest of the data, but it is right there in the training set. An algorithm that mislabels it mislabels every future test point from that subpopulation, a fraction of the test distribution, while the optimal algorithm gets them right. Averaging over given "seen once" turns each mislabeled singleton into an expected cost of ; Feldman's proof does this bookkeeping exactly.
Hence the role of the tail. If every subpopulation is frequent () there are almost no singletons, and if the rare ones are vanishingly rare () they will almost never recur at test time: in both cases memorizing buys almost nothing. A long tail puts many subpopulations near , where a singleton is likely to have test-time relatives.
Feldman's example is a Zipf prior, with the frequency of the -th most common point proportional to , over points and samples. Then , while the rarest point has frequency only about ; about 17% of the samples are singletons; and the points never seen at all make up about 17% of the distribution too, as the Good–Turing estimate of the missing mass, the fraction of singletons, predicts.
In the Zipf example, , a fraction 0.17 of the training examples are singletons, and the 10 classes are equally likely. An algorithm ignores the singletons and guesses their labels at random. How much extra test error does the bound charge it, in percentage points?
Show the answer
7.2 points
It mislabels singletons in expectation, each costing : , about 7 points, against an optimal error of about 15% (90% of the 17% of the distribution never seen in training). Feldman reports about 7% for this example. Ignoring the tail raises the error from about 15% to about 22%.
Measuring what networks memorize
Feldman and Zhang (2020) measured memorization directly. For an algorithm , randomness of initialization and data order included, and a training set , the memorization score of example and its influence on a test example are
An example is memorized if the model gets it right only when it has seen it. Leaving out one example at a time would need on the order of retrainings per example for a standard error , millions of runs for 50,000 examples. Instead, train models on random subsets of size , and for each example compare the models that saw it with those that did not.
import numpy as np
def memorization(train, X, y, t=2000, frac=0.7, seed=0):
"""Subsampled memorization scores (Feldman & Zhang, 2020).
train(X, y) must return a function that maps inputs to predicted labels."""
rng = np.random.default_rng(seed)
n = len(y)
hit_in, cnt_in = np.zeros(n), np.zeros(n)
hit_out, cnt_out = np.zeros(n), np.zeros(n)
for _ in range(t):
inside = np.zeros(n, dtype=bool)
inside[rng.choice(n, size=int(frac * n), replace=False)] = True
correct = train(X[inside], y[inside])(X) == y # one model, scored on every example
hit_in += correct & inside
cnt_in += inside
hit_out += correct & ~inside
cnt_out += ~inside
return hit_in / cnt_in - hit_out / cnt_out # P[right | i in S] - P[right | i not in S]One pass trains models and scores every example at once. Feldman and Zhang used and models for ImageNet or for MNIST and CIFAR-100, with ResNet-50 on ImageNet and CIFAR-100; the estimate is the memorization score averaged over subsets of size , a smoothed version of the leave-one-out definition. With a nearest-neighbor learner on a toy dataset, typical points score about 0, a lone point of a rare class and a mislabeled point both score 1, and each copy of a duplicated pair scores about 0.3, the chance that its twin is missing from the subset.
Of 2,000 models trained on random 70% subsets, 1,400 included example , and 1,330 of those classified it correctly; of the 600 that did not include it, 180 did. What is its memorization estimate?
Show the answer
0.65
. The model almost always gets the example right after seeing it and usually gets it wrong otherwise: the rest of the data do not imply its label. With , about 70% of the models include any given example, so both averages rest on hundreds of models.
What do networks memorize? On MNIST few examples have high scores; on CIFAR-100 and ImageNet many do, and on ImageNet about 32% of the training examples have memorization estimates of at least 0.3. Examples scoring near 0 are typical of their class; those near 1 are atypical, ambiguous or mislabeled. They are also useful: removing the ImageNet examples scoring at least 0.3 cost about 3.4 points of test accuracy, against about 2.6 points for removing a random 32% of the data. Most randomly chosen examples are easy and redundant; the memorized ones carry more than their share.
The sharpest test of the theory is in the influence scores. Feldman and Zhang looked for pairs of a highly memorized training example (score at least 0.25) and a test example of the same class that it strongly influences (at least 0.15). They found 35 such pairs on MNIST, 1,015 on CIFAR-100 and 1,641 on ImageNet, where the pairs covered 1,462 test examples (2.92% of the test set), 1,298 of them influenced by a single training example. The paired images are visibly similar, sometimes nearly identical: a memorized training image is what lets the network get its rare relative in the test set right, the mechanism behind . Gradient-based approximations to such scores, which avoid retraining, are the subject of Influence Functions & Data Attribution.
An example has a memorization score near 1. What is it most likely to be?
- A typical example of its class
- An exact duplicate of many other training images
- Either the lone representative of a rare subpopulation or a mislabeled example, which the score alone cannot tell apart
- An example the network never manages to fit
Show the answer
C. Either the lone representative of a rare subpopulation or a mislabeled example, which the score alone cannot tell apart
A score near 1 means the network is right on the example only when it has trained on it, so nothing else in the data implies its label. That holds for a unique but correct example and for a mislabeled one alike. An algorithm that fits the useful tail must therefore fit some noise as well, and Feldman's theory says this is the price of near-optimal accuracy.
Memorization in language models
For a language model the natural notion is verbatim: a string is extractable with tokens of context if some length- prefix , with followed by in the training data, makes greedy decoding produce (extraction attacks are covered in the Artificial Intelligence course's Attacks on Models). Carlini, Ippolito, Jagielski, Lee, Tramèr and Zhang (2023) measured it on the GPT-Neo models trained on the Pile and found three log-linear trends. Memorization grows with model size: on their evaluation set, which over-represents duplicated text, each tenfold increase in parameters raised the extractable fraction by about 19 percentage points, and the 6-billion-parameter GPT-J memorized at least 1% of its training data. It grows with duplication: sequences repeated more often are extracted more often. And it grows with context: longer prompts extract more.
Is that memorization or just good prediction? GPT-2 models, trained on other data, completed only about 6% of the same evaluation sequences, against 40% for the similar-sized 1.3-billion-parameter GPT-Neo trained on the Pile, and what GPT-2 did complete was mostly predictable text such as number sequences and repetitions. The larger models really do store more of their training data.
Duplication is the lever practitioners control. Lee, Ippolito, Nystrom, Zhang, Eck, Callison-Burch and Carlini (2022) found standard corpora full of repeats: near-duplicates made up between 3.04% (C4) and 13.63% (RealNews) of the training examples, and a single 61-word English sentence appeared more than 60,000 times in C4. Models trained on these corpora emitted memorized text in over 1% of their unprompted output. After deduplication they did so about ten times less often and needed fewer training steps for the same or better accuracy, and evaluation became more honest, since over 4% of standard validation sets overlapped with the training data (Data Quality, Filtering & Mixtures).
Verbatim extraction is dominated by duplicated and predictable text, which is not memorization in Feldman's sense: removing one copy of a software license changes nothing. Counterfactual memorization (Zhang, Ippolito, Lee, Jagielski, Tramèr & Carlini, 2023) carries the Feldman–Zhang score over to language models: how much a model's predictions on a document change when that document is left out of training, estimated from many models trained on random subsets. It separates the rare documents a model has truly memorized from familiar phrases, public knowledge and templated text that any model predicts.
Two further results complete the picture. Larger language models memorize faster, and can memorize a larger fraction of their data before they overfit (Tirumala, Markosyan, Zettlemoyer & Aghajanyan, 2022). And for some natural prediction tasks, such as next-symbol prediction and labeling clusters, every sufficiently accurate learner must encode nearly all the information about many of its training examples, irrelevant information included (Brown, Bun, Feldman, Smith & Talwar, 2021).
Which training text is likely to have the highest counterfactual memorization in a language model?
- A unique document seen once, whose details the model reproduces only when it was trained on it
- A software license that appears thousands of times in the corpus
- A common English phrase
- A document the model predicts equally well whether or not it was in the training set
Show the answer
A. A unique document seen once, whose details the model reproduces only when it was trained on it
Counterfactual memorization is the change in the model's predictions on a document when that document is removed from training. A license or a common phrase has many other copies or is predictable anyway, so removing one occurrence changes little; a unique document is predicted well only if it was seen. Verbatim extraction, by contrast, is dominated by duplicated text.
Privacy and the price of the tail
Memorized examples can leak, and differential privacy exists to prevent exactly that. An algorithm is -differentially private if for any two training sets and that differ by one example and any set of possible outputs, (Dwork et al., 2006). DP-SGD achieves this for deep networks by clipping each example's gradient and adding Gaussian noise (Abadi et al., 2016). By construction, no single example can change the model much, and that caps memorization.
Apply the definition to the event "the model labels as ", with :
Subtract the second probability from both sides: every memorization score is capped,
Now take a singleton whose label the rest of the data cannot predict: given it is uniform over classes. Averaged over that label, a model trained without the example is right with probability , so a model trained with it is right with probability at most
This is Feldman's bound for private algorithms, which he proves even when only a change of the example's label must be protected. Each such singleton is mislabeled with probability at least , and by Feldman's theorem each mislabeling costs about : a private learner pays in proportion to the mass of its tail. The cap is informative only while , that is, .
A model is trained with -differential privacy at and negligible , on 10 equally likely classes. At most what probability can it have of correctly labeling a singleton whose label the rest of the data cannot predict?
Show the answer
0.74
, against nearly 1 for a model free to memorize. At the cap is ; from upward it exceeds 1 and says nothing about this example. Strong privacy and fitting the unpredictable tail are incompatible.
The theory also predicts where the cost lands: on the tail, which is where small groups live. Bagdasaryan, Poursaeed and Shmatikov (2019) observed exactly this. Models trained with DP-SGD lost much more accuracy on underrepresented classes and subgroups than on the majority: a gender classifier on faces lost more accuracy on darker-skinned faces, and similar gaps appeared for sentiment analysis of tweets in African-American English and for underrepresented species in iNaturalist. Where the non-private model was already less accurate on a group, the private model widened the gap: "the poor become poorer". The authors traced the effect to gradient clipping and noise, which suppress the contributions of rare, hard examples the most; Feldman's theory explains why the lost accuracy cannot be recovered without memorizing.
Privacy is not the only force that trims the tail. Pruning and quantization preserve top-line accuracy while disproportionately hurting a small set of atypical or noisy examples from the long tail (Hooker, Courville, Clark, Dauphin & Frome, 2019; Pruning, Sparsity & Lottery Tickets). Training on generated data erases the tails first (Synthetic Data & Model Collapse). And an average accuracy can hide all of this, which is why robustness work tracks the worst group (Shortcut Learning & Spurious Correlations).
Key takeaways
- On long-tailed data, an algorithm's excess test error is at least times the number of singletons it mislabels, where is the expected frequency of a subpopulation seen exactly once (Feldman, 2020). For a Zipf prior with , , and not fitting the singletons costs about 7 points against an optimal 15%.
- Memorization scores, , estimated from thousands of models trained on random 70% subsets, are high for atypical, ambiguous and mislabeled examples. On ImageNet about 32% of the examples score at least 0.3 and are worth more than random ones, and many test examples are rescued by a single memorized training relative (Feldman & Zhang, 2020).
- In language models, extractable memorization grows log-linearly with model size, duplication and prompt length (Carlini et al., 2023); deduplication cuts emitted memorized text about tenfold (Lee et al., 2022); counterfactual memorization separates rare memorized documents from common or repeated text.
- -differential privacy caps every memorization score at and accuracy on an unpredictable singleton at , so its cost lands on the tail: DP-SGD hurts underrepresented groups most (Bagdasaryan, Poursaeed & Shmatikov, 2019), and compression and synthetic data trim the tail too.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
What does measure in Feldman's theorem?
- The fraction of training examples that are singletons
- The probability that a singleton is mislabeled
- The expected frequency of a subpopulation given that it appears exactly once in the training set, which is the expected test error caused by mislabeling one singleton
- The error of the optimal algorithm
Show the answer
C. The expected frequency of a subpopulation given that it appears exactly once in the training set, which is the expected test error caused by mislabeling one singleton
By Bayes' rule, . Mislabeling a singleton mislabels its whole subpopulation at test time, a fraction of the distribution, so each mislabeled singleton costs in expectation.
An image has an exact duplicate elsewhere in the training set, and the network fits both copies perfectly. Why does each copy get a low memorization score?
- Because the network ignores duplicated images
- Because duplicates are always mislabeled
- Because memorization scores are computed only on test images
- Because when one copy is left out, the other usually remains, so the model trained without the example still classifies it correctly
Show the answer
D. Because when one copy is left out, the other usually remains, so the model trained without the example still classifies it correctly
The score is the accuracy on with in the training set minus the accuracy without it. With a twin present the second term stays high, so the difference is small: with random 70% subsets, roughly the 30% chance that the twin is also missing. Memorization in Feldman's sense is about information that only this example provides.
A model trained with differential privacy loses more accuracy on an underrepresented subgroup than on the majority. Why does the long-tail theory predict this?
- Privacy noise is added only to the minority's examples
- Differential privacy caps how much any single example can change the model, which limits memorization; a small subgroup has more examples that are singletons or nearly so, and each unfitted one costs about
- The minority's labels are noisier
- Private training uses fewer epochs
Show the answer
B. Differential privacy caps how much any single example can change the model, which limits memorization; a small subgroup has more examples that are singletons or nearly so, and each unfitted one costs about
An -private algorithm can raise its accuracy on an example by including it only by a bounded factor, so it cannot memorize the tail. The tail is where small groups live: more of their subpopulations are seen once or a few times, so they absorb more of the cost.
GPT-2 models completed about 6% of Carlini et al.'s evaluation sequences from the Pile, while a GPT-Neo of similar size trained on the Pile completed about 40%. What does the comparison establish?
- That most of the sequences GPT-Neo completes are memorized from its training data, not predictable from general language skill
- That GPT-2 is a better language model than GPT-Neo
- That memorization is independent of the training data
- That deduplication has no effect on memorization
Show the answer
A. That most of the sequences GPT-Neo completes are memorized from its training data, not predictable from general language skill
GPT-2 never trained on the Pile, so it measures how many of these sequences any good language model could complete. The gap, 40% against 6%, is what GPT-Neo stored from its own training data; the few sequences GPT-2 completed were mostly predictable ones such as number sequences and repetitions.
Further reading
- V. Feldman, "Does learning require memorization? A short tale about a long tail," STOC (2020).
- V. Feldman & C. Zhang, "What neural networks memorize and why: discovering the long tail via influence estimation," NeurIPS (2020).
- N. Carlini, D. Ippolito, M. Jagielski, K. Lee, F. Tramèr & C. Zhang, "Quantifying memorization across neural language models," ICLR (2023).
- K. Lee, D. Ippolito, A. Nystrom, C. Zhang, D. Eck, C. Callison-Burch & N. Carlini, "Deduplicating training data makes language models better," ACL (2022).
- C. Zhang, D. Ippolito, K. Lee, M. Jagielski, F. Tramèr & N. Carlini, "Counterfactual memorization in neural language models," NeurIPS (2023).
- E. Bagdasaryan, O. Poursaeed & V. Shmatikov, "Differential privacy has disparate impact on model accuracy," NeurIPS (2019).