$\newcommand{\argmin}{\textrm{argmin}} \newcommand{\argmax}{\textrm{argmax}} \newcommand{\v}[2]{{#1}_{\mathrm{#2}}} \newcommand{\Exp}{\mathbb{E}} \newcommand{\Var}{V} \newcommand{\Obs}{\mathcal{O}} \newcommand{\RR}{\mathbb{R}} \newcommand{\matA}{\mathbf{A}} \newcommand{\matB}{\mathbf{B}} \newcommand{\matW}{\mathbf{W}} \newcommand{\matX}{\mathbf{X}} \newcommand{\matY}{\mathbf{Y}} \newcommand{\vx}{\mathbf{x}} \newcommand{\vy}{\mathbf{y}} \newcommand{\card}[1]{\left|#1\right|} \newcommand{\mat}[1]{\mathbf{#1}} \newcommand{\RV}{\mathbf{#1}} \newcommand{\RVX}{\mathbf{X}} \newcommand{\RVY}{\mathbf{X}} \newcommand{\RVY}{\mathbf{X}} \newcommand{\dpartial}[2]{\frac{\partial #1}{\partial #2}} \newcommand{\seq}[2]{#1: #2} \newcommand{\softmax}{\textrm{softmax}} \newcommand{\Length}{L} \newcommand{\Tokens}{\mathcal{T}} \newcommand{\token}{t} \newcommand{\tokens}{\mathbf{t}} \newcommand{\prefix}{\mathbf{s}} \newcommand{\rep}[2]{\mathbf{r}_{#1}\left(#2\right)} \newcommand{\trep}[2]{\mathbf{x}^{(#1)}_{#2}} \newcommand{\tyrep}[2]{\mathbf{y}^{(#1)}_{#2}} \newcommand{\tXrep}[3]{\mathbf{#1}^{(#2)}_{#3}} % After SA \newcommand{\sarep}[2]{\mathbf{x}^{(#1{\scriptsize \angle SA})}_{#2}} \newcommand{\carep}[2]{\mathbf{x}^{(#1{\scriptsize \angle CA})}_{#2}} \newcommand{\arep}[2]{\mathbf{x}^{(#1{\scriptsize \angle A})}_{#2}}$
LLMs - Training LLMs and Generation
Benjamin Piwowarski
Cours 2
Press ? for help on keyboard shortcuts
Slides in PDF
► Overview

Today's lecture

  1. How to train encoders and decoders?
    From pre-training to fine-tuning
  2. How to generate text?
    Sampling strategies
    Maximum likelihood decoding
    Guided and constrained generation

Practical

  1. Generating text with pre-trained models
    Top-p, top-k, temperature, beam search
  2. Fine-tuning an encoder
    Sentiment analysis on IMDB
  3. Guided and Constrained Text Generation
    Generating answer avoiding tokens
    Generating formatted (JSON) answers
    Biasing answers towards positive/negative sentiments

Training

► Pre-Training Large Language Models

Data collection

Unlabeled Text Data

Web Crawled Data
Books, Articles
Domain-Specific Corpora

Labeled Data

Human Annotations (NLP Datasets)

Loss Functions

Encoder

Masked Language Modeling
Next Sentence Prediction
Replaced Token Detection

Decoder

Maximum Likelihood Estimation
Span Prediction
Reinforcement Learning

Data Collection

► Data Sources: Specific Web Resources

High-quality, curated sources

  1. Books
    Good for long-range dependencies
  2. Wikipedia
    High-quality encyclopedic content
  3. News Articles
    Quality journalism from major publishers (but (c) issues)
  4. Forums and Social Media (Reddit, StackExchange, BlueSky etc.)
    Good for dialogues pre-training
► Data Sources: Generic Web Crawls

Raw and filtered web-scale corpora

  1. Common Crawl
    Open repository of petabyte-scale web crawl data
    Raw, unfiltered web content
  2. C4 (Colossal Cleaned Corpus)
    Filtered Common Crawl (English, quality filtering)
    Documenting Large Webtext Corpora: A Case Study on the Colossal Clean Crawled Corpus:
    2021. http://arxiv.org/abs/2104.08758.
  3. RefinedWeb
    Heavily filtered Common Crawl for high-quality text
    The RefinedWeb Dataset for Falcon LLM: Outperforming Curated Corpora with Web Data, and Web Data Only:
    2023. http://arxiv.org/abs/2306.01116.
► Cleaning the data: Deduplication
Deduplicating Training Data Makes Language Models Better:
2022. http://arxiv.org/abs/2107.06499.

Why deduplicate?

  1. Reduces training time and costs
  2. Increasingly harmful to model quality as parameter count increases (only for web-based data?)
    Scaling Laws and Interpretability of Learning from Repeated Data:
    2022. http://arxiv.org/abs/2205.10487.
  3. Reduces memorization
    Extracting Training Data from Large Language Models:
    2021. http://arxiv.org/abs/2012.07805.

How?

Exact
Using Suffix Array or hashing (MD5, SHA-1)
N-Gram based
MinHash
Locality-Sensitive Hashing
LSH (text-specific hashing)
► Cleaning the data: Filtering

Remove low-quality & offensive content

  1. Language detection
  2. Offensive content filtering
  3. Length-based filtering
  4. Domain-specific filtering
Challenges in Detoxifying Language Models:
2021. http://arxiv.org/abs/2109.07445.
Documenting Large Webtext Corpora: A Case Study on the Colossal Clean Crawled Corpus:
2021. http://arxiv.org/abs/2104.08758.
► Case study: RefinedWeb – Deduplication

Normalizing the content

Uses the GPT-2 tokenizer (Byte-Pair Encoding, BPE)

MinHash

Broder, A.Z.
1997. On the Resemblance and Containment of Documents. Proceedings. Compression and Complexity of SEQUENCES 1997 (Cat. No.97TB100171).
Approximates the Jaccard Similarity between the sets of n-grams ($n=5$) $$J\left(d_i, d_j\right)=\frac{\left|d_i \cap d_j\right|}{\left|d_i \cup d_j\right|}$$ with an empirical threshold of $0.8$
Computes the hash $h_s$ of each $n$-gram $s$ using Tabulation Hashing
Random value for each position and token in the vocabulary
Use the minimum (over $h_s$) of $b$ (20) hash functions for each of the $r$ (450) buckets
Equal value in one bucket = potential match
$$P\left(d_i, d_j \mid \operatorname{Jaccard}\left(d_i, d_j\right)=s_{i, j}\right)=1-\left(1-s_{i, j}^b\right)^r$$
► Case study: RefinedWeb – Filtering

Banned URLs
Aggregated list of about 4.6M URLs – with some false positives (web sites hosting user content) that were manually classified

Using rules

Removing high quality data

arxiv, AskUbuntu, StackOverflow, NIH Abstracts, Github, Ubuntu IRC, HackerNews, FreeLaw, Reddit, Europarl, United States Patents, Wikipedia
► Data Sources: Combined Datasets

The Pile (825 GB)

22 diverse datasets: CommonCrawl, books, Wikipedia, arXiv, GitHub, etc.
Replaced by the Common Pile in early 2025 (8TB)
The Common Pile v0.1: An 8TB Dataset of Public Domain and Openly Licensed Text:
2025. http://arxiv.org/abs/2506.05209.
The Pile: An 800GB Dataset of Diverse Text for Language Modeling:
2020. http://arxiv.org/abs/2101.00027.
► Data Sources: NLP Datasets
Sentiment Analysis
IMDB, SST, ...
"The movie was absolutely incredible! The acting was superb and I was completely engaged from start to finish." $\rightarrow$ Positive
Question Answering
SQuAD, Natural Questions, ...
Context: The Great Wall of China was built over many centuries by different Chinese dynasties. The Ming Dynasty, which ruled from 1368 to 1644, constructed most of the wall that exists today.
Question: Which dynasty built most of the Great Wall of China that exists today?
$\rightarrow$ Ming Dynasty
Text Classification
AG News, DBpedia, ...
"Apple Inc. announced today that it has achieved record-breaking quarterly revenue of $120 billion, driven primarily by strong iPhone sales in emerging markets." $\rightarrow$ Business
► Data Sources: Instruction Tuning Collections
Task-specific dataset compilations for instruction tuning
  1. FLAN (Finetuned Language Net)
    1,800+ tasks from 400+ datasets
    Formatted as instructions (e.g., "Translate to French: ...", "Summarize: ...")
    Wei, J. et al.
    2021. Finetuned Language Models Are Zero-Shot Learners.
  2. SuperNaturalInstructions
    1,600+ NLP tasks with expert-written instructions
    Super-NaturalInstructions: Generalization via Declarative Instructions on 1600+ NLP Tasks:
    2022. http://arxiv.org/abs/2204.07705.
  3. P3 (Public Pool of Prompts)
    170+ datasets with multiple prompt templates
    Generalizes the idea of prompts for few-shot learning
    Sanh, V. et al.
    2022. Multitask Prompted Training Enables Zero-Shot Task Generalization.
► Example: FLAN
Wei, J. et al.
2021. Finetuned Language Models Are Zero-Shot Learners.
► Examples
BERT and GPT-1
BookCorpus (self-published books from Smashwords, 800M words)
(BERT only) English Wikipedia (2,500M words)
Devlin, J. et al.
2018. BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding.
Radford, A. et al.
2018. Improving Language Understanding by Generative Pre-Training.
neoBERT
NeoBERT: A Next-Generation BERT:
2025. http://arxiv.org/abs/2502.19587.
The RefinedWeb Dataset for Falcon LLM: Outperforming Curated Corpora with Web Data, and Web Data Only:
2023. http://arxiv.org/abs/2306.01116.
GPT-3
Brown, T.B. et al.
2020. Language Models Are Few-Shot Learners.
  1. Filtered Common Crawl (de-duplication)
  2. WebText2 (filtered from outbound links on Reddit)
  3. Books1 and Books2 (two internet-based books corpora)
  4. English Wikipedia
► Examples
GPT-3 + FLAN (Instruct models)
Wei, J. et al.
2021. Finetuned Language Models Are Zero-Shot Learners.
GPT-3 finetuned on FLAN tasks
Improves performance over unseen tasks
This is especially important when increasing the size of models
► Combined Dataset Example: Dolmino

Dolmino (used to train OLMo)

2 OLMo 2 Furious:
2025. http://arxiv.org/abs/2501.00656.

Pretraining data: OLMo 2 Mix 1124

Mid-training data: Dolmino Mix 1124

► Conclusion

Key Takeaways

  1. Diverse and high-quality data is crucial for training effective LLMs
  2. Data cleaning (deduplication, filtering) improves model performance
  3. Combining multiple data sources can enhance model generalization
  4. Instruction-tuning and scale is key to generalization

Training Encoders

► Masked-Language Modeling
Masked Language Modeling (MLM)
Original text
$\tokens_{1 \ldots L}$
Corrupted text
$$ \tilde \tokens_i = \begin{cases} \kappa(\tokens_i) & \text{with probability } p_{mask} \\ \tokens_i & \text{otherwise} \end{cases} $$
Loss
$$ \mathcal{L} = - \sum_{i \in M} \log p_\theta(\tokens_i | \tilde \tokens_{1 \ldots L}) $$ where $M$ is the set of masked token positions
► Masked-Language Modeling (2)
Problem statement
We have a corrupted text $\tilde \tokens_{1 \ldots L}$
How to compute $p_\theta(\tokens_i | \tilde \tokens_{1 \ldots L})$?
  1. We compute the contextualized representation $\tXrep{\tilde x}{N}{1 \ldots L}$
    Using a Transformer decoder (masked self-attention, with auto-regressive masking)
  2. Then use a linear layer + softmax (un-embedding matrix) to get probabilities over the vocabulary $$ p_\theta(\tokens_i | \tilde \tokens_{1 \ldots L}) = \text{softmax}(\matW_u \tXrep{\tilde x}{N}{i} + \mat{b}_u) $$
► Masked-Language Modeling (3)
BERT-style masking
Devlin, J. et al.
2018. BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding.
  1. 15% of tokens selected for possible masking
  2. Of these:
    • 80% replaced with [MASK]
    • 10% replaced with a random token
    • 10% left unchanged

Other Masking Strategies

  1. Whole Word Masking
    If any subword of a word is masked, mask the entire word
    Cui, Y. et al.
    2021. Pre-Training with Whole Word Masking for Chinese BERT.
    Models: BERT, RoBERTa
  2. Frequency-Based Masking
    More frequent words have a lower probability of being masked
► Text/Sentence encoding
Given two sentences A and B, predict if B follows A in the original text
Masked Language Modeling (MLM)
Input
[CLS] $\tokens_{A}$ [SEP] $\tokens_{B}$ [SEP]
Loss
$$ \mathcal{L} = - \log p_\theta(y | \tokens_{A}, \tokens_{B}) $$ where $y$ is 1 if B follows A, 0 otherwise
Not really used in practice (further works have shown that it did not change anything)
► Replaced Token Detection
Motivation
Instead of masking tokens, replace them with plausible alternatives
Model learns to detect replaced tokens, encouraging deeper understanding
Clark, K. et al.
2019. ELECTRA: Pre-training Text Encoders as Discriminators Rather Than Generators.
The generator
Masked language model (like BERT)
The discriminator
Predicts whether each token was replaced by the generator
► Replaced Token Detection (2)
Used in Electra and DeBERTaV3
Clark, K. et al.
2019. ELECTRA: Pre-training Text Encoders as Discriminators Rather Than Generators.
He, P. et al.
2022. DeBERTaV3: Improving DeBERTa Using ELECTRA-Style Pre-Training with Gradient-Disentangled Embedding Sharing.
The generator/discriminator share the same embeddings
The generator is smaller (e.g. half the number of layers in DeBERTaV3) than the discriminator
More efficient than MLM (each token contributes to the loss)
Better performance with less compute
Requires training two models (generator + discriminator)
► Conclusion

Two main training procedures

  • Generative: Masked Language Modelling: with special tricks!
  • Discriminative: ELECTRA-style
No clear winner
Sanh, V. et al.
2019. DistilBERT, a Distilled Version of BERT: Smaller, Faster, Cheaper and Lighter.
Compares DeBERTaV3 and ModernBERT
ModernBERT preferred because of its long context, faster training, inference speed
simpler (MLM) methods are preferred

Training Decoders

► Causal Language Modeling

CLM = Maximum Likelihood Estimation

Given a sequence of tokens $\tokens_{1 \ldots L}$, maximize the likelihood:
$$ \mathcal{L} = - \sum_{i=1}^{L} \log p_\theta(\tokens_i | \tokens_{1 \ldots i-1}) $$
► Maximum Likelihood Estimation: Training with Teacher Forcing

Teacher forcing

So what's wrong
The model is never exposed to a series of mistakes when learning - at inference time... this might lead to problems
► Exposure bias
The space of generate sentences is very large
Easy to be at a stage where the model don't know!
This leads to degenerated texts
Problems also occur in other generative tasks
Lamb, A. et al.
2016. Professor Forcing: A New Algorithm for Training Recurrent Networks.
In practice, not a problem for LLMs trained on massive data... but still relevant for alignment phases (or when training with small datasets)!
► Computing the distribution over words in a decoder
Problem statement
We have a prefix $\tokens_{1 \ldots L-1}$
How to compute $p_\theta(\tokens_i | \tokens_{1 \ldots i-1})$?
  1. We compute the contextualized representation $\trep{N}{1 \ldots L-1}$
    Using a Transformer decoder (masked self-attention, with auto-regressive masking)
  2. Then use a linear layer + softmax (un-embedding matrix) to get probabilities over the vocabulary $$ p_\theta(\tokens_i | \tokens_{1 \ldots i-1}) = \text{softmax}(\matW_u \trep{N}{i-1} + \mat{b}_u) $$
► Alternative losses: scrambled token prediction
Instead of predicting the next token, predict a randomly chosen token from the sequence
Encourages the model to understand the overall context rather than just local continuity
Used in T5
Raffel, C. et al.
2019. Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer.
Not really used in practice in LLMs (CLM is simpler and works well enough)
► Reinforcement Learning for LLMs

Why RL for LLMs?

Instruction tuning (FLAN) allows us to enable language models to follow novel user instructions that are not seen during finetuning (this is what the users of LMs want!)
Limitations of MLE for instruction following
  • Getting data is expensive, especially for very complex tasks
  • Some tasks may not have one single acceptable output (Exposure bias)
  • Does not directly model human preferences

RLHF: Reinforcement Learning from Human Feedback

Train a reward model from human preferences
Use RL to optimize the language model policy
► RLHF Pipeline

Step 1: Supervised Fine-tuning

  1. Collect high-quality demonstrations
  2. Fine-tune pre-trained LM with supervised learning
  3. Creates initial policy $\pi_{\theta_{SFT}}$

Step 2: Reward Model Training

  1. Sample prompts, generate multiple responses
  2. Collect human preference comparisons
  3. Train reward model $r_\phi(\tokens)$ to predict preferences

Step 3: RL Optimization

  1. Use RL algorithm (PPO) to optimize policy
  2. Maximize expected reward (while staying close to initial policy)
  3. PPO, GRPO, DPO...
  4. (go back to step 2)
► PPO: Proximal Policy Optimization
Schulman, J. et al.
2017. Proximal Policy Optimization Algorithms.

Key Idea

Used in ChatGPT, InstructGPT
Training Language Models to Follow Instructions with Human Feedback:
2022. http://arxiv.org/abs/2203.02155.
Optimize a PPO-like loss $$ \begin{aligned} \operatorname{objective}(\phi)= & E_{(x, y) \sim D_{\pi_\phi^{\mathrm{RL}}}}\left[\left( r_\theta(x, y) - V_\phi(x, y)\right) -\beta \log \left(\pi_\phi^{\mathrm{RL}}(y \mid x) / \pi^{\mathrm{SFT}}(y \mid x)\right)\right]+ \\ & \gamma E_{x \sim D_{\text {pretrain }}}\left[\log \left(\pi_\phi^{\mathrm{RL}}(x)\right)\right] \end{aligned} $$
$\pi_\phi^{\mathrm{RL}}$ the trained policy
$r_\theta(x, y)$ = reward model score, $V_\phi(x,y)$ the value function
$\text{KL}(\pi_\theta || \pi^{ref})$: KL divergence from reference policy (prevents mode collapse)
► DPO: Direct Preference Optimization
Direct Preference Optimization: Your Language Model Is Secretly a Reward Model:
2023. http://arxiv.org/abs/2305.18290.

Key Insight

Skip the reward model! Optimize policy directly from preferences

From RL to Supervised Learning

DPO shows PPO optimization is equivalent to:
$$ \mathcal{L}_{DPO}(\pi_\theta) = -\mathbb{E}_{(x,y_+,y_-)} \left[ \log \sigma \left( \beta \log \frac{\pi_\theta(y_+|x)}{\pi^{ref}(y_+|x)} - \beta \log \frac{\pi_\theta(y_-|x)}{\pi^{ref}(y_-|x)} \right) \right] $$
where $y_+$ is preferred over $y_-$ (labelled data) and $\sigma$ is the sigmoid function
Simpler: No reward model, no RL training loop
More stable: Standard supervised learning
Memory efficient: Only need policy and reference models

Can be even simplified further

Llama 2: Open Foundation and Fine-Tuned Chat Models:
2023. http://arxiv.org/abs/2307.09288.
$$ \mathcal{L}_{\text {ranking }}=-\log \left(\sigma\left(r_\theta\left(x, y_c\right)-r_\theta\left(x, y_r\right)-m(r)\right)\right) $$
► DPO vs PPO

PPO

More flexible
Can incorporate non-preference rewards
Can do online learning
Complex training
4 models needed
Unstable, requires tuning
Computationally expensive

Used in

InstructGPT, ChatGPT

DPO

Simple training
Direct supervised learning
Only 2 models needed
More stable
Less hyperparameter tuning
Limited to preference data
Cannot use arbitrary reward functions

Used in

Mistral models
► GRPO: Group Relative Policy Optimization

Motivation

PPO is complex and unstable
DPO limited to offline preference data
Can we get PPO's flexibility with DPO's simplicity?

Key Ideas

DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models:
2024. https://arxiv.org/abs/2402.03300v3.
DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model:
2024. http://arxiv.org/abs/2405.04434.
  1. Generate multiple responses per prompt (a group)
  2. No separate value model needed: Use group statistics for advantage estimation
    $\hat{A}_i = \frac{r_i - \text{mean}(r_{\text{group}})}{\text{std}(r_{\text{group}})}$
Simpler than PPO (no value model)
Can use arbitrary reward functions (unlike DPO)
More stable than PPO

Finetuning

► Transfer Learning: Pre-training + Finetuning
Devlin, J. et al.
2018. BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding.

Why Finetuning?

  1. Pre-trained models learn general language understanding
  2. Finetuning adapts them to specific downstream tasks
  3. Much faster and cheaper than training from scratch
  4. Requires much less task-specific data

The Process

  1. Start with pre-trained model (BERT, GPT, T5, etc.)
  2. Add task-specific head (if needed, e.g. for encoders)
  3. Train on task-specific data with lower learning rate
  4. Optionally freeze some layers to prevent catastrophic forgetting
► Common Finetuning Tasks

Encoder Models (BERT-like)

  • Text Classification
    Sentiment analysis, topic classification
  • Token Classification
    Named Entity Recognition (NER), POS tagging
  • Question Answering
    Extractive QA (SQuAD)
  • Sentence Similarity
    Semantic textual similarity

Decoder Models (GPT-like)

  • Text Generation
    Completion, creative writing
  • Instruction Following
    Chat, task completion
  • Code Generation
    Code completion, debugging

Encoder-Decoder (T5-like)

  • Translation, Summarization
  • Text-to-text tasks
► Best Practices for Finetuning

Learning Rate

  • Use lower learning rates than pre-training
  • Typical: 1e-5 to 5e-5 for full finetuning
  • Use learning rate warmup

Regularization

  • Weight decay (0.01 typical)
  • Gradient clipping
  • Dropout (if not already in model)

Data Considerations

  • More data = better results (but diminishing returns)
  • Balance dataset classes
  • Use data augmentation when applicable
  • Monitor for overfitting on small datasets

Text Generation

► Goal and motivation
Understanding Contextual Generation is Key
  • LLMs are multitask learners & problem solvers via prompting
  • Evaluation of linguistic abilities of LLMs requires generation
    Agreement, proper word order, semantic consistency etc.
  • Good artificial data helps ML
    Privacy, confidentiality, distillation / data augmentation, artificial text detection
  • "Think" relies on good generation
    A key aspect of recent LLMs architectures

Basics

► A Language Model is a Distribution
Language is a probability distribution over tokens
$$ p_\theta(\tokens_{\seq{1}{L}}) $$
The sample space of sequences of tokens = Kleene closure of $\Tokens$
$$ \tokens \in \cup_{\Length=1}^{\infty} \in \Tokens^L $$
Well, not so true (because of the EOS token), but close enough...

Local Normalization

Factorized as product of conditionals
$$ p_\theta(\tokens_{\seq{1}{L}}) = \prod_{i=1}^{L} p_\theta(\tokens_i | \tokens_{\seq{1}{i-1}}) $$
Notice that there is a twist: the length $L$ is also a random variable!
= Not the real Kleen closure of $\Tokens$
► Challenge 1: Quality vs. Diversity trade-off

Two main types of "generation"

Decoding
Find the most probable text $\tokens_{\seq{1}{L}}$
Useful for translation, summarization, question answering...
Sampling
Generate diverse texts according to $p_\theta(\tokens_{\seq{1}{L}})$
Useful for data augmentation, text completion, creative writing...

Trade-off between quality and diversity

Decoding: high quality, low diversity
Sampling: high diversity, lower quality
► Challenge 2: Language Model (de)generation
  • High dimensional discrete space
    Vocabulary size $|\Tokens|$ typically 30k-200k
    Sentence of length $L$: $|\Tokens|^L$ possible sequences
  • Long-range dependencies
    Coherence, consistency over long texts
► Challenge 3: How to evaluate generated texts?
(more on this in another lecture)
  • N-gram overlap metrics (BLEU, ROUGE)
    Need human reference
    Poor correlation when model is strong
  • Embedding-based metrics (BERTScore, MoverScore)
    Better correlation but still needs reference
  • Reference-less metrics (QuestEval, MAUVE)
    Promising but still under active research
    Rely on statistical models
  • Human evaluation
    Gold standard but costly and time-consuming

Generation as decoding

► Decoding (argmax)
Formalizing Text Generation as Search
(Un-)Conditional text generation is formalized as:
$$\tokens^* = \argmax_{\tokens_{P\ldots L}} p_\theta(\tokens_{P+1 \ldots L} | \tokens_{\seq{1}{P}}) $$
Finding $L$ is part of the problem
Uses special tokens (end of sequence, e.g. )
Often bounded by a max length $L_{max}$
Unconditional generation: case $P=0$
► Greedy Decoding

Simplest Decoding Strategy

At each step, select the most probable token
$$ \tokens_L = \argmax_{\tokens} p_\theta(\tokens | \tokens_{1..L-1}) $$

Algorithm

  1. Start with prompt/prefix
  2. Compute $p_\theta(\cdot | \tokens_{1..L-1})$
  3. Select $\tokens_t = \argmax_t p_\theta(\token | \tokens_{1..L-1})$
  4. Repeat until EOS or max length
Fast and deterministic
Simple to implement
Myopic - no backtracking
Can lead to repetitive text
Locally optimal, not globally
► Beam Search: Principle
Lowerre, B.T.
1976. The HARPY Speech Recognition System.

Idea

Maintain $k$ best partial sequences (beams) at each step
Explore multiple paths simultaneously

Why Beam Search?

Greedy decoding: keeps only 1 hypothesis
Exhaustive search: $|\Tokens|^L$ combinations (intractable)
Beam search: middle ground with $k$ hypotheses
Beam width $k$
$k = 1$: equivalent to greedy
$k = 5$-$10$: typical for translation/summarization
Larger $k$ = more exploration but slower
► Beam Search: Algorithm

Step-by-Step Process

  1. Initialize with $K$ beams $\tokens_{\seq{1}{1}}^{(k)}$ with log-probability $s^{(k)}_{\seq{1}{1}} = \log p_\theta(\tokens_{\seq{1}{1}}^{(k)})$
  2. For each step $l$:
    1. The candidates for the next step are all the sequences $\tokens_{\seq{1}{l}} = \left(\tokens_{\seq{1}{l-1}}^{(k)}, \token\right)_{t\in \Tokens, k\in\{1, \ldots, K\}}$
    2. Select those with the $K$ highest scores (log-probability) $$\log p_\theta\left( (\tokens_{\seq{1}{l-1}}^{(k)}, \token) \right) = s^{(k)}_{\seq{1}{l-1}} + \log p_\theta(\token | \tokens^{(k)}_{\seq{1}{l-1}})$$
    3. Keep the $K$ tokens with the highest $s^{(k)}_{\seq{1}{l}} = s^{(k)}_{\seq{1}{l-1}} + \log p(\tokens^{(k)}_t | \tokens^{(k)}_{\seq{1}{l-1}})$
    4. Prune completed sequences (EOS)
  3. Return highest-scoring complete sequence
  4. Note that many computations can be avoided ($K$ most probable tokens per beam only)
► Beam search is not surprising
Holtzman, A. et al.
2019. The Curious Case of Neural Text Degeneration.
► Variations around Beam Search: Monte-Carlo Tree Search
Chaslot, G. et al.
2008. Monte-Carlo Tree Search: A New Framework for Game AI.
Mixes a min-max algorithm and Monte-Carlo
Usefull to play games
but also to generate sentences!
Often used with an auxilliary function
Scialom, T. et al.
2021. To Beam Or Not To Beam: That Is a Question of Cooperation for Language GANs.
► Beam Search: Pitfalls

Known Issues

  1. Generic/Boring Outputs
    Favors safe, common sequences
    "I don't know" problem in QA
    Solution: Add diversity penalty or use sampling
  2. Length Bias
    Without normalization, prefers shorter sequences (especially with high $K$)
    Solution: Length normalization or length penalty
  3. Lack of Diversity
    All beams converge to similar sequences
    Solution: Diverse beam search (group beams)
  4. Computational Cost
    $k \times$ slower than greedy
    Memory: need to store $k$ sequences

Generation as sampling

► Sampling: Ancestral Sampling
Generating text by sampling from a Language Model
Ancestral sampling principle:
  1. Sample $\tokens_1$ from $P_\theta(\tokens_1)$
  2. Sample $\tokens_2$ from $p_\theta(\tokens_2|\tokens_1)$
  3. ...
  4. Sample $\tokens_L$ from $p_\theta(\tokens_T|\tokens_{\seq{1}{L-1}})$
Produces diverse texts
but can produce low-probability (bad) texts
Top-$K$, nucleus, typical, eta sampling all improve over basic sampling by restricting the set of tokens to sample $\Tokens^+ \subseteq \Tokens$
► Top-K Sampling
Fan, A. et al.
2018. Hierarchical Neural Story Generation. Proceedings of the 56th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers).

Idea

Sample only from the $k$ most probable tokens at each step
Prevents unlikely (nonsensical) tokens

Algorithm

  1. Compute $p_\theta(\tokens_t | \tokens_{\seq{1}{l-1}})$
  2. Keep top-$k$ tokens $\Tokens^+$
  3. Renormalize: $p'(\token) = \frac{p(\token| \tokens_{\seq{1}{l-1}})}{\sum_{\token' \in \Tokens^+} p(\token'| \tokens_{\seq{1}{l-1}})}$
  4. Sample from $p'(\token)$
Prevents very unlikely tokens
Simple and fast
Fixed $k$ doesn't adapt to distribution
May be too restrictive or too loose
► Nucleus (Top-p) Sampling
Holtzman, A. et al.
2019. The Curious Case of Neural Text Degeneration.

Idea

Dynamically select smallest set with cumulative probability $\geq p$
Adapts to model's confidence

Algorithm

  1. Find the smallest $\Tokens^{(p)}\subseteq \Tokens$ where $\sum_{v \in \Tokens^{(p)}} p_\theta(\token | \tokens_{\seq{1}{L}}) \geq p$
  2. Renormalize and sample from $\Tokens^{(p)}$
Adaptive behavior
Confident prediction → small nucleus (few tokens)
Uncertain prediction → large nucleus (many tokens)
Typical: $p = 0.9$ or $p = 0.95$
Adapts to distribution shape
Better than fixed top-k
Still may include unlikely tokens if distribution is flat
May exclude likely tokens if distribution is sharp
► Locally Typical Sampling
Meister, C. et al.
2023. Locally Typical Sampling.

Motivation

High probability ≠ typical (psycholinguistics studies)
Information content matters: surprisal $= -\log p(x)$

Key Insight

Sample tokens with information close to expected
Avoid both too surprising and too boring

Algorithm

  1. Compute entropy: $H = -\sum_x p(x) \log p(x)$
  2. For each token: deviation $= |\log p(x) - H|$
  3. Keep tokens with small deviation (within $\tau$)
  4. Sample from this set
More human-like text
Balances predictability and surprise
► Eta ($\eta$) Sampling
Truncation Sampling as Language Model Desmoothing:
2022. http://arxiv.org/abs/2210.15191.

Idea

Entropy-aware adaptive threshold
Adjust cutoff based on distribution entropy

Method

Sample from $$\Tokens^+ = \left\{ \token: p(\token) > \eta \cdot \max_{\token'} p(\token') \right\} \text{ with } \eta = \min \left(\epsilon, \alpha \exp -H\left(\token \right)\right)$$ where $H$ is the entropy of $p(\cdot)$
Adaptive threshold
Low entropy (confident) → stricter $\eta$ (high threshold)
High entropy (uncertain) → relaxed $\eta$ (low threshold)
Adapts to model confidence
Good quality-diversity balance
► Consistent Decoding for Consistent Models
Consistent model
Welleck, S. et al.
2020. Consistency of a Recurrent Language Model With Respect to Incomplete Decoding. Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP).
A consistent model is such that $p_\theta(L=\infty)=0$
Inconsistency of standard decoding
Many decoding and sampling methods (greedy, beam search, top-$k$, typical, $\eta$, etc.) may produce infinite sequences with non-zero probability even if the model is consistent
Solution: enforce end-of-sequence token generation
  • Include the EOS token in the candidate set at each step
  • Modify decoding/sampling to always so that the probability of generation of the EOS token increases at each step
  • Sufficient condition: $\exists \epsilon, \,\, p(eos)>\epsilon$

