Log inStart free
LESSON 11.02 · 6 STAGES · 3 CONTROLS · 3 CHECKS

Masked language modeling

Watch a model hide words in a text and guess them from both sides.


EXPLAINER · 11.02 · TRAINING BAY
01
Stage 1 of 6 · Pick tokens
Masked language modeling picks 15% of the tokens at random. Here it picks 3 of 20.
Explain it simply

You see a short text of 20 words. The outlined words are the picks, chosen at random. The model must later guess each pick. With 15 percent, 3 of the 20 words are picked.

A row of 20 word cells. 3 cells have an outline: token 2, bird; token 10, ate; token 18, the.

tokenpick, mask rate[MASK]random word, lossprediction
Toy: 20 tokens, word pairs counted in 14 sentences
HOVER OR TAP A SHAPE TO SEE ITS NUMBERS
Both sides
Which side of a pick the model reads.
15%
The share of tokens the model must guess.
80/10/10
What each picked token turns into.
STAGE 1 / 6
MATH · STAGE 1HOVER A SYMBOL OR A SHAPE
k=round⁡(r⋅n)\sy{k}{param}{k} = \operatorname{round}(\sy{r}{param}{r}\cdot \sy{n}{data}{n})
k=round⁡(0.15⋅20)=3k = \operatorname{round}(0.15\cdot 20) = 3

The number of picks is the rate times the text length, rounded.

Show the code ▾Hide the code ▴ · Try it yourself · Python 3
import math

corpus = [
    "the cat sat on the mat .",
    "the dog sat on the rug .",
    "the bird sat in the tree .",
    "the cat sat on the rug .",
    "the dog sat on the mat .",
    "the cat sat in the tree .",
    "the bird sang in the tree .",
    "the bird sang on the mat .",
    "the cat ate the fish .",
    "the dog ate the bone .",
    "the bird ate the seed .",
    "the dog ate the fish .",
    "the cat ate the bird .",
    "the dog sat on the bone .",
]
vocab = ["the", "cat", "dog", "bird", "sat", "ate", "sang", "on", "in", "mat", "rug", "tree", "fish", "bone", "seed", "."]
V, k = len(vocab), 0.01  # 16 words, add-k smoothing
count = {a: {b: 0 for b in vocab} for a in vocab}
for s in corpus:
    prev = "."
    for w in s.split():
        count[prev][w] += 1
        prev = w
T = {a: {b: (count[a][b] + k) / (sum(count[a].values()) + k * V) for b in vocab} for a in vocab}

text = "the bird sang in the tree . the dog ate the bone . the cat sat on the mat .".split()
n = len(text)  # 20
# one seeded draw (seed 607): the shuffled positions, a fate number u and a random word per position
order = [9, 1, 17, 2, 14, 0, 8, 12, 5, 4, 3, 11, 10, 13, 7, 19, 16, 6, 18, 15]
u = [0.431, 0.682, 0.285, 0.720, 0.766, 0.646, 0.998, 0.971, 0.735, 0.806, 0.781, 0.371, 0.154, 0.762, 0.251, 0.185, 0.325, 0.923, 0.442, 0.937]
rand = [4, 4, 15, 1, 5, 11, 14, 0, 7, 6, 10, 9, 8, 3, 13, 10, 14, 9, 5, 1]

rate, rule, context = 0.15, "80/10/10", "both sides"
picks = sorted(order[: round(rate * n)])
x = list(text)
for i in picks:
    if rule == "all mask" or u[i] < 0.8:
        x[i] = "[MASK]"
    elif u[i] < 0.9:
        x[i] = vocab[rand[i]]
print(" ".join(x))  # the [MASK] sang in the tree . the dog sang the bone . the cat sat on the mat .

def e(o, w):  # the chance that the original word w shows as token o
    if o == "[MASK]":
        return rate * (1 if rule == "all mask" else 0.8)
    if rule == "all mask":
        return (1 - rate) * (o == w)
    return (1 - rate) * (o == w) + rate * (0.1 / V + 0.1 * (o == w))

def norm(p):
    s = sum(p.values())
    return {w: v / s for w, v in p.items()}

L, a = [], dict(T['.'])  # left messages: P(word | tokens before)
for i in range(n):
    L.append(norm(a))
    f = norm({w: L[i][w] * e(x[i], w) for w in vocab})
    a = {b: sum(f[w] * T[w][b] for w in vocab) for b in vocab}
R, b = [None] * n, {w: 1.0 for w in vocab}  # right messages: P(tokens after | word)
R[n - 1] = norm(b)
for i in range(n - 2, -1, -1):
    b = norm({w: sum(T[w][v] * e(x[i + 1], v) * b[v] for v in vocab) for w in vocab})
    R[i] = b

loss = 0
for i in picks:
    if context == "left only":
        p = L[i]
    else:
        p = norm({w: L[i][w] * R[i][w] * e(x[i], w) for w in vocab})
    loss -= math.log(p[text[i]])
    print(i + 1, text[i], x[i], f"{p[text[i]]:.2f}")
    # 2 bird [MASK] 0.96
    # 10 ate sang 0.95
    # 18 the the 1.00
print(f"{loss / len(picks):.2f}")  # 0.03

Copy it into a file and run it. It prints the input and each pick's chance.

Common mix-ups

MYTHThe model learns only from the [MASK] tokens.

FIXA random word and a kept word are picks too. At token 10 the model reads sang and must still answer ate.

MYTHMasking more tokens gives the model more to learn.

FIXMore picks leave less context. At 80%, bird gets only 0.29, and the mean loss per pick rises to 0.94.

Predict, then reveal
0 / 3 REVEALED
Q01If the model reads only the left side, does the loss at token 2 go up or down?
1 · GUESS2 · TRY IT IN THE DIAGRAM
Q02Reading both sides at a 40% mask rate, is bird easier or harder to guess?
1 · GUESS2 · TRY IT IN THE DIAGRAM
Q03If every pick becomes [MASK], how sure is the model of a word it can see?
1 · GUESS2 · TRY IT IN THE DIAGRAM

Takeaways

  1. Masked language modeling hides 15% of tokens and predicts them from both sides.
  2. The loss counts only the picks, so a pass trains on few tokens.
  3. Random and kept picks make the model check every word it sees.