ApX logoApX logo
ModelsCalculatorHardwareCoursesPricing
ApX logoApX logo
ModelsCalculatorHardwareCoursesPricing

Masterclass

How To Build A Large Language Model
Chapter 1: Introduction to Large-Scale Language Modeling
Defining Large Language Models
Historical Context of Sequence Modeling
The Significance of Scale
Computational Challenges Overview
Software and Hardware Ecosystem
Chapter 2: Mathematical Preliminaries for LLMs
Linear Algebra Review: Vectors and Matrices
Calculus Review: Gradients and Optimization
Probability and Statistics Fundamentals
Numerical Stability Considerations
Notation Used Throughout This Course
Chapter 3: Revisiting Sequence Processing Architectures
Fundamentals of Recurrent Neural Networks (RNNs)
Limitations of Simple RNNs
Long Short-Term Memory (LSTM) Networks
Gated Recurrent Units (GRUs)
Sequence-to-Sequence Models with RNNs
Chapter 4: The Transformer Architecture
Overcoming Recurrence with Attention
Scaled Dot-Product Attention
Multi-Head Attention Mechanism
Positional Encoding Techniques
Encoder and Decoder Stacks
The Role of Layer Normalization and Residual Connections
Chapter 5: Tokenization for Large Vocabularies
The Need for Subword Tokenization
Byte Pair Encoding (BPE) Algorithm
WordPiece Tokenization
SentencePiece Implementation
Handling Special Tokens
Vocabulary Size Selection Trade-offs
Chapter 6: Sourcing and Acquiring Massive Text Datasets
Identifying Potential Data Sources
Utilizing Common Crawl Data
Web Scraping Techniques at Scale
Leveraging Open Licensed Datasets
Data Acquisition Legal Considerations
Chapter 7: Data Cleaning and Preprocessing Pipelines
Strategies for Quality Filtering
Text Normalization Methods
Handling Boilerplate and Markup Removal
Near-Duplicate and Exact Duplicate Detection
Language Identification and Filtering
Building Scalable Preprocessing Pipelines
Chapter 8: Building and Managing Large-Scale Datasets
Data Storage Formats (Text, Arrow, Parquet)
Distributed File Systems (HDFS, S3)
Data Indexing for Efficient Retrieval
Dataset Versioning and Reproducibility
Streaming Data Loaders for Training
Chapter 9: Data Sampling Strategies for Training
Importance of Data Mixture Composition
Source Weighting Strategies
Temperature-Based Sampling
Introduction to Curriculum Learning
Data Pacing and Annealing Schedules
Chapter 10: Implementing the Transformer from Scratch
Setting up the Project Environment
Implementing Scaled Dot-Product Attention
Building the Multi-Head Attention Layer
Implementing the Position-wise Feed-Forward Network
Constructing the Encoder and Decoder Layers
Assembling the Full Transformer Model
Chapter 11: Scaling Transformers: Architectural Choices
Scaling Laws for Neural Language Models
Depth vs Width Trade-offs
Choice of Activation Functions (ReLU, GeLU, SwiGLU)
Normalization Layer Placement (Pre-LN vs Post-LN)
Introduction to Sparse Attention Mechanisms
Chapter 12: Initialization Techniques for Deep Networks
The Importance of Proper Initialization
Xavier (Glorot) Initialization
Kaiming (He) Initialization
Initialization in Transformer Components
Small Initialization for Final Layers
Chapter 13: Positional Encoding Variations
Limitations of Absolute Positional Encodings
Relative Positional Encoding Concepts
Implementation of Shaw et al.'s Relative Position
Transformer-XL Relative Positional Encoding
Rotary Position Embedding (RoPE)
Chapter 14: Advanced Architectural Modifications
Parameter-Efficient Fine-Tuning Needs
Adapter Modules for Transformers
Introduction to Mixture-of-Experts (MoE)
Routing Mechanisms in MoE
Load Balancing in MoE Layers
Chapter 15: Distributed Training Strategies
Motivation: Why Distributed Training?
Data Parallelism (DP)
Tensor Parallelism (TP)
Pipeline Parallelism (PP)
Hybrid Approaches (DP+TP, DP+PP, etc.)
Communication Overhead Analysis
Chapter 16: Implementing Distributed Training Frameworks
Overview of Distributed Training Libraries
Introduction to DeepSpeed
Using DeepSpeed ZeRO Optimizations
Introduction to Megatron-LM
Configuring Tensor and Pipeline Parallelism in Megatron-LM
Combining Frameworks and Strategies
Chapter 17: Optimization Algorithms for LLMs
Review of Gradient Descent Variants (SGD, Momentum)
Adaptive Optimizers: Adam and AdamW
Learning Rate Scheduling Strategies
Gradient Clipping Techniques
Choosing Optimizer Hyperparameters (lr, betas, eps, weight_decay)
Chapter 18: Hardware Considerations for LLM Training
GPU Architectures (NVIDIA Ampere, Hopper)
TPU Architectures (Google TPUs)
Memory Requirements (HBM, GPU RAM)
Interconnect Technologies (NVLink, InfiniBand)
Hardware Selection Trade-offs (Cost, Performance, Availability)
Chapter 19: Checkpointing and Fault Tolerance
The Need for Checkpointing in Long Training Runs
Saving Model State (Weights, Optimizer States)
Handling Distributed Checkpointing
Asynchronous vs Synchronous Checkpointing
Checkpoint Frequency and Storage Management
Resuming Training from Checkpoints
Chapter 20: Mixed-Precision Training Techniques
Introduction to Floating-Point Formats (FP32, FP16, BF16)
Benefits of Lower Precision (Speed, Memory)
Challenges with FP16 Training (Range Issues)
Loss Scaling Techniques
Using BF16 (BFloat16) Format
Framework Support for Mixed Precision (AMP)
Chapter 21: Intrinsic Evaluation Metrics
Concept of Language Model Evaluation
Perplexity: Definition and Calculation
Interpreting Perplexity Scores
Bits Per Character/Word
Effect of Tokenization on Perplexity
Chapter 22: Extrinsic Evaluation on Downstream Tasks
Rationale for Downstream Task Evaluation
Common Downstream NLP Tasks
Fine-tuning Procedures for Evaluation
Standard Benchmarks: GLUE and SuperGLUE
Few-Shot and Zero-Shot Evaluation
Developing Custom Evaluation Tasks
Chapter 23: Analyzing Model Behavior
Challenges in Interpreting LLMs
Attention Map Visualization
Probing Internal Representations
Neuron Activation Analysis
Identifying Failure Modes
Chapter 24: Identifying and Mitigating Training Instabilities
Common Symptoms of Instability
Monitoring Training Metrics (Loss, Grad Norm)
Diagnosing Loss Spikes
Debugging Numerical Precision Issues
Stabilization Techniques Revisited (Clipping, LR, Warmup)
Impact of Architectural Choices on Stability
Chapter 25: Fine-tuning for Alignment: Supervised Fine-Tuning (SFT)
Goals of LLM Alignment
Introduction to Supervised Fine-Tuning (SFT)
Creating High-Quality Instruction Datasets
Data Formatting for SFT (Prompts, Completions)
The SFT Training Process and Hyperparameters
Evaluating SFT Models on Alignment Goals
Chapter 26: Reinforcement Learning from Human Feedback (RLHF)
The RLHF Pipeline Overview
Collecting Human Preference Data
Training the Reward Model (RM)
Introduction to Proximal Policy Optimization (PPO)
RL Fine-tuning with PPO
The Role of the KL Divergence Penalty
Challenges and Considerations in RLHF
Alternatives: Direct Preference Optimization (DPO)
Chapter 27: Model Compression Techniques
Motivation for Model Compression
Weight Quantization (INT8, INT4)
Activation Quantization Considerations
Network Pruning (Structured vs Unstructured)
Knowledge Distillation
Evaluating Performance vs Compression Trade-offs
Chapter 28: Efficient Inference Strategies
Challenges in Autoregressive Decoding
Key-Value (KV) Caching
Optimized Attention Implementations (FlashAttention)
Batching Strategies for Throughput
Speculative Decoding
Chapter 29: Serving LLMs at Scale
API Design for LLM Interaction
Model Serving Frameworks (Triton, TorchServe)
Handling Concurrent Requests
Load Balancing Across Model Instances
Monitoring Serving Performance and Cost
Chapter 30: Continuous Training and Model Updates
Motivation for Continuous Improvement
Strategies for Continual Pre-training
Strategies for Continual Fine-Tuning (SFT/RLHF)
Incorporating New Data Sources Safely
Updating Models with Architectural Changes
Versioning, Deployment, and Rollback Strategies

