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

Transformer-XL Relative Positional Encoding

While absolute positional encodings, whether sinusoidal or learned, provide the necessary sequence order information to Transformers, they have limitations. They typically assume a maximum sequence length, and their ability to generalize to sequences longer than those seen during training can be restricted. Furthermore, they don't explicitly represent the relative distance between tokens, which might be a more natural way for attention mechanisms to operate.

The Transformer-XL architecture, introduced by Dai et al. (2019), proposed a novel relative positional encoding scheme designed specifically to address these issues, particularly in the context of processing longer sequences using a segment-level recurrence mechanism (though the encoding method itself is valuable independently). Instead of adding positional information to the word embeddings, Transformer-XL injects relative position information directly into the attention score calculation.

Core Idea of Transformer-XL Relative Encoding

The central idea is to modify how the attention score between a query at position iii and a key at position jjj is computed. In the standard Transformer, the score depends on the query qiq_iqi​ and the key kjk_jkj​, where both potentially contain absolute positional information added to their respective embeddings.

Transformer-XL reformulates the attention score calculation to explicitly depend on the relative distance (i−j)(i-j)(i−j). It achieves this by making two primary modifications:

  1. Relative Position Embeddings for Keys: Instead of using absolute position embeddings pjp_jpj​ for the key vector, it uses relative position embeddings Ri−jR_{i-j}Ri−j​ that represent the offset between the query and key positions. These embeddings Ri−jR_{i-j}Ri−j​ are typically fixed sinusoidal encodings, similar to the original Transformer, but they encode the relative distance rather than an absolute position. Importantly, the same relative embedding RkR_kRk​ is used for all query positions iii when a key is kkk positions away (i.e., j=i−kj = i-kj=i−k). This allows the model to potentially generalize to unseen relative distances.

  2. Decomposition of Query Interaction: The query vector qiq_iqi​ interacts differently with the content and positional aspects. The standard dot product qiTkjq_i^T k_jqiT​kj​ is decomposed into multiple terms that separate content-content interaction, content-position interaction, and position-position interaction using dedicated trainable parameters.

Mathematical Formulation

Let qi=WQxiq_i = W_Q x_iqi​=WQ​xi​ be the query vector for token xix_ixi​ at position iii, and kj=WKxjk_j = W_K x_jkj​=WK​xj​ be the content-based key vector for token xjx_jxj​ at position jjj. Let Ri−jR_{i-j}Ri−j​ be the sinusoidal embedding vector for the relative position i−ji-ji−j. In the standard Transformer, the core term inside the softmax would be approximately qiT(kj+pj)q_i^T (k_j + p_j)qiT​(kj​+pj​).

Transformer-XL replaces this with a more sophisticated calculation for the attention score Ai,jA_{i,j}Ai,j​:

Ai,jrel=qiTWKxj⏟(a) content-based+qiTWRRi−j⏟(b) content-position+uTWKxj⏟(c) global content bias+vTWRRi−j⏟(d) global position biasA_{i,j}^{rel} = \underbrace{q_i^T W_K x_j}_{\text{(a) content-based}} + \underbrace{q_i^T W_R R_{i-j}}_{\text{(b) content-position}} + \underbrace{u^T W_K x_j}_{\text{(c) global content bias}} + \underbrace{v^T W_R R_{i-j}}_{\text{(d) global position bias}}Ai,jrel​=(a) content-basedqiT​WK​xj​​​+(b) content-positionqiT​WR​Ri−j​​​+(c) global content biasuTWK​xj​​​+(d) global position biasvTWR​Ri−j​​​

Here:

  • WQ,WKW_Q, W_KWQ​,WK​ are the usual weight matrices for queries and content-based keys.
  • WRW_RWR​ is a new trainable weight matrix applied to the relative position embeddings Ri−jR_{i-j}Ri−j​.
  • uuu and vvv are new trainable parameter vectors.
  • Ri−jR_{i-j}Ri−j​ is a fixed (usually sinusoidal) encoding representing the relative distance i−ji-ji−j. It does not depend on the specific content xix_ixi​ or xjx_jxj​.