Constrained Generation

► Constraining Text Generation

Why Constrain Generation?

Control attributes of generated text without retraining
  • Control sentiment (positive/negative)
  • Control topic (science, politics, sports)
  • Control style (formal/informal)
  • Satisfy hard constraints (keywords, format)
  • Avoid toxicity or bias

Types of Constraints

Hard Constraints
Enforce specific tokens or patterns (practical)
Can be tricky
NeuroLogic Decoding: (Un)Supervised Neural Text Generation with Predicate Logic Constraints:
2021. http://arxiv.org/abs/2010.12884.
Soft Constraints
Encourage certain attributes (sentiment, topic)
Methods: PPLM, FUDGE, GeDi
Krause, B. et al.
2020. GeDi: Generative Discriminator Guided Sequence Generation.
Plug and Play Language Models: A Simple Approach to Controlled Text Generation:
2020. http://arxiv.org/abs/1912.02164.
Yang, K. and Klein, D.
2021. FUDGE: Controlled Text Generation With Future Discriminators. Proceedings of the 2021 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies.
► Plug and Play Language Models (PPLM)
Plug and Play Language Models: A Simple Approach to Controlled Text Generation:
2020. http://arxiv.org/abs/1912.02164.

Key Idea

Steer generation by modifying hidden states at each step
No retraining needed - works with any pre-trained LM!