Byte Pair Encoding (BPE) Algorithm

Standard word-level tokenization runs into significant problems when dealing with the massive and diverse text corpora used to train large language models. Primarily, it struggles with out-of-vocabulary (OOV) words and the sheer size of the potential vocabulary. Byte Pair Encoding (BPE) offers an effective data-driven solution to these challenges. Originally developed as a data compression algorithm, BPE has been successfully adapted for text tokenization, creating a vocabulary of subword units.

The core idea behind BPE is elegantly simple: it starts with a vocabulary consisting of all individual characters present in the training corpus and iteratively merges the most frequently occurring adjacent pair of symbols to form new, longer subword symbols. This process continues for a predetermined number of merges, effectively controlling the final vocabulary size.

The BPE Training Process

Let's walk through how the BPE algorithm learns its vocabulary and merge rules from a corpus.

  1. Initialization:

    • Define the desired final vocabulary size, VtargetV_{target}Vtarget​.
    • Represent each word in the training corpus as a sequence of characters, adding a special end-of-word symbol (often </w> or </w>) to distinguish word boundaries. For example, "lower" becomes l, o, w, e, r, </w>.
    • The initial vocabulary consists of all unique characters present in the corpus.
  2. Iteration: Repeat the following steps until the desired vocabulary size VtargetV_{target}Vtarget​ is reached or a set number of merge operations have been performed:

    • Count Pairs: Identify all adjacent pairs of symbols (characters or already merged subwords) in the current representation of the corpus and count their frequencies.
    • Find Most Frequent Pair: Select the pair (s1,s2)(s_1, s_2)(s1​,s2​) that occurs most frequently.
    • Merge: Create a new symbol s12s_{12}s12​ representing the merged pair. Add s12s_{12}s12​ to the vocabulary.
    • Update Corpus Representation: Replace all occurrences of the adjacent pair (s1,s2)(s_1, s_2)(s1​,s2​) in the corpus representation with the new symbol s12s_{12}s12​. Record this merge operation (e.g., "merge s1s_1s1​ and s2s_2s2​ into s12s_{12}s12​").

