LeetLLM
My PlanLearnGlossaryTracksPracticeBlog
LeetLLM

Your go-to resource for mastering AI & LLM systems.

Product

  • Learn
  • Glossary
  • Tracks
  • Practice
  • Blog
  • RSS

Legal

  • Terms of Service
  • Privacy Policy

© 2026 LeetLLM. All rights reserved.

All Topics
Your Progress
0%

0 of 177 articles completed

🛠️Computing Foundations0/9
Git, Shell, Linux for AIDocker for Reproducible AIPython for AI EngineeringNumPy and Tensor ShapesCUDA for ML TrainingMPS & Metal for ML on MacData Structures for AISQL and Data ModelingAlgorithms for ML Engineers
📊Math & Statistics0/8
Gradients and BackpropVectors, Matrices & TensorsLinear Algebra for MLAdam, Momentum, SchedulersProbability for Machine LearningStatistics and UncertaintyDistributions and SamplingHypothesis Tests, Intervals, and pass@k
📚Preparation & Prerequisites0/13
Neural Networks from ScratchCNNs from ScratchTraining & BackpropagationSoftmax, Cross-Entropy & OptimizationRNNs, LSTMs, GRUs, and Sequence ModelingAutoencoders and VAEsThe Transformer Architecture End-to-EndLanguage Modeling & Next TokensFrom GPT to Modern LLMsPrompt Engineering FundamentalsCalling LLM APIs in ProductionFirst AI App End-to-EndThe LLM Lifecycle
🧮ML Algorithms & Evaluation0/11
Linear Regression from ScratchLogistic Regression and MetricsDecision Trees, Forests, and BoostingReinforcement Learning BasicsValidation and LeakageClustering and PCACore Retrieval AlgorithmsDecoding AlgorithmsExperiment Design and A/B TestingPyTorch Training LoopsDataset Pipelines and Data Quality
📦Production ML Systems0/6
Feature Engineering for Production MLBatch and Streaming Feature PipelinesGradient Boosted Trees in ProductionRanking and Recommendation SystemsForecasting and Anomaly DetectionMonitoring Predictive Models
🧪Core LLM Foundations0/8
The Bitter Lesson & ComputeBPE, WordPiece, and SentencePieceStatic to Contextual EmbeddingsPerplexity & Model EvaluationFile Ingestion for AIChunking StrategiesLLM Benchmarks & LimitationsInstruction Tuning & Chat Templates
🧰Applied LLM Engineering0/24
Dimensionality Reduction for EmbeddingsCoT, ToT & Self-Consistency PromptingFunction Calling & Tool UseMCP & Tool Protocol StandardsContext EngineeringPrompt Injection DefenseResponsible AI GovernanceData Labeling and Human FeedbackEvaluating AI AgentsProduction RAG PipelinesHybrid Search: Dense + SparseReranking and Cross-Encoders for RAGRAG Evaluation for Reliable AnswersLLM-as-a-Judge EvaluationBias & Fairness in LLMsHallucination Detection & MitigationLLM Observability & MonitoringExperiment Tracking with MLflow and W&BPrompt Optimization with DSPyModel Versioning & DeploymentSemantic Caching & Cost OptimizationLLM Cost Engineering & Token EconomicsModel Gateways, Routing, and FallbacksDesign an Automated Support Agent
🎓Portfolio Capstones0/9
Capstone: Delivery ETA PredictionCapstone: Product RankingCapstone: Demand ForecastingCapstone: Image Damage ClassifierCapstone: Production ML PipelineCapstone: Document QACapstone: Eval DashboardCapstone: Fine-Tuned ClassifierCapstone: Reproducible ML Study
🧠Transformer Deep Dives0/8
Sentence Embeddings & Contrastive LossEmbedding Similarity & QuantizationScaled Dot-Product AttentionVision Transformers and Image EncodersPositional Encoding: RoPE & ALiBiLayer Normalization: Pre-LN vs Post-LNMechanistic InterpretabilityDecoding Strategies: Greedy to Nucleus
🧬Advanced Training & Adaptation0/16
Scaling Laws & Compute-Optimal TrainingPre-training Data at ScaleBuild GPT from Scratch LabJAX for PyTorch ResearchersContinued Pretraining for Domain ShiftSynthetic Data PipelinesSupervised Fine-Tuning PipelineMixed Precision TrainingDistributed Training: FSDP & ZeROLoRA & Parameter-Efficient TuningReward Modeling from Preference DataRLHF & DPO AlignmentConstitutional AI & Red TeamingRLVR & Verifiable RewardsKnowledge Distillation for LLMsModel Merging and Weight Interpolation
🤖Advanced Agents & Retrieval0/16
Vector DB Internals: HNSW & IVFAdvanced RAG: HyDE & Self-RAGGraphRAG & Knowledge GraphsRAG Security & Access ControlStructured Output GenerationReAct & Plan-and-ExecuteGuardrails & Safety FiltersCode Generation & SandboxingComputer-Use / GUI / Browser AgentsHuman-in-the-Loop Agent ArchitectureAI Coding Workflow with AgentsAgent Memory & PersistenceAgent Failure & RecoveryRecursive Language Models (RLM)Multi-Agent OrchestrationCapstone: Production Agent
⚡Inference & Production Scale0/19
Inference: TTFT, TPS & KV CacheMulti-Query & Grouped-Query AttentionKV Cache & PagedAttentionPrefix Caching and Prompt CachingFlashAttention & Memory EfficiencyContinuous Batching & SchedulingScaling LLM InferenceModel Parallelism for LLM InferenceModel Quantization: GPTQ, AWQ & GGUFLocal LLM DeploymentSLM Specialization & Edge DeploymentSpeculative DecodingLong Context Window ManagementMixture of Experts ArchitectureMamba & State Space ModelsReasoning & Test-Time ComputeAdvanced MLOps & DevOps for AIGPU Serving & AutoscalingA/B Testing for LLMs
🏗️System Design Capstones0/9
Content Moderation SystemCode Completion SystemMulti-Tenant LLM PlatformLLM-Powered Search EngineVision-Language Models & CLIPMultimodal LLM ArchitectureDiffusion Models: Images & TextReal-Time Voice AI AgentReasoning & Test-Time Compute
🎤AI Lab Interviewing0/4
AI Lab Coding Interview: Python SystemsAI Lab System Design InterviewAI Lab Behavioral InterviewAI Lab Technical Presentation
🔬Project Deep Dives0/17
Deep Dive - vLLMDeep Dive - SkyRLDeep Dive - FlashAttentionDeep Dive - FlashInferDeep Dive - DeepGEMMDeep Dive - NCCLDeep Dive - MegatronDeep Dive - DeepSpeedDeep Dive - RayDeep Dive - MLflowDeep Dive - PyTorchDeep Dive - TransformersDeep Dive - SGLangDeep Dive - slimeDeep Dive - DeepEPDeep Dive - TinkerDeep Dive - Light-PEFT
Back to Topics
LearnProject Deep DivesDeep Dive - DeepSpeed
⚡HardFine-Tuning & Training

