$\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}}$
LLM - Large Language Models
Benjamin Piwowarski
Lesson 1: Introduction (master MIND)
Press ? for help on keyboard shortcuts
Slides in PDF
► Organization

Outline

  1. Language models and Transformer Architectures
  2. Generating and Training
  3. Efficient LLMs: inference & architectures
  4. Prompting and Evaluation
  5. Information Retrieval & RAG
  6. Multi-*: Multi-Modal, Multi-Lingual LLMs and Tools
  7. Trust, transparency and reliability: alignment & Steering, biases, hallucinations & safety, prompt injection, explainability and intepretability
► Organization (2)

Marks

Final Exam (50%)
  • One week before the exam: you will be given an article to read
  • Questions on the paper ⊕ general questions on the course
Pratical (50%)
  • Project (code + report) on the themes seen during practical lessons
► Organization (3)

To communicate

Personal matters
benjamin.piwowarski@cnrs.fr
General questions
Mattermost (LLM)
► Today
  • Introduction
  • Tasks and applications
  • Distributed Word Representation
  • Neural Models for Natural Language Processing
    • Quick glance at "history" (CNN, RNN)
    • (Self) Attention Models: Transformer-based Architectures
  • Training Transformers and LLMs (some hints)

Text and applications

► Textual Data: Characteristics

Different sources, different forms

Always complex structure

► Textual Data: Arbitrariness of the Symbol

Image = Continuous Space

Text = Arbitrariness of the Symbol

Image Space
How to compare Cat ... Dog ?
No natural distance
► Textual Data: Compositionality of the language
Compositionality
The meaning of a complex expression is determined by the meanings of its constituent parts and the rules used to combine them
Examples
  • Word level: "un" + "happy" → "unhappy"
  • Phrase level: "red" + "car" → "red car"
  • Sentence level: "The cat" + "sat on the mat" → "The cat sat on the mat"
Challenge
Understanding language requires understanding both individual units AND their composition
► Textual Data: Context is important
Polysemy and Ambiguity
The same word or sentence can have different meanings depending on context
Word level
  • "bank": financial institution vs. river bank
  • "bat": flying mammal vs. sports equipment
Sentence level
  • "I saw her duck"
    • witnessed her lower her head
    • observed her pet waterfowl
  • "The chicken is ready to eat"
    • the chicken is cooked and prepared for consumption
    • the chicken is hungry and wants to eat
Implication for NLP
Word and sentence representations must be contextual to capture meaning accurately
► A lot of text-related tasks

  • Indexing and Information Retrieval
  • Thematic classification / sentiments
  • Translation
  • Information extraction
  • Question answering
  • ...

Two main families of models: classification and generation

► Problems: Text Similarity
Applications
Information retrieval, textual inference
Related issues
efficiency (indexing, pre-selection)


Idea
Ranking documents = classifying a pair of texts
► Problems: Text Annotation
Applications
  • Segmentation
  • Named entity recognition
  • Semantic annotation
  • Question-Answering
The goal is to classify each word of the text
word 1 word 2 word 3 word 4 ...
cl. 1 cl. 2 cl. 3 cl. 4 ...
► Problems: Text Annotation
Information Extraction

We classify each word in the class B (begin) | E (end) | I (intermediate) - Type

Sophie went to Jean Jaurès Boulevard
EB-Name NA NA B-Location I-Location E-Location

Result

  • Name: Sophie
  • Location: Jean-Jaurès Boulevard
► Problems: Text Classification
Applications
  • Text classification
  • Sentiment detection


The goal is to classify a text
word 1 word 2 word 3 word 4 ...
class
► Problems: Generating Text
Goal
The goal is to "decode a text"
Principle
$s_t \in \RR^n$ represents the text generated up to token $t$
  • $s_0$ represents the initial state (= question representation, etc.)
  • $s_t$ is computed with a recurrent, convolutional, or self-attention network
A state $s_t$ defines a probability over words $$\prod_t P(w_t | s_t)\mathrm{\ with\ } s_{t+1} = f(\vx_t, s_t)$$
Applications
  • Machine translation
  • Image captioning
  • Dialogue
  • Data-to-text
  • ...
► Conclusion
Text characteristics: many different styles, symbol arbitrariness, compositionality, context
Tasks: Everything is classification (word-level, text-level, bi-text level)
Consequences
Computing a good representation of text of words is key to any NLP task,
but this is a very difficult thing...
and this where models have struggled for a long time!
Two main questions
Segmentation: What are the basic units of text?
Representation: How to represent them?