A Small Example

For example, a tiny corpus with word counts: {'low': 5, 'lower': 2, 'newest': 6, 'widest': 3}.

Step 0: Initialization

  • Represent words as character sequences + </w>:
    • low: l o w </w> (occurs 5 times)
    • lower: l o w e r </w> (occurs 2 times)
    • newest: n e w e s t </w> (occurs 6 times)
    • widest: w i d e s t </w> (occurs 3 times)
  • Initial vocabulary: {l, o, w, </w>, e, r, n, s, t, i, d}
  • Desired vocabulary size: Let's aim for a few merges for demonstration.

Step 1: Count Pairs and Merge

  • Count adjacent pairs across the whole corpus (based on frequencies):
    • (l, o): 5 + 2 = 7
    • (o, w): 5 + 2 = 7
    • (w, </w>): 5
    • (w, e): 2 + 6 = 8
    • (e, r): 2
    • (r, </w>): 2
    • (n, e): 6
    • (e, w): 6
    • (e, s): 6 + 3 = 9 <- Most frequent
    • (s, t): 6 + 3 = 9 <- Equally frequent (let's pick (e, s))
    • (t, </w>): 6 + 3 = 9 <- Equally frequent
    • (w, i): 3
    • (i, d): 3
    • (d, e): 3
  • Merge (e, s) into a new symbol es. Vocabulary size increases.
  • Update corpus:
    • l o w </w> (5)
    • l o w e r </w> (2)
    • n e w es t </w> (6)
    • w i d es t </w> (3)
  • Record merge: e + s -> es

Step 2: Count Pairs and Merge

  • Recalculate pair frequencies in the updated corpus:
    • (l, o): 7
    • (o, w): 7
    • (w, </w>): 5
    • (w, e): 2 + 6 = 8
    • (e, r): 2
    • (r, </w>): 2
    • (n, e): 6
    • (e, w): 6
    • (w, es): 6
    • (es, t): 6 + 3 = 9 <- Most frequent (or equally with (t, </w>))
    • (t, </w>): 6 + 3 = 9
    • (w, i): 3
    • (i, d): 3
    • (d, es): 3
  • Merge (es, t) into a new symbol est.
  • Update corpus:
    • l o w </w> (5)
    • l o w e r </w> (2)
    • n e w est </w> (6)
    • w i d est </w> (3)
  • Record merge: es + t -> est

Step 3: Count Pairs and Merge

  • Recalculate frequencies:
    • ...
    • (est, </w>): 6 + 3 = 9 <- Most frequent (or equally with (t, </w>) if est wasn't picked in step 2)
    • ...
  • Merge (est, </w>) into est</w>.
  • Update corpus:
    • l o w </w> (5)
    • l o w e r </w> (2)
    • n e w est</w> (6)
    • w i d est</w> (3)
  • Record merge: est + </w> -> est</w>

This process continues. If we performed more merges, pairs like (l, o), (o, w), (w, e) might also get merged, potentially forming low or we. The final vocabulary would contain single characters and common multi-character subwords like es, est, est</w>, etc., based on their frequency in the training data.

Tokenizing New Text with Learned BPE

Once the BPE vocabulary and the ordered list of merge operations are learned from the training corpus, tokenizing new text involves the following steps:

  1. Split the input word into a sequence of characters. Add the end-of-word symbol </w>.
  2. Iteratively apply the learned merge operations in the same order they were learned during training. For each learned merge (s1,s2)→s12(s_1, s_2) \rightarrow s_{12}(s1​,s2​)→s12​, find all adjacent occurrences of (s1,s2)(s_1, s_2)(s1​,s2​) in the current sequence and replace them with s12s_{12}s12​.
  3. Continue until no more learned merges can be applied to the sequence.
  4. The resulting sequence of symbols (characters and subwords) is the tokenized representation. Each symbol corresponds to an ID in the final vocabulary.

For example, if we learned merges e + s -> es and then es + t -> est, tokenizing "tests" would proceed as:

  1. Initial: t, e, s, t, s, </w>
  2. Apply e + s -> es: t, es, t, s, </w>
  3. Apply es + t -> est: No adjacent es, t pair exists.
  4. Final tokens: t, es, t, s, </w>

If t + s -> ts was also learned after est, it might apply now: t, es, ts, </w>. The order of merges matters.

Handling Unknown Words

A significant advantage of BPE is its inherent ability to handle words not seen during training (OOV words). Since the initial vocabulary includes all single characters, any word can be broken down into a sequence of characters if necessary. If parts of the word correspond to learned subwords, those will be used; otherwise, it falls back to individual characters. For instance, if "huggingface" wasn't in the training data, but "hugg", "ing", "face" were learned subwords (or could be formed by merges), it might be tokenized as hugg, ing, face, </w>. If not, it might become h, u, g, g, i, n, g, f, a, c, e, </w>. There are no true "unknown" tokens in the sense of needing a dedicated [UNK] token, although one might still be included for other purposes.

Implementation Notes

  • Byte-Level BPE: A common variant operates on bytes instead of characters. This is particularly useful as it guarantees a fixed initial vocabulary size (256 bytes) and naturally handles all Unicode characters without needing special handling for accents or unseen characters. The logic remains the same, just merging frequent byte pairs.
  • Libraries: Implementing BPE efficiently requires careful handling of data structures and counts. Fortunately, libraries like Hugging Face's tokenizers provide optimized implementations. Training a BPE tokenizer might look like this (pseudo-code):
# BPE Training Loop
corpus = ["low low low low low", "lower lower", ...] # Your text data
word_counts = get_word_counts(corpus)
vocab = initialize_with_characters(word_counts)
splits = initial_split_words(word_counts) # e.g., {'l o w </w>': 5, ...}
num_merges = target_vocab_size - len(vocab)
merges = {} # Store learned merges

for i in range(num_merges):
  pair_counts = count_adjacent_pairs(splits)
  if not pair_counts:
    break
  most_frequent_pair = find_most_frequent(pair_counts)
  new_token = merge_pair(most_frequent_pair)
  vocab.add(new_token)
  merges[most_frequent_pair] = new_token
  splits = apply_merge_to_splits(splits, most_frequent_pair, new_token)

# Save vocab and merges

In practice, you'll typically use established libraries. Here's how you might use a pre-trained BPE tokenizer (like GPT-2's) with the Hugging Face transformers library in a PyTorch context:

import torch
from transformers import GPT2Tokenizer

# Load a pre-trained BPE tokenizer
tokenizer = GPT2Tokenizer.from_pretrained('gpt2')

text = "lower newest widest"
encoded_input = tokenizer(text, return_tensors='pt') # pt for PyTorch tensors

print("Input Text:", text)
print("Token IDs:", encoded_input['input_ids'])
# Example Output (IDs will vary): tensor([[ 3224, 29976, 23564]])
# Note 'lower' is one token, 'newest' is one, 'widest' is one in GPT-2's vocab

print(
    "Decoded Tokens:",
    tokenizer.convert_ids_to_tokens(encoded_input['input_ids'][0])
)
# Example Output: ['lower', 'Ġnewest', 'Ġwidest']
# The 'Ġ' (U+0120) often indicates
# the start of a word/token preceded by space.

# Handling potentially unknown combinations (though BPE handles OOV chars/bytes)
text_oov = "supercalifragilisticexpialidocious"
encoded_oov = tokenizer(text_oov, return_tensors='pt')
print("\nOOV-like Text:", text_oov)
print("Token IDs:", encoded_oov['input_ids'])
print(
    "Decoded Tokens:",
    tokenizer.convert_ids_to_tokens(encoded_oov['input_ids'][0])
)
# Example Output: ['super', 'cal', 'if', 'rag', 'il',
# 'istic', 'exp', 'ial', 'id', 'ocious']
# The word is broken down into known subword units from the GPT-2 vocabulary.

This code snippet demonstrates how a trained BPE tokenizer segments text into subword units represented by numerical IDs, ready for input into a model like a Transformer. It also shows the OOV handling where an unseen word is broken down into recognizable pieces.

Vocabulary Size Trade-off

The number of merge operations performed during BPE training directly determines the final vocabulary size. This presents a trade-off:

  • Larger Vocabulary: Can represent frequent words and morphemes with single tokens, leading to shorter token sequences for common text. However, it increases the size of the model's embedding layer (∣V∣×dmodel|V| \times d_{model}∣V∣×dmodel​) and might include very rare subwords.
  • Smaller Vocabulary: Results in longer token sequences as words are broken down into smaller units more often. This can increase computational cost during sequence processing but reduces the embedding layer size and might offer better generalization for rare or morphologically complex words by composing them from smaller pieces.

Choosing the right vocabulary size is an empirical process, often guided by the scale of the model, the characteristics of the training data, and downstream task performance. BPE provides the mechanism to control this balance.

In summary, BPE is a powerful and widely used subword tokenization technique. By learning to merge frequent character or byte pairs from a large corpus, it creates a vocabulary that effectively handles large amounts of text, avoids OOV issues, and allows control over the balance between vocabulary size and sequence length.

  • A New Algorithm for Data Compression, Philip Gage, 1994 C/C++ Users Journal, Vol. 12 - Original paper introducing Byte Pair Encoding as a general data compression algorithm.
  • Neural Machine Translation of Rare Words with Subword Units, Rico Sennrich, Barry Haddow, and Alexandra Birch, 2016 Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers) (Association for Computational Linguistics) DOI: 10.18653/v1/P16-1162 - Seminal work adapting BPE for neural machine translation, leading to its widespread adoption in NLP.
  • Language Models are Unsupervised Multitask Learners, Alec Radford, Jeffrey Wu, Rewon Child, David Luan, Dario Amodei, and Ilya Sutskever, 2019 (OpenAI) - Introduces Byte-Level BPE (BBPE) for tokenization in the GPT-2 model, addressing challenges with arbitrary Unicode text.
  • Natural Language Processing with Transformers: Building Innovative Applications with 🤗 Transformers, Lewis Tunstall, Leandro von Werra, and Thomas Wolf, 2022 (O'Reilly Media) - A practical and up-to-date overview of tokenization techniques, including BPE, within the context of modern LLMs and the Hugging Face ecosystem.

© 2026 ApX Machine Learning