Labs · BERT, part by part

Masking and the prediction head

Fifteen per cent of the tokens chosen — 80 % masked, 10 % replaced by a random word, 10 % kept — the prediction head's scores over the vocabulary at every position, and a loss counted at the chosen positions only.

LMLM=−1∣C∣∑i∈Clog⁡pi[ti]L_{\text{MLM}} = -\frac{1}{|C|}\sum_{i \in C} \log p_i[t_i]Opens at 8 tokens · a vocabulary of 12 · d_model = 8

In plain words: BERT learns from ordinary text by hiding some of it and guessing it back — its first training task, masked language modelling (MLM). In every sentence about 15 in 100 words are chosen. Most chosen words are hidden behind [MASK]; a few are swapped for a random word, a few are left as they are, so the model can never trust what it sees at a position. At every position the prediction head gives each word of the vocabulary a score, turned into probabilities by a softmax; only the guesses at the chosen positions count towards the cross-entropy loss the model learns from. The choice here is the platform's own masking code, and the head is its untrained prediction head. The final vectors (what the encoder hands the head) are test data, drawn once to point at the words of the preset's sentence, as a trained encoder's would — they are not computed from the masked sentence, and editing a word does not redraw them.

In the formula, C is the set of chosen positions and |C| how many there are, ti the original word at position i and pi the head's probabilities there. The head is one projection: logits = h · W_head + b_head, with W_head of shape d_model × |V| = 8 × 12 (|V| is the vocabulary's size, 12 words; d_model is how many numbers each position's vector holds). BERT's own head adds a dense layer, GELU (a smooth activation function, a softer cousin of ReLU) and LayerNorm before that projection and shares its weights with the token table; this lab keeps the single projection worked example 03 traces, where it is called the readout head. Other pages say masked positions for what this lab calls the chosen ones: the kept and swapped positions are scored too. The seed is the number that fixes the random draws: the same seed gives the same choice every time, and another seed may give another choice.

15 % of the content tokens chosen; of those, 80 % become [MASK], 10 % a random word, 10 % stay as they are. Only the chosen positions are scored.

Chosen, masked, predicted, scored

Reads /api/labs/masking — loading

Computing…

Masking and the prediction head — Labs — TransformerLab