How It Works

  1. Generate token representation $\mathbf{h}_i$ from LM
  2. Compute gradient of attribute model $\log p(a_i|\tokens_{\seq{1}{i}})$ w.r.t. $\mathbf{h}_i$
  3. Update $\mathbf{h}_i$ in direction that increases desired attribute
  4. Generate token from modified $\mathbf{h}_i$
  5. Repeat for each token
No model retraining required
Can combine multiple attributes
Slower generation (gradient computation)
May reduce fluency
► PPLM: Algorithm
Plug and Play Language Models: A Simple Approach to Controlled Text Generation:
2020. http://arxiv.org/abs/1912.02164.

Objective

Maximize both language model likelihood and attribute model score:
$$p(\tokens | a) \propto p(\tokens) \cdot p(a | \tokens)$$
where $a$ is the desired attribute (e.g., positive sentiment)

Gradient Update

At each step, update hidden state:
$$\mathbf{h}_i \leftarrow \mathbf{h}_i + \alpha \nabla_{\mathbf{h}_i} \log p(a | \mathbf{h}_i)$$
$\alpha$ controls strength of attribute
Attribute Models
Bag of Words: encourage specific keywords
Discriminator: neural classifier for sentiment/topic
Multiple attributes can be combined
► Soft Constraints: Class-Conditional Language Models

