Setting the Blanks

TransformersMedium+20 XP+20

Setting the Blanks

BERT learns language without a single human label: hide some of the words in a sentence and train the model to guess them from everything around them. The text is its own answer key.

Before a sentence reaches the model, a small preprocessing step decides what to hide. It works one position at a time, using random numbers. So that your output can be checked, the random numbers have already been drawn: every position comes with a roll (pick, action, swap).

Step 1: choose positions. A position is chosen when pick < rate. BERT uses rate = 0.15, so about 15% of the words. A position that is not chosen goes into the input exactly as it was, and its action and swap are ignored.

Step 2: decide what the model sees at each chosen position. If a chosen word were always replaced by [MASK], the model would only ever learn to predict where it sees [MASK], a token that never shows up in the real text it is later fine-tuned on. So action picks one of three treatments:

actionwhat goes into the input
below 0.8the token "[MASK]"
from 0.8 up to, but not including, 0.9the word swap (a random word from the vocabulary)
0.9 or abovethe original word, unchanged

Step 3: write the answer key. The label at a position is the original word if that position was chosen in Step 1, and None if it was not.

Task: write mask_tokens(tokens, rolls, rate), where tokens is a list of words and rolls holds one (pick, action, swap) tuple per word. Return a tuple (inputs, labels) of two lists, each the same length as tokens:

  • inputs: what the model actually reads,
  • labels: what it is asked to predict at each position.

This one function is the whole trick behind pretraining on raw text: it turns any sentence into a supervised example, with no person needed to write the answers.

the
cat
[MASK]
on
the
mat
one word is hidden — guess it from the rest

Hide about 15% of the words and train the model to fill them in. No labels needed — the text is its own answer key.

Examples

tokens = ["the", "river", "bank", "flooded"]
rolls = [(0.62, 0.30, "cat"), (0.07, 0.55, "sky"), (0.91, 0.02, "ran"), (0.12, 0.85, "blue")]
rate = 0.15
returns (['the', '[MASK]', 'bank', 'blue'], [None, 'river', None, 'flooded'])
tokens = ["she", "sold", "old", "maps", "today"]
rolls = [(0.05, 0.93, "wet"), (0.40, 0.10, "run"), (0.11, 0.20, "far"), (0.03, 0.88, "tin"), (0.70, 0.99, "hat")]
rate = 0.15
returns (['she', 'sold', '[MASK]', 'tin', 'today'], ['she', None, 'old', 'maps', None])

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run