Deep Dive - DeepSpeed

Read DeepSpeed from its engine boundary through ZeRO state ownership, layer-time gathers, CPU and NVMe offload, pipeline limits, checkpoint recovery, governance, and source code.

20 min read
Learning path
Step 168 of 177 in the full curriculum
Deep Dive - MegatronDeep Dive - Ray

Personalize this lesson

Adapt explanations and teaching visuals to your background and preferred voice.

A model can fit in GPU memory for inference and still fail before its first training step. Training also keeps gradients, optimizer moments, master weights, and activations. For mixed-precision Adam, model states alone can consume roughly eight times the low-precision parameter file.

DeepSpeed turns those copies into explicit ownership decisions. Its best-known mechanism, ZeRO (Zero Redundancy Optimizer), partitions optimizer state, gradients, and eventually parameters across data-parallel ranks. The model's math stays the same; where each tensor lives and when it moves change.[1]Reference 1ZeRO: Memory Optimizations Toward Training Trillion Parameter Models.https://arxiv.org/abs/1910.02054

DeepSpeed ZeRO state ownership matrix for four data-parallel ranks. Optimizer state becomes one-quarter per rank at stage 1, gradients join at stage 2, and parameters join at stage 3, while activation memory remains local at every stage. DeepSpeed ZeRO state ownership matrix for four data-parallel ranks. Optimizer state becomes one-quarter per rank at stage 1, gradients join at stage 2, and parameters join at stage 3, while activation memory remains local at every stage.
Read down each ZeRO stage. Optimizer state shards first, gradients next, and parameters last. Activations stay local, so ZeRO alone can't solve every training out-of-memory error.

What DeepSpeed takes over