Key Idea

Use auxiliary models to guide generation based on desired attributes

GeDi (Generative Discriminator)

Krause, B. et al.
2020. GeDi: Generative Discriminator Guided Sequence Generation.
Generative approach: Uses small control-code LMs $p(\tokens | a)$
Trained on class-specific data with control codes
At generation: compare likelihoods across classes
$$p(a | \tokens) \propto \frac{p(\tokens | a)}{p(\tokens)}$$
Fast inference (no gradients)
Strong attribute control
Requires training class-conditional LMs

FUDGE (Future Discriminator)

Yang, K. and Klein, D.
2021. FUDGE: Controlled Text Generation With Future Discriminators. Proceedings of the 2021 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies.
Predicts attribute from future tokens (not just past)
At generation: scores token by future attribute prediction
$$p(\tokens_i | \tokens_{\seq{1}{i}}, a) \propto p(\tokens_i | \tokens_{\seq{1}{i-1}}) \cdot p(a | prefix=\tokens_{\seq{1}{i}})$$
More fluent than PPLM (Bayesian guidance)
Can use any base LM (no retraining)
Requires training discriminator model
Slower than GeDi (Bayesian inference)
► Hard Constraints: Constrained Decoding

Exact Constraint Satisfaction

Enforce specific tokens, phrases, or logical constraints
Useful for controllable generation with guarantees

