Masked Language Models

Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 9

51 cards

Introduction

  1. What is masked language modeling?
    A training paradigm for bidirectional encoders (e.g. BERT): instead of predicting the next word, a word in the middle is masked and the model guesses it from the words on both sides, so it sees both left and right context.
  2. How are masked language models usually fine-tuned for a downstream task?
    Add a neural classifier on top of the pretrained network’s top layer and train it on labeled data for the task (e.g. named entity tagging, natural language inference).
  3. What is transfer learning?
    Acquiring knowledge from one task or domain and applying (transferring) it to a new task, as in the pretrain–fine-tune paradigm.

9.1 Three architectures for language models

  1. What are the three common LM architectures?
    The decoder, the encoder, and the encoder-decoder.
    decoderencoderenc-decleft → rightnext tokenstokens↔ both sidesvector per tokentokensencdectokensother tokens
  2. What does a decoder model do, and which LLMs are decoders?
    It takes input tokens and generates output tokens one at a time, with information flowing left to right: a generative model. GPT, Claude, Llama and Mistral are decoders.
  3. What does an encoder model do, and how is it typically used?
    It takes a token sequence and outputs a vector representation for each token. Encoders are usually masked LMs (BERT, RoBERTa); they aren’t used to generate text but are fine-tuned as classifiers (sentiment, topic…).
  4. What distinguishes the encoder-decoder architecture, and where is it used?
    It maps input tokens to output tokens with only a loose relationship between them: outputs can come from a very different token set and be much longer or shorter. Used for machine translation and speech recognition.

9.2 Bidirectional transformer encoders

  1. For what kinds of tasks is the left-to-right restriction of decoders a limitation?
    Tasks where processing a token benefits from future tokens, especially sequence labeling: named entity tagging, part-of-speech tagging, parsing.
  2. What is the focus of a bidirectional encoder, compared with a causal model?
    Computing contextualized representations of the input tokens, using the entire input sequence, rather than generating the next token.
  3. Why are masked LMs called encoder-only?
    They produce an encoding for each input token but generally aren’t used to produce running text by decoding/sampling.
  4. In what two ways do bidirectional encoders differ from causal transformers?
    Attention isn’t causal (a token can attend to following tokens), and training predicts tokens in the middle of the text rather than at the end.
  5. How is bidirectional attention implemented?
    By simply removing the causal mask: \(\text{head} = \text{softmax}\big(\frac{QK^\top}{\sqrt{d_k}}\big)V\). Everything else in the transformer block stays the same.
  6. What tokenization do BERT-style encoders use, and what complication does it cause?
    Subword tokens (BPE, WordPiece or SentencePiece Unigram LM). For tasks that need words, like parsing, subwords must sometimes be mapped back to words.
  7. How large are masked language models compared to causal LLMs?
    Much smaller: typically orders of magnitude fewer parameters than large causal LLMs.

9.3 Training bidirectional encoders

  1. Why can’t a bidirectional encoder be trained with next-word prediction?
    Without the causal mask, the next word is directly visible in the context, so the task is trivial.
  2. What is the cloze task?
    A fill-in-the-blank task: given a sequence with one or more elements missing, predict the missing elements (“The ___ of Walden Pond is so beautifully…”).
  3. What is denoising as a training method?
    Corrupting the input (masking, substituting, reordering, deleting, inserting words) and training the model to recover the original.
  4. Describe the BERT masking procedure.
    A sample of tokens (15% in BERT) is chosen. Of these, 80% are replaced with [MASK], 10% with a random token sampled by unigram probability, and 10% are left unchanged. The model must predict the original token at each chosen position.

    “So long and thanks for all the fish”

    chosen tokenmodel input
    long[MASK]
    thanks[MASK]
    theapricot (random)
    The loss is computed only at the chosen positions.
  5. Why doesn’t BERT always replace chosen tokens with [MASK]?
    [MASK] never appears at fine-tuning or inference time. If the model only predicted at [MASK] positions it would learn to predict only there; random replacements and unchanged tokens make it try to predict every input token.
  6. How does a masked LM predict the token at a masked position?
    The final layer’s output \(h^L_i\) for that position goes through the LM head: logits \(u_i = h^L_i E^\top\), probabilities \(y_i = \text{softmax}(u_i)\).
  7. What is the MLM loss?
    The average negative log probability of the correct tokens over the set \(M\) of chosen positions: \(L_{MLM} = -\frac{1}{|M|}\sum_{i \in M}\log P(x_i \mid h^L_i)\).
  8. In what sense is BERT training inefficient?
    Only the chosen tokens (about 15%) contribute to the loss; the others play no role in learning. (ELECTRA uses all positions.)
  9. What is Next Sentence Prediction (NSP), and what is it for?
    A second BERT objective: given a pair of sentences, predict whether they are actually adjacent in the corpus or the second was randomly chosen (50/50). It targets sentence-pair relationships: paraphrase, entailment, discourse coherence.
  10. What special tokens and embeddings does BERT add for sentence pairs?
    [CLS] prepended to the input, [SEP] between the sentences and at the end, and segment embeddings (first/second) added to the token and position embeddings.
  11. How is NSP predicted?
    From the final-layer vector of the [CLS] token, with a learned classification head: \(y = \text{softmax}(h^L_{CLS}W_{NSP})\), trained with cross-entropy, combined with the MLM loss.
  12. Why does the [CLS] representation tend to capture the whole sequence?
    Because it is the direct input to the NSP classifier, training pushes it to contain information about the sequence as a whole.
  13. How does RoBERTa’s training regime differ from BERT’s?
    It drops next sentence prediction: inputs are simply contiguous sentences (starting with [CLS]), packed across document boundaries with separators up to the context length, with large batches.
  14. How is the training data sampled to build a multilingual tokenizer vocabulary?
    Not uniformly (which would favor English), but by reweighting each language’s share: \(q_i = \frac{p_i^\alpha}{\sum_j p_j^\alpha}\) with \(p_i\) its proportion of sentences and \(\alpha\) about 0.3, which upweights less-represented languages.
  15. What are the advantages of a multilingual encoder over many monolingual ones?
    One model instead of a hundred, and better performance on low-resource languages by leveraging similar higher-resource languages in the training data.
  16. What is the curse of multilinguality?
    When the number of languages grows very large, performance on each language degrades compared with a model trained on fewer languages.
  17. What does it mean that multilingual models “have an accent”?
    Grammatical structures of higher-resource languages (often English) bleed into the representations of lower-resource languages, making them slightly more English-like.

9.4 Fine-tuning for classification

  1. What are the two ways to use pretrained LMs for downstream tasks?
    Prompting the model in natural language so it generates what we want, or fine-tuning: adding application-specific circuitry (a head) on top and training it on labeled data, freezing or only minimally adjusting the pretrained parameters.
  2. How is an encoder fine-tuned for sequence classification, e.g. sentiment?
    Pass the text through the encoder, take the final-layer [CLS] vector (or the mean of the token outputs), and feed it to a classifier head: \(y = \text{softmax}(h^L_{CLS}W_C)\), with \(W_C\) of shape \([d \times \text{classes}]\), trained with cross-entropy.
  3. During classification fine-tuning, are the pretrained weights updated?
    They can be, but reasonable performance usually needs only minimal changes, often limited to the last few transformer layers.
  4. How is sequence-pair classification done with an encoder?
    As in NSP training: input [CLS] sentence A [SEP] sentence B [SEP], and classify the final [CLS] vector with a learned head.
  5. What is natural language inference (NLI)?
    Also called recognizing textual entailment: given a premise and a hypothesis, classify their relationship as entails, contradicts or neutral, in the loose sense of how a typical human would read them.
  6. Classify: premise “I’m confused.”, hypothesis “Not all of it is very clear to me.”
    Entails.
  7. Name a dataset for natural language inference.
    MultiNLI (Multi-Genre Natural Language Inference).

9.5 Sequence labeling: named entity recognition

  1. What is sequence labeling?
    Assigning each token a label from a small fixed set, e.g. named entity recognition or part-of-speech tagging.
  2. What is a named entity, and what is NER?
    Roughly anything referred to by a proper name: a person, location, organization. Named entity recognition finds the spans of text that are proper names and tags their type. The term is often extended to dates, times and prices.
  3. What are the four most common named entity types?
    PER (person), LOC (location), ORG (organization), GPE (geo-political entity).
  4. What is NER useful for?
    Linking text to knowledge sources like Wikipedia, measuring sentiment toward particular entities, and anonymizing text for privacy.
  5. Why is NER difficult?
    Segmentation ambiguity (which tokens form an entity span, when most words aren’t entities) and type ambiguity: Washington can be a person, a sports team (ORG), a city (LOC) or a government (GPE).
  6. What is BIO tagging?
    A way to turn span recognition into per-token labeling: B marks the first token of a span, I a token inside a span, O a token outside any span, with B and I tags per entity type (\(2n + 1\) tags for \(n\) types).
    wordBIOBIOES
    JaneB-PERB-PER
    VillanuevaI-PERE-PER
    ofOO
    UnitedB-ORGB-ORG
    AirlinesI-ORGE-ORG
    ChicagoB-LOCS-LOC
  7. What are IO and BIOES tagging?
    IO drops the B tag, losing information about where adjacent spans begin. BIOES adds E for the end of a span and S for a single-token span.
  8. How does an encoder do NER as sequence labeling?
    Pass each token’s final output vector through a classifier \(y_i = \text{softmax}(h^L_iW_K)\) over the \(k\) tags and take the argmax per token, or pass the distributions to a CRF layer that models tag transitions.
  9. How do you handle the mismatch between word-level BIO annotations and subword tokens?
    Training: give every subword token the tag of the word it came from. Decoding: use the tag predicted for the first subword of each word (or combine the subwords’ tag distributions).
  10. How is NER evaluated, and what is the unit of response?
    Precision, recall and F1 (with paired bootstrap tests for significance), counting entities, not words, as units: Jane Villanueva is one response.
  11. Why does segmentation complicate NER evaluation?
    Labeling only Jane instead of Jane Villanueva as PER causes two errors (a false positive and a false negative), and training is per word while evaluation is per entity.

Summary

  1. How do contextual embeddings relate to word senses?
    A word sense is a discrete representation of one aspect of a word’s meaning; contextual embeddings give a richer continuous, high-dimensional model of meaning in context.
  2. How can the similarity of two words in context be measured with an encoder?
    By the cosine between their contextual embeddings, although some transformations of the embeddings are needed first.

Source