Pre-processing

► Pre-processing
Text pre-processing
Whatever the NLP task... you need to cleaning and preparing raw text data for analysis or model training. There are usually three steps:
The different steps
  1. Tokenization: breaking down into meaningful units
    Whatever the NLP task ... you need to cleaning and preparing raw text data for analysis or model training
  2. Text removal: cleaning up "useless units"
    Whatever the NLP task ... you need to cleaning and preparing raw text data for analysis or model training
  3. Normalization: stemming, lemmatization, lowercasing...
    whatever nlp task clean prepare raw text data analysismodel train

Discussion: what are the limits?

► Language Units
Word
Most natural?
Large vocabulary
Unknown words
Character
No unknown words
Small vocabulary
Less semantic / natural
Sub-units (unsupervised algorithm)
Intermediate between word and character / trained unsupervised
Example
An osteopath can fix your back
An / ▁osteo / path / ▁can / ▁fix / ▁your / ▁back /
► Tokenization Algorithms: Byte Pair Encoding (BPE)
Sennrich, R. et al.
2016. Neural Machine Translation of Rare Words with Subword Units. Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers).
How It Works
  1. Start with a character-level vocabulary (or bytes for byte-level BPE)
  2. Find the most frequent adjacent pair of tokens in the corpus
  3. Merge that pair into a single new token
  4. Repeat N times (typically 32,000 merges)
Example
Start: "l o w e r" (characters)
  • Iteration 1: Most frequent pair is (l, o) → merge to "lo w e r"
  • Iteration 2: Most frequent pair is (lo, w) → merge to "low e r"
  • Iteration 3: Most frequent pair is (low, e) → merge to "low"
Key Characteristic
Greedy, frequency-based: Always picks the globally most frequent pair
Used in: GPT-2, GPT-3, NeoBERT, ...
► Tokenization Algorithms: WordPiece
Schuster, M. and Nakajima, K.
2012. Japanese and Korean Voice Search. 2012 IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP).
How It Works
  1. Start with a character-level vocabulary
  2. For each possible pair, compute a likelihood score
  3. Merge the pair with the highest likelihood (not frequency)
  4. Repeat N times
Likelihood Formula
Uses Pointwise mutual information betweens the two tokens
$$\text{PMI} = \log \frac{P(AB)}{P(A\bullet) \times P(\bullet B) } = \log \frac{\text{count}(\text{pair})}{\text{count}(\text{first}) \times \text{count}(\text{second})}$$
Key Characteristic
Probabilistic, likelihood-based: Finds more linguistically meaningful splits
Used in: BERT, DistilBERT, RoBERTa, ...
► Tokenization Algorithms: SentencePiece
Kudo, T.
2018. Subword Regularization: Improving Neural Network Translation Models with Multiple Subword Candidates.
Unigram Model
Assumes that a segmentation is modeled by a unigram distribution
$$P(\mathbf{x})=\prod_{i=1}^M p\left(x_i\right) \text{ for a segmentation } \mathbf{x}=\left(x_1, \ldots, x_M\right) $$
The likelihood of a dataset $D$ is given by
$$\mathcal{L}=\sum_{s=1}^{|D|} \log \left(P\left(X^{(s)}\right)\right)=\sum_{s=1}^{|D|} \log \left(\sum_{\mathbf{x} \in \mathcal{S}\left(X^{(s)}\right)} P(\mathbf{x})\right)$$
Removing tokens
  1. Start with a large initial vocabulary $\{x_i\}$
  2. Iteratively remove the token that increases overall loss the least
  3. Continue until target vocabulary size is reached
► Tokenization Algorithms: SentencePiece (2)
Example
Text: "reading"
SentencePiece (BPE mode):
  • Raw input: "▁reading" (space is explicit character)
  • Tokens: ['▁read', 'ing']