Ordinary PyTorch code owns the model, optimizer, backward call, gradient synchronization, and step. deepspeed.initialize(...) wraps that stack in a DeepSpeedEngine. The engine tracks microsteps, accumulation boundaries, distributed groups, precision, gradient reduction, optimizer stepping, monitoring, and checkpoints.[2]Reference 2Training APIhttps://deepspeed.readthedocs.io/en/latest/training.html[3]Reference 3DeepSpeed Source Repositoryhttps://github.com/deepspeedai/DeepSpeed/tree/c455031422641a825588c926455458c82b27b6c0

The user-facing loop stays small:

train_step.py
1engine, optimizer, dataloader, scheduler = deepspeed.initialize( 2 model=model, 3 model_parameters=model.parameters(), 4 training_data=dataset, 5 config="ds_config.json", 6) 7 8loss = engine(batch) 9engine.backward(loss) 10engine.step()

That compact API hides a serious contract. DeepSpeed must know global batch arithmetic, gradient-accumulation boundaries, data-parallel groups, parameter ownership, precision, and checkpoint layout. A wrong config can preserve execution while silently changing effective batch size, update frequency, or throughput.

💡 Key insight: DeepSpeed is an execution engine, not a memory-only switch. It owns enough of the training step to reschedule state and communication. That control makes config review and checkpoint testing necessary.

Build the memory ledger first

Let Ψ\PsiΨ be parameter count. A common mixed-precision Adam setup keeps low-precision parameters and gradients plus three FP32 arrays: master weights, first moment mmm, and second moment vvv.

Model stateTypical bytes per parameterWhy it exists
FP16 or BF16 parameter2Forward and backward compute
FP16 or BF16 gradient2Backward result before update
FP32 master parameter4Stable optimizer update
FP32 first moment mmm4Adam momentum estimate
FP32 second moment vvv4Adam variance estimate
Total before activations16Replicated model state under plain data parallelism

This 16Ψ16\Psi16Ψ estimate is a planning model, not a universal allocator receipt. Optimizer implementation, gradient dtype, flat buffers, fragmentation, temporary gathers, and quantized states can change it. Activations, attention workspaces, and CUDA runtime memory sit outside the table.

For four data-parallel ranks, the idealized per-rank state becomes:

MZ1=4Ψ+12Ψ4=7Ψ,M_{Z1} = 4\Psi + \frac{12\Psi}{4} = 7\Psi,MZ1​=4Ψ+412Ψ​=7Ψ, MZ2=2Ψ+14Ψ4=5.5Ψ,M_{Z2} = 2\Psi + \frac{14\Psi}{4} = 5.5\Psi,MZ2​=2Ψ+414Ψ​=5.5Ψ, MZ3=16Ψ4=4Ψ.M_{Z3} = \frac{16\Psi}{4} = 4\Psi.MZ3​=416Ψ​=4Ψ.

At stage 1, parameters and gradients remain replicated, costing 4Ψ4\Psi4Ψ, while 12Ψ12\Psi12Ψ of optimizer and master state is sharded. Stage 2 also partitions the 2Ψ2\Psi2Ψ gradient block. The third stage shards every listed state. Temporary buffers and live layers make observed peaks higher.

The following copy-runnable estimator makes rank count and parameter count easy to change. It reports decimal gigabytes and leaves activation memory out on purpose.

zero_memory_estimator.py
1parameters = 1_000_000_000 2data_parallel_ranks = 4 3 4bytes_per_param = { 5 "DDP": 16, 6 "ZeRO-1": 4 + 12 / data_parallel_ranks, 7 "ZeRO-2": 2 + 14 / data_parallel_ranks, 8 "ZeRO-3": 16 / data_parallel_ranks, 9} 10 11for name, value in bytes_per_param.items(): 12 memory_gb = parameters * value / 1e9 13 print(f"{name:7s} {memory_gb:4.1f} GB per rank before activations")
Output
1DDP 16.0 GB per rank before activations 2ZeRO-1 7.0 GB per rank before activations 3ZeRO-2 5.5 GB per rank before activations 4ZeRO-3 4.0 GB per rank before activations

The three ZeRO stages

Each stage adds one partitioned state type. Higher isn't automatically better. Choose the lowest stage that fits while meeting throughput and recovery targets.[4]Reference 4ZeRO Configurationhttps://deepspeed.readthedocs.io/en/stable/zero3.html

StagePartitioned across data ranksWhat remains replicatedMain new cost
ZeRO-1Optimizer states and master weightsParameters and gradientsSharded optimizer bookkeeping
ZeRO-2Optimizer states and gradientsParametersReduce-scatter and gradient partition flow
ZeRO-3Optimizer states, gradients, parametersCurrent gathered working setParameter all-gathers, prefetch, release, harder checkpoints