Constrained Search

Modify search to only keep sequences satisfying constraints
Constraints: required keywords, forbidden tokens, formats
Use cases
"Generate review containing 'excellent' and 'innovative'"
"Generate text avoiding toxic words"
"Follow specific format (e.g., JSON structure)"
Uses a Finite State Automata
Guarantees constraint satisfaction (somehow)
No extra models needed
Simple to implement
Limited to exact token matching
Can reduce fluency if constraints too strict
Exponential complexity for complex constraints
► Hard Constraints: Constrained Decoding (2)

NeuroLogic Decoding

NeuroLogic Decoding: (Un)Supervised Neural Text Generation with Predicate Logic Constraints:
2021. http://arxiv.org/abs/2010.12884.
Combines beam search with constraint satisfaction
Supports complex logical constraints (AND, OR, NOT)
Uses satisfiability solver to prune invalid beams
Modified beam search (scores for how satisfiable is the output so far)
Advanced constraints
"Include 'climate' AND ('warming' OR 'change')"
"Mention 'Paris' but NOT in context of 'fashion'"
Lexical constraints with logical operators
Flexible constraint specification
Handles complex logical formulas
Better quality than greedy constraint matching
More complex implementation
Higher computational cost

Conclusion

► Text Generation: Summary

Key Concepts Covered