Key Characteristic
Language-independent, no pre-processing: Works on any language without language-specific preprocessing
Used in: T5, mT5, XLNet, LLaMA, multilingual models
► Tokenization Algorithms: Comparison
AspectBPEWordPieceSentencePiece
Selection CriterionMost frequent pairHighest likelihoodRemove lowest-loss token
Pre-tokenizationNeeded (whitespace)Needed (whitespace)Not needed
Space HandlingImplicit or Ġ markerImplicit or ## markerExplicit ▁ marker
Language SupportEnglish-focusedEnglish-focusedMultilingual
Merging DirectionBottom-up (char → word)Bottom-up (char → word)Top-down (many → few)
► Examples
Examples of BPE vs SentencePiece (Unigram) segmentation
Bostrom, K. and Durrett, G.
2020. Byte Pair Encoding Is Suboptimal for Language Model Pretraining. Findings of the Association for Computational Linguistics: EMNLP 2020.
► Limits
Junk Tokens
After merging (BPE/WordPiece), some tokens might be left-over. Why?
Bostrom, K. and Durrett, G.
2020. Byte Pair Encoding Is Suboptimal for Language Model Pretraining. Findings of the Association for Computational Linguistics: EMNLP 2020.
Multiple segmentation
Multiple segmentation can lead to the same text
Kudo, T.
2018. Subword Regularization: Improving Neural Network Translation Models with Multiple Subword Candidates.
Multilinguality
Vocabulary can get big when tokenizing texts in multiple languages (and tokens even less meaningful)
Some works still study how to deal with character/byte-level tokenization, more on this week 3!
Non exhaustive list:
Dynamic Chunking for End-to-End Hierarchical Sequence Modeling:
2025. http://arxiv.org/abs/2507.07955.
Byte Latent Transformer: Patches Scale Better Than Tokens:
2024. http://arxiv.org/abs/2412.09871.
► The modern pre-processing pipeline

Training

  1. Training: Training a tokenizer on a representative set of texts (WordPiece, BPE or SentencePiece)

Inference

  1. Tokenization: breaking down text into meaningful units
  2. Text removal: cleaning up "useless units"
  3. Normalization: lowercasing (uncased) or nothing (cased)

Distributed Word Representations

► Document Representation: Bag of Words
How to process documents?
Bag-of-words approach
► Document Representation: Bag of Words

Similarity = dot product

sum of products of weights in each dimension
"the blue truck" . "the blue vehicle" = 2
"the blue truck" . "the blue building" = 2
► Document Representation: What We Would Like...

Moving to a semantic space!

…
Vehicle Transport Color Color Construction … …
truck 0.5 0.5 0 0 0 …
vehicle 1 0 0 0.1 0 …
blue 0 0 0.5 0.7 0 …
building 0 0 0 0.1 0.8 …
We can now compare words (and sentences)
► Building Abstract Semantic Spaces
A solution
Exploit regularities
Representation in a vector space $\mathbb{R}^n$
🗓️ Precursors : Saussure/Wittgenstein, then Zellig Harris and John Firth
Word sequence
The boy went...
  • to the dentist
  • to school
  • to the moon
  • ...
In practice, simpler = word co-occurrences
► Solution: Co-occurrence Graph
► Solution: Vector Spaces
Representation
$$\mathrm{cat} = (\underbrace{-0.15, -0.02, -0.23, -0.23, -0.18, \ldots}_{n\ \mathrm{numbers}})$$
$$\mathrm{dog} = (\underbrace{-0.40, 0.37, 0.02, -0.34, 0.05, \ldots }_{n\ \mathrm{numbers}})$$
$$\mathrm{computer} = (\underbrace{-0.27, -0.14, 0.23, -0.26, 0.09, \ldots}_{n\ \mathrm{numbers}})$$
Similarity
$$s(\mathrm{cat},\mathrm{dog}) = (-0.15\times -0.40) + (-0.02\times 0.37) + (-0.23\times -0.02) + \cdots = 0.8$$
$$s(\mathrm{cat},\mathrm{computer}) = (-0.15*-0.27) + (-0.02\times -0.14) + (-0.23\times 0.23) + \cdots = 0.25$$
► Word Learning
► Representation Spaces: Relations
Transformation = Relation
A geometric transformation corresponds to a semantic relation
Example
$$\v{x}{man} = \v{x}{woman} + \v{t}{womanhood}$$
$$\v{x}{uncle} = \v{x}{aunt} + \v{t}{womanhood}$$
$$\ldots$$
These regularities are identified a posteriori from the learning.
Mikolov, T. et al.
2013. Distributed Representations of Words and Phrases and Their Compositionality. NIPS’14.
► Representation Spaces: Similarities
► Representation Space and Generation

A nice brand new representation space

For a word $x\in \mathcal V$, we associate a vector $\hat m$ $$x: m \in \mathcal V \rightarrow \hat m_1 \in \mathbb R^d$$
We can now compare two words
We define similarity by the dot product
$s(m_1, m_2) = x(m_1) \cdot x(m_2)$
... and generate them
But we can also use this metric to define which word to generate
Idea = we want to generate a word corresponding to $x\in \mathbb R^d$
  1. We compute $x \cdot \hat m$ for every word in the vocabulary
  2. Then we normalize ($-x \cdot \hat m$ is the term's energy)
  3. $$ P(\mbox{generate }m | x) = \frac{ \exp(x \cdot \hat m) }{ \sum_{m^\prime} \exp(x \cdot \hat m^\prime) } $$
► Other Word Representation Models

There are other word representation models

Non-Contextual

  • Glove
    Global vectors learned from word co-occurrence statistics
    Pennington, J. et al.
    2014. Glove: Global Vectors for Word Representation.
  • FastText
    Word embeddings enhanced with subword information (character n-grams)
    Joulin, A. et al.
    2016. Bag of Tricks for Efficient Text Classification.

Contextual

  • Elmo
    Embeddings from Language Models using bidirectional LSTMs
    Peters, M.E. et al.
    2018. Deep Contextualized Word Representations. NAACL.
  • Transformer architectures, e.g. BERT
    Deep bidirectional representations using masked language modeling
    Devlin, J. et al.
    2018. BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding.

Neural Models for Natural Language Processing

► Summary
Currently, there are 4 solutions to represent sentences and/or solve text tasks:
Recurrent Networks
Processing sequences unit by unit
Possibility of using memories (attention)
Use cases: any task
Convolutional Networks
Hierarchical pattern detection
Use cases: classification (topic, sentiment)
Interaction Models
Alignment of two texts
Use cases: Information retrieval, inference (is this the right answer?)
Self-Attention Models
Contextual representation
Use cases: any task
► Three main types of architectures
Encoder
Represents each token / text by a vector in $\mathbb{R}^d$
(usually) bi-directional
tasks: token or text-level classification
Decoder
Token/Text representation depends on the previous ones
uni-directional
tasks: token or text-level classification, generation
Encoder-Decoder
Combines an encoder (e.g. query, document to analyze) and a decoder (generation)
tasks: Same as decoder
Nowadays, mostly for multi-modal inputs
► Principle of Recurrent Models
At each time $t$ is associated
  • A state $s_t \in \RR^n$
  • An input $x_t \in \RR^p$
Colah's blog
Principle
The next state is computed from the input $x_t$ and the previous state $s_{t-1}$:
$$s_{t} = f_\theta(s_{t-1}, x_t)$$
► Introduction
You've seen them in images... quick reminders
► Idea 1: Data has symmetry axes
Invariance hypothesis (by translation)
Processing does not change depending on position
In video, independence by translation (3D)
In images, independence by translation (2D)
In text, independence by translation (1D)
In text
Analyzing I loved this movie does not depend on context
► Idea 2: Compositionality of Processing
Abstraction by composition
By composing convolutional layers, we detect increasingly complex patterns
In images: edges, ..., objects
In text, word groups, .., sentence fragments
In text
Analyzing I loved this movie can be done in two steps:
  1. Detect
    • "I loved" [ME/LIKE]
    • "this movie" [OBJECT]
  2. Detect [ME/LIKE] [OBJECT] = positive sentiment
► Convolutional Models - Principle
Detect a pattern "I like"
► Convolutional Models - Dependencies
We try to detect combinations of patterns in the sequence "don't like" AND "horror films" in the sequence
► Application Example: Classification
► Limitations of RNNs and CNNs
Recurrent Neural Networks (RNNs)
  • Sequential processing: Cannot parallelize across time steps
    Must process tokens one by one, slow for long sequences
  • Long-range dependencies: Hard to capture distant relationships
    Vanishing gradients despite LSTM/GRU improvements
  • Information bottleneck: Fixed-size hidden state
    All past information compressed into single vector
Convolutional Neural Networks (CNNs)
  • Limited receptive field: Need many layers for long-range dependencies
    Each layer only sees local context (e.g., 3-5 tokens)
  • Not position-aware: Same pattern everywhere
    Difficult to model positional relationships
  • Fixed pattern size: Kernel size determines what patterns can be detected
    Hard to capture variable-length dependencies
💡 Solution: Self-attention mechanisms

Attention and Memory

► From RNNs to Memory-based Models
Given the shortcomings of RNNs...
  • Information bottleneck (fixed-size hidden state)
  • Difficulty with long-range dependencies
  • Sequential processing limitations

Inspiration from human cognition

Working Memory
Humans don't compress everything into a single representation
We have a working memory that we can query when needed
A new approach
What if neural networks could use external memory?
Allow models to store and retrieve information dynamically
► Early Memory-based Approaches
Neural Turing Machines & Memory Networks
Graves, A. et al.
2014. Neural Turing Machines.
Weston, J. et al.
2014. Memory Networks.
  • Explicit external memory component
  • Read (and write) operations controlled by attention
  • Can learn algorithms and store/retrieve facts
Example: Question Answering with Memory Networks
Weston, J. et al.
2014. Memory Networks.
Story: "John went to the kitchen. Mary got the milk. John moved to the garden."
Question: "Where is John?"
Memory: Store each sentence as a separate memory slot
Process: Query memory with the question → Retrieve relevant facts → Answer "garden"
► Example: Text as Memory
The text itself can serve as memory
Translation
Vinyals, O. et al.
2017. Pointer Networks.
► How it Works

Let a "memory" $M=\{\mat{m}_i \in \RR^{n_m}\}$

We can extract from each memory element:
A key
a key $k(\mat{m}_i) \in \RR^{n_k}$ that allows searching for a memory element
A value
a value $v(\mat{m}_i) \in \RR^{n_v}$ that contains the value associated with this element

Given $\vx \in \RR^{n}$, we

  1. Determine the query $q(\vx) \in \RR^{n_k}$
  2. Compute an attention probability $$\log p(A_i | \vx, M) = K + k(\mat{m}_i) \cdot q(\vx) $$
  3. Compute the output $f(\vx) = \sum_i p(A_i) v(\mat{m}_i)$
► How it Works (2)
Reading a memory composed of 5 units
► Conclusion
Some attempts to build read/write memories for neural networks have been attempted using the same principles (with limited success)
Graves, A. et al.
2014. Neural Turing Machines.
Weston, J. et al.
2014. Memory Networks.
memory-based networks have improved first automated translation (January 2017)
Vinyals, O. et al.
2017. Pointer Networks.
before the first paper on Transformer architectures appeared – also on translation (June 2017)
Vaswani, A. et al.
2017. Attention Is All You Need.

Transformers and LLMs

► Self-Attention Model
Vaswani, A. et al.
2017. Attention Is All You Need.
Big ideas
  1. Text contextualization (memory, without recurrence)
    The text is its memory
  2. Limited vocabulary
    With BPE initially
  3. Pre-trained model (unsupervised) on large amounts of text
    With BERT (encoder architecture)
  4. Multi-task training
    With
    Raffel, C. et al.
    2019. Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer.
► Contextualization
We use self-attention mechanisms (memory = text) that allow contextualizing each input token
Vaswani, A. et al.
2017. Attention Is All You Need.
Input are tokens $t_1, \ldots, t_6$
We obtain contextualized representations $x_1, \ldots, x_6$
► Basic architecture
Pre-processing
Tokenization and normalization $\tokens_{\seq{1}{L}} = \tokens_1, \ldots, \tokens_L \in \{1, \ldots, V\}$
Inputs
Initial input: from tokens $\tokens_{\seq{1}{L}}$ to vectors $\trep{0}{\seq{1}{L}} = \trep{0}{1}, \ldots, \trep{0}{L} \in \mathbb{R}^d$
$n$ layers
Each layer $\ell \in \{1, \ldots, n \}$ is made of several block
  1. Self-Attention $\trep{\ell-1}{\seq{1}{L}} \rightarrow \sarep{\ell}{\seq{1}{L}}$
  2. Only for a decoder in an encoder-decoder
    Attention on the encoder $\carep{\ell}{\seq{1}{L}}$
  3. A two-layer feedforward neural network (~ associative memory)
    $\arep{\ell-1}{\seq{1}{L}} \rightarrow \trep{\ell}{\seq{1}{L}}$
► Architecture: the input
The input
Uses an embedding table $\rep{sem}{\tokens_i} \in \mathbb{R}^d$
The self-attention process is invariant to permutations
How to include positional information?
Absolute Positional Embeddings
Positional embedding $\rep{pos}{i} \in \mathbb{R}^d$
$\rep{pos}{i}$ can either be learnable parameters (BERT), or
$$ \begin{aligned} P E_{(p o s, 2 i)} & =\sin \left(p o s / 10000^{2 i / d_{\text {model }}}\right) \\ P E_{(p o s, 2 i+1)} & =\cos \left(p o s / 10000^{2 i / d_{\text {model }}}\right) \end{aligned} $$
The input of a transformer is then $\rep{pos}{i} + \rep{sem}{\tokens_i}$
► Positional Embeddings: Attention Patterns
Attention map for positional embeddings
Observations
  • Periodic pattern: Diagonal stripes with regular spacing
  • Symmetry: Pattern is symmetric around the diagonal
  • Decay: Attention strength decreases with distance
► Architecture: Multi-Head Attention
Multi-Head Attention $\mat{z}_{1, \ldots, L }= MHA(\vx_{1\ldots L}, \vy_{1\ldots L'})$
For each head $h$, we compute the attention probability:
$\alpha^h_{ij} = \frac{1}{\sqrt{d_h}}\mat{Q_h} \vx_i \cdot \mat{K_h} \vy_j$ ➡️ $p(j|i, h) = \mathop{\mathrm{softmax}}_j(\alpha_{i\bullet})$
Finally, we can compute the output of the the attention as:
$$\mat{z_i} = \sum_h \mat{O}_h \sum_j p(j|i,h) \mat{V}_h \vy_j \text{ with } \mat{V}_h \vy_j \in \mathbb{R}^{d_h}$$
Self-Attention and Cross-Attention Layer
$$\sarep{\ell}{\seq{1}{L}} = LN\left(\trep{\ell-1}{\seq{1}{L}} + MHA(\trep{\ell-1}{\seq{1}{L}}, \trep{\ell-1}{\seq{1}{L}})\right)$$
with $LN$ a layer normalization: $LN(\vx) = \gamma \odot \frac{\vx - \mu}{\sigma} + \beta$
In the case of cross-attention in decoder ($n'$ the number of layer of the encoder)
$$\carep{\ell}{\seq{1}{L}} = LN\left(\trep{\ell-1}{\seq{1}{L}} + MHA(\trep{\ell-1}{\seq{1}{L}},{\color{blue} \tyrep{n'}{1\ldots L'}})\right)$$
► Architecture: Masked and Biased Multi-Head Attention
Causal mask
For autoregressive models (e.g., GPT), we mask future positions
$$M_{ij} = \begin{cases} 0 & \text{if } i \geq j \\ -\infty & \text{if } i < j \end{cases}$$
The attention scores become: $\alpha^h_{ij} = \mat{Q_h} \vx_i \cdot \mat{K_h} \vy_j + M_{ij}$
Example for sequence length 4
$$ M = \begin{bmatrix} 0 & -\infty & -\infty & -\infty \\ 0 & 0 & -\infty & -\infty \\ 0 & 0 & 0 & -\infty \\ 0 & 0 & 0 & 0 \end{bmatrix} $$
After softmax, positions only attend to current and previous positions
► Architecture: The feedforward network
After attention aggregates information across tokens, we need to process each position independently
Role of the FFN
  • Attention: communication between positions
  • FFN: computation within each position
  • Each token is processed identically but independently
FFN: Token-wise operation
FFN is a two-layer neural network
$$\mat{z} = \mat{V} \mathrm{\phi}(\mat{U} \vx + \mat{b}) + \mat{c}$$ with $\mat{W_1} \in \mathbb{R}^{d_1}$, $d_1 >> d$ (e.g. $d_1=4d$ in BERT) and $\phi$ an activation function, e.g. in BERT a ReLU $\phi(\vx) = \max(\vx, 0)$
The $i$th output of the overall FFN network:
$$ \vy_i = \sum_i \text{ReLU}(\mat{U} \vx + \mat{b})_i \mat{V}_{\bullet i}+ \mat{c}_i$$
► Recent evolution

Since 2018, a number of changes have occurred

  1. Relative Positional Embeddings: ROPE, ALiBi
  2. Pre-normalization to post-normalization
  3. Shift from LayerNorm to RMSNorm
  4. FFN activation function: from ReLU to SWIGLU
  5. Sparse Attention Patterns
► Alternative: Relative Position Biases
The problem with absolute positions
  • Absolute positional embeddings (sinusoidal or learned) encode where a token is
  • But often what matters is the relative distance between tokens
  • Example: "the cat" should have similar representations whether at positions (0,1) or (10,11)
Add position information to attention scores
Instead of adding positional embeddings to inputs, bias the attention directly
$$\alpha^h_{ij} = \mat{Q_h} \vx_i \cdot \mat{K_h} \vy_j + {\color{blue} b_{i-j}}$$
where $b_{i-j}$ depends only on the relative distance $i-j$
  • Used in T5, DeBERTa, and many recent models
  • Can handle sequences longer than training length
  • Often clips distances: $b_{\min(k, i-j)}$ for some maximum $k$
► Alternative: Relative Position Biases (2)
Advantages
  • Better generalization to different sequence lengths
  • More flexible - model learns what distances matter
  • Can be combined with absolute positions if needed
► Modern Positional Encodings: RoPE
RoPE: Rotary Position Embedding
RoFormer: Enhanced Transformer with Rotary Position Embedding:
2022. http://arxiv.org/abs/2104.09864.
Encode relative positions through rotation
Apply rotation $\boldsymbol{R}_{\Theta, m}^d$ to query and key vectors based on their positions $m$
$$ \small \boldsymbol{R}_{\Theta, m}^d=\left(\begin{array}{ccccccc} \cos m \theta_1 & -\sin m \theta_1 & 0 & 0 & \cdots & 0 & 0 \\ \sin m \theta_1 & \cos m \theta_1 & 0 & 0 & \cdots & 0 & 0 \\ 0 & 0 & \cos m \theta_2 & -\sin m \theta_2 & \cdots & 0 & 0 \\ 0 & 0 & \sin m \theta_2 & \cos m \theta_2 & \cdots & 0 & 0 \\ \vdots & \vdots & \vdots & \vdots & \ddots & \vdots & \vdots \\ 0 & 0 & 0 & 0 & \cdots & \cos m \theta_{d / 2} & -\sin m \theta_{d / 2} \\ 0 & 0 & 0 & 0 & \cdots & \sin m \theta_{d / 2} & \cos m \theta_{d / 2} \end{array}\right) $$
where $\theta_i = 10000^{-2i/d}$
  • Key property: $\mat{q}_m^T \mat{k}_j$ depends only on relative position $m-n$
  • Used in GPT-3, LLaMA, ...
  • Excellent extrapolation to longer sequences
► Modern Positional Encodings: ALiBi – Attention with Linear Biases
Train Short, Test Long: Attention with Linear Biases Enables Input Length Extrapolation:
2022. http://arxiv.org/abs/2108.12409.
Simple linear penalty based on distance
Add a bias to attention scores proportional to distance:
$$\text{softmax}(q_i K^T + m \cdot [0, -1, -2, \ldots, -(i-1)])$$
where $m$ is a head-specific slope set before training (e.g., $m_h = 2^{-8h/H}$)
  • No positional embeddings needed - only bias in attention
  • Different slopes for different heads
  • Very strong extrapolation capability
► Modern activation functions for the FFN

FFN activation functions have evolved

ReLU
$$\text{ReLU}(x) = \max(0, x)$$
Devlin, J. et al.
2018. BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding.
Vaswani, A. et al.
2017. Attention Is All You Need.
GELU (2016, Transformers)
$$\text{GELU}(x) = x \cdot \Phi(x) = x \cdot \frac{1}{2}\left[1 + \text{erf}\left(\frac{x}{\sqrt{2}}\right)\right]$$
► Modern activation functions for the FFN (2)

SwiGLU (2020, Modern LLMs)

GLU Variants Improve Transformer:
2020. http://arxiv.org/abs/2002.05202.
Based on Gated Linear Units (GLU)
Language Modeling with Gated Convolutional Networks:
2017. http://arxiv.org/abs/1612.08083.
The SwiGLU activation function is defined as $$\text{SwiGLU}(\vx) = \text{Swish}_\beta(\mat{T}\vx + \mat{b}) \otimes (\mat{U} \vx + \mat{c})$$
where $\text{Swish}(\vx) = x \cdot \sigma(\beta x)$
Improved performance over GELU
Used in most modern architectures
► Architecture: Pre vs Post-Normalization

Two options

  1. Post = After adding each residual, normalize the outputs
  2. Pre = Before computing the residual, normalize the outputs
Post-normalization (Original Transformer)
Self-attention block:
$$\sarep{\ell}{\seq{1}{L}} = \mathrm{LayerNorm}(\trep{\ell-1}{\seq{1}{L}} + MHA(\trep{\ell-1}{\seq{1}{L}}, \trep{\ell-1}{\seq{1}{L}}))$$
Feedforward block:
$$\trep{\ell}{\seq{1}{L}} = \mathrm{LayerNorm}(\sarep{\ell}{\seq{1}{L}} + \mathrm{FFN}(\sarep{\ell}{\seq{1}{L}}))$$
Normalization applied after residual connection
► Architecture: Pre vs Post-Normalization (2)
Pre-normalization (Modern LLMs)
Self-attention block:
$$\sarep{\ell}{\seq{1}{L}} = \trep{\ell-1}{\seq{1}{L}} + MHA(\mathrm{LayerNorm}(\trep{\ell-1}{\seq{1}{L}}), \mathrm{LayerNorm}(\trep{\ell-1}{\seq{1}{L}}))$$
Feedforward block:
$$\trep{\ell}{\seq{1}{L}} = \sarep{\ell}{\seq{1}{L}} + \mathrm{FFN}(\mathrm{LayerNorm}(\sarep{\ell}{\seq{1}{L}}))$$
Normalization applied before the transformation
Comparison
  • Post-norm: Original Transformer architecture
    • Requires careful learning rate warmup
    • Can be unstable with deep networks
  • Pre-norm: Used in GPT, BERT variants, modern LLMs
    • More stable training / Better gradient flow
    • Easier to train very deep networks (e.g., GPT-3 with 96 layers)
► From LayerNorm to RMSNorm
LayerNorm (Original)
Normalizes across all features using mean and variance:
$$LN(\vx) = \gamma \odot \frac{\vx - \mu}{\sqrt{\sigma^2 + \epsilon}} + \beta$$
where $\mu = \frac{1}{d}\sum_{i=1}^d x_i$ and $\sigma^2 = \frac{1}{d}\sum_{i=1}^d (x_i - \mu)^2$
  • Centers and scales the activations
  • Learnable parameters: $\gamma$ (scale) and $\beta$ (shift)
► From LayerNorm to RMSNorm (2)
RMSNorm: Root Mean Square Normalization
Zhang, B. and Sennrich, R.
2019. Root Mean Square Layer Normalization.
Simplifies by removing mean centering:
$$\text{RMSNorm}(\vx) = \gamma \odot \frac{\vx}{\text{RMS}(\vx)}$$
where $\text{RMS}(\vx) = \sqrt{\frac{1}{d}\sum_{i=1}^d x_i^2 + \epsilon}$
  • No mean centering - only scale normalization
  • Only learnable scale parameter $\gamma$ (no shift $\beta$)
  • Faster: 7-64% speedup over LayerNorm
  • Simpler: Fewer operations
Why the shift?
  • Empirically, re-centering (subtracting mean) provides little benefit
  • RMS normalization alone is sufficient for stable training
► Encoders vs Decoders
Encoders are better suited for understanding tasks (classification, extraction) whereas decoders are better for generation tasks (text generation, translation)
Ettin paired encoder & decoder
Seq vs Seq: An Open Suite of Paired Encoders and Decoders:
2025. http://arxiv.org/abs/2507.11412.
Models with same sizes trained with the same data
Models in the preferred architecture (e.g. encoders in MNLI) do better than the opposite architecture even with an order of magnitude greater size
► Conclusion

Transformer architecture has evolved since 2017

  • Positional embeddings: from absolute to relative (RoPE, ALiBi)
  • Normalization: from LayerNorm post-norm to RMSNorm pre-norm
  • Activation functions: from ReLU to SwiGLU
  • Attention patterns: from dense to sparse / efficient (more on this later)

but the core principles remain the same!

  • Self-Attention for contextualization (+ cross-attention in encoder-decoders)
  • Feedforward networks for per-token computation
  • Stacking layers with residual connections

Encoder vs Decoders

  • Encoders for understanding tasks
  • Decoders for generation tasks
  • Encoder-Decoders: multi-modal tasks (e.g., image captioning, table QA, ...)