Stage 1 is useful when Adam state dominates memory and full weights still fit. The second stage often gives a strong fine-tuning balance because parameters stay resident while gradients and optimizer state shard. Move to stage 3 when even replicated parameters are too large.

The original DeepSpeed ZeRO tutorial demonstrates a 1.5-billion-parameter GPT-2-style model on eight 32 GB V100 GPUs. It reports 18 GB of Adam state, then reduces that block to 2.25 GB per device with ZeRO-1 by partitioning it eight ways.[4]Reference 4ZeRO Configurationhttps://deepspeed.readthedocs.io/en/stable/zero3.html Treat those numbers as one documented setup, not a multiplier for newer hardware or every optimizer.

Configure behavior, then verify arithmetic

A DeepSpeed JSON file selects precision, batch decomposition, optimizer, and ZeRO behavior. For a four-rank run, the configuration below uses BF16 and ZeRO-2.

ds_config.json
1{ 2 "train_batch_size": 64, 3 "train_micro_batch_size_per_gpu": 2, 4 "gradient_accumulation_steps": 8, 5 "bf16": { "enabled": true }, 6 "zero_optimization": { 7 "stage": 2, 8 "contiguous_gradients": true, 9 "overlap_comm": true, 10 "reduce_scatter": true, 11 "reduce_bucket_size": 200000000 12 }, 13 "optimizer": { 14 "type": "AdamW", 15 "params": { 16 "lr": 0.00002, 17 "betas": [0.9, 0.999], 18 "eps": 1e-8, 19 "weight_decay": 0.01 20 } 21 } 22}

The global batch identity is:

Bglobal=Bmicro×A×Ndata=2×8×4=64.B_{global} = B_{micro} \times A \times N_{data} = 2 \times 8 \times 4 = 64.Bglobal​=Bmicro​×A×Ndata​=2×8×4=64.

BmicroB_{micro}Bmicro​ is samples per GPU per microstep, AAA is accumulation steps, and NdataN_{data}Ndata​ is data-parallel ranks. If the launch uses eight ranks without changing another term, global batch doubles. Learning-rate and schedule assumptions may then be wrong even though training runs.

Bucket size controls another tradeoff. Small buckets start communication early but increase launch overhead. Large buckets use links efficiently but need more temporary memory and may finish too late to hide under backward compute. Measure exposed communication in a timeline rather than copying a round number from another model.

ZeRO-3 works one layer at a time

ZeRO-3 stores a parameter shard on each rank during steady state. Before a module computes, ranks all-gather that module's parameter shards into a full working copy. After the module no longer needs the full weights, DeepSpeed can release them and return to shards.[4]Reference 4ZeRO Configurationhttps://deepspeed.readthedocs.io/en/stable/zero3.html

ZeRO stage 3 execution map. A rank starts with a parameter shard, all-gathers the current module, computes forward or backward, releases full parameters, and repeats for another module. Backward gradients reduce-scatter into owned shards for a later optimizer step, with optional CPU or NVMe swapping. ZeRO stage 3 execution map. A rank starts with a parameter shard, all-gathers the current module, computes forward or backward, releases full parameters, and repeats for another module. Backward gradients reduce-scatter into owned shards for a later optimizer step, with optional CPU or NVMe swapping.
Separate module work from the optimizer boundary. Parameters gather and release around each module; backward gradients reduce-scatter into owned shards, then the optimizer updates those shards after backward finishes.

Backward produces gradients for the gathered layer. Reduce-scatter combines those gradients and leaves each rank with the shard it owns. Each rank updates its local optimizer and parameter shard, so no rank needs every Adam moment.

Prefetch and persistence settings decide how aggressively DeepSpeed overlaps future gathers and keeps small or frequently reused parameters resident. Too little prefetch exposes communication. Too much prefetch recreates the memory spike sharding was meant to avoid.

Dynamic modules need explicit boundaries

Stage 3 expects every rank to gather parameters in compatible order. Dynamic control flow, tied weights, or modules whose parameters are accessed outside their own forward() can break that assumption. DeepSpeed provides mechanisms such as external-parameter registration and leaf-module configuration for these cases.[4]Reference 4ZeRO Configurationhttps://deepspeed.readthedocs.io/en/stable/zero3.html

A useful debugging reduction disables dynamic branches and runs the smallest deterministic batch. Compare loss and parameter updates against an unsharded baseline. Restore model features one at a time after the gather order is stable.

Offload trades capacity for a slower tier

ZeRO-Offload moves optimizer state and optimizer computation toward host CPU memory. ZeRO-Infinity extends the hierarchy so parameters and optimizer state can use CPU memory or NVMe with staging and overlap.[5]Reference 5ZeRO-Offload: Democratizing Billion-Scale Model Traininghttps://www.usenix.org/conference/atc21/presentation/ren-jie[6]Reference 6ZeRO-Infinity: Breaking the GPU Memory Wall for Extreme Scale Deep Learning.https://arxiv.org/abs/2104.07857

The configuration can look small:

ds_config_offload.json
1{ 2 "zero_optimization": { 3 "stage": 3, 4 "offload_optimizer": { 5 "device": "cpu", 6 "pin_memory": true 7 }, 8 "offload_param": { 9 "device": "nvme", 10 "nvme_path": "/local_nvme/deepspeed" 11 } 12 } 13}

The performance model isn't small. A step may wait on GPU-to-CPU DMA, CPU Adam work, pinned-memory pressure, NVMe queue depth, filesystem contention, or NUMA placement. Offload can make a model fit while reducing tokens per second enough to miss the training deadline.

Treat the memory hierarchy as a pipeline:

TierCapacityRelative speedWhat to measure
GPU HBMSmallestFastestPeak allocated and reserved bytes
CPU memoryLargerSlower path over PCIe or coherent linkTransfer overlap, pinning, NUMA locality
Local NVMeLargestStorage latency and bandwidthRead/write throughput, queue depth, free space

⚠️ Common mistake: “Fits” isn't a throughput result. Record step time, tokens per second, exposed transfer time, CPU utilization, and storage bandwidth after every offload change.

NCCL moves the shards DeepSpeed schedules

DeepSpeed decides which data-parallel group owns a shard, when a bucket is ready, and whether communication should overlap. NCCL executes the GPU collectives on NVIDIA systems. The two projects solve adjacent layers.

ZeRO-2 commonly replaces one replicated gradient all-reduce result with reduce-scatter ownership. ZeRO-3 adds parameter all-gathers around module execution. ZeRO++ adds communication-oriented options such as quantized weight exchange, hierarchical partition groups, and quantized gradients to reduce pressure on slower links.[4]Reference 4ZeRO Configurationhttps://deepspeed.readthedocs.io/en/stable/zero3.html

If a stage change hurts throughput, inspect both sides. DeepSpeed logs and profiler traces show bucket timing and overlap. NCCL traces and network counters show algorithm, route, and achieved communication. Tuning only one layer can misdiagnose a topology problem as a bucket problem.

DeepSpeed is broader than ZeRO

ZeRO is the center of gravity, but the repository contains more systems:

AreaSource or APIJob
Training enginedeepspeed/runtime/engine.pyWrap model, optimizer, backward, step, batches, monitoring
ZeRO-1 and ZeRO-2runtime/zero/stage_1_and_2.pyGradient and optimizer partitions
ZeRO-3runtime/zero/stage3.py, partition_parameters.pyParameter gathers, release, gradient shards
Offloadruntime/swap_tensor/, ops/aio/, CPU AdamMove and update state outside HBM
Pipeline parallelismruntime/pipe/Partition layers and schedule microbatches
Tensor parallelismmodule_inject/, AutoTP pathsReplace compatible modules with tensor-parallel forms
Expert parallelismmoe/MoE groups, experts, routing support
Inferenceinference/Inference engine, kernels, tensor-parallel injection
Profiling and monitoringprofiling/, monitor/FLOPs, timing, and metric integrations

DeepSpeed's built-in PipelineEngine is not a promise that every ZeRO stage composes with every pipeline setup. In the pinned snapshot, it rejects ZeRO-2 and ZeRO-3 for that engine path. Separate Megatron-DeepSpeed integrations and other runtimes have different composition contracts.[3]Reference 3DeepSpeed Source Repositoryhttps://github.com/deepspeedai/DeepSpeed/tree/c455031422641a825588c926455458c82b27b6c0

Feature matrices need source and version context. “DeepSpeed supports pipeline plus ZeRO” is too broad to choose a runtime path. Ask which engine, model wrapper, ZeRO stage, checkpoint format, and tested release combination is involved.

Read initialization into the optimizer

Start at deepspeed/__init__.py. initialize(...) selects the communication backend, initializes distributed state, parses config, and returns the engine plus wrapped optimizer, data loader, and scheduler.[3]Reference 3DeepSpeed Source Repositoryhttps://github.com/deepspeedai/DeepSpeed/tree/c455031422641a825588c926455458c82b27b6c0