Decoding Methods

  • Greedy decoding: fast but myopic
  • Beam search: explores multiple paths
  • MCTS: combines search and sampling

Sampling Methods

  • Ancestral: diverse but risky
  • Top-K: fixed threshold
  • Nucleus (Top-p): adaptive probability
  • Typical & Eta: entropy-aware

Constrained Generation

  • Soft: PPLM, GeDi, FUDGE
    Control attributes via guidance
  • Hard: Constrained beam search, NeuroLogic
    Enforce exact constraints

Quality vs. Diversity Trade-off

Decoding: high quality, low diversity
Sampling: high diversity, variable quality
The eternal dilemma
► Text Generation: Still an Open Problem
Why is text generation still challenging?
  1. Combinatorial Explosion
    Search space: $|\Tokens|^L$ (intractable)
  2. Quality-Diversity Trade-off
    Decoding: high-prob, low-diversity
    Sampling: diverse, lower quality
  3. Evaluation is Difficult
    Metrics correlate poorly with humans
    No universal metric for all aspects
  1. Long-Range Dependencies
    Maintaining consistency is hard
    Exposure bias during training
  2. Controllability vs. Fluency
    Strong constraints → reduced fluency
    Weak constraints → poor control
  3. Task-Specific Requirements
    Translation: beam search
    Creative writing: sampling
    No one-size-fits-all solution
Text generation remains one of the most exciting and challenging areas in NLP!