Let's break down the terms:

  • (a) Content-based Addressing: This is the standard term measuring the similarity between the query content qiq_iqi​ and the content kj=WKxjk_j = W_K x_jkj​=WK​xj​.
  • (b) Content-Position Addressing: This term captures how the query content qiq_iqi​ relates to the relative position i−ji-ji−j of the key. The query interacts with the transformed relative position embedding WRRi−jW_R R_{i-j}WR​Ri−j​.
  • (c) Global Content Bias: This term adds a bias based only on the key's content xjx_jxj​. The trainable vector uuu learns a global preference for certain types of key content, independent of the query qiq_iqi​.
  • (d) Global Position Bias: This term adds a bias based only on the relative position i−ji-ji−j. The trainable vector vvv learns a global preference for certain relative distances, independent of the query qiq_iqi​.

The final attention weights are obtained by applying softmax over these scores Ai,jrelA_{i,j}^{rel}Ai,jrel​ (usually after scaling by 1dk\frac{1}{\sqrt{d_k}}dk​​1​).

Implementation Aspects

Generating the relative positional encodings Ri−jR_{i-j}Ri−j​ typically involves creating standard sinusoidal encodings for a maximum expected relative distance (e.g., from −L-L−L to +L+L+L, where LLL is the context length or segment length). During the attention calculation for a query at position iii, you would look up the appropriate encoding RkR_{k}Rk​ for each key at position j=i−kj=i-kj=i−k.

The introduction of the trainable vectors uuu and vvv and the separate projection matrix WRW_RWR​ adds parameters compared to the standard Transformer attention, but allows for more detailed modeling of relative positional importance.

A simplified PyTorch-style outline for calculating the relative attention scores might look like this (focusing on the score calculation, omitting multi-head and other details):

import torch
import torch.nn as nn
import math

class RelativeSinusoidalPositionalEncoding(nn.Module):
    # Generates fixed sinusoidal encodings for relative positions
    def __init__(self, d_model, max_len=5000):
        super().__init__()
        self.d_model = d_model
        pe = torch.zeros(max_len, d_model)
        position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
        div_term = torch.exp(torch.arange(0, d_model, 2).float() *
                           (-math.log(10000.0) / d_model))
        pe[:, 0::2] = torch.sin(position * div_term)
        pe[:, 1::2] = torch.cos(position * div_term)
        # We need encodings for relative positions [-max_len+1, max_len-1]
        # Create double the length and slice later. Store centrally shifted.
        pe_full = torch.cat([
            pe.flip(0)[:-1, :],
            pe
        ], dim=0) # size (2*max_len - 1, d_model)
        self.register_buffer('pe', pe_full)
        self.max_len = max_len

    def forward(self, seq_len_q, seq_len_k):
        # Assume query length seq_len_q, key length seq_len_k
        # We need relative positions from -(seq_len_k - 1)
        # to (seq_len_q - 1)
        # In self-attention, seq_len_q == seq_len_k == L
        # Relative indices range from -(L-1) to (L-1)
        # Map these indices to the stored buffer [0, 2*max_len - 2]
        # Example for self-attention (L=seq_len_q=seq_len_k)
        relative_indices = torch.arange(
            seq_len_k - 1, -seq_len_q, -1, dtype=torch.long
        )
        # Shift indices to be positive for lookup in 'pe' buffer
        # Center is at max_len - 1
        buffer_indices = relative_indices + self.max_len - 1
        relative_encodings = self.pe[buffer_indices]
        # Shape (seq_len_q + seq_len_k - 1, d_model)
        # We need a matrix R of shape (seq_len_q, seq_len_k, d_model)
        # where R[i, j, :] = encoding for relative distance (i - j)
        # This requires careful slicing/indexing based on the use case
        # (self-attention vs encoder-decoder)
        # For self-attention (seq_len_q=L, seq_len_k=L):
        # We need encodings R_{i-j} for i in [0, L-1], j in [0, L-1]
        # The relative distances range from -(L-1) to L-1
        # The relative_encodings buffer holds encodings for distances k
        # from L-1 down to -(L-1)
        start_idx = self.max_len - seq_len_k
        end_idx = start_idx + seq_len_q + seq_len_k - 1
        # Select the relevant part of the buffer
        rel_enc = self.pe[start_idx:end_idx]
        # Shape (L+L-1, d_model) for self-attention

        # Create the final matrix R (L, L, d_model) efficiently
        # This might involve clever slicing or matrix operations
        # For simplicity, let's assume we have a function
        # `get_rel_embeddings(rel_enc, L)`
        # that returns the (L, L, d_model) matrix.
        # R = get_rel_embeddings(rel_enc, seq_len_q) # Placeholder
        # # for complex indexing
        # return R

        # Simplified: Let's focus on the attention score calculation
        # assuming R_ij matrix is available
        pass
        # Returning the buffer for now, actual use requires more
        # indexing logic


class TransformerXLRelativeAttention(nn.Module):
    def __init__(self, d_model, nhead):
        super().__init__()
        self.d_model = d_model
        self.nhead = nhead
        self.d_head = d_model // nhead

        self.W_q = nn.Linear(d_model, d_model)
        self.W_k = nn.Linear(d_model, d_model)
        self.W_v = nn.Linear(d_model, d_model)
        self.W_r = nn.Linear(d_model, d_model)
        # Projection for relative embeddings

        # Trainable parameters u and v
        # (shared across heads initially for simplicity)
        self.u = nn.Parameter(torch.Tensor(self.nhead, self.d_head))
        self.v = nn.Parameter(torch.Tensor(self.nhead, self.d_head))
        nn.init.xavier_uniform_(self.u)
        nn.init.xavier_uniform_(self.v)

        self.dropout = nn.Dropout(0.1)
        self.scale = 1.0 / math.sqrt(self.d_head)

        # Assume RelativeSinusoidalPositionalEncoding module provides R
        # self.relative_pos_encoder = RelativeSinusoidalPositionalEncoding(
        #     d_model, max_len)

    def forward(self, query_embed, key_embed, value_embed, R_ij,
                mask=None):
        # query_embed, key_embed, value_embed:
        #   (batch_size, seq_len, d_model)
        # R_ij: Precomputed relative positional encodings projection
        #       W_R * R_{i-j}
        #       Expected shape for efficient computation:
        #       (batch_size, nhead, seq_len_q, d_head) for term (b)
        #       And (batch_size, nhead, seq_len_k, d_head) for term (d)
        #       after multiplying by v
        # Mask: (batch_size, seq_len_q, seq_len_k)

        batch_size, seq_len_q, _ = query_embed.size()
        seq_len_k = key_embed.size(1)

        Q = self.W_q(query_embed).view(
            batch_size, seq_len_q, self.nhead, self.d_head
        )
        K = self.W_k(key_embed).view(
            batch_size, seq_len_k, self.nhead, self.d_head
        )
        V = self.W_v(value_embed).view(
            batch_size, seq_len_k, self.nhead, self.d_head
        )
        # R_ij needs to be projected by W_r and reshaped appropriately
        # before passing here
        # Projected R_ij = self.W_r(raw_R_ij).view(....)

        # Transpose for attention calculation:
        # (batch_size, nhead, seq_len, d_head)
        Q = Q.transpose(1, 2)
        K = K.transpose(1, 2)
        V = V.transpose(1, 2)

        # Term (a): Content-based
        AC = torch.matmul(Q + self.u.unsqueeze(0).unsqueeze(2),
                          K.transpose(-2, -1))
        # Q shape: (batch, nhead, seq_len_q, d_head)
        # K^T shape: (batch, nhead, d_head, seq_len_k)
        # Result AC shape: (batch, nhead, seq_len_q, seq_len_k)
        # Here we add global content bias 'u' to the query side

        # Term (b) and (d): Position-based
        # This requires careful handling of R_ij tensor shapes
        # and relative indexing
        # Assume R_proj = W_r(R) is precomputed and shaped
        # (seq_len_q, seq_len_k, nhead, d_head)
        # R_proj = R_proj.permute(2, 0, 3, 1)
        # -> (nhead, seq_len_q, d_head, seq_len_k)
        # Term (b): (Q + self.v) * R_proj
        # BD = torch.matmul(Q + self.v.unsqueeze(0).unsqueeze(2), R_proj)
        # Pseudocode - dimensions need care

        # Simplified calculation showing the concept -
        # actual implementation is complex
        # due to efficient computation of relative terms using matrix shifts
        # or skewing.
        # See Dai et al. (2019) Appendix B for efficient implementation details.

        # Placeholder for combined score calculation:
        # scores = AC + BD # Placeholder for the full score calculation

# Let's use a placeholder for scores:
        # Assuming AC represents the sum of terms (a) and (c)
        # Assuming BD represents the sum of terms (b) and (d)
        # computed efficiently
        # scores = (AC + BD) * self.scale # Placeholder

        # Fake scores for demonstration structure
        scores = AC * self.scale

        if mask is not None:
             # Ensure mask has compatible shape
             # (batch_size, 1, seq_len_q, seq_len_k)
             scores = scores.masked_fill(mask == 0, -1e9)

        attn_weights = torch.softmax(scores, dim=-1)
        attn_weights = self.dropout(attn_weights)

        output = torch.matmul(attn_weights, V)
        # (batch, nhead, seq_len_q, d_head)
        output = output.transpose(1, 2).contiguous().view(
            batch_size, seq_len_q, self.d_model
        )

        return output, attn_weights

Note: The actual implementation of term (b) and (d) requires careful tensor manipulation (often involving skewing matrices) to perform the relative position calculations efficiently without explicitly constructing the full Ri−jR_{i-j}Ri−j​ matrix for every pair (i,j)(i,j)(i,j) at each step. The code above simplifies this part.

Advantages of Transformer-XL Relative Encoding

  1. Generalization to Longer Sequences: Since relative positions are used, the model isn't tied to specific absolute positions learned during training. It can potentially handle sequences longer than those seen during training, as the relative offsets remain meaningful.
  2. Explicit Relative Information: It directly encodes the distance between tokens, which can be more informative for attention than absolute positions alone.
  3. Enables Segment-Level Recurrence: This encoding scheme was fundamental to the Transformer-XL's main contribution: processing sequences segment by segment while reusing hidden states from previous segments. The relative encoding ensures positional consistency across segment boundaries.

Compared to the approach by Shaw et al., which adds relative position biases after the main query-key dot product, Transformer-XL integrates the relative position information more deeply into the score calculation by having the query interact directly with relative position embeddings (qiTWRRi−jq_i^T W_R R_{i-j}qiT​WR​Ri−j​) and incorporating global position biases (vTWRRi−jv^T W_R R_{i-j}vTWR​Ri−j​).

In summary, the Transformer-XL relative positional encoding offers an alternative to absolute encodings. By focusing on relative distances and decomposing the attention score calculation, it provides better generalization capabilities for sequence length and forms a foundation for architectures designed to handle very long contexts. Its implementation requires careful handling of relative positional embeddings and additional trainable parameters, but the benefits for long-sequence modeling are significant.

  • Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context, Zihang Dai, Zhilin Yang, Yiming Yang, Jaime Carbonell, Quoc V. Le, Ruslan Salakhutdinov, 2019 Proceedings of the 57th Annual Meeting of the Association for Computational Linguistics (ACL) DOI: 10.48550/arXiv.1901.02860 - The original paper introducing the Transformer-XL architecture and its relative positional encoding scheme, including detailed mathematical formulations and implementation strategies.
  • Attention Is All You Need, Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser, Illia Polosukhin, 2017 Advances in Neural Information Processing Systems (NeurIPS) 30 DOI: 10.48550/arXiv.1706.03762 - The seminal paper that introduced the Transformer architecture and its original absolute sinusoidal positional encoding, providing background for subsequent relative encoding methods.
  • Self-Attention with Relative Position Representations, Peter Shaw, Jakob Uszkoreit, Ashish Vaswani, 2018 NAACL 2018 DOI: 10.48550/arXiv.1803.02155 - Introduces an earlier approach to relative positional encoding in self-attention, which uses learnable relative position biases, offering a comparison point to Transformer-XL's method.

© 2026 ApX Machine Learning