Diagram showing Host setup, Runtime path, 1 · deepspeed.initialize config + distributed, and 2 · DeepSpeedEngine model + batch contract. Diagram showing Host setup, Runtime path, 1 · deepspeed.initialize config + distributed, and 2 · DeepSpeedEngine model + batch contract.
Host setup, Runtime path, 1 · deepspeed.initialize config + distributed, and 2 · DeepSpeedEngine model + batch contract.

Then follow the selected stage:

  • Stage 1 or 2: runtime/zero/stage_1_and_2.py flattens groups, creates partitions, registers gradient handling, and coordinates reductions.
  • Stage 3: runtime/zero/stage3.py builds sharded optimizer state while partition_parameters.py manages parameter status, gathers, and repartitioning.
  • CPU or NVMe offload: runtime/swap_tensor/, asynchronous I/O operators, and CPU optimizer code expose the slower memory tier.
  • Pipeline mode: runtime/pipe/engine.py owns stage IDs, neighbors, microbatches, and pipeline-specific reduction scheduling.

The source map prevents a common reading mistake. DeepSpeedEngine.step() isn't where every optimization lives. It delegates to optimizer wrappers, communication layers, hooks, swap engines, and checkpoint utilities selected at initialization.

Checkpoints are part of the runtime design

A ZeRO checkpoint is distributed training state, not automatically one portable model file. Each rank can write shards of parameters, optimizer state, scheduler state, and metadata. World size and parallel layout affect how those shards are interpreted.

DeepSpeed's ZeRO tutorial documents zero_to_fp32.py and get_fp32_state_dict_from_zero_checkpoint for consolidating ZeRO checkpoints.[4]Reference 4ZeRO Configurationhttps://deepspeed.readthedocs.io/en/stable/zero3.html Universal Checkpointing targets resume across different parallel configurations by converting state into a topology-independent form.[7]Reference 7Universal Checkpointing with DeepSpeed: A Practical Guide.https://www.deepspeed.ai/tutorials/universal-checkpointing/

Test four paths before a long run:

  1. Save a checkpoint at the intended scale.
  2. Kill every worker and restore training.
  3. Verify loss, scheduler, optimizer step, and sample counters continue correctly.
  4. Export a consolidated model and load it in the evaluation or serving runtime.

A directory existing isn't enough. Checkpoint success means the resumed job produces the expected next update and the exported model matches a reference output within the chosen precision tolerance.

DeepSpeed, FSDP, and Megatron answer different questions

These systems overlap, but their default centers differ.

SystemCenter of gravityStrong fitMain integration cost
DeepSpeedConfig-driven training engine and optimization suiteZeRO stages, offload, broad training featuresEngine ownership, config surface, version combinations
PyTorch FSDPPyTorch-native parameter sharding wrapperTeams staying inside PyTorch APIs and distributed checkpointingWrap policy, state-dict modes, reshard timing
Megatron CoreModel-parallel transformer building blocksTP, PP, CP, EP, specialized large-model schedulesModel architecture and rank-mesh complexity

FSDP and ZeRO-3 share a core idea: parameters, gradients, and optimizer state can remain sharded until computation needs them. API boundaries, scheduling, checkpoint formats, mixed-precision policies, and ecosystem integration differ.

Megatron can be paired with distributed optimizer or sharding choices and DeepSpeed-based integrations. Don't select by project logo. Select from model shape, network topology, framework ownership, checkpoint requirements, team expertise, and measured end-to-end throughput.

Production debugging loop

Begin with a small unsharded reference on fixed data. Record loss, gradient norm, optimizer step, global batch, precision, and a checkpoint round trip. That reference tells you whether a later failure changed math or only systems behavior.

Add one mechanism at a time:

StepChangeEvidence to record
1Plain distributed data parallelLoss parity and baseline tokens/sec
2ZeRO-1 or ZeRO-2Per-rank state memory and collective timeline
3Overlap and bucket tuningExposed communication, peak temporary memory
4ZeRO-3Parameter gather cadence and live working set
5CPU offloadTransfer time, CPU optimizer time, NUMA placement
6NVMe offloadStorage bandwidth, queueing, free-space guard
7Checkpoint conversionRestore parity and portable export

For a hang, find the earliest rank error before reading peer timeout stacks. Loss divergence calls for one-update comparison with identical data and math. Throughput drops need a step-time split across compute, collectives, CPU work, I/O, and idle gaps.

Useful questions stay concrete:

  • Did global batch change with world size?
  • Are activations, model state, or temporary gathers causing the peak?
  • Does every rank cross the same accumulation boundary?
  • Are all-gathers hidden under compute or exposed?
  • Did offload move the bottleneck to CPU, PCIe, or storage?
  • Can the latest checkpoint restore after every worker exits?

Project origin, governance, and license

DeepSpeed began in Microsoft Research and was part of Microsoft's AI at Scale work. The current project lives in the deepspeedai/DeepSpeed organization and uses a Technical Steering Committee (TSC) under AI & Data, a directed fund of The Linux Foundation.[8]Reference 8DeepSpeed Project Charter and Governancehttps://github.com/deepspeedai/DeepSpeed/blob/c455031422641a825588c926455458c82b27b6c0/GOVERNANCE.md

The pinned committer roster shows a cross-organization group rather than one company team:[9]Reference 9DeepSpeed TSC Committershttps://github.com/deepspeedai/DeepSpeed/blob/c455031422641a825588c926455458c82b27b6c0/COMMITTERS.md

CommitterAffiliation listed in roster
Olatunji RuwaseSnowflake
Logan AdamsMicrosoft
Masahiro TanakaAnyscale
Jeff RasleySnowflake
Minjia ZhangUIUC
Ashwin AjiAMD
Sam ForemanArgonne National Laboratory
Zhipeng WangGoogle
Guokai MaIntel

The TSC can add or remove committers and governs technical direction. Public contributions use Developer Certificate of Origin sign-off. DeepSpeed code uses Apache License 2.0; project governance places documentation under Creative Commons Attribution 4.0.[8]Reference 8DeepSpeed Project Charter and Governancehttps://github.com/deepspeedai/DeepSpeed/blob/c455031422641a825588c926455458c82b27b6c0/GOVERNANCE.md[10]Reference 10DeepSpeed Apache License 2.0https://github.com/deepspeedai/DeepSpeed/blob/c455031422641a825588c926455458c82b27b6c0/LICENSE

Papers behind the system

DeepSpeed grew through a sequence of systems papers rather than one isolated algorithm.

WorkCore contributionOperational lesson
ZeRO (SC 2020)Partition redundant optimizer state, gradients, and parametersThree ownership stages and memory formulas
DeepSpeed tutorial (KDD 2020)System stack for large-model trainingEngine-level combination of memory, communication, and parallelism
ZeRO-Offload (USENIX ATC 2021)Move selected state and compute to CPUCapacity versus host-bandwidth tradeoff
ZeRO-Infinity (SC 2021)Extend offload across heterogeneous memoryGPU, CPU, and NVMe working-set pipeline

ZeRO names the partitioning family.[1]Reference 1ZeRO: Memory Optimizations Toward Training Trillion Parameter Models.https://arxiv.org/abs/1910.02054 The KDD tutorial describes DeepSpeed as a broader system of training optimizations.[11]Reference 11DeepSpeed: System Optimizations Enable Training Deep Learning Models with Over 100 Billion Parametershttps://dl.acm.org/doi/10.1145/3394486.3406703 ZeRO-Offload and ZeRO-Infinity push ownership beyond GPU memory, which is why modern DeepSpeed tuning includes DMA and storage measurements alongside GPU kernels.[5]Reference 5ZeRO-Offload: Democratizing Billion-Scale Model Traininghttps://www.usenix.org/conference/atc21/presentation/ren-jie[6]Reference 6ZeRO-Infinity: Breaking the GPU Memory Wall for Extreme Scale Deep Learning.https://arxiv.org/abs/2104.07857

Research results establish that a design can work under reported conditions. A production decision still needs your model, network, optimizer, precision, sequence length, checkpoint cadence, and failure policy.

Strengths and weaknesses

DeepSpeed's strengths are practical:

  • ZeRO stages expose a clear progression from optimizer sharding to full model-state sharding.
  • CPU and NVMe offload make capacity a tiered-memory problem.
  • Engine integration keeps the user loop compact.
  • Broad features cover training, inference, pipeline execution, MoE, profiling, and accelerator backends.
  • Framework integrations make ZeRO reachable from common model stacks.
  • Public governance and source provide code-level debugging paths.

Its weaknesses come from that same breadth:

  • Large config and feature surface creates interactions that aren't all valid together.
  • Engine ownership can make framework-native debugging or migration harder.
  • ZeRO-3 replaces memory replication with frequent communication and temporary gathers.
  • Offload can trade an OOM for an unacceptable step time.
  • Sharded checkpoints require explicit recovery and export work.
  • JIT-compiled operators and accelerator compatibility add installation risk.
  • Documentation examples can outlive their exact hardware and version assumptions.

Choose DeepSpeed when its engine, ZeRO, or offload features solve a measured constraint and your team can own the integration. A smaller native stack can be easier when the model already fits and advanced DeepSpeed features add little.

Build a decision receipt

Run the estimator with your parameter count and data-parallel degree. Add measured activation peak, temporary gather buffers, and a safety margin. Predict the lowest ZeRO stage that fits.

Then run a short controlled experiment for plain DDP, your chosen ZeRO stage, and one fallback stage. Keep model, data order, optimizer, precision, and global batch fixed. Record:

  • Maximum allocated and reserved GPU memory per rank
  • Tokens per second and step-time distribution
  • Collective time split by reduce-scatter and all-gather
  • CPU, PCIe, and NVMe use if offload is enabled
  • Loss and gradient parity over several updates
  • Save, kill, restore, and export results

Finish with one sentence: “We chose stage X because constraint Y improved by Z, while cost W stayed within limit Q.” That receipt is more useful than a copied config because it explains what the system proved.

Takeaways

  • DeepSpeed wraps the training step so it can control state ownership, collectives, accumulation, precision, and checkpoints.
  • Mixed-precision Adam can require about 16 bytes of model state per parameter before activations.
  • ZeRO-1 shards optimizer state, ZeRO-2 adds gradients, and ZeRO-3 adds parameters.
  • Stage 3 saves steady-state memory by gathering each working set near layer execution.
  • Offload expands capacity but spends CPU, interconnect, and storage bandwidth.
  • NCCL moves bytes; DeepSpeed decides groups, buckets, and schedule.
  • Checkpoint restore and portable export are runtime requirements, not cleanup tasks.
  • Current governance is cross-company under Linux Foundation AI & Data, with Apache-2.0 code.

Mastery quiz

Complete the lesson

Mastery Check

Answer every question, then check your score. Score 75% or higher to mark this lesson complete.

1.What changes first when moving from plain data parallelism to ZeRO-1?
2.Under the article's 16-byte mixed-precision Adam model, what is idealized ZeRO-3 state memory per parameter on four data-parallel ranks?
3.Which pressure is least likely to improve from a ZeRO-2 to ZeRO-3 change?
4.Why does ZeRO-3 all-gather parameters near module execution?
5.A four-rank config uses microbatch 2 and eight accumulation steps. What global batch does it describe?
6.A model fits after NVMe offload, but tokens per second collapse. Which evidence is most useful next?
7.Why should a team test save, kill, restore, and export before a long ZeRO run?
8.Which statement best describes current DeepSpeed project ownership?

8 questions remaining.

Next Step
Continue to Deep Dive - Ray

DeepSpeed coordinates one distributed training job at tensor and optimizer granularity. Ray widens the <span data-glossary="control-plane">control plane</span> to schedule data processing, training, reinforcement learning, tuning, and serving work across a cluster.

PreviousDeep Dive - Megatron
Share this article
XFacebookLinkedInBlueskyRedditHacker NewsEmail
References

ZeRO: Memory Optimizations Toward Training Trillion Parameter Models.

Rajbhandari, S., et al. · 2020 · SC 2020

Training API

DeepSpeed Team · 2026

DeepSpeed Source Repository

DeepSpeed Contributors · 2026

ZeRO Configuration

DeepSpeed Team · 2026

ZeRO-Offload: Democratizing Billion-Scale Model Training

Ren, J., Rajbhandari, S., Aminabadi, R. Y., et al. · 2021 · USENIX ATC 2021

ZeRO-Infinity: Breaking the GPU Memory Wall for Extreme Scale Deep Learning.

Rajbhandari, S., et al. · 2021 · SC 2021

Universal Checkpointing with DeepSpeed: A Practical Guide.

DeepSpeed Team · 2026

DeepSpeed Project Charter and Governance

DeepSpeed Project · 2026

DeepSpeed TSC Committers

DeepSpeed Project · 2026

DeepSpeed Apache License 2.0

DeepSpeed Project · 2026

DeepSpeed: System Optimizations Enable Training Deep Learning Models with Over 100 Billion Parameters

Rasley, J., Rajbhandari, S., Ruwase, O., & He, Y. · 2020 · KDD 2020 Tutorial

Discussion

Questions and insights from fellow learners.

Discussion loads when you reach this section.