Multilingual Pre-training and Data Balancing › Implementation: Building and Inspecting a Mixture
Language AI HandbookAll chapters We start with imports and an illustrative corpus. The counts are the ones in the table above, in millions of surviving documents.
The code in this section is deliberately minimal. The sampler itself is three lines; everything else is diagnostics, because the diagnostics are where the understanding lives. The goal is not to provide a production data loader but to make the quantities in the equations visible and manipulable.
PythonIn [7]Expand
import numpy as np
import pandas as pd
rng = np.random.default_rng(7)
languages = [
"English",
"Chinese",
"Spanish",
"Arabic",
"Hindi",
"Swahili",
"Welsh",
"Yoruba",
]
# Millions of documents surviving filtering. Skewed, but less skewed than raw crawl.
p = tilt_pThese illustrative counts define a large head and small tail. All language shares in the fixture are positive, so the code’s zero-exponent endpoint is unambiguous on this input.
The sampling function is three lines. Everything else in this section is diagnostics.
PythonIn [8]Expand
def temperature_mixture(p, alpha):
"""Renormalised mixture weights q_i proportional to p_i ** alpha."""
w = np.power(p, alpha)
return w / w.sum()
alphas = [1.0, 0.5, 0.3, 0.1, 0.0]This helper only normalizes the exponentiated shares. The chapter gives a separate cap function, shows document-to-token conversion inline, and specifies language multipliers in an equation.
Now build the comparison table. At the column is just the natural share; at every language is at 0.125.
PythonIn [9]Expand
table = pd.DataFrame({"p (natural)": p}, index=languages)
for a in alphas:
table[f"alpha={a}"] = temperature_mixture(p, a)
mixture_shares = table.iloc[:, 1:].to_numpy().T
print(table.round(4).to_string())ConsoleOut [9]Expand
p (natural) alpha=1.0 alpha=0.5 alpha=0.3 alpha=0.1 alpha=0.0 English 0.5772 0.5772 0.3358 0.2410 0.1591 0.125 Chinese 0.1757 0.1757 0.1852 0.1687 0.1413 0.125 Spanish 0.1004 0.1004 0.1400 0.1426 0.1336 0.125 Arabic 0.0690 0.0690 0.1161 0.1275 0.1287 0.125 Hindi 0.0502 0.0502 0.0990 0.1158 0.1247 0.125 Swahili 0.0151 0.0151 0.0542 0.0807 0.1105 0.125 Welsh 0.0075 0.0075 0.0383 0.0656 0.1031 0.125 Yoruba 0.0050 0.0050 0.0313 0.0581 0.0990 0.125
Reading the table from left to right shows the compression directly. At the columns are the natural shares. At the ratio between English and Yoruba has fallen from roughly 115:1 to roughly 11:1. At it is roughly 4:1. At it is 1:1. The head never disappears until the exponent hits zero, which is why temperature sampling is described as compression rather than balancing.
The table also shows a subtlety that is easy to miss: the middle-tier languages move relatively little compared to the extremes. Spanish at 10% goes to about 14% at , while English falls from 57.7% to 24.1% and Yoruba's share rises nearly twelvefold. Temperature sampling is most active at the extremes; the middle is comparatively stable.
At , English falls from 57.7% to about 24.1% of the mixture while Yoruba rises from 0.50% to about 5.8%. Note that the head is still larger than the tail: temperature sampling compresses the distribution, it does not flatten it.
The share alone hides the repetition cost, so let us compute effective epochs directly.
PythonIn [10]Expand
q03 = temperature_mixture(p, 0.3)
epochs = q03 / p
print(f"{'Language':<10}{'share p':>10}{'share q':>10}{'epochs/pass':>14}")
for lang, pi, qi, ei in zip(languages, p, q03, epochs):
print(f"{lang:<10}{pi:>10.4f}{qi:>10.4f}{ei:>14.2f}")ConsoleOut [10]Expand
Language share p share q epochs/pass English 0.5772 0.2410 0.42 Chinese 0.1757 0.1687 0.96 Spanish 0.1004 0.1426 1.42 Arabic 0.0690 0.1275 1.85 Hindi 0.0502 0.1158 2.31 Swahili 0.0151 0.0807 5.36 Welsh 0.0075 0.0656 8.71 Yoruba 0.0050 0.0581 11.57
English receives about 0.42 effective epochs per pass and Yoruba about 11.6. The second number measures the expected volume of draws from the existing Yoruba corpus.
English at 0.42 means fewer than half as many draws as there are English documents per pass. Yoruba at 11.6 means the expected number of draws is nearly twelve times its corpus size. The loader determines which documents account for those draws.
Figure @fig-temperature-shares shows the same numbers across the exponent grid.
VisualizationOut [11]Expand

The bar heights show English losing share and Yoruba gaining it as the mixture approaches uniform. Middle languages can change direction across the sweep. The ordering of languages is preserved for positive exponents even when an individual language's share rises and then falls.
Figure @fig-effective-epochs plots expected repetition on a log scale. An audit can use these expected rates alongside measured corpus coverage and held-out performance.
VisualizationOut [12]Expand

Above the dashed line, the expected draw volume exceeds the corresponding corpus size. Yoruba is close to 11.6 effective epochs.
The log scale keeps values visible across more than an order of magnitude. The dashed line marks expected draws equal to corpus size.
A mixture table shows Yoruba at 5.8% of the draws. That share gives the loader a budget approaching twelve times the size of the Yoruba corpus per nominal pass.
Capping a language's mixture share
A common share cap limits how much mixture mass any single language can receive. For eight languages, the cap must be at least 12.5% because the shares must sum to one. The algorithm fixes languages that would exceed the cap and divides the remaining mass among the free languages in proportion to their original weights.
PythonIn [13]Expand
def capped_mixture(p, alpha, cap):
"""Return capped shares for a corpus with positive language weights."""
if not p.size or not 1.0 / p.size <= cap <= 1:
raise ValueError(
"The cap must allow all language shares to sum to one."
)
if cap == 1.0 / p.size:
return np.full(p.size, cap)
weights = temperature_mixture(p, alpha)
shares = np.zeros_like(weights)
free = np.ones(p.size, dtype=bool)
while free.any():
remaining = 1.0 - shares.sum()
free_weights = weights[free]
proposed = remaining * free_weights / free_weights.sum()
over = proposed > cap + 1e-12
if not over.any():
shares[free] = proposed
break
fixed = np.flatnonzero(free)[over]
shares[fixed] = cap
free[fixed] = False
return sharesAt the minimum cap, every share must equal the cap. The helper returns that uniform vector directly. Above the minimum, each iteration either finishes or fixes at least one additional language. The tolerance in the loop accounts for small roundoff in candidate shares.
PythonIn [14]Expand
for n_languages in (49, 98):
uniform_cap = 1.0 / n_languages
positive_weights = np.arange(1, n_languages + 1)
np.testing.assert_array_equal(
capped_mixture(positive_weights, 0.3, uniform_cap),
np.full(n_languages, uniform_cap),
)
share_cap = 0.13
capped_shares = capped_mixture(p, 0.3, share_cap)
capped = pd.DataFrame(
{
"alpha=0.3 (uncapped)": q03,
"alpha=0.3, cap=0.15": capped_mixture(p, 0.3, 0.15),
f"alpha=0.3, cap={share_cap:.2f}": capped_shares,
},
index=languages,
)
print(capped.round(4).to_string())ConsoleOut [14]Expand
alpha=0.3 (uncapped) alpha=0.3, cap=0.15 alpha=0.3, cap=0.13 English 0.2410 0.1500 0.1300 Chinese 0.1687 0.1500 0.1300 Spanish 0.1426 0.1500 0.1300 Arabic 0.1275 0.1500 0.1300 Hindi 0.1158 0.1447 0.1300 Swahili 0.0807 0.1008 0.1300 Welsh 0.0656 0.0819 0.1167 Yoruba 0.0581 0.0725 0.1033
At 15%, English falls from 24.1% and Chinese from 16.87% to the cap. A cap of 13% redistributes more mass to the languages that remain below it. A common cap limits absolute mixture share. To limit a particular language to at most effective epochs, use a language-specific bound .
The next figure compares effective epochs before and after applying the 13% share cap. Redistribution increases the expected draw volume for Welsh and Yoruba even though both remain below the cap.
PythonIn [15]Expand
cap_epochs = capped_shares / p
uncapped_epochs = q03 / p
cap_x = np.arange(len(languages))VisualizationOut [16]Expand

The unit question, in code
Fertility changes what a share means. Suppose we sample documents at with the fertility values below. The resulting token shares can differ from the document shares.
The fertility values below are illustrative. Assume equal mean word counts per document across languages so that fertility ratios also give the ratios of mean tokenized document lengths.
PythonIn [17]Expand
# Tokens per whitespace-separated word, illustrative but in the realistic range
fertility = np.array([1.0, 1.6, 1.2, 1.4, 1.8, 2.2, 1.7, 2.6])
expected_tokens_per_word = q03 @ fertility
compute_share = q03 * fertility / expected_tokens_per_wordThis calculation uses token share as a compute proxy under comparable cost per token. Replace the fertility vector by mean tokens per document if average document lengths differ. If processing one group includes extra padding, count those processed positions separately when estimating its compute.
PythonIn [18]Expand
unit_check = pd.DataFrame(
{
"document share": q03,
"tokens per word": fertility,
"token share (compute proxy)": compute_share,
},
index=languages,
)
print(unit_check.round(4).to_string())
print(
f"\nMean tokens per word under this mixture: {expected_tokens_per_word:.2f}"
)ConsoleOut [18]Expand
document share tokens per word token share (compute proxy) English 0.2410 1.0 0.1597 Chinese 0.1687 1.6 0.1789 Spanish 0.1426 1.2 0.1134 Arabic 0.1275 1.4 0.1182 Hindi 0.1158 1.8 0.1382 Swahili 0.0807 2.2 0.1177 Welsh 0.0656 1.7 0.0739 Yoruba 0.0581 2.6 0.1000 Mean tokens per word under this mixture: 1.51
With equal mean document lengths in words, Yoruba’s token share divided by its document share is its fertility divided by the mixture-weighted average fertility, about . With comparable cost per token, this ratio serves as a compute proxy. For a FLOP budget, also account for processing factors such as padding and sequence length.
The lesson is not that one unit is correct. It is that the unit must be stated. A mixture reported in documents and a mixture reported in tokens can look identical in a table and behave very differently in training. When you compare two published mixtures, or when you hand a mixture to an engineer, specify the unit, the fertility assumption, and whether the shares are before or after capping.
The next cell divides each language’s token share by its document share. Bars above one show languages with a larger share of tokens than documents in this example.
PythonIn [19]Expand
unit_ratio = compute_share / q03
unit_x = np.arange(len(languages))VisualizationOut [20]Expand

Comments
Add to the conversation
A question, a correction, or an example from your own work.
No comments yet. Be the first to share your thoughts!