Skip to content

mekalakarthik05/Transformers

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

2 Commits
Β 
Β 
Β 
Β 

Repository files navigation

πŸš€ Transformers in Large Language Models (LLMs)

A Complete Theoretical and Mathematical Study Guide

Transformers are the foundational architecture behind the modern artificial intelligence revolution. Introduced in 2017, they discarded sequential processing in favor of the Self-Attention Mechanism, allowing models to process language in parallel and understand deep, long-range context. This architectural breakthrough is the engine powering Large Language Models (LLMs) like GPT, BERT, and LLaMA.

This handbook provides a mathematically rigorous, structurally complete breakdown of how Transformers operate from the ground up.


πŸ“¦ Repository Structure

transformers-study-guide/

β”œβ”€β”€ README.md
β”‚   Complete theoretical study guide

└── Transformers.ipynb
    PyTorch implementation notebook

πŸ“‘ Table of Contents


PART I β€” Foundations

🎯 Learning Objectives

Learning Outcome

Establish a concrete understanding of the goals and scope of this text.

Core Concepts

Upon completing this study guide, students will be able to:

  1. Mathematically derive the Scaled Dot-Product Attention mechanism.
  2. Trace exact, multidimensional tensor shapes through every stage of a Transformer layer.
  3. Implement a generative GPT-style Transformer purely in PyTorch.
  4. Analyze the computational constraints of $O(N^2)$ scaling and the engineering solutions required for modern LLMs.

Mathematical Explanation

Not applicable for this section.

Real-World Example

A student utilizing this guide will transition from treating ChatGPT as a "black box" to understanding the exact floating-point matrix multiplications occurring on the NVIDIA GPUs powering it.


Prerequisites

Learning Outcome

Identify the foundational knowledge required to digest the mathematics in this handbook.

Core Concepts

  • Basic Python: Array manipulation and loops.
  • Linear Algebra: Deep understanding of vectors, matrices, dot products, and matrix multiplication.
  • Probability: Understanding distributions and exponential functions.
  • Neural Networks: Familiarity with feed-forward networks, loss functions, and backpropagation.

Mathematical Explanation

Not applicable for this section.

Real-World Example

To understand how an LLM predicts the next word, one must first understand how a basic neural network performs linear regression using linear algebra.


Notation Table

Learning Outcome

Standardize the dimensional variables used throughout all mathematical and code examples.

Core Concepts

This text utilizes standard academic notation for Transformer tensor dimensions.

