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

Tensor Parallelism (TP)

While Data Parallelism (DP) effectively utilizes multiple devices by replicating the model and processing different data slices, it requires each device to hold the entire model. For truly massive models, even a single replica might exceed the memory capacity of one accelerator. Furthermore, some individual operations within the model, like the large linear transformations in feed-forward networks or attention mechanisms, can become computational bottlenecks. This is where Tensor Parallelism (TP), sometimes called intra-layer model parallelism, becomes necessary.

Instead of splitting the data or the sequence of layers, Tensor Parallelism splits the actual tensors (weights, activations, gradients) within a specific operation across multiple devices. This allows computations on these large tensors to be performed in parallel, distributing both the memory footprint and the computational load of individual layers.

Splitting Linear Layers

The most straightforward application of TP is in large linear layers, which are fundamental components of both the multi-layer perceptron (MLP) and attention blocks in Transformers. For example, a linear transformation Y=XAY = XAY=XA, where XXX is the input activation and AAA is the weight matrix. We can parallelize this matrix multiplication across, for example, two devices in two primary ways: column parallelism and row parallelism.

Column Parallelism

In column parallelism, the weight matrix AAA is split vertically (along its columns) across devices. If we have two devices, we split AAA into A=[A1,A2]A = [A_1, A_2]A=[A1​,A2​]. The input XXX is typically broadcast or made available to both devices. Each device then computes a part of the output:

  • Device 1 computes: Y1=XA1Y_1 = X A_1Y1​=XA1​
  • Device 2 computes: Y2=XA2Y_2 = X A_2Y2​=XA2​

The final output YYY is obtained by concatenating the results along the column dimension: Y=[Y1,Y2]Y = [Y_1, Y_2]Y=[Y1​,Y2​].

Column parallelism for Y=XAY = XAY=XA. The weight matrix AAA is split into A1A_1A1​ and A2A_2A2​. The input XXX is multiplied by each part on separate GPUs. The results Y1Y_1Y1​ and Y2Y_2Y2​ are concatenated to form the final output YYY.

Mathematically, the forward pass involves XA=X[A1,A2]=[XA1,XA2]X A = X [A_1, A_2] = [X A_1, X A_2]XA=X[A1​,A2​]=[XA1​,XA2​]. The backward pass requires gradients with respect to XXX and AAA. The gradient ∂L∂A\frac{\partial L}{\partial A}∂A∂L​ is naturally partitioned (∂L∂A1\frac{\partial L}{\partial A_1}∂A1​∂L​, ∂L∂A2\frac{\partial L}{\partial A_2}∂A2​∂L​). However, computing the gradient ∂L∂X\frac{\partial L}{\partial X}∂X∂L​ requires summing contributions from both paths: ∂L∂X=∂L∂Y1A1T+∂L∂Y2A2T\frac{\partial L}{\partial X} = \frac{\partial L}{\partial Y_1} A_1^T + \frac{\partial L}{\partial Y_2} A_2^T∂X∂L​=∂Y1​∂L​A1T​+∂Y2​∂L​A2T​. This summation is typically achieved using an all-reduce communication collective across the devices holding A1A_1A1​ and A2A_2A2​.

Row Parallelism

In row parallelism, the weight matrix AAA is split horizontally (along its rows). For two devices, A=[A1A2]A = \begin{bmatrix} A_1 \\ A_2 \end{bmatrix}A=[A1​A2​​]. The input XXX is also partitioned along its columns (often because it's the output of a preceding column-parallel layer). For simplicity in this isolated view, assume the input XXX is available on both devices. Each device computes a partial result based on its slice of the weights:

  • Device 1 computes: Y1=XA1Y_1 = X A_1Y1​=XA1​ (Note: This formula is slightly simplified. In practice, XXX would be partitioned, e.g., X=[X1,X2]X=[X_1, X_2]X=[X1​,X2​], and Device 1 computes X1A1X_1 A_1X1​A1​, Device 2 computes X2A2X_2 A_2X2​A2​. We show the common pattern used in combination with column parallelism later).
  • Device 2 computes: Y2=XA2Y_2 = X A_2Y2​=XA2​

Unlike column parallelism, the final output YYY is the sum of the partial results: Y=Y1+Y2Y = Y_1 + Y_2Y=Y1​+Y2​.

Row parallelism for Y=XAY = XAY=XA. The weight matrix AAA is split into A1A_1A1​ and A2A_2A2​ (row-wise). Partial results Y1Y_1Y1​ and Y2Y_2Y2​ are computed on separate GPUs. An all-reduce operation sums these results to produce the final output YYY.

Mathematically, Y=X[A1A2]Y = X \begin{bmatrix} A_1 \\ A_2 \end{bmatrix}Y=X[A1​A2​​] isn't standard matrix multiplication notation if XXX is treated as a single block. The actual operation in context (e.g., following a column-split layer) is Y=X1A1+X2A2Y = X_1 A_1 + X_2 A_2Y=X1​A1​+X2​A2​, where X=[X1,X2]X=[X_1, X_2]X=[X1​,X2​]. The forward pass requires an all-reduce operation to perform this summation across devices. The backward pass for ∂L∂X\frac{\partial L}{\partial X}∂X∂L​ involves partitioned gradients based on the partitioned AAA: ∂L∂X1=∂L∂YA1T\frac{\partial L}{\partial X_1} = \frac{\partial L}{\partial Y} A_1^T∂X1​∂L​=∂Y∂L​A1T​ and ∂L∂X2=∂L∂YA2T\frac{\partial L}{\partial X_2} = \frac{\partial L}{\partial Y} A_2^T∂X2​∂L​=∂Y∂L​A2T​. The gradient ∂L∂A\frac{\partial L}{\partial A}∂A∂L​ is directly computed on each device for its corresponding weight slice.

Tensor Parallelism in Transformers

Tensor Parallelism is typically applied strategically within Transformer blocks to balance computation and minimize communication overhead. A common pattern, popularized by frameworks like Megatron-LM, combines column and row parallelism within the MLP block and applies similar partitioning to the attention mechanism.

MLP Block: A standard Transformer MLP block computes Y=Activation(XA)B+XY = \text{Activation}(XA)B + XY=Activation(XA)B+X (including residual connection). TP is applied as follows:

  1. First Linear Layer (XAXAXA): Use column parallelism for matrix AAA. Split A=[A1,A2]A = [A_1, A_2]A=[A1​,A2​]. Compute Z1=XA1Z_1 = XA_1Z1​=XA1​ and Z2=XA2Z_2 = XA_2Z2​=XA2​ on respective devices. The output is [Z1,Z2][Z_1, Z_2][Z1​,Z2​]. This step involves an all-reduce for the gradient calculation in the backward pass, but the forward pass requires no communication if XXX is already available on both devices.
  2. Activation: Apply the activation function (e.g., GeLU, SwiGLU) element-wise to the partitioned outputs: G1=Activation(Z1)G_1 = \text{Activation}(Z_1)G1​=Activation(Z1​), G2=Activation(Z2)G_2 = \text{Activation}(Z_2)G2​=Activation(Z2​). No communication needed.
  3. Second Linear Layer (GBGBGB): Use row parallelism for matrix BBB. Split B=[B1B2]B = \begin{bmatrix} B_1 \\ B_2 \end{bmatrix}B=[B1​B2​​]. Device 1 computes Y1=G1B1Y_1 = G_1 B_1Y1​=G1​B1​, and Device 2 computes Y2=G2B2Y_2 = G_2 B_2Y2​=G2​B2​.
  4. Summation: The final output of the linear transformation is Y=Y1+Y2Y = Y_1 + Y_2Y=Y1​+Y2​. This summation is performed using an all-reduce collective in the forward pass. The gradient calculation in the backward pass requires no all-reduce for the inputs G1,G2G_1, G_2G1​,G2​.

This combination cleverly arranges the parallelism such that the communication required for the forward pass (all-reduce after the second linear layer) and the backward pass (all-reduce for ∇X\nabla X∇X after the first linear layer) do not overlap unnecessarily, optimizing the flow.

Attention Block: TP can also be applied to the self-attention mechanism.

  1. Q, K, V Projections: The weight matrices WQW_QWQ​, WKW_KWK​, and WVW_VWV​ used to project the input into queries, keys, and values are often split using column parallelism, similar to the first linear layer of the MLP. Q=XWQQ = XW_QQ=XWQ​, K=XWKK = XW_KK=XWK​, V=XWVV = XW_VV=XWV​ are computed in parallel across devices, resulting in partitioned Q=[Q1,Q2]Q = [Q_1, Q_2]Q=[Q1​,Q2​], K=[K1,K2]K = [K_1, K_2]K=[K1​,K2​], V=[V1,V2]V = [V_1, V_2]V=[V1​,V2​].
  2. Attention Score Calculation: The attention scores S=softmax(QKTdk)S = \text{softmax}(\frac{QK^T}{\sqrt{d_k}})S=softmax(dk​​QKT​) involve matrix multiplications between the partitioned Q and K tensors. This requires careful implementation and communication (e.g., all-gather operations might be needed depending on the specific splitting strategy) to compute the full attention matrix or its necessary parts on each device.
  3. Value Aggregation: The output O=SVO = SVO=SV involves multiplying the attention scores SSS with the partitioned value tensors VVV.
  4. Output Projection: The final linear layer in the attention block (OWOO W_OOWO​) is typically parallelized using row parallelism, similar to the second linear layer of the MLP. This requires an all-reduce in the forward pass to combine the results.

The implementation details within the attention block can be intricate, involving optimized kernels and communication patterns to handle the sequence length and head dimensions efficiently.

Communication Costs

A significant drawback of Tensor Parallelism is the increased communication overhead compared to Data Parallelism. While DP typically involves one all-reduce per training step (for gradients), TP introduces communication within the forward and backward passes of each Transformer block.

  • Column Parallelism: Requires communication (all-reduce) for gradient computation w.r.t input XXX during the backward pass.
  • Row Parallelism: Requires communication (all-reduce) for summing outputs during the forward pass.
  • Attention: Can involve additional communication like all-gather depending on implementation.

These communication operations (like all-reduce) involve synchronizing and exchanging data across all devices participating in the TP group. The volume of data exchanged depends on the size of the activations or gradients being communicated. This communication cost scales with the number of devices in the TP group and can become a performance bottleneck if the interconnect bandwidth between devices (e.g., NVLink, InfiniBand) is insufficient relative to the computation speed.

Advantages and Strategies

  • Enables Larger Models: TP is essential when model layers themselves are too large for a single device's memory.
  • Complements Other Strategies: It can be combined with DP and PP (Pipeline Parallelism) to form hybrid parallelism approaches (e.g., using TP within a pipeline stage, which is then replicated using DP).
  • Potential for Overlap: Sophisticated implementations might overlap communication with computation to hide latency.

However, here are the key points:

  • Implementation Complexity: Requires careful code modifications or reliance on specialized libraries like NVIDIA's Megatron-LM or Microsoft's DeepSpeed, which provide optimized implementations of TP for Transformers.
  • Communication Bottleneck: Performance is highly sensitive to the interconnect bandwidth and topology of the compute cluster. Scaling TP to a large number of devices can lead to diminishing returns if communication dominates.

Here's a PyTorch-style snippet illustrating the idea of splitting a weight matrix for column parallelism (this is highly simplified and omits communication and gradient handling):

import torch
import torch.nn as nn

# Assume world_size is the number of GPUs for TP
# Assume rank is the current GPU's rank in the TP group

class ColumnParallelLinear(nn.Module):
    def __init__(self, input_size, output_size, world_size, rank):
        super().__init__()
        self.input_size = input_size
        # Each GPU handles a slice of the output features
        self.output_size_per_partition = output_size // world_size
        self.world_size = world_size
        self.rank = rank

        # Initialize only the part of the weight matrix for this rank
        self.weight = nn.Parameter(
            torch.randn(self.output_size_per_partition, self.input_size)
        )
        # Bias is also partitioned
        self.bias = nn.Parameter(
            torch.randn(self.output_size_per_partition)
        )

    def forward(self, x):
        # Assume input x is available on all GPUs (broadcast or result of
        # all-reduce)
        # Matrix multiplication happens only on the local partition of the weight
        # Output_partition = X * A_partition^T + b_partition
        # Note: PyTorch linear layers expect weight as
        # (out_features, in_features)
        output_partition = nn.functional.linear(x, self.weight, self.bias)

        # In a real implementation, this output_partition would need to be
        # gathered across GPUs if the next layer isn't row-parallel.
        # For the Megatron-LM MLP pattern (Col->Row), no forward comms needed
        # here.

        # Backward pass communication (all-reduce for grad_X) is handled
        # by custom autograd functions in libraries like Megatron-LM.

        return output_partition # Returns only the slice computed by this GPU

In summary, Tensor Parallelism is a powerful technique for distributing the computation and memory of individual large layers across multiple devices. While it introduces significant communication overhead, it is often a necessary component, alongside Data and Pipeline Parallelism, for training state-of-the-art large language models that push the boundaries of single-accelerator capabilities. Frameworks like Megatron-LM and DeepSpeed abstract away much of the complexity, providing optimized building blocks for implementing TP effectively.

  • DeepSpeed: System Optimizations for Large-Scale Model Training, Jie Ren, Hao Li, Samyam Rajbhandari, Conglong Li, Di He, Zhicheng Cui, Xuanli Chen, Junchao Li, Sholto Scruton, Minjia Zhang, 2021 ACM SIGOPS Operating Systems Review, Vol. 55 (ACM) DOI: 10.1145/3452044.3483742 - Describes DeepSpeed, a comprehensive framework providing optimized distributed training capabilities, including various forms of model parallelism that complement tensor parallelism.
  • ZeRO: Memory Optimizations Toward Training Trillion Parameter Models, Samyam Rajbhandari, Jeff Rasley, Olatunji Ruwase, Yuxiong He, 2020 SC '20: Proceedings of the International Conference for High Performance Computing, Networking, Storage and Analysis (IEEE Computer Society) DOI: 10.1109/SC45903.2020.00078 - While focusing on memory optimization for optimizer states, gradients, and parameters, ZeRO is crucial for enabling the training of models large enough to necessitate tensor parallelism.

© 2026 ApX Machine Learning