Skip to content
HasanAI
Log in Sign up

🎭 BERT: Pre-training of Deep Bidirectional Transformers

Hide 15% of the tokens and recover them from both sides
Ten Landmark Papers Intermediate
Contents

    BERT: Bidirectional Encoders (Devlin et al., 2019)

    GPT reads left to right because it is trained to predict the next token. That works for generation, but it is a handicap for understanding. The meaning of a word often depends on what comes after it: in "the bank of the river", the disambiguating word is two positions to the right.

    BERT, Pre-training of Deep Bidirectional Transformers for Language Understanding, keeps the Transformer encoder, lets every token see every other token, and replaces next-token prediction with a different training game: hide some tokens and recover them from both sides.

    1. Why you cannot simply train a bidirectional language model
    2. Masked language modelling and the 80/10/10 rule, simulated
    3. A task only a bidirectional model can solve, trained both ways
    4. Inputs: [CLS], [SEP], and three embeddings added together
    5. BERT-base and BERT-large, counted to 110M and 340M
    6. Fine-tuning, next-sentence prediction, and what came after

    For the same encoder applied to brain signals instead of text, see BERT on EEG.

    helpers ready

    1. Why not a bidirectional language model?

    A left-to-right model predicts token $i$ from tokens $< i$. A right-to-left model predicts it from tokens $> i$. ELMo trained one of each and concatenated their features, which is shallow bidirectionality: the two directions never meet inside the network.

    Making a single deep network bidirectional breaks the objective. If every layer sees every position, then by layer 2 the representation at position $i$ already contains token $i$ itself, gathered through its neighbours. The model would "predict" each word by copying it.

    BERT's answer is to remove the token from the input and then predict it. The paper calls this the masked LM, after the 1953 Cloze test.

    2. Masked LM and the 80/10/10 rule

    Choose 15% of token positions at random. For each chosen position:

    • 80% of the time, replace the token with [MASK]
    • 10% of the time, replace it with a random token
    • 10% of the time, leave it unchanged

    The loss is computed only at the chosen positions. The mixing is there because [MASK] never appears at fine-tuning time. If the model only ever saw [MASK] at predicted positions, it could learn that ordinary tokens need no thought. The random and unchanged cases force it to keep a good representation of every input token, since any one of them might be a target.

    ==============================================================================
      SIMULATING THE MASKING RULE ON 2 MILLION TOKENS
    ==============================================================================
    
    Fractions of ALL tokens
    ------------------------------------------------------------------------------
      chosen as targets        0.1497   (theory 0.15)
      became [MASK]            0.1199   (theory 0.12)
      became a random token    0.0148   (theory 0.015)
      chosen but unchanged     0.0150   (theory 0.015)
    
    What the model sees at a target position
    ------------------------------------------------------------------------------
      P(input is [MASK]            | target) = 0.8010
      P(input equals the answer    | target) = 0.1004
      P(input is some other token  | target) = 0.0987
      [PASS] 12% / 1.5% / 1.5% of all tokens, within 0.1%

    3. A task only a bidirectional model can solve

    To see what bidirectionality buys, here is a task built so the answer depends on both sides. Sequences of 12 digits. Even positions are random. Each odd position holds the sum of its two neighbours, mod 10:

    $$x_{2j+1} = (x_{2j} + x_{2j+2}) \bmod 10$$

    Two models with the same architecture and size:

    • BERT-style: no attention mask; a random odd position is replaced by [MASK] and predicted.
    • GPT-style: causal mask, predict each token from the ones before it.

    At an odd position, the left-to-right model has seen $x_{2j}$ but not $x_{2j+2}$, and $x_{2j+2}$ is a uniformly random digit. So it cannot do better than 10%, however long it trains. The bidirectional model has everything it needs.

    ==============================================================================
      SAME TRANSFORMER, TWO ATTENTION PATTERNS
    ==============================================================================
      BERT-style (bidirectional)   accuracy at the sum positions after 1,500 steps: 1.000
      GPT-style (causal)           accuracy at the sum positions after 1,500 steps: 0.101
      chance                       0.100
      [PASS] the bidirectional model solves it (> 95%)
      [PASS] the causal model is stuck near chance (< 15%), as the argument predicts

    4. Inputs: [CLS], [SEP] and three embeddings

    BERT's input packs one or two text segments into a single sequence:

    [CLS] my dog is cute [SEP] he likes play ##ing [SEP]

    Each position's input vector is the sum of three learned embeddings:

    $$\text{input}_i = E_{\text{token}}[x_i] + E_{\text{segment}}[A \text{ or } B] + E_{\text{position}}[i]$$

    • WordPiece tokens, 30,522 of them (rare words split into pieces such as play ##ing)
    • Segment A or B, telling the two sentences apart
    • Learned positions, up to 512

    The final hidden state of [CLS] is a summary of the whole sequence, used for classification.

    5. BERT-base and BERT-large, counted

    The paper reports 110M parameters for BERT-base (L=12, H=768, A=12) and 340M for BERT-large (L=24, H=1024, A=16). Counting every matrix, bias and layer norm:

    ==============================================================================
      COUNTING BERT
    ==============================================================================
      BERT-base  embeddings  23.8M + 12 layers   85.1M + pooler 0.59M =  109.5M   (paper: 110M)
      BERT-large embeddings  31.8M + 24 layers  302.3M + pooler 1.05M =  335.1M   (paper: 340M)
    
    Check the formula against a real PyTorch encoder of BERT-base shape
    ------------------------------------------------------------------------------
      [PASS] one layer: formula 7,087,872 == PyTorch 7,087,872

    6. Fine-tuning, next-sentence prediction, and what came after

    Fine-tuning is lightweight. For classification, put a linear layer on the [CLS] state. For question answering (SQuAD), learn just two vectors, a start vector $S$ and an end vector $E$. The probability that the answer starts at token $i$ is $\text{softmax}_i(S \cdot T_i)$, where $T_i$ is the final hidden state, and the end is predicted the same way. Everything else is the pre-trained network.

    The paper also trained a second objective, next-sentence prediction: given segments A and B, is B the actual next sentence (50% of the time) or a random one? The paper's ablation found it helped. RoBERTa (2019) later trained longer, on more data, with dynamic masking and without NSP, and matched or beat BERT. So NSP is the part of the recipe that did not last.

    Results. BERT-large set new records on eleven tasks: a GLUE score of 80.5 (7.7 points above the previous best), MultiNLI accuracy of 86.7%, and SQuAD v1.1 F1 of 93.2.

    Summary

    • A deep bidirectional language model would see the answer through its neighbours, so BERT hides 15% of tokens and predicts them: the masked LM.
    • Of the chosen tokens, 80% become [MASK], 10% a random token and 10% stay unchanged. The simulation reproduces 12%, 1.5% and 1.5% of all tokens.
    • On a task where the answer depends on the right-hand context, the bidirectional model learns it and the causal model provably cannot.
    • Inputs are token + segment + position embeddings, with [CLS] and [SEP]. The configurations count to 109.5M and 335M parameters, within 2% of the paper's 110M and 340M.
    • The trade-off: an encoder like BERT understands but does not generate. That is why later work split into encoders for retrieval and classification and decoders (the GPT line) for generation.