Sub topic 9
Unequal data and temperature-based language sampling
This chapter assumes you know how a masked language model is pretrained, what a batch and an epoch are, and how to read basic NumPy. The previous chapters covered the shared vocabulary and the pretraining setup. Here we look at one decision inside that setup: how often each language appears in training.
The problem: web text is very unequal
Multilingual pretraining corpora such as Wikipedia or CommonCrawl are dominated by a few languages. English can have hundreds of times more text than Swahili. If you shuffle all the text together and sample uniformly, the model sees languages in proportion to their size. Two things follow:
- Low-resource languages are a tiny fraction of the updates. The model may learn little about them, and its shared representations may not cover them well.
- The vocabulary and the model's capacity drift toward the largest languages.
The opposite fix is to sample every language equally. This also fails. A language with 10 MB of text would be repeated thousands of times, and the model would memorize it instead of learning from it. High-resource languages would also get far fewer updates than they could use.
Temperature-based sampling sits between these two extremes and lets you choose where.
The sampling formula
Let n_i be the amount of data in language i (sentences, tokens, or bytes). The natural proportion is:
p_i = n_i / sum_j n_j
The sampling probability used in training is the smoothed version:
q_i = p_i^alpha / sum_j p_j^alpha
The exponent alpha is between 0 and 1. Some papers instead use a temperature T = 1 / alpha and write p_i^(1/T). The two forms are equivalent.
| alpha | T | Behavior |
|---|---|---|
| 1.0 | 1 | Natural proportions. Large languages dominate. |
| 0.7 | about 1.4 | Mild smoothing. mBERT used a smoothing factor of 0.7. |
| 0.5 | 2 | Square-root smoothing. Used in the original XLM. |
| 0.3 | about 3.3 | Strong smoothing. Used by XLM-R and mT5. |
| 0.0 | infinite | Uniform over languages. |
Raising to a power below 1 compresses differences. The big languages lose share and the small ones gain it. Renormalizing makes the result a probability distribution again.
Computing it
The code below uses invented corpus sizes, in millions of sentences, for four languages. It prints the natural proportions, the smoothed ones, and how many times each language's data is repeated.
import numpy as np
sizes = {"en": 3000.0, "de": 800.0, "hi": 100.0, "sw": 10.0}
langs = list(sizes)
n = np.array([sizes[l] for l in langs])
p = n / n.sum()
def sampling_probs(p, alpha):
w = p ** alpha
return w / w.sum()
for alpha in [1.0, 0.5, 0.3, 0.0]:
q = sampling_probs(p, alpha)
print(f"alpha={alpha}")
for lang, p_i, q_i in zip(langs, p, q):
# q/p = passes over this language's data, relative to one
# natural-size training budget
print(f" {lang}: p={p_i:.4f} q={q_i:.4f} repeat factor={q_i / p_i:.2f}")With alpha=0.3 the output is approximately:
| Language | Natural p | Smoothed q | Repeat factor q/p |
|---|---|---|---|
| en | 0.767 | 0.452 | 0.59 |
| de | 0.205 | 0.304 | 1.49 |
| hi | 0.026 | 0.163 | 6.4 |
| sw | 0.003 | 0.082 | 32 |
English drops from 77% to 45% of the sampled data. Swahili rises from 0.3% to about 8%. The last column is the key diagnostic. If your training budget equals one natural pass over the whole corpus, Swahili is seen about 32 times and English about 0.6 times. That repeat factor is where the risk of overfitting comes from.
Drawing the languages during training
A simple sampler picks a language for each batch from q and then reads a batch from that language's data stream.
import numpy as np
rng = np.random.default_rng(0)
langs = ["en", "de", "hi", "sw"]
q = np.array([0.452, 0.304, 0.163, 0.081])
q = q / q.sum() # guard against rounding in the hand-typed values
counts = {l: 0 for l in langs}
for _ in range(10_000):
lang = rng.choice(langs, p=q)
counts[str(lang)] += 1
print(counts)Over 10,000 draws the counts approach q times 10,000. In a real pipeline each language is typically a streaming dataset that loops when it runs out. That looping is how a small language is repeated many times.
Where to apply the sampling
The smoothing can be applied at different granularities. Sampling per batch keeps each batch single-language, which can make the batch statistics less representative. Sampling per example mixes languages inside a batch, which usually gives smoother gradients but needs all corpora open at once. Both implement the same q. They differ in the variance of the training signal.
It also applies to the vocabulary
The tokenizer is trained on text too. XLM-R trains its SentencePiece model on a sample drawn with the same kind of smoothing, with alpha = 0.3. Without that, the 250,000 pieces would mostly be English and other large-language pieces. Low-resource languages would be split into many short fragments. Smoothing before tokenizer training gives small languages more whole-word and long-subword pieces. It does not remove the problem entirely, as the later chapter on tokenization disparity shows.
Choosing alpha
There is no universal best value. The trade-off looks like this.
- Higher alpha (closer to 1). High-resource languages get the best possible performance. Low-resource languages lag, and transfer to them from related languages is weaker.
- Lower alpha (closer to 0). Low-resource languages improve, up to a point. High-resource languages lose accuracy because they get fewer updates, and tiny corpora are repeated many times and overfit.
- Moderate alpha (0.3 to 0.5). This is the common compromise. The XLM and XLM-R papers report that moving from natural sampling toward smoothing helps low-resource languages at a small cost to high-resource ones.
When you pick a value, check the repeat factor for your smallest language against your total training budget. A repeat factor of 30 on a 10 MB corpus means the model sees the same sentences dozens of times. Past a few epochs, extra repeats mostly help memorization.
A related approach, UniMax, takes this idea directly. It samples close to uniformly but caps the number of epochs over any one language, so small corpora are not repeated beyond a chosen limit. It is a different knob for the same trade-off.
Failure modes
- Overfitting the smallest languages. Training loss for the tiny language falls while its downstream accuracy stalls. Watch per-language validation perplexity, not just the average.
- Noisy language labels. Smoothing amplifies bad data. If a language's corpus is 20% misidentified text, upsampling it by 30 times upsamples the noise by 30 times. Clean and deduplicate before you set
alpha. - Averaging hides the damage. An overall score is dominated by whichever languages are most numerous in the evaluation set. Report per-language numbers, as covered in the benchmarks chapter.
- Interaction with capacity. Giving more weight to many languages does not add parameters. Raising the share of small languages puts more pressure on a fixed-size model, which connects to the next chapter on the curse of multilinguality.
Exercise
Two languages have natural proportions p = 0.9 and p = 0.1. Compute the sampling probabilities with alpha = 0.5 and the repeat factor for the smaller language.
Show answer
Square roots are about 0.9487 and 0.3162, summing to about 1.2649. So q is about 0.75 and 0.25. The repeat factor for the smaller language is q/p = 0.25 / 0.1 = 2.5, so it is seen 2.5 times per natural-size budget.
Exercise
A team lowers alpha from 0.5 to 0.2 and sees the average XNLI-style accuracy stay flat, but accuracy on its smallest language drops. Give two plausible causes and one check for each.
Show answer
(1) Overfitting from heavy repetition: check the repeat factor and the validation loss of that language across training. (2) Starvation of larger related languages that the small language relied on for transfer: check whether accuracy on those larger languages also fell, and compare against a run with a moderate alpha. The flat average hides these effects, so compare per-language scores.