LogoLogo
Continuum WebsiteContinuum ApplicationsContinuum KnowledgeAxolotl Platform
Continuum Knowledge
Continuum Knowledge
  • Continuum
  • Data
    • Datasets
      • Pre Training Data
      • Types of Fine Tuning
      • Self Instruct Paper
      • Self-Alignment with Instruction Backtranslation
      • Systematic Evaluation of Instruction-Tuned Large Language Models on Open Datasets
      • Instruction Tuning
      • Instruction Fine Tuning - Alpagasus
      • Less is More For Alignment
      • Enhanced Supervised Fine Tuning
      • Visualising Data using t-SNE
      • UMAP: Uniform Manifold Approximation and Projection for Dimension Reduction
      • Training and Evaluation Datasets
      • What is perplexity?
  • MODELS
    • Foundation Models
      • The leaderboard
      • Foundation Models
      • LLama 2 - Analysis
      • Analysis of Llama 3
      • Llama 3.1 series
      • Google Gemini 1.5
      • Platypus: Quick, Cheap, and Powerful Refinement of LLMs
      • Mixtral of Experts
      • Mixture-of-Agents (MoA)
      • Phi 1.5
        • Refining the Art of AI Training: A Deep Dive into Phi 1.5's Innovative Approach
      • Phi 2.0
      • Phi-3 Technical Report
  • Training
    • The Fine Tuning Process
      • Why fine tune?
        • Does Fine-Tuning LLMs on New Knowledge Encourage Hallucinations?
        • Explanations in Fine Tuning
      • Tokenization
        • Tokenization Is More Than Compression
        • Tokenization - SentencePiece
        • Tokenization explore
        • Tokenizer Choice For LLM Training: Negligible or Crucial?
        • Getting the most out of your tokenizer for pre-training and domain adaptation
        • TokenMonster
      • Parameter Efficient Fine Tuning
        • P-Tuning
          • The Power of Scale for Parameter-Efficient Prompt Tuning
        • Prefix-Tuning: Optimizing Continuous Prompts for Generation
        • Harnessing the Power of PEFT: A Smarter Approach to Fine-tuning Pre-trained Models
        • What is Low-Rank Adaptation (LoRA) - explained by the inventor
        • Low Rank Adaptation (Lora)
        • Practical Tips for Fine-tuning LMs Using LoRA (Low-Rank Adaptation)
        • QLORA: Efficient Finetuning of Quantized LLMs
        • Bits and Bytes
        • The Magic behind Qlora
        • Practical Guide to LoRA: Tips and Tricks for Effective Model Adaptation
        • The quantization constant
        • QLORA: Efficient Finetuning of Quantized Language Models
        • QLORA and Fine-Tuning of Quantized Language Models (LMs)
        • ReLoRA: High-Rank Training Through Low-Rank Updates
        • SLoRA: Federated Parameter Efficient Fine-Tuning of Language Models
        • GaLora: Memory-Efficient LLM Training by Gradient Low-Rank Projection
      • Hyperparameters
        • Batch Size
        • Padding Tokens
        • Mixed precision training
        • FP8 Formats for Deep Learning
        • Floating Point Numbers
        • Batch Size and Model loss
        • Batch Normalisation
        • Rethinking Learning Rate Tuning in the Era of Language Models
        • Sample Packing
        • Gradient accumulation
        • A process for choosing the learning rate
        • Learning Rate Scheduler
        • Checkpoints
        • A Survey on Efficient Training of Transformers
        • Sequence Length Warmup
        • Understanding Training vs. Evaluation Data Splits
        • Cross-entropy loss
        • Weight Decay
        • Optimiser
        • Caching
      • Training Processes
        • Extending the context window
        • PyTorch Fully Sharded Data Parallel (FSDP)
        • Train Short, Test Long: Attention with Linear Biases Enables Input Length Extrapolation
        • YaRN: Efficient Context Window Extension of Large Language Models
        • Sliding Window Attention
        • LongRoPE
        • Reinforcement Learning
        • An introduction to reinforcement learning
        • Reinforcement Learning from Human Feedback (RLHF)
        • Direct Preference Optimization: Your Language Model is Secretly a Reward Model
  • INFERENCE
    • Why is inference important?
      • Grouped Query Attention
      • Key Value Cache
      • Flash Attention
      • Flash Attention 2
      • StreamingLLM
      • Paged Attention and vLLM
      • TensorRT-LLM
      • Torchscript
      • NVIDIA L40S GPU
      • Triton Inference Server - Introduction
      • Triton Inference Server
      • FiDO: Fusion-in-Decoder optimised for stronger performance and faster inference
      • Is PUE a useful measure of data centre performance?
      • SLORA
  • KNOWLEDGE
    • Vector Databases
      • A Comprehensive Survey on Vector Databases
      • Vector database management systems: Fundamental concepts, use-cases, and current challenges
      • Using the Output Embedding to Improve Language Models
      • Decoding Sentence-BERT
      • ColBERT: Efficient and Effective Passage Search via Contextualized Late Interaction over BERT
      • SimCSE: Simple Contrastive Learning of Sentence Embeddings
      • Questions Are All You Need to Train a Dense Passage Retriever
      • Improving Text Embeddings with Large Language Models
      • Massive Text Embedding Benchmark
      • RocketQAv2: A Joint Training Method for Dense Passage Retrieval and Passage Re-ranking
      • LLM2Vec: Large Language Models Are Secretly Powerful Text Encoders
      • Embedding and Fine-Tuning in Neural Language Models
      • Embedding Model Construction
      • Demystifying Embedding Spaces using Large Language Models
      • Fine-Tuning Llama for Multi-Stage Text Retrieval
      • Large Language Model Based Text Augmentation Enhanced Personality Detection Model
      • One Embedder, Any Task: Instruction-Finetuned Text Embeddings
      • Vector Databases are not the only solution
      • Knowledge Graphs
        • Harnessing Knowledge Graphs to Elevate AI: A Technical Exploration
        • Unifying Large Language Models and Knowledge Graphs: A Roadmap
      • Approximate Nearest Neighbor (ANN)
      • High Dimensional Data
      • Principal Component Analysis (PCA)
      • Vector Similarity Search - HNSW
      • FAISS (Facebook AI Similarity Search)
      • Unsupervised Dense Retrievers
    • Retrieval Augmented Generation
      • Retrieval-Augmented Generation for Large Language Models: A Survey
      • Fine-Tuning or Retrieval?
      • Revolutionising Information Retrieval: The Power of RAG in Language Models
      • A Survey on Retrieval-Augmented Text Generation
      • REALM: Retrieval-Augmented Language Model Pre-Training
      • Retrieve Anything To Augment Large Language Models
      • Generate Rather Than Retrieve: Large Language Models Are Strong Context Generators
      • Active Retrieval Augmented Generation
      • DSPy: LM Assertions: Enhancing Language Model Pipelines with Computational Constraints
      • DSPy: Compiling Declarative Language Model Calls
      • DSPy: In-Context Learning for Extreme Multi-Label Classification
      • Optimizing Instructions and Demonstrations for Multi-Stage Language Model Programs
      • HYDE: Revolutionising Search with Hypothetical Document Embeddings
      • Enhancing Recommender Systems with Large Language Model Reasoning Graphs
      • Retrieval Augmented Generation (RAG) versus fine tuning
      • RAFT: Adapting Language Model to Domain Specific RAG
      • Summarisation Methods and RAG
      • Lessons Learned on LLM RAG Solutions
      • Stanford: Retrieval Augmented Language Models
      • Overview of RAG Approaches with Vector Databases
      • Mastering Chunking in Retrieval-Augmented Generation (RAG) Systems
    • Semantic Routing
    • Resource Description Framework (RDF)
  • AGENTS
    • What is agency?
      • Rephrase and Respond: Let Large Language Models Ask Better Questions for Themselves
      • Types of Agents
      • The risk of AI agency
      • Understanding Personality in Large Language Models: A New Frontier in AI Psychology
      • AI Agents - Reasoning, Planning, and Tool Calling
      • Personality and Brand
      • Agent Interaction via APIs
      • Bridging Minds and Machines: The Legacy of Newell, Shaw, and Simon
      • A Survey on Language Model based Autonomous Agents
      • Large Language Models as Agents
      • AI Reasoning: A Deep Dive into Chain-of-Thought Prompting
      • Enhancing AI Reasoning with Self-Taught Reasoner (STaR)
      • Exploring the Frontier of AI: The "Tree of Thoughts" Framework
      • Toolformer: Revolutionising Language Models with API Integration - An Analysis
      • TaskMatrix.AI: Bridging Foundational AI Models with Specialised Systems for Enhanced Task Completion
      • Unleashing the Power of LLMs in API Integration: The Rise of Gorilla
      • Andrew Ng's presentation on AI agents
      • Making AI accessible with Andrej Karpathy and Stephanie Zhan
  • Regulation and Ethics
    • Regulation and Ethics
      • Privacy
      • Detecting AI Generated content
      • Navigating the IP Maze in AI: The Convergence of Blockchain, Web 3.0, and LLMs
      • Adverse Reactions to generative AI
      • Navigating the Ethical Minefield: The Challenge of Security in Large Language Models
      • Navigating the Uncharted Waters: The Risks of Autonomous AI in Military Decision-Making
  • DISRUPTION
    • Data Architecture
      • What is a data pipeline?
      • What is Reverse ETL?
      • Unstructured Data and Generatve AI
      • Resource Description Framework (RDF)
      • Integrating generative AI with the Semantic Web
    • Search
      • BM25 - Search Engine Ranking Function
      • BERT as a reranking engine
      • BERT and Google
      • Generative Engine Optimisation (GEO)
      • Billion-scale similarity search with GPUs
      • FOLLOWIR: Evaluating and Teaching Information Retrieval Models to Follow Instructions
      • Neural Collaborative Filtering
      • Federated Neural Collaborative Filtering
      • Latent Space versus Embedding Space
      • Improving Text Embeddings with Large Language Models
    • Recommendation Engines
      • On Interpretation and Measurement of Soft Attributes for Recommendation
      • A Survey on Large Language Models for Recommendation
      • Model driven recommendation systems
      • Recommender AI Agent: Integrating Large Language Models for Interactive Recommendations
      • Foundation Models for Recommender Systems
      • Exploring the Impact of Large Language Models on Recommender Systems: An Extensive Review
      • AI driven recommendations - harming autonomy?
    • Logging
      • A Taxonomy of Anomalies in Log Data
      • Deeplog
      • LogBERT: Log Anomaly Detection via BERT
      • Experience Report: Deep Learning-based System Log Analysis for Anomaly Detection
      • Log-based Anomaly Detection with Deep Learning: How Far Are We?
      • Deep Learning for Anomaly Detection in Log Data: A Survey
      • LogGPT
      • Adaptive Semantic Gate Networks (ASGNet) for log-based anomaly diagnosis
  • Infrastructure
    • The modern data centre
      • Enhancing Data Centre Efficiency: Strategies to Improve PUE
      • TCO of NVIDIA GPUs and falling barriers to entry
      • Maximising GPU Utilisation with Kubernetes and NVIDIA GPU Operator
      • Data Centres
      • Liquid Cooling
    • Servers and Chips
      • The NVIDIA H100 GPU
      • NVIDIA H100 NVL
      • Lambda Hyperplane 8-H100
      • NVIDIA DGX Servers
      • NVIDIA DGX-2
      • NVIDIA DGX H-100 System
      • NVLink Switch
      • Tensor Cores
      • NVIDIA Grace Hopper Superchip
      • NVIDIA Grace CPU Superchip
      • NVIDIA GB200 NVL72
      • Hopper versus Blackwell
      • HGX: High-Performance GPU Platforms
      • ARM Chips
      • ARM versus x86
      • RISC versus CISC
      • Introduction to RISC-V
    • Networking and Connectivity
      • Infiniband versus Ethernet
      • NVIDIA Quantum InfiniBand
      • PCIe (Peripheral Component Interconnect Express)
      • NVIDIA ConnectX InfiniBand adapters
      • NVMe (Non-Volatile Memory Express)
      • NVMe over Fabrics (NVMe-oF)
      • NVIDIA Spectrum-X
      • NVIDIA GPUDirect
      • Evaluating Modern GPU Interconnect
      • Scalable Hierarchical Aggregation and Reduction Protocol (SHARP)
      • Next-generation networking in AI environments
      • NVIDIA Collective Communications Library (NCCL)
    • Data and Memory
      • NVIDIA BlueField Data Processing Units (DPUs)
      • Remote Direct Memory Access (RDMA)
      • High Bandwidth Memory (HBM3)
      • Flash Memory
      • Model Requirements
      • Calculating GPU memory for serving LLMs
      • Transformer training costs
      • GPU Performance Optimisation
    • Libraries and Complements
      • NVIDIA Base Command
      • NVIDIA AI Enterprise
      • CUDA - NVIDIA GTC 2024 presentation
      • RAPIDs
      • RAFT
    • Vast Data Platform
      • Vast Datastore
      • Vast Database
      • Vast Data Engine
      • DASE (Disaggregated and Shared Everything)
      • Dremio and VAST Data
    • Storage
      • WEKA: A High-Performance Storage Solution for AI Workloads
      • Introduction to NVIDIA GPUDirect Storage (GDS)
        • GDS cuFile API
      • NVIDIA Magnum IO GPUDirect Storage (GDS)
      • Vectors in Memory