Symbol Meaning
B Batch Size (Number of sequences processed simultaneously)
N Sequence Length (Number of tokens in the sequence)
$d_{model}$ Embedding Dimension (Size of the vector representing a token)
d_k Key/Query Dimension (Size of a single attention head's projection)
d_v Value Dimension (Usually equal to $d_k$)
H Number of Attention Heads
V Vocabulary Size (Total number of unique tokens in the tokenizer)

Mathematical Explanation

A single batch of text entering a Transformer is mathematically represented as a 3D tensor: $$ X \in \mathbb{R}^{B \times N \times d_{model}} $$

Real-World Example

If you process 32 sentences ($B=32$), each containing 512 words ($N=512$), and every word is represented by a vector of 768 numbers ($d_{model}=768$), the resulting matrix contains $32 \times 512 \times 768 = 12,582,912$ discrete floating-point numbers.


Complete Transformer Architecture Diagram

Learning Outcome

Visualize the macro-level data flow through a Generative Transformer.

Core Concepts

The entire architecture is a strictly ordered sequence of mathematical transformations designed to extract semantic meaning and predict the next token.

Diagram

graph TD
  Input[Input Text] --> Tokenizer[Tokenizer]
  Tokenizer --> TokenIDs[Token IDs]
  TokenIDs --> Embed[Embedding Layer]
  Embed --> Pos[Positional Encoding]
  Pos --> Block
  
  subgraph Transformer Blocks
    Block --> MHA[Multi-Head Attention]
    MHA --> AddNorm1[Residual Add & LayerNorm]
    AddNorm1 --> FFN[Feed-Forward Network]
    FFN --> AddNorm2[Residual Add & LayerNorm]
  end
  
  AddNorm2 --> Final[Final Hidden States]
  Final --> Linear[Linear Layer]
  Linear --> Softmax[Softmax]
  Softmax --> Output[Output Token]
Loading

Mathematical Explanation

Not applicable for this section.

Real-World Example

When a prompt is inputted into a model, the sequence is processed through the tokenization and embedding layers, passing through the stacked Transformer blocks, before the final linear layer outputs the next token.


Mathematical Foundations

Learning Outcome

Understand the mathematical entitiesβ€”Vectors, Matrices, Dot Products, and Softmaxβ€”that act as the building blocks of neural operations.

Core Concepts

Neural networks do not process text strings; they process multidimensional floating-point tensors.

  • Vector: A 1D array of numbers. Represents a point or direction in space.
  • Matrix: A 2D grid of numbers. Matrices act as linear transformations, projecting vectors from one dimension to another.

Mathematical Explanation

The Dot Product: A geometric measurement of similarity between two vectors of equal length. $$ A \cdot B = \sum_{i=1}^n a_i b_i $$

Softmax: Converts a vector of arbitrary raw numbers (logits) into a valid probability distribution. $$ \text{Softmax}(x_i) = \frac{\exp(x_i)}{\sum_{j} \exp(x_j)} $$

Real-World Example

If two word vectors, King and Monarch, point in the same direction in a high-dimensional space, their dot product is highly positive, signaling to the network that they share semantic similarity.


Evolution Before Transformers

Learning Outcome

Trace the historical progression of NLP algorithms to identify the critical sequential flaws that necessitated the invention of the Transformer.

Core Concepts

  • Bag of Words / One-Hot Encoding: Resulted in sparse, high-dimensional vectors that did not capture semantic similarity or token order.
  • Word2Vec: Mapped words to dense vectors. However, vectors were static. "Bank" had one vector regardless of context.
  • RNNs (Recurrent Neural Networks): Attempted to build context by processing text sequentially, passing a "hidden state" from left to right.

Mathematical Explanation

RNNs calculate the hidden state at time $t$ based on the hidden state at time $t-1$: $$ h_t = f(W_h h_{t-1} + W_x x_t) $$ This mathematical sequence is the fatal flaw. The strict $O(N)$ sequential bottleneck prevents parallelization on modern GPU hardware. Repeated multiplications cause the gradients to decay (Vanishing Gradient problem).

Real-World Example

When an RNN processes long sequences, the influence of early states (e.g., $h_1$) decays exponentially through successive matrix multiplications, limiting the model's ability to maintain long-range context.


PART II β€” Core Transformer Architecture

Tokenization

Learning Outcome

Understand how raw strings are converted into processable integer sequences.

Core Concepts

Transformers cannot read text. Before entering the network, text is split into subwords using algorithms like Byte-Pair Encoding (BPE) and mapped to integer IDs from a fixed Vocabulary.

Mathematical Explanation

Tokenization is a discrete mapping function $T$: $$ T: \text{String} \rightarrow {0, 1, \dots, V-1}^N $$ Where $N$ is the sequence length, and each integer $i \in [0, V-1]$.

Real-World Example

The string "Transformers are great" might be split by a BPE tokenizer into 4 subwords: [Trans, formers, are, great] and converted to IDs: [4512, 891, 312, 908].


Embeddings

Learning Outcome

Understand the transformation of discrete tokens into dense vectors.

Core Concepts

  • Embedding Matrix: A massive lookup table where every vocabulary token has a dedicated floating-point vector.
  • Dense Vector Representations: Unlike sparse One-Hot vectors, dense vectors pack semantic meaning into a continuous space.
  • Semantic Similarity: Words with similar meanings exist geometrically closer to each other in this high-dimensional space.

Mathematical Explanation

The Embedding Matrix $E$ is defined as: $$ E \in \mathbb{R}^{V \times d_{model}} $$ Where $V$ is the vocabulary size, and $d_{model}$ is the embedding dimension. An embedding lookup maps a batch of integer token IDs to their corresponding vectors: $$ x \in {0, 1, \dots, V-1}^{B \times N} \rightarrow X \in \mathbb{R}^{B \times N \times d_{model}} $$ Where the row at index $x_{b,n}$ in $E$ represents the token embedding vector.

Numerical Example

Token IDs:
[101, 2057, 2293, 102]

↓

Embedding Vectors:
[
 [0.12, -0.33, ...],
 [1.21, 0.98, ...],
 ...
]

Real-World Example

Because embeddings capture geometric semantics, they allow algebraic manipulation of concepts. The classic example in a well-trained embedding space is: Vector(King) - Vector(Man) + Vector(Woman) $\approx$ Vector(Queen).


🧠 Attention Mechanism

Learning Outcome

Understand the conceptual shift from the Encoder-Decoder bottleneck to dynamic Attention.

Core Concepts

  • The Bottleneck: Early translation models compressed an entire source sentence into a single vector. For long sentences, this was an impossible bottleneck.
  • Attention (2014): A breakthrough allowing a Decoder to "look back" at all source hidden states and dynamically weight which word was most important at the current generation step.

Mathematical Explanation

Attention creates a context vector $c_i$ by taking a weighted sum of the encoder hidden states $h_j$: $$ c_i = \sum_{j} \alpha_{ij} h_j $$ Where $\alpha_{ij}$ is the attention weight probability distribution over the source words, defined as: $$ \alpha_{ij} = \frac{\exp(e_{ij})}{\sum_{k} \exp(e_{ik})} $$ Where $e_{ij}$ represents the output of an alignment model scoring the similarity between the previous decoder state and the encoder representation $h_j$.

Real-World Example

While generating the French word "chat", the model calculates high attention weights for the English source words "The" and "cat", and near-zero weights for irrelevant words in the sentence.


Self-Attention

Learning Outcome

Understand how the Transformer repurposed Attention to operate on a single sequence in parallel.

Core Concepts

  • Self-Attention: Every word evaluates its mathematical relevance to every other word in the same sequence, simultaneously.
  • Contextual Representation: Words dynamically merge with surrounding context, altering their vector space to resolve ambiguity.
  • Parallel Processing: The sequence is processed as a unified matrix, eliminating RNN sequential bottlenecks.

Diagram: Self-Attention Flow

graph LR
  X[Input Embeddings]
  
  X --> Q[Query]
  X --> K[Key]
  X --> V[Value]
  
  Q --> Score[QK^T]
  K --> Score
  
  Score --> Softmax
  Softmax --> Weights
  
  Weights --> Context
  
  V --> Context
  
  Context --> Output
Loading

Mathematical Explanation

Self-Attention mathematically relates the entire input sequence $X$ to itself, generating an $N \times N$ similarity matrix.

Real-World Example

In the sentence "The bank of the river", Self-Attention links the word "bank" heavily to "river", mathematically shifting the vector for "bank" away from "finance" and towards "nature".


πŸ”‘ Query-Key-Value (QKV)

Learning Outcome

Understand the three distinct linear projections that facilitate Self-Attention.

Core Concepts

To allow tokens to communicate, the model generates three vectors for every token:

  • Query (Q): What semantic information am I looking for?
  • Key (K): What semantic information do I contain?
  • Value (V): What is my actual underlying meaning?

Mathematical Explanation

Given an input embedding matrix $X \in \mathbb{R}^{B \times N \times d_{model}}$, the model applies three learnable weight matrices ($W^Q, W^K, W^V$) to project the data: $$ Q = X W^Q $$ $$ K = X W^K $$ $$ V = X W^V $$ Where the weights are defined as: $$ W^Q \in \mathbb{R}^{d_{model} \times d_k}, \quad W^K \in \mathbb{R}^{d_{model} \times d_k}, \quad W^V \in \mathbb{R}^{d_{model} \times d_v} $$ The resulting projected matrices have shapes: $$ Q \in \mathbb{R}^{B \times N \times d_k}, \quad K \in \mathbb{R}^{B \times N \times d_k}, \quad V \in \mathbb{R}^{B \times N \times d_v} $$

Real-World Example

The Query-Key-Value paradigm operates analogously to database retrieval. A query vector (Q) is matched against key vectors (K) representing stored tokens. The resulting similarity coefficients weight the corresponding value vectors (V) to compile the output.


Scaled Dot Product Attention

Learning Outcome

Mathematically derive the core formula of the Transformer architecture.

Core Concepts

The formula executes the logic: match Queries to Keys to get a score, scale the score so gradients don't vanish, turn the scores into percentages, and extract the Values.

Mathematical Explanation

$$ \text{Attention}(Q, K, V) = \text{Softmax} \left( \frac{QK^T} {\sqrt{d_k}} \right)V $$

  1. Dot Product ($QK^T$): Multiplies the query matrix $Q$ by the transpose of the key matrix $K$ over the sequence and projection dimensions. This yields the raw attention scores of shape $(B, N, N)$.
  2. Scaling ($\sqrt{d_k}$): High dimensionality $d_k$ causes dot products to grow large in magnitude, pushing the Softmax function into regions with near-zero gradients. We divide by $\sqrt{d_k}$ to stabilize the variance of the logits.
  3. Softmax: Applied along the last dimension to normalize the scores into an $(B, N, N)$ attention weight probability distribution.
  4. Value Aggregation ($\times V$): Multiplies the attention weights by the value matrix $V$, yielding the final contextualized outputs of shape $(B, N, d_v)$.

Real-World Example

If the sequence is "The cat", "cat" dots with "The" to score $3.0$, and "cat" dots with "cat" to score $6.0$. After Softmax, "cat" pays $99%$ attention to its own Value vector and $1%$ to "The".


Multi-Head Attention

Learning Outcome

Understand how splitting the attention mechanism isolates different linguistic features.

Core Concepts

A single attention calculation averages out context. To capture complex grammar, the $d_{model}$ vector is split into $H$ heads.

  • Head 1 finds verbs.
  • Head 2 finds adjectives.

Mathematical Explanation

$$ \text{MultiHead}(Q, K, V) = \text{Concat}(\text{head}1, \dots, \text{head}H)W^O $$ Where each head is: $$ \text{head}i = \text{Attention}(Q W_i^Q, K W_i^K, V W_i^V) $$ And the projection matrices are defined as: $$ W_i^Q \in \mathbb{R}^{d{model} \times d_k}, \quad W_i^K \in \mathbb{R}^{d{model} \times d_k}, \quad W_i^V \in \mathbb{R}^{d{model} \times d_v}, \quad W^O \in \mathbb{R}^{H d_v \times d_{model}} $$ In execution, input shape $(B, N, d_{model})$ is projected in parallel using concatenated weights of shape $(d_{model}, H d_k)$, reshaped to $(B, N, H, d_k)$, and transposed to $(B, H, N, d_k)$. The attention output of shape $(B, H, N, d_v)$ is transposed back to $(B, N, H, d_v)$, concatenated to $(B, N, H d_v)$, and projected back using $W^O$ to shape $(B, N, d_{model})$.

Real-World Example

In the sentence "The bark of the tree", Head A links "bark" to "tree" (identifying it as nature), while Head B ensures "The" properly modifies "bark" grammatically.


Cross-Attention

Learning Outcome

Understand the bridge mechanism between Encoder and Decoder modules.

Core Concepts

In Encoder-Decoder models (like translation), the Decoder needs to look at the translated source text.

  • Query: Comes from the Decoder's current state.
  • Key & Value: Come from the Encoder's final output.

Mathematical Explanation

$$ \text{CrossAttention}(Q_{dec}, K_{enc}, V_{enc}) = \text{Softmax}\left(\frac{Q_{dec}K_{enc}^T}{\sqrt{d_k}}\right)V_{enc} $$

Real-World Example

Command context maps words dynamically. When the Decoder generates the French word "chien", the Cross-Attention Query searches the English Encoder's Keys to find "dog", and extracts the English "dog" Value representation to guide the generation.


Positional Encoding

Learning Outcome

Understand how the Transformer overcomes its native inability to recognize sequence order.

Core Concepts

Because Attention evaluates all tokens simultaneously via matrix multiplication, the model has absolutely no concept of word order.

  • The Fix: Before entering the Attention layer, we add a mathematical "time-stamp" vector to the embedding vector. (Note: Modern LLMs replace static additions with Rotary Position Embeddings or RoPE).

Mathematical Explanation

The original paper used sine and cosine waves: $$ PE_{(pos, 2i)} = \sin\left(\frac{pos}{10000^{2i/d_{\text{model}}}}\right) $$ $$ PE_{(pos, 2i+1)} = \cos\left(\frac{pos}{10000^{2i/d_{\text{model}}}}\right) $$

Real-World Example

Without positional encodings, "Dog bites man" and "Man bites dog" yield identical mathematical sums in the Attention layer. The encodings force "Dog at position 0" to be mathematically distinct from "Dog at position 2".


πŸ—οΈ Transformer Block

Learning Outcome

Understand the auxiliary components that stabilize the core MHA mechanism in deep networks.

Core Concepts

  • Residual Connections: Highways that add the original input to the output ($x + \text{Layer}(x)$) to prevent Vanishing Gradients.
  • LayerNorm: Normalizes the data to a mean of 0 and variance of 1 to stabilize training. (Modern LLMs often prefer RMSNorm).
  • Feed-Forward Network (FFN): Processes each token independently. Expands dimensionality by 4x to memorize factual knowledge. (Modern LLMs often prefer SwiGLU).

Diagram: Transformer Block

graph TD
  Input --> LN1[LayerNorm]
  LN1 --> MHA[Multi-Head Attention]
  MHA --> Add1[Residual Add]
  Add1 --> LN2[LayerNorm]
  LN2 --> FFN[Feed-Forward Network]
  FFN --> Add2[Residual Add]
  Add2 --> Output
Loading

Mathematical Explanation

Pre-Norm formulation: $$ x = x + \text{MHA}(\text{LayerNorm}(x)) $$ $$ x = x + \text{FFN}(\text{LayerNorm}(x)) $$

Real-World Example

Residual connections provide a direct path for gradients to propagate backward through the network without attenuation, mitigating the vanishing gradient problem in deep architectures.


Tensor Shape Walkthrough

Learning Outcome

Track exact dimensional changes through a block to bridge theory and code.

Core Concepts

Let $B=32$, $N=512$, $d_{model}=768$, $H=12$, Vocab $V=50K$.

Mathematical Explanation

  • Input IDs: $(32, 512)$
  • Embeddings: $(32, 512, 768)$
  • Q, K, V Projections: $(32, 512, 768)$
  • Split into Heads: $(32, 12, 512, 64)$
  • Attention Scores ($QK^T$): $(32, 12, 512, 512)$
  • Attention Output ($\times V$): $(32, 12, 512, 64)$
  • Concatenation: $(32, 512, 768)$
  • FFN Expand: $(32, 512, 3072)$
  • Final Output: $(32, 512, 768)$
  • Logits: $(32, 512, 50000)$

Real-World Example

Because the tensor shape entering the block $(32, 512, 768)$ matches the shape exiting the block $(32, 512, 768)$, multiple blocks can be sequentially stacked to construct deep architectures.


Padding and Attention Masks

Learning Outcome

Understand how tensors handle variable-length sequences in batches.

Core Concepts

GPUs require perfect rectangular matrices (e.g., $32 \times 512$). If a sentence only has 100 words, the remaining 412 slots are filled with a [PAD] token (integer 0). We use a Padding Mask to force the Attention mechanism to ignore these zeros.

Mathematical Explanation

Before Softmax, the $N \times N$ mask overwrites pad positions with $-\infty$: $$ \text{Scores}{mask} = QK^T + M{pad} $$ Where $M_{pad}$ contains $0$ for valid tokens and $-\infty$ for pad tokens. Softmax($-\infty$) = 0.

Real-World Example

If we don't mask the padding tokens, the word "cat" might accidentally pay 10% of its mathematical attention to blank empty space, corrupting the generation.


PART III β€” Scaling Transformers

πŸ“Š Complexity Analysis

Learning Outcome

Mathematically understand the bottlenecks preventing Transformers from processing infinite text.

Core Concepts

Self-Attention demands calculating the relationship between every token and every other token.

Mathematical Explanation

For sequence length $N$ and embedding dimension $d_{model}$:

  • Time Complexity: $O(N \cdot d_{model}^2 + N^2 \cdot d_{model})$ per block layer.
    • Linear projection projection calculations ($Q, K, V, O$) scale as $O(N \cdot d_{model}^2)$.
    • Self-attention matrix calculations ($QK^T$ score product and the value aggregation step) scale quadratically as $O(N^2 \cdot d_{model})$.
  • Memory Complexity: $O(N \cdot d_{model} + H \cdot N^2)$ per block layer, where $H$ is the number of heads.
    • Storing the activations for the sequence scales linearly as $O(N \cdot d_{model})$.
    • Materializing the attention similarity matrices in memory scales quadratically as $O(H \cdot N^2)$.

Real-World Example

A 1-Million token context window (Gemini 1.5 Pro) requires evaluating 1 Trillion relationships per attention head. Standard attention computations result in high activation memory footprints, exceeding GPU memory capacity and necessitating IO-aware algorithms like FlashAttention.


⚑ Efficient Attention

Learning Outcome

Analyze the architectural hacks used to bypass $O(N^2)$ scaling.

Core Concepts

Instead of full $N \times N$ attention, models approximate the matrix.

  • Longformer: Uses a sliding window (tokens only look at nearby neighbors) with global hubs.
  • BigBird: Combines random attention, window attention, and global attention.
  • Mistral / Mixtral: Uses Sliding Window Attention (SWA) and Grouped Query Attention (GQA) to drastically extend context limits without memory explosions.

Mathematical Explanation

SWA reduces complexity from $O(N^2)$ to $O(N \times W)$, where $W$ is a fixed window size (e.g., 4096 tokens).

Real-World Example

Mistral-7B can process entire books because it doesn't force word 100,000 to mathematically attend directly to word 1; it propagates context efficiently through sliding windows.


Weight Tying

Learning Outcome

Understand a memory-saving trick for language models.

Core Concepts

The input Embedding matrix and the output Logits linear layer have the exact same shape $(V, d_{model})$. Weight Tying forces them to share the exact same weights in memory.

Mathematical Explanation

$$ W_{embed} = W_{logits}^T $$ This assumes the output projection layer has no bias terms. By forcing the input representation projection and the output vocabulary prediction parameters to share weights, parameter footprints are reduced and the geometric learning behavior of token alignment is regularized.

Real-World Example

For a vocab of $50K$ and $d_{model}$ of $4096$, tying the weights saves $50,000 \times 4096 = 204$ Million parameters from consuming GPU VRAM.


Modern Transformer Improvements

Learning Outcome

Understand the breakthrough techniques engineered for Trillion-parameter bounds.

Core Concepts

  • KV Cache: Caches previous Keys and Values in VRAM to prevent recalculating past tokens during generation.
  • FlashAttention: Tiles attention computations into ultra-fast SRAM, completely bypassing the slow $O(N^2)$ HBM materialization.
  • MoE (Mixture of Experts): Slices the massive FFN into 8 smaller "Experts". A router sends tokens to only the top 2 experts, saving FLOPs.
  • LoRA (Low-Rank Adaptation): Fine-tuning by freezing the base model and training tiny $A$ and $B$ decomposed matrices.

Mathematical Explanation

  • LoRA Decomposition: $$ \Delta W \approx B \times A $$ Where base model weights $W \in \mathbb{R}^{d \times k}$ are frozen, and weight update parameter changes $\Delta W$ are approximated by low-rank matrices $B \in \mathbb{R}^{d \times r}$ and $A \in \mathbb{R}^{r \times k}$ where $r \ll \min(d, k)$. Matrix $A$ is typically initialized using a zero-mean Gaussian distribution $\mathcal{N}(0, \sigma^2)$, and matrix $B$ is initialized to 0, ensuring $\Delta W = 0$ at training onset.
  • Rotary Position Embeddings (RoPE): RoPE applies a rotation matrix to Query ($Q$) and Key ($K$) projections along 2D coordinate slices of head dimensions. For a 2D slice $x = (x_1, x_2)^T$ at position $m$, the transformation is defined as: $$ R_{\Theta, m}^2 \begin{pmatrix} x_1 \ x_2 \end{pmatrix} = \begin{pmatrix} \cos m\theta & -\sin m\theta \ \sin m\theta & \cos m\theta \end{pmatrix} \begin{pmatrix} x_1 \ x_2 \end{pmatrix} $$ This formulation encodes relative position directly into the dot product relation of keys and queries.

Real-World Example

LoRA allows researchers to fine-tune a massive 70B parameter model on a single consumer GPU, as they only train 0.1% of the total weights.


PART IV β€” Transformer Architectures

Encoder Architecture

Learning Outcome

Understand the bidirectional foundation of BERT.

Core Concepts

The Encoder uses Unmasked Self-Attention. Word 3 looks at Word 1 (past) and Word 5 (future) simultaneously.

Diagram: Encoder vs Decoder

graph LR
  Encoder --> Bidirectional[Bidirectional Attention]
  Decoder --> Causal[Causal Attention]
  
  Bidirectional --> Understanding
  Causal --> Generation
Loading

Mathematical Explanation

The attention matrix $QK^T$ remains unmasked, resulting in $100%$ context evaluation.

Real-World Example

Used in Google Search algorithms. It reads the entire user query forwards and backwards to grasp perfect grammatical intent before returning search results.


Decoder Architecture

Learning Outcome

Understand the autoregressive foundation of GPT.

Core Concepts

The Decoder uses Masked Self-Attention.

Mathematical Explanation

During the $QK^T$ matrix multiplication, the upper-right triangle (future tokens) is overwritten with $-\infty$. $$ \text{Softmax}(-\infty) = 0 $$ This blinds the model to the future.

Real-World Example

Modern conversational models (e.g., GPT-4) utilize Decoder-only architectures. They ingest a prompt, calculate token probabilities, autoregressively sample the next token, and append it back to the context window.


Architecture Comparison Table

Learning Outcome

Quickly contrast model purposes.

Core Concepts

Model Architecture Purpose
Transformer Encoder-Decoder Translation
BERT Encoder Only Understanding / Search
GPT Decoder Only Autoregressive Generation

Encoder-only models specialize in language understanding, Decoder-only models specialize in autoregressive text generation, and Encoder-Decoder models combine both capabilities for sequence-to-sequence tasks such as translation and summarization.

Mathematical Explanation

Not applicable for this section.

Real-World Example

You cannot use BERT to write an essay (it cannot generate text autoregressively). You cannot use GPT for optimal sentence classification (it cannot look backwards from the end of the sentence).


PART V β€” Transformers in Modern LLMs

Training Transformers

Learning Outcome

Understand the mathematical pipeline of training an LLM.

Core Concepts

  • Forward Pass: Pass dataset through model to output next-word probabilities.
  • Cross Entropy Loss: Mathematically penalizes wrong predictions.
  • Backpropagation: The Chain Rule calculates gradients backwards.
  • Gradient Descent (AdamW): Optimizes the weights to minimize loss.

Mathematical Explanation

Cross Entropy Loss over a target token distribution $p$ and predicted token distribution $q$ is defined as: $$ H(p,q)

-\sum_{x} p(x)\log q(x) $$ For a single training prediction where the target token is index $y$, the loss simplifies to the negative log-likelihood of the softmax target probability: $$ \mathcal{L} = -\log \left( \frac{\exp(z_y)}{\sum_{j} \exp(z_j)} \right) $$ Where $z$ represents the output logits vector from the final linear projection layer.

Real-World Example

If the correct next word is "Paris", $p(x) = 1.0$. If the model predicted "Paris" with probability $q(x) = 0.01$, the logarithmic penalty is massive, forcing an aggressive weight update.


Inference

Learning Outcome

Understand probabilistic text generation.

Core Concepts

  • Temperature ($T$): Scales logits. $T>1$ increases randomness. $T \rightarrow 0$ makes it greedy.
  • Top-P (Nucleus): Samples from tokens whose cumulative probability equals $P$.

Mathematical Explanation

Temperature scaling: $$ p_i = \frac{\exp(z_i / T)}{\sum_j \exp(z_j / T)} $$

Real-World Example

Setting $T = 0.1$ is perfect for coding tasks requiring exact syntax. Setting $T = 0.9$ is perfect for writing creative poetry.


Prompting and In-Context Learning

Learning Outcome

Understand how large models learn without gradient updates.

Core Concepts

Massive LLMs exhibit Few-Shot Learning. By providing examples in the prompt, the Attention mechanism dynamically maps the pattern into the activation space without permanently changing the $W$ matrices.

Mathematical Explanation

Not applicable for this section.

Real-World Example

Prompting: "English: Cat $\rightarrow$ French: Chat. English: Dog $\rightarrow$ French:". The model recognizes the translation pattern via Self-Attention and generates "Chien".


Modern LLM Training Pipeline

Learning Outcome

Understand the multi-stage pipeline required to build a conversational AI.

Core Concepts

  1. Pretraining: Massive internet scraping. Next-Token prediction.
  2. SFT: Supervised Fine-Tuning. High-quality Q&A data.
  3. RLHF / DPO: Alignment to human preferences.

Diagram: Training Pipeline

graph LR
  Pretraining --> SFT
  SFT --> RLHF
  RLHF --> DPO
  DPO --> Assistant
Loading

Mathematical Explanation

Not applicable for this section.

Real-World Example

Pretraining establishes general language modeling and factual knowledge representations, SFT aligns the output format to instruction/response conventions, and RLHF aligns model behavior with safety and utility guidelines.


End-to-End Inference Pipeline

Learning Outcome

Visualize the unbroken data flow of a generation loop.

Core Concepts

Autoregressive generation is an infinite loop terminating on an [EOS] token.

Diagram: Inference Pipeline

graph TD
  Prompt --> Tokenization
  Tokenization --> Embeddings
  Embeddings --> TransformerLayers
  TransformerLayers --> Logits
  Logits --> Softmax
  Softmax --> Sampling
  Sampling --> GeneratedToken
  GeneratedToken --> Prompt
Loading

Mathematical Explanation

Not applicable for this section.

Real-World Example

To generate a 10-word sentence, the 96-layer matrix operation executes 10 times, appending one word per loop.


Architecture Families

Learning Outcome

Identify the lineage of modern open-source LLMs.

Core Concepts

  • LLaMA (Meta): SwiGLU activations, RoPE, RMSNorm. A widely adopted family of open-source foundation models.
  • Mistral: Sliding Window Attention, MoE architectures.
  • T5 (Google): Classic Encoder-Decoder fine-tuned for text-to-text formatting.

Mathematical Explanation

Not applicable for this section.

Real-World Example

If you want to build a RAG application locally, you download an architecture derived from the LLaMA family from HuggingFace, because it performs strongly across standardized benchmarks.


Multimodal Transformers

Learning Outcome

Understand how the Transformer generalizes beyond text to vision and audio.

Core Concepts

Because Transformers process arbitrary $N$-length arrays of vectors, you can pass them any data type, provided you can embed that data into a dense vector space.

  • Vision Transformer (ViT): Chops an image into $16 \times 16$ pixel patches. Each patch is flattened into a 1D vector and projected into $d_{model}$.
  • CLIP: Aligns text embeddings and image embeddings into the exact same vector space.

Mathematical Explanation

For a Vision Transformer (ViT), we process an image mathematically: $$ \text{Image} \in \mathbb{R}^{H \times W \times C} $$ It is chopped into flattened patches: $$ \text{Patches} \in \mathbb{R}^{N_{patches}\times(P^2C)} $$ It is then linearly projected into the embedding space: $$ \text{Embeddings} \in \mathbb{R}^{N_{patches}\times d_{model}} $$ where $$ N_{patches} = \frac{HW}{P^2} $$ This transforms a 2D image matrix into the exact $(N, d_{model})$ shape required by the standard Attention layer.

Real-World Example

This patching mechanism allows multimodal models to ingest an image, project it to the token embedding space, and process it through the Self-Attention mechanism alongside text tokens.


PART VI β€” References

πŸ“š Core References

The foundational academic literature underlying the engineering of modern LLMs.

  • Vaswani et al., "Attention Is All You Need", 2017.
  • Devlin et al., "BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding", 2018.
  • Radford et al., "Language Models are Unsupervised Multitask Learners" (GPT-2), 2019.
  • Brown et al., "Language Models are Few-Shot Learners" (GPT-3), 2020.
  • Hu et al., "LoRA: Low-Rank Adaptation of Large Language Models", 2021.
  • Dao et al., "FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness", 2022.
  • Raffel et al., "Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer" (T5), 2019.
  • Touvron et al., "LLaMA: Open and Efficient Foundation Language Models", 2023.

Additional Reading

  • Kudo & Richardson, "SentencePiece: A simple and language independent subword tokenizer", 2018.
  • Wu et al., "Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation", 2016.
  • Dosovitskiy et al., "An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale" (ViT), 2020.
  • Radford et al., "Learning Transferable Visual Models From Natural Language Supervision" (CLIP), 2021.
  • Rafailov et al., "Direct Preference Optimization: Your Language Model is Secretly a Reward Model" (DPO), 2023.
  • Press et al., "Train Short, Test Long: Attention with Linear Biases Enables Input Length Extrapolation" (ALiBi), 2021.
  • Peng et al., "YaRN: Efficient Context Window Extension of Large Language Models", 2023.
  • Zhang & Sennrich, "Root Mean Square Layer Normalization" (RMSNorm), 2019.
  • Shazeer, "GLU Variants Improve Transformer" (SwiGLU), 2020.
  • Beltagy et al., "Longformer: The Long-Document Transformer", 2020.
  • Jiang et al., "Mistral 7B", 2023.

About

No description, website, or topics provided.

Resources

Stars

9 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors