Data mixtures: which examples get the next update?
预训练数据混合
Separate document and token shares, train a two-domain model, and compare raw-loss and reference-adjusted reweighting.
data-mixturesHalf the documents need not mean half the tokens
Suppose you sample documents equally from two domains. Documents in the first contain one token on average; documents in the second contain eight. After enough draws, the second domain supplies about eight ninths of the tokens, even though both supplied half the documents. “A 50–50 mixture” is incomplete until you specify what is being counted.
Pretraining datasets combine sources with different lengths, repetition rates, vocabulary and difficulty. The GPT-3 paper, section 2.2, describes adding reference corpora to a filtered web corpus and deduplicating within and across datasets. That establishes a concrete example of a constructed training mix; it does not tell us that one set of proportions is best for every model.
The next question is which domains deserve more updates. High loss can signal something still learnable—or something intrinsically unpredictable. DoReMi uses a reference model to distinguish the proxy model’s loss from a reference level, rather than simply assigning more weight to whichever domain has the largest raw loss.
Sampling, optimization and evaluation can use different weights
Let be a domain distribution and let nonnegative weights sum to one. A mixture first chooses a domain and then draws an example from that domain:
If the sampling unit is a document with mean token length , the long-run token share under independent repeated draws is
This conversion assumes finite positive mean lengths and that the sampled documents are fully consumed. Fixed-length chunking, packing, truncation and dropping partial batches can change the relation. A mixture defined directly over token chunks needs its own accounting.
For stated per-domain mean token losses , a weighted objective is
Here the weights apply to domain losses already normalized per token. They do not automatically equal document-sampling probabilities from the previous equation. The code below uses exact population losses for two one-token domains, so this ambiguity disappears in the training calculation.
Our two domains generate a binary label with probabilities and . One shared scalar logit predicts for both. It cannot represent both target probabilities simultaneously. With Bernoulli cross-entropy, differentiating the weighted objective gives
This closed form is an analytic baseline for the actual gradient updates. Uniform weights yield . Changing the mixture changes the best shared prediction; it does not give the one-parameter model a second parameter.
Reference adjustment needs care. Let and be losses on token in domain , containing tokens. Compare the mean excess with a tokenwise-clipped mean:
They need not rank domains in the same order. DoReMi’s equation 1 defines a mean-excess minimax objective, while Algorithm 1 clips per-token excess losses before aggregating the scores used to update domain weights. Averaging first and clipping later changes that algorithm. The paper explicitly describes this implementation detail.
Exponentiated ascent raises weights on domains with larger scores, then mixes in a small uniform component to avoid losing coverage:
Here is the weight step size and the smoothing weight. The proxy then receives a gradient update using the current domain weights. In our example that gradient is the weighted cross-entropy gradient above; the fixed reference loss has zero derivative. We do not differentiate the clipped score as though it were the proxy’s replacement loss.
DoReMi returns time-averaged domain weights for a subsequent main-model training run:
These weights are not necessarily the last iterate. The original method trains a small reference model, tunes weights with a small proxy, and trains a larger main model using the resulting mix. The teaching experiment substitutes known synthetic domain probabilities for the reference and retrains the same small model capacity, so it cannot establish transfer to a larger model.
Watch the trade-off move between two domains
Run with Python 3.12 and NumPy 1.26.4. The program uses exact expectations over the two Bernoulli labels rather than randomly sampled text. It compares a fixed uniform mixture with 1,000 reweighting steps based on raw loss or tokenwise-clipped reference excess. Weight learning rate 0.4, smoothing 0.01 and model learning rate 0.15 are teaching choices, not the paper’s hyperparameters.
"""Exact two-domain Bernoulli teaching problem; not a DoReMi replication."""
import json
import math
import numpy as np
TARGETS=np.array([.9,.5])
def normalized(weights):
w=np.asarray(weights,float)
if w.shape!=(2,) or not np.all(np.isfinite(w)) or np.any(w<0) or w.sum()<=0:
raise ValueError("Need two finite nonnegative weights with positive sum")
return w/w.sum()
def sigmoid(w):
return float(np.exp(-np.logaddexp(0.,-w)))
def domain_losses(w):
return np.logaddexp(0.,w)-TARGETS*w
def clipped_excess(w):
# Known synthetic domain oracles replace the paper's trained reference model.
one=np.logaddexp(0.,-w)+np.log(TARGETS)
zero=np.logaddexp(0.,w)+np.log1p(-TARGETS)
return TARGETS*np.maximum(one,0)+(1-TARGETS)*np.maximum(zero,0)
def update_weights(weights, scores, eta=.4, smoothing=.01):
weights=normalized(weights);scores=np.asarray(scores,float)
if scores.shape!=(2,) or not np.all(np.isfinite(scores)) or np.any(scores<0):
raise ValueError("Need two nonnegative finite scores")
if not math.isfinite(eta) or eta<0 or not 0<=smoothing<=1:
raise ValueError("Invalid step or smoothing")
active=weights>0
logits=np.full(2,-np.inf)
logits[active]=np.log(weights[active])+eta*(scores[active]-scores[active].max())
new=np.exp(logits-logits.max());new/=new.sum()
return (1-smoothing)*new+smoothing/2
def fit_fixed(weights,steps=1000):
weights=normalized(weights);w=0.
for _ in range(steps):
w-=.15*float(weights@(sigmoid(w)-TARGETS))
return dict(q=sigmoid(w),losses=domain_losses(w).tolist(),
known_optimum=float(weights@TARGETS))
def tune(mode='excess',steps=1000):
if mode not in {'raw','excess'} or not isinstance(steps,int) or steps<=0:
raise ValueError("Choose raw/excess and a positive step count")
weights=np.array([.5,.5]);total=np.zeros(2);w=0.;trace=[]
for t in range(steps):
scores=clipped_excess(w) if mode=='excess' else domain_losses(w)
weights=update_weights(weights,scores)
total+=weights
w-=.15*float(weights@(sigmoid(w)-TARGETS))
if t%100==0 or t==steps-1:
trace.append(dict(step=t+1,q=sigmoid(w),weight=weights.tolist(),scores=scores.tolist()))
average=total/steps
return dict(average=average.tolist(),last=weights.tolist(),trace=trace,
fresh_model=fit_fixed(average))
def token_shares(domain_weights,mean_lengths):
weights=normalized(domain_weights);lengths=np.asarray(mean_lengths,float)
if lengths.shape!=(2,) or not np.all(np.isfinite(lengths)) or np.any(lengths<=0):
raise ValueError("Positive finite mean document lengths required")
weighted=weights*lengths
return (weighted/weighted.sum()).tolist()
def demo():
w=math.log(.7/.3)
entropy=-(TARGETS*np.log(TARGETS)+(1-TARGETS)*np.log1p(-TARGETS))
return dict(targets=TARGETS.tolist(),entropy=entropy.tolist(),
uniform=fit_fixed([.5,.5]),raw=tune('raw'),excess=tune('excess'),
token_shares=token_shares([.5,.5],[1.,8.]),
at_q_point7=dict(raw=domain_losses(w).tolist(),
mean_excess=(domain_losses(w)-entropy).tolist(),
clipped_token_excess=clipped_excess(w).tolist()))
if __name__=='__main__':
print(json.dumps(demo(),indent=2))
At prediction , raw losses are about 0.441405 and 0.780324. The second domain has larger raw loss. Subtracting each domain’s oracle entropy gives mean excesses about 0.116322 and 0.087177, so the first is larger. Clipping each token’s excess before averaging gives about 0.226183 and 0.255413, reversing that ordering again. The exact placement of a max changes the weighting signal.
The raw-loss procedure averages about 0.137943 weight on the first domain; a fresh model trained with that mixture predicts about 0.555177. The reference-adjusted procedure averages about 0.488451 on the first domain and predicts about 0.695381. Its losses are approximately 0.445836 and 0.775994, versus 0.610629 and 0.699274 under raw-loss weights. The first domain improves and the second worsens. The uniform analytic baseline remains competitive and is slightly better on an equal-weight average than the reference-adjusted result. This experiment does not award the adaptive method a universal win.
The code uses log-space weight updates on the currently positive support. A boundary test with weights [1,0] and scores [0,10000] checks that numerical underflow cannot destroy the update before smoothing restores positive coverage. Independent finite differences verify the model gradient; a hand calculation checks the exponential weight ratio; fixed-mixture training matches its closed-form optimum.
For domains and full-population steps in this tiny model, scalar-domain arithmetic costs . The retained trace adds storage proportional to the number of snapshots; without it, the update needs working memory. Actual language-model forward/backward passes, reference-score computation, data loading and the reference/proxy runs dominate the corresponding real system costs.
Weights are a policy, not a quality label
A domain can receive low weight because the proxy already models it well, because it has high irreducible uncertainty, or because the chosen reference is poor. Those interpretations are not interchangeable. Reference-model mismatch can distort the apparent learning headroom; a domain average can also hide a harmed subgroup.
Keep the evaluation mix fixed when comparing training mixes, and report per-domain results alongside the aggregate. Otherwise, changing the test weights can make a model appear better without changing any predictions. Oversampling a small domain increases repeated exposure; it does not create new independent data. Deduplicate before auditing effective exposure, and keep held-out evaluation text out of mixture tuning unless it is explicitly a development set.
The toy’s one shared logit deliberately limits capacity. A domain-conditioned model with separate parameters could represent both probabilities, changing the trade-off. DoReMi’s larger-model transfer is an empirical question in the original paper, not something established by our scalar calculation. A fixed mixture based on clear requirements and a held-out sweep is often the right baseline before adding an adaptive weighting procedure.
Name the denominator before choosing the weights
- Two domains are drawn equally by document and have mean lengths 1 and 8. What token shares do you expect?
Answer: Expected token masses are 0.5 and 4, totaling 4.5. Shares are and . Equal document probabilities are not equal token exposure under this sampling policy.
- With label probabilities 0.9 and 0.5 and mixture weights 0.8 and 0.2, what is the optimal shared prediction?
Answer: . The weighted gradient vanishes there. The answer is neither domain’s true probability because one shared parameter compromises between them.
- Why can clipping each token before averaging disagree with clipping a mean excess afterward?
Answer: Positive and negative token differences cancel in the mean; tokenwise clipping removes the negative terms first. At , the example’s two versions even reverse the domain ranking. Neither operation can be substituted for the other without changing the procedure.
- The adaptive mix improves one domain’s loss and hurts another’s. What should a report show?
Answer: Both domain results, the fixed evaluation weights, the uniform or requirement-based baseline, and the cost of learning the weights. An average alone can conceal the trade-off, and a scalar proxy does not prove a benefit for a larger main model.
Treat a mixture recipe as an experimental choice
DoReMi, section 2 and Algorithm 1, supports the reference/proxy/main workflow, clipped scoring detail, smoothed exponential update and average weights. GPT-3, section 2.2, supplies an example of combining and deduplicating multiple data sources, not a justification for this chapter’s synthetic proportions. No paper benchmark is reproduced. Continue with training-data deduplication to inspect whether apparent data exposure is actually repeated content.
Make a prediction, then check
Two domains are sampled equally by document, with mean lengths 1 and 8. What are their expected token shares?
Learning objectives
- Convert domain sampling weights into expected token exposure under variable lengths.
- Derive the weighted Bernoulli optimum and inspect per-domain trade-offs.
- Distinguish mean excess loss from clipping each token before aggregation.
Prerequisites & connections
Explore related knowledge →References
- DoReMi: Optimizing Data Mixtures Speeds Up Language Model Pretraining
Sang Michael Xie; Hieu Pham; Xuanyi Dong; Nan Du; Hanxiao Liu; Yifeng Lu; Percy Liang; Quoc V. Le; Tengyu Ma; Adams Wei Yu · 2023 - Language Models are Few-Shot Learners — NeurIPS 2020
Tom B. Brown; Benjamin Mann; Nick Ryder; Melanie Subbiah; Jared Kaplan; Prafulla Dhariwal; Arvind Neelakantan; Pranav Shyam; Girish Sastry; Amanda Askell; Sandhini Agarwal; Ariel Herbert-Voss; Gretchen Krueger; Tom Henighan; Rewon Child; Aditya Ramesh; Daniel M. Ziegler; Jeffrey Wu; Clemens Winter; Christopher Hesse; Mark Chen; Eric Sigler; Mateusz Litwin; Scott Gray; Benjamin Chess; Jack Clark; Christopher Berner; Sam McCandlish; Alec Radford; Ilya Sutskever; Dario Amodei · 2020
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-20 · Single AI author read DoReMi section2/equation1/Algorithm1, viewed PDF3/4, and additionally read GPT3 conference section2.2. Seven paired equations and four explained exercises. Exact two-domain Bernoulli training, analytic fixed-mixture optimum, independent gradient checks, tokenwise clipping versus mean excess, stable log-weight boundary and domain trade-offs. Known synthetic reference, same-capacity retraining; no larger-model transfer claim.
- Single AI author read DoReMi section2/equation1/Algorithm1, viewed PDF3/4, and additionally read GPT3 conference section2.2. Seven paired equations and four explained exercises. Exact two-domain Bernoulli training, analytic fixed-mixture optimum, independent gradient checks, tokenwise clipping versus mean excess, stable log-weight boundary and domain trade-offs. Known synthetic reference, same-capacity retraining; no larger-model transfer claim.
- Four computed SVG variants per topic;9 numeric/geometry tests and18 responsive cases passed. Six final Chinese-mobile/English-desktop screenshots actually inspected. Full article acceptance recorded separately.
Source locations checked:
- DoReMi: Optimizing Data Mixtures Speeds Up Language Model Pretraining · Read section 2, equation 1 and Algorithm 1; visually checked PDF pages 3–4. Reference/proxy/main separation, per-token clipping before domain aggregation, exponentiated updates and averaged weights. No benchmark or large-model transfer reproduced.
- Language Models are Few-Shot Learners — NeurIPS 2020 · Original Source object/access date preserved; additionally read section2.2 text lines150–178 on reference corpora added to filtered web text and fuzzy deduplication within/across datasets. No mixing-weight performance claim.
Related topics