Powered by GitBook
LogoLogo

Continuum - Accelerated Artificial Intelligence

  • Continuum Website
  • Axolotl Platform

Copyright Continuum Labs - 2023

On this page
  • Compute Requirements
  • Parameter vs Dataset Tradeoffs
  • Engineering Takeaways for Compute Costs
  • Memory Requirements
  • Inference
  • Training
  • Model Parameters
  • Gradients
  • Activations and Batch Size
  • Total Training Memory
  • Distributed Training
  • Conclusion

Was this helpful?

  1. Infrastructure
  2. Data and Memory

Transformer training costs

PreviousCalculating GPU memory for serving LLMsNextGPU Performance Optimisation

Last updated 11 months ago

Was this helpful?

Computation and memory usage for transformers

Compute Requirements

The basic equation giving the cost to train a transformer model is given by:

𝐶≈𝜏𝑇=6𝑃𝐷𝐶≈𝜏𝑇=6𝑃𝐷C≈𝜏T=6PD

where:

  • (C)( C ) (C)is the total compute required to train the transformer model, measured in floating point operations (FLOPs): C=Cforward+Cbackward C = C_{\text{forward}} + C_{\text{backward}}C=Cforward​+Cbackward​

  • (Cforward)( C_{\text{forward}} ) (Cforward​)is the compute required for the forward pass: Cforward≈2×P×D C_{\text{forward}} \approx 2 \times P \times D Cforward​≈2×P×D

  • (Cbackward)( C_{\text{backward}} )(Cbackward​) is the compute required for the backward pass: Cbackward≈4×P×D C_{\text{backward}} \approx 4 \times P \times D Cbackward​≈4×P×D

  • (τ)( \tau )(τ) represents the aggregate throughput of your hardware setup: [τ=(No. of GPUs)×(Actual FLOPs per GPU)][ \tau = (\text{No. of GPUs}) \times (\text{Actual FLOPs per GPU}) ][τ=(No. of GPUs)×(Actual FLOPs per GPU)]

  • (T)( T )(T) is the time spent training the model, in seconds: [T=Cτ] [ T = \frac{C}{\tau} ][T=τC​]

  • (P)( P )(P) is the number of parameters in the transformer model.

  • (D)( D )(D) is the dataset size, measured in tokens.

Sources

These units provide different ways to conceptualise and quantify the computational effort required to train models, depending on the context and scale of the operations.

One useful distinction to keep in mind is the concept of Actual FLOPs.

While GPU accelerator whitepapers usually advertise their theoretical FLOPs, these are never met in practice (especially in a distributed setting).

Some common reported values of Actual FLOPs in a distributed training setting are reported below in the Computing Costs section.

Parameter vs Dataset Tradeoffs

Although strictly speaking you can train a transformer for as many tokens as you like, the number of tokens trained can highly impact both the computing costs and the final model performance making striking the right balance important.

Let’s start with the elephant in the room: “compute optimal” language models.

Often referred to as “Chinchilla scaling laws” after the model series in the paper that gave rise to current beliefs about the number of parameters, a compute optimal language model has a number of parameters and a dataset size that satisfies the approximation 𝐷=20𝑃.

This is optimal in one very specific sense: in a resource regime where using 1,000 GPUs for 1 hour and 1 GPU for 1,000 hours cost you the same amount, if your goal is to maximise performance while minimising the cost in GPU-hours to train a model you should use the above equation.

We do not recommend training a LLM for less than 200B tokens.

Although this is “chinchilla optimal” for many models, the resulting models are typically quite poor.

For almost all applications, we recommend determining what inference cost is acceptable for your use case and training the largest model you can to stay under that inference cost for as many tokens as you can.

Engineering Takeaways for Compute Costs

Computing costs for transformers are typically listed in GPU-hours or FLOP-seconds.

  • GPT-NeoX achieves 150 TFLOP/s/A100 with normal attention and 180 TFLOP/s/A100 with Flash Attention. This is in line with other highly optimized libraries at scale, for example Megatron-DS reports between 137 and 163 TFLOP/s/A100.

  • As a general rule of thumb, you should always be able to achieve approximately 120 TFLOP/s/A100. If you are seeing below 115 TFLOP/s/A100 there is probably something wrong with your model or hardware configuration.

  • With high-quality interconnect such as InfiniBand, you can achieve linear or sublinear scaling across the data parallel dimension (i.e. increasing the data parallel degree should increase the overall throughput nearly linearly). Shown below is a plot from testing the GPT-NeoX library on Oak Ridge National Lab’s Summit supercomputer. Note that V100s are on the x-axis, while most of the numerical examples in the post are for A100s.

Memory Requirements

Transformers are typically described in terms of their size in parameters.

However, when determining what models can fit on a given set of computing resources you need to know how much space in bytes the model will take up.

This can tell you how large a model will fit on your local GPU for inference, or how large a model you can train across your cluster with a certain amount of total accelerator memory.

Inference

Model Weights

Most transformers are trained in mixed precision, either fp16 + fp32 or bf16 + fp32.

This cuts down on the amount of memory required to train the models, and also the amount of memory required to run inference.

We can cast language models from fp32 to fp16 or even int8 without suffering a substantial performance hit.

These numbers refer to the size in bits a single parameter requires. Since there are 8 bits in a Byte, we divide this number by 8 to see how many Bytes each parameter requires

  • In int8, memorymodel=(1 byte/param)⋅(No. params)

  • In fp16 and bf16, memorymodel=(2 bytes/param)⋅(No. params)

  • In fp32, memorymodel=(4 bytes/param)⋅(No. params)

There is also a small amount of additional overhead, which is typically irrelevant to determining the largest model that will fit on your GPU. In our experience this overhead is ≤ 20%.

Total Inference Memory

In addition to the memory needed to store the model weights, there is also a small amount of additional overhead during the actual forward pass. In our experience this overhead is ≤ 20% and is typically irrelevant to determining the largest model that will fit on your GPU.

In total, a good heuristic answer for “will this model fit for inference” is:

Total MemoryInference≈(1.2)×Model Memory

Training

In addition to the model parameters, training requires the storage of optimiser states and gradients in device memory.

This is why asking “how much memory do I need to fit model X” immediately leads to the answer “this depends on training or inference.” Training always requires more memory than inference, often very much more!

Model Parameters

First off, models can be trained in pure fp32 or fp16:

  • Pure fp32, memorymodel=(4 bytes/param)⋅(No. params)

  • Pure fp16, memorymodel=(2 bytes/param)⋅(No. params)

This technique seeks to maximise the throughput of GPU tensor cores while maintaining convergence.

The modern DL training landscape frequently uses mixed-precision training because:

1) fp32 training is stable, but has a high memory overhead and doesn’t exploit NVIDIA GPU tensor cores, and

2) fp16 training is stable but difficult to converge.

  • Mixed-precision (fp16/bf16 and fp32), memorymodel=(2 bytes/param)⋅(No. params)

plus an additional size (4 bytes/param)⋅(#params) copy of the model that we count within our optimizer states.

Optimizer States

Adam is magic, but it’s highly memory inefficient. In addition to requiring you to have a copy of the model parameters and the gradient parameters, you also need to keep an additional three copies of the gradient parameters. Therefore,

  • For vanilla AdamW, memoryoptimizer=(12 bytes/param)⋅(No. params)

    • fp32 copy of parameters: 4 bytes/param

    • Momentum: 4 bytes/param

    • Variance: 4 bytes/param

    • fp32 copy of parameters: 4 bytes/param

    • Momentum: 1 byte/param

    • Variance: 1 byte/param

  • For SGD-like optimizers with momentum, memoryoptimizer=(8 bytes/param)⋅(No. params)

    • fp32 copy of parameters: 4 bytes/param

    • Momentum: 4 bytes/param

Gradients

Gradients can be stored in fp32 or fp16 (Note that the gradient datatype often matches the model datatype. We see that it therefore is stored in fp16 for fp16 mixed-precision training), so their contribution to memory overhead is given by:

  • In fp32, memorygradients=(4 bytes/param)⋅(No. params)

  • In fp16, memorygradients=(2 bytes/param)⋅(No. params)

Activations and Batch Size

Modern GPUs are typically bottlenecked by memory, not FLOPs, for LLM training.

Therefore activation recomputation/checkpointing is an extremely popular method of trading reduced memory costs for extra compute costs.

Activation recomputation/checkpointing works by recomputing activations of certain layers instead of storing them in GPU memory.

The reduction in memory depends on how selective we are when deciding which layers to clear, but Megatron’s selective recomputation scheme is depicted in the figure below:

The dashed red line indicates the memory capacity of an A100-80GB GPU, and “present work” indicates the memory requirements after applying selective activation recomputation.

The basic equation giving the memory required to store activations for a transformer model is given by:

memoryactivationsNo Recomputation=𝑠𝑏ℎ𝐿(10+24𝑡+5𝑎⋅𝑠ℎ⋅𝑡) bytes

memoryactivationsSelective Recomputation=𝑠𝑏ℎ𝐿(10+24𝑡) bytes

memoryactivationsFull Recomputation=2⋅𝑠𝑏ℎ𝐿 bytes

where:

  • 𝑠 is the sequence length, in tokens

  • 𝑏 is the batch size per GPU

  • ℎ is the dimension of the hidden size within each transformer layer

  • 𝐿 is the number of layers in the transformer model

  • 𝑎 is the number of attention heads in the transformer model

  • 𝑡 is the degree of tensor parallelism being used (1 if not)

  • We assume no sequence parallelism is being used

  • We assume that activations are stored in fp16

The additional recomputation necessary also depends on the selectivity of the method, but it’s bounded above by a full additional forward pass. Hence the updated cost of the forward pass is given by:

Total Training Memory

Therefore, a good heuristic answer for “will this model fit for training” is:

Total MemoryTraining=Model Memory+Optimiser Memory+Activation Memory+Gradient Memory

Distributed Training

Sharded Optimizers

Such sharding strategies reduce the optimizer overhead by a factor of No. GPUs, which is why a given model configuration may fit at large scale but OOM at small scales.

If you’re looking to calculate the memory overhead required by training using a sharded optimizer, you will need to include the equations from the figure below.

In the language of this blog post (assuming mixed-precision and the Adam optimizer):

  • For ZeRO-1,

Total MemoryTraining≈Model Memory+Optimizer memory(No. GPUs)+Activation Memory+Gradient Memory

  • For ZeRO-2,

Total MemoryTraining≈Model Memory+Activation Memory+Optimizer Memory+Gradient Memory(No. GPUs)

  • For ZeRO-3,

Total MemoryTraining≈Activation Memory+Model Memory+Optimizer Memory+Gradient Memory(No. GPUs)+(ZeRO-3 Live Params)

Note that ZeRO-3 introduces a set of live parameters. This is because ZeRO-3 introduces a set of config options (stage3_max_live_parameters, stage3_max_reuse_distance, stage3_prefetch_bucket_size, stage3_param_persistence_threshold) that control how many parameters are within GPU memory at a time (larger values take more memory but require less communication). Such parameters can have a significant effect on total GPU memory.

Total MemoryTraining≈Model Memory+Optimizer Memory(No. GPUs)+Activation Memory(Tensor-Parallel-Size)+Gradient Memory

3D Parallelism

Parallelism for LLMs comes in 3 primary forms:

Data parallelism: Split the data among (possibly model-parallel) replicas of the model

Pipeline or Tensor/Model parallelism: These parallelism schemes split the parameters of the model across GPUs. Such schemes require significant communication overhead, but their memory reduction is approximately:

memorymodelw/ parallelism≈Model Memory(Pipe-Parallel-Size)×(Tensor-Parallel-Size)

memorygradientsw/ parallelism≈Gradient Memory(Pipe-Parallel-Size)

Note that this equation is approximate due to the facts that (1) pipeline parallelism doesn’t reduce the memory footprint of activations, (2) pipeline parallelism requires that all GPUs store the activations for all micro-batches in-flight, which becomes significant for large models, and (3) GPUs need to temporarily store the additional communication buffers required by parallelism schemes.

Sharded Optimizers + 3D Parallelism

When ZeRO is combined with tensor and/or pipeline parallelism, the resulting parallelism strategy forms a mesh like the following:

As an important aside, the DP degree is vital for use in calculating the global batch size of training. The data-parallel degree depends on the number of complete model replicas:

DP Degree = No. GPUs(Pipe-Parallel-Size)×(Tensor-Parallel-Size)

  • ZeRO-3 gathers the full layer parameters from other ranks, processes a full input on the now-local full layer, then frees the memory that was allocated to hold the remote ranks' parameters.

  • Tensor Parallelism gathers the remote activations for the local input from other ranks, processes a partition of the input using the local layer partition, then sends the next layer's activations to remote ranks

For the majority of Eleuther's work, we train with pipeline and tensor parallelism along with ZeRO-1. This is because we find ZeRO-3 to be too communication-heavy for our hardware at large scales, and instead use pipeline parallelism across nodes along with tensor parallelism within nodes.

Putting everything together for a typical 3D-parallel ZeRO-1 run with activation partitioning:

Total MemoryTraining≈Model Memory(Pipe-Parallel-Size)×(Tensor-Parallel-Size)+Optimizer Memory(No. GPUs)+Activation Memory(Tensor-Parallel-Size)+Gradient Memory(Pipe-Parallel-Size)

Conclusion

It's important to discuss the units of (C)( C )(C).

(C)( C ) (C)is a measure of total compute and can be quantified in various units such as:

FLOP-seconds, which combines the number of floating point operations per second with the duration of computation: [FLOP-seconds=[Floating Point Operations per Second]×[Seconds]] [ \text{FLOP-seconds} = [\text{Floating Point Operations per Second}] \times [\text{Seconds}] ][FLOP-seconds=[Floating Point Operations per Second]×[Seconds]]

GPU-hours, which multiplies the number of GPUs by the time in hours: [GPU-hours=[No. of GPUs]×[Hours]][ \text{GPU-hours} = [\text{No. of GPUs}] \times [\text{Hours}] ][GPU-hours=[No. of GPUs]×[Hours]]

PetaFLOP-days, often used in scaling laws papers, measures the total floating point operations over days, specifically: [PetaFLOP-days=1015×24×3600 total floating point operations][ \text{PetaFLOP-days} = 10^{15} \times 24 \times 3600 \text{ total floating point operations} ][PetaFLOP-days=1015×24×3600 total floating point operations]

We will not investigate the sources of this overhead in this blog post and leave it to other posts or locations for now, instead focusing on memory for model training in the rest of this post. If you’re interested in learning more about the calculations required for inference, check out . Now, on to training!

In addition to the common model weight datatypes discussed in Inference, training introduces mixed-precision training such as .

For 8-bit optimizers like , memoryoptimizer=(6 bytes/param)⋅(No. params)

See for further details and the derivation of the equations below

2𝑃𝐷≤𝐶forward≤4𝑃𝐷2𝑃𝐷≤𝐶forward≤4𝑃𝐷2PD≤Cforward≤4PD

The massive memory overheads for optimizers is the primary motivation for sharded optimizers such as and .

For some sample calculations of sharded optimisation, see the following figure from the paper (Note that 𝑃𝑜𝑠 𝑃𝑜𝑠+𝑔 and 𝑃𝑜𝑠+𝑔+𝑝 are commonly denoted as ZeRO-1, ZeRO-2, ZeRO-3, respectively. ZeRO-0 commonly means “ZeRO disabled”):

Where (DP Degree) is just (No. GPUs) unless pipeline and/or tensor parallelism are applied. See for details.

Note that ZeRO can also partition activations over data parallel ranks via ZeRO-R. This would also bring the memoryactivations above the tensor parallelism degree 𝑡. For more details, read the associated and (note in GPT-NeoX, this is the partition_activations flag). If you are training a huge model, you would like to trade some memory overhead for additional communication cost, and activations become a bottleneck. As an example of using ZeRO-R along with ZeRO-1:

Pipeline parallelism and tensor parallelism are compatible with all stages of ZeRO. However, it's difficult to maintain efficiency when combining pipeline parallelism with ZeRO-2/3's gradient sharding (Because ZeRO-2 shards the gradients, but pipeline parallelism accumulates them. It's possible to carefully define a pipeline schedule and overlap communication to maintain efficiency, but it's difficult to the point that DeepSpeed currently forbids it: . Tensor parallelism, however, is complementary to all stages of ZeRO because on each rank:

EleutherAI engineers frequently use heuristics like the above to plan efficient model training and to debug distributed runs. We hope to provide some clarity on these often-overlooked implementation details, and would love to hear your feedback at if you would like to discuss or think we’ve missed anything!

this fantastic blog post covering inference in depth
AMP
bitsandbytes
Reducing Activation Recomputation in Large Transformer Models
ZeRO
FSDP
ZeRO
Sharded Optimizers + 3D Parallelism
ZeRO paper
config options
https://github.com/microsoft/DeepSpeed/blob/v0.10.1/deepspeed/runtime/pipe/engine.py#L71)
contact@eleuther.ai
3D parallelism
LogoScaling Laws for Neural Language ModelsarXiv.org
LogoTraining Compute-Optimal Large Language ModelsarXiv.org
LogoReducing Activation Recomputation in Large Transformer ModelsarXiv.org
ZeRO legend
Different floating point formats and their relative bits for precision and range
activation memory
ZeRO illustration
GPT-NeoX scaling