Explain some of the pre-training mechanisms used for Large Language Models (LLMs).
Pre-training objectives teach language models syntax, reasoning, and world knowledge from unlabeled text without human annotations. Major objectives include Causal Language Modeling (next-token prediction in GPT/LLaMA), Masked Language Modeling (bidirectional reconstruction in BERT), Span Corruption (T5), Fill-in-the-Middle for code, and Permuted Language Modeling (randomized autoregressive factorization in XLNet). Modern frontier LLMs largely standardize on CLM because every token yields a training gradient and directly matches autoregressive inference.
Study Card: Pre-training Mechanisms for Large Language Models (LLMs)
Direct Answer
Large Language Models acquire broad grammatical, semantic, and reasoning capabilities via self-supervised pre-training objectives over massive unlabeled corpora:
- Causal Language Modeling (CLM / Next-Token Prediction): Used by decoder-only LLMs (GPT, LLaMA, Claude, Gemini). Factorizes sequence probability autoregressively:
Every token receives a training loss signal, and the training objective matches autoregressive generation directly.
- Masked Language Modeling (MLM): Used by bidirectional encoders (BERT, RoBERTa). Randomly corrupts ~15% of tokens with
[MASK](or random/unchanged tokens) and predicts them from bidirectional context. - Span Corruption / Prefix LM: Used by encoder-decoder models like T5/UL2; replaces contiguous token spans with sentinel tokens (
<extra_id_0>) and reconstructs the missing spans autoregressively. - Fill-in-the-Middle (FIM): Rearranges prefix-middle-suffix segments so causal LLMs learn infilling (widely used in code LLMs) without changing decoder-only architecture.
- Permuted Language Modeling (PLM): Used by XLNet; preserves the input’s original positional encodings while sampling random autoregressive factorization orders via two-stream self-attention, capturing bidirectional context without
[MASK]train-test mismatch:
- Next Sentence Prediction (NSP): Originally paired with BERT MLM to classify consecutive sentences, though RoBERTa later showed NSP was largely unnecessary compared to training on longer contiguous document spans.
Key Terms
- Causal Language Modeling (CLM): Left-to-right next-token prediction using causal attention masking; dominates frontier generative LLMs.
- Masked Language Modeling (MLM): Bidirectional reconstruction of masked tokens; excels at discriminative encoding and embeddings.
- Span Corruption: Reconstructing masked multi-token spans rather than single tokens (T5/UL2).
- Permuted Language Modeling (PLM): Factorizing sequence likelihood across random token orderings via permutation attention masks while keeping original positions intact.
- Fill-in-the-Middle (FIM): Formatting
<PRE> prefix <SUF> suffix <MID> middleso causal models predict infills conditioned on both left and right context.
Example
Consider the sentence "The quick brown fox jumps over the lazy dog":
- CLM (GPT/LLaMA): Predicts each next token left-to-right—predicting
"fox"from"The quick brown","jumps"from"The quick brown fox", and so on across every token. - MLM (BERT): Masks tokens as
"The quick brown [MASK] jumps over the lazy [MASK]"and predicts"fox"and"dog"using context from both sides. - PLM (XLNet): Keeps every token’s original position index (
1..9), samples a random factorization permutation such as[3, 7, 1, 4, ...], and masks attention so position4("fox") only sees tokens preceding it in that permutation (3: "brown",7: "the",1: "The"), learning bidirectional dependencies without[MASK]tokens.
Code Implementation
import torch
import torch.nn.functional as F
# Runnable PyTorch demonstration of Causal LM (CLM) vs. Masked LM (MLM) training objectives
torch.manual_seed(0)
vocab_size = 50
batch_size, seq_len = 2, 10
tokens = torch.randint(1, vocab_size, (batch_size, seq_len))
MASK_ID = 0
# 1. Causal Language Modeling (CLM): shift logits and targets by 1 token
# Every position t in [0, seq_len - 2] predicts token t + 1
clm_logits = torch.randn(batch_size, seq_len, vocab_size, requires_grad=True)
shift_logits = clm_logits[:, :-1, :].reshape(-1, vocab_size)
shift_targets = tokens[:, 1:].reshape(-1)
clm_loss = F.cross_entropy(shift_logits, shift_targets)
print(f"CLM next-token loss (over 100% of shifted tokens): {clm_loss.item():.4f}")
# 2. Masked Language Modeling (MLM): mask ~15% of tokens and compute loss ONLY on masked positions
mask_probs = torch.full(tokens.shape, 0.2)
masked_indices = torch.bernoulli(mask_probs).bool()
if not masked_indices.any():
masked_indices[0, 0] = True # Guarantee at least one masked token
mlm_inputs = tokens.clone()
mlm_inputs[masked_indices] = MASK_ID
mlm_labels = torch.full_like(tokens, -100) # PyTorch ignore_index = -100
mlm_labels[masked_indices] = tokens[masked_indices]
mlm_logits = torch.randn(batch_size, seq_len, vocab_size, requires_grad=True)
mlm_loss = F.cross_entropy(mlm_logits.view(-1, vocab_size), mlm_labels.view(-1), ignore_index=-100)
print(f"MLM masked-token loss (over {int(masked_indices.sum())} masked tokens): {mlm_loss.item():.4f}")
# With Hugging Face `transformers`:
# from transformers import pipeline
# fill_mask = pipeline("fill-mask", model="bert-base-uncased")
# generator = pipeline("text-generation", model="gpt2")
# out = generator("The quick brown fox jumps over the", max_new_tokens=20)
Related Concepts
- Transfer Learning & Instruction Tuning (SFT/RLHF): Pre-training builds raw capability; SFT and preference alignment adapt LLMs into instruction-following assistants.
- Data Curation & Packing: Packing full-length documents and deduplicating corpora maximize pre-training compute efficiency.
- Scaling Laws: Empirical power laws relating validation loss to parameters, dataset tokens, and pre-training FLOPs.
- Tokenizer Design (BPE / SentencePiece): Subword tokenization strongly impacts pre-training efficiency, multilingual coverage, and context utilization.