DeepSpeed vs Megatron-LM vs FSDP: How to Choose Your Large Model Training Framework
This article compares DeepSpeed, Megatron-LM, and PyTorch FSDP2 for large language model training, providing memory formulas, communication analysis, capability matrices, and a fair benchmarking methodology to help teams select the right framework based on model scale, hardware, and operational constraints.
Reading font

Version Baselines
The analysis uses specific versions: PyTorch 2.14.1 (FSDP2 via fully_shard, GA 2026-09-02), DeepSpeed v0.20.1 (2026-11-24), Megatron Core core_v0.20.1 (2026-11-19). Hardware assumption: 2-4 nodes, each with 8×H100 80GB, NVLink intra-node, 400Gb InfiniBand inter-node. All memory calculations are formula-derived, not measured; no throughput or MFU numbers are provided — readers must run the benchmark in Part 4.
What Each Framework Is
FSDP2 : PyTorch's built-in fully sharded data parallel. Uses torch.distributed.fsdp.fully_shard for parameter-granularity sharding atop DTensor. Composable with DTensor tensor parallel and torch.distributed.pipelining pipeline parallel. Checkpoints via torch.distributed.checkpoint (DCP). Legacy FullyShardedDataParallel is FSDP1; migration guide exists.
DeepSpeed : ZeRO-centric optimization library driven by a JSON config. Provides ZeRO-1/2/3, CPU/NVMe offload, pipeline parallel, Ulysses sequence parallel, AutoTP tensor parallel, MoE. Mature integration with Hugging Face Trainer and Accelerate.
Megatron Core : NVIDIA's component library for large-model training (also in Megatron-LM repo with reference scripts). Core capabilities: tensor parallel (with sequence parallel), pipeline parallel (1F1B and interleaved), context parallel, expert parallel, distributed optimizer, FP8 via Transformer Engine. Recent versions add Megatron-FSDP. Models must be built with Megatron Core layers or converted via Megatron Bridge.
Memory: How Model State Is Sharded
Base Formula
With Adam optimizer and BF16 mixed precision, each parameter occupies ~16 bytes in model state: BF16 parameter (2B), BF16 gradient (2B), FP32 master param + 1st/2nd moments (12B). This decomposition comes from the ZeRO paper. Let Ψ = parameter count, N = data parallel degree. Per-GPU model state memory:
DDP (no sharding): 16Ψ
ZeRO-1: 4Ψ + 12Ψ/N (optimizer state sharded)
ZeRO-2: 2Ψ + 14Ψ/N (gradients also sharded)
ZeRO-3: 16Ψ/N (parameters also sharded)
These exclude activations, communication buffers, temporaries, fragmentation. If gradient buffer uses FP32, gradient term becomes 4 bytes.
Framework Mapping
DeepSpeed : stage 1/2/3 maps directly.
FSDP2 : reshard_after_forward=True (default) ≈ ZeRO-3 (parameters freed after forward, re-gathered in backward). False retains full parameters until backward ends, memory closer to ZeRO-2, saves one parameter all-gather.
Megatron Core : --use-distributed-optimizer shards optimizer state (ZeRO-1 class). Megatron-FSDP offers higher sharding levels.
Concrete Example
8B model, 16 GPUs pure data parallel (Ψ=8×10⁹, N=16, 1GB=10⁹ bytes):
DDP : 16 × 8e9 = 128 GB (exceeds 80GB GPU)
ZeRO-1 : 4 × 8e9 + 12×8e9/16 = 32 + 6 = 38 GB
ZeRO-2 : 2 × 8e9 + 14×8e9/16 = 16 + 7 = 23 GB
ZeRO-3 : 16 × 8e9 / 16 = 8 GBFor 70B on 16 GPUs with ZeRO-3: 16×70×10⁹/16 = 70 GB model state alone, leaving no room for activations. Options: add GPUs, add tensor/pipeline parallel to reduce per-GPU load, or offload to CPU — each aligns with different frameworks (FSDP2/DeepSpeed, Megatron, DeepSpeed respectively).
Activations Must Be Measured
Activation memory depends on sequence length, micro-batch, hidden size, layers, activation checkpointing — no reliable universal formula. Measure by reading torch.cuda.max_memory_allocated() in the training loop, sweeping micro-batch from small to large until OOM. All three frameworks support activation checkpointing: PyTorch's torch.utils.checkpoint, DeepSpeed's activation checkpointing, Megatron's full and selective recomputation.
Communication & Capabilities: Where Differences Lie
Communication Volume Determines Network Dependency
Per ZeRO paper: DDP does one gradient all-reduce per step (~2Ψ). ZeRO-3/FSDP need forward parameter all-gather, backward parameter all-gather, gradient reduce-scatter — total ~3Ψ, ~1.5× DDP. Pure sharded data parallel hits cross-node bandwidth limits first. Framework mitigations:
FSDP2 : 2D DeviceMesh for HSDP — shard intra-node, replicate inter-node, leaving only gradient sync across nodes.
DeepSpeed : ZeRO++ hierarchical partitioning (hpZ) same idea; also quantized communication options.
Megatron : Tensor parallel inside node (NVLink); cross-node carries data parallel and pipeline parallel traffic. Megatron-FSDP also supports different sharding levels inside/outside NVLink domain.
FSDP2 HSDP only requires changing 1D mesh to 2D (replace init_device_mesh line; fully_shard receives 2D mesh, replicates on dim 0, shards on dim 1). DeepSpeed ZeRO++ enabled in zero_optimization section with zero_hpz_partition_size = GPUs per node, plus zero_quantized_weights and zero_quantized_gradients (introduce numerical error; require convergence re-verification). Tensor parallel involves collectives every layer forward/backward; degree usually ≤ GPUs per node. Pipeline parallel has bubble overhead: 1F1B bubble ratio ≈ (p−1)/m (p=pipeline stages, m=micro-batches per global batch); interleaved scheduling divides by model chunks per device. Too few micro-batches makes pipeline parallel inefficient.
Capability Comparison
Sharded DP : DeepSpeed ZeRO-1/2/3; Megatron distributed optimizer + Megatron-FSDP; FSDP2 fully_shard.
Tensor Parallel : DeepSpeed AutoTP; Megatron native TP + sequence parallel; FSDP2 DTensor parallelize_module.
Pipeline Parallel : DeepSpeed PipelineModule; Megatron 1F1B + interleaved; FSDP2 torch.distributed.pipelining.
Long Sequence : DeepSpeed Ulysses; Megatron context parallel; FSDP2 context parallel (maturity per version docs).
MoE/Expert Parallel : DeepSpeed MoE + AutoEP; Megatron EP with multiple dispatch backends; FSDP2 needs manual composition (see TorchTitan).
CPU/NVMe Offload : DeepSpeed most mature; Megatron non-mainline (check --help); FSDP2 CPUOffloadPolicy (CPU only).
Low Precision : DeepSpeed per version docs; Megatron Transformer Engine FP8; FSDP2 via torchao.
Checkpoint Format : DeepSpeed ZeRO sharded + Universal Checkpointing; Megatron torch_dist distributed format; FSDP2 DCP.
Model Code Intrusion : DeepSpeed low (wrap engine); Megatron high (must use its components); FSDP2 low (per-layer fully_shard calls).
Notable details: Megatron Core invests deepest in MoE and extreme scale (core_v0.20.0 release notes show dense MoE dispatch backends, new architectures, Megatron-FSDP v2 — currently experimental, requires TP=1 and expert TP=1). DeepSpeed recent versions fix ZeRO-3, AutoEP, AutoTP, offload correctness (v0.20.1 changelog lists multiple gradient/offload/checkpoint fixes — read before upgrading). FSDP2 advantage: "just PyTorch" — stack traces, debug tools, torch.compile support identical to vanilla PyTorch.
Operational Cost
Images & Dependencies : FSDP2 needs only PyTorch. DeepSpeed includes C++/CUDA extensions, JIT-compiles on first use (needs nvcc, ninja); multi-node simultaneous first launch triggers per-rank compilation → unpredictable startup, may hit distributed init timeout. Pre-compile operators in image build, verify with ds_report. Megatron Core depends on Transformer Engine with tight version coupling (core_v0.20.1 upgrades TE 2.20→2.21); NVIDIA recommends NGC PyTorch or NeMo containers; self-assembly costly.
Data Format : Megatron reference scripts use preprocessed indexed binary datasets (require preprocessing). FSDP2 and DeepSpeed accept custom DataLoaders.
Launch : All can use torchrun on Kubernetes. DeepSpeed's own launcher defaults to SSH/pdsh (awkward in containers); with torchrun DeepSpeed reads its env vars for init.
Export & Deploy : FSDP2 trained HF models export directly. DeepSpeed ZeRO-3 checkpoints are sharded — enable 16-bit weight aggregation or use zero_to_fp32.py to merge. Megatron checkpoints need conversion to HF format (via Megatron Bridge) for most inference engines.
Fair Benchmarking: Same Yardstick Validation
Control Variables
Software : Same base image, same PyTorch & NCCL; framework-specific deps installed separately.
Hardware : Same node pool, same GPU count; avoid node-to-node variance.
Model : Same architecture, param count, sequence length; structural differences recorded in deviation notes.
Batch : Same tokens per step (micro-batch × data-parallel × grad-accum steps).
Optimizer : Same AdamW hyperparams, same grad clipping; LR schedule identical.
Precision : BF16, same recomputation strategy; align where possible.
Unavoidable differences: Megatron uses Transformer Engine fused kernels, FSDP2 uses PyTorch SDPA, DeepSpeed has custom kernels. These are intrinsic framework capabilities — don't force alignment, but record them; never present two numbers side-by-side as pure framework overhead comparison.
Metric Definitions
Tokens/s/GPU : Drop first 20 warmup steps; use median step time of stable region.
MFU : For dense Transformer, approximate MFU ≈ 6 × N × T / (G × P) (N=params, T=global tokens/sec, G=GPUs, P=GPU BF16 dense peak FLOPS). Ignores attention compute; underestimates at long sequence — use same formula across runs.
Peak Memory : Max of torch.cuda.max_memory_allocated() across all ranks.
Step Time P50/P95 : P95 ≫ P50 indicates periodic jitter (data loading, checkpoint, network).
Convergence Consistency : Fixed dataset, first 1000 steps, compare loss curves. Random data only tests throughput, not convergence.
Checkpoint : Save time, file count/size, loss continuity after resume.
Failure Recovery : Kill one rank; measure time from failure to training restart.
Recording Template
Table with rows: Version/Image, Parallel Config, tokens/s/GPU, MFU, Peak Mem GiB, Step P50/P95, 1000-step loss diff, ckpt save/resume time, Deviation Notes. Columns for DeepSpeed, Megatron, FSDP2.
FSDP2 Reference Script
Complete runnable throughput test ( fsdp2_bench.py), uses random tokens, not for convergence. Requires PyTorch ≥2.6 ( fully_shard public API). Launched with torchrun; non-zero exit = failure. Key points: fully_shard must be called bottom-up: each Transformer layer first, then root module. Official docs specify this order. Wrapping only root treats whole model as one communication group → peak memory near unsharded. MixedPrecisionPolicy: param BF16 compute, gradient reduce FP32 — matches DeepSpeed BF16 config.
Run twice with --reshard-after-forward 1 and 0 to observe memory/communication trade-off from Part 2.
Launch (2 nodes, 8 GPUs each; NODE_RANK and MASTER_ADDR injected by scheduler):
set -euo pipefail
: "${NODE_RANK:?NODE_RANK is required}"
: "${MASTER_ADDR:?MASTER_ADDR is required}"
torchrun --nnodes=2 --nproc-per-node=8 --node-rank="${NODE_RANK}" --master-addr="${MASTER_ADDR}" --master-port=29500 fsdp2_bench.py --layers 16 --seq 4096Example output format (placeholder values):
params=0.xxxB world=16 step_p50=x.xxxs step_p95=x.xxxs tokens_per_s_per_gpu=xxxx peak_mem_gib=xx.xxDeepSpeed Counterpart: Same Model, ZeRO-3
Config ds_zero3.json with hyperparams matching FSDP2 script. Replace model wrapping and training loop in fsdp2_bench.py (from fully_shard through training loop) save as ds_bench.py:
import deepspeed
deepspeed.init_distributed(dist_backend="nccl")
model = TinyLM(args.vocab, args.dim, args.heads, args.layers)
engine, _, _, _ = deepspeed.initialize(
model=model, model_parameters=model.parameters(), config="ds_zero3.json")
for step in range(args.steps):
x = torch.randint(0, args.vocab, (args.micro_batch, args.seq + 1), device=engine.device)
logits = engine(x[:, :-1])
loss = F.cross_entropy(logits.float().reshape(-1, args.vocab), x[:, 1:].reshape(-1))
engine.backward(loss)
engine.step()Notes: Gradient clipping, optimizer step, zero_grad handled by engine per config — don't call again externally. For large models, construct inside deepspeed.zero.Init() context to avoid full model instantiation per rank. DeepSpeed Dec 2025 core API update introduced PyTorch-style backward; article uses engine.backward() for broader compatibility. Bucket sizes (reduce, prefetch, persistence threshold) are common starting points, not optimal — tune one at a time, re-run full metric set.
Megatron Counterpart: Reference Script Launch Args
Run from Megatron-LM repo root. Args per core_v0.20.x pretrain_gpt.py --help. Align with above: TP=1, PP=1 pure data parallel + distributed optimizer:
set -euo pipefail
: "${NODE_RANK:?NODE_RANK is required}"
: "${MASTER_ADDR:?MASTER_ADDR is required}"
: "${CKPT_DIR:?CKPT_DIR is required}"
torchrun --nnodes=2 --nproc-per-node=8 --node-rank="${NODE_RANK}" --master-addr="${MASTER_ADDR}" --master-port=29500 \
pretrain_gpt.py \
--tensor-model-parallel-size 1 \
--pipeline-model-parallel-size 1 \
--use-distributed-optimizer \
--num-layers 16 --hidden-size 2048 --num-attention-heads 16 \
--seq-length 4096 --max-position-embeddings 4096 \
--disable-bias-linear --untie-embeddings-and-output-weights \
--micro-batch-size 1 --global-batch-size 16 \
--lr 3e-4 --adam-beta1 0.9 --adam-beta2 0.95 --weight-decay 0.1 --clip-grad 1.0 \
--train-iters 200 --bf16 \
--mock-data --tokenizer-type NullTokenizer --vocab-size 32000 \
--ckpt-format torch_dist --save "${CKPT_DIR}" --save-interval 100 \
--log-interval 10 --eval-iters 0Deviation notes: Megatron GPT includes positional encoding, different activation/normalization implementations, defaults to Transformer Engine fused kernels — all affect throughput; record them. After aligned run, do separate "Megatron recommended config" experiment (e.g., --tensor-model-parallel-size 2 --sequence-parallel) to see hardware-specific gains. Keep results separate; don't mix comparisons.
Decision Criteria
Define upfront per business goals, e.g.:
Target model fits target GPU count with memory headroom (peak < some fraction of VRAM).
Throughput meets training timeline.
First 1000-step loss diff vs baseline framework within BF16 noise floor (determine by running same framework twice with different seeds).
Checkpoint resume yields continuous loss, acceptable resume time.
If any criterion fails, do not switch.
Migration & Rollback Boundaries
Checkpoint Convertibility
Weights usually convertible : DeepSpeed ZeRO checkpoint → zero_to_fp32.py merge; FSDP2 DCP → torch.distributed.checkpoint.format_utils to plain torch.save; Megatron ↔ HF via Megatron Bridge. Convert to HF format, then load into target framework.
Optimizer states usually NOT directly convertible : Different sharding layouts, param naming, state organization. Cross-framework migration = new optimizer; re-plan LR warmup, closely monitor post-migration loss.
Recommended Migration Steps
Freeze baseline : Record recent N steps loss, throughput, eval metrics on old framework.
Convert & verify weights : After conversion, evaluate on same eval set; diff beyond numerical error → stop, debug conversion.
Small trial run : Continue training few hundred steps on new framework from converted weights; compare loss curve & throughput.
Resume drill : Save & resume once on new framework; confirm loss continuity.
Cutover : After all pass, switch production job to new framework.
Rollback Boundaries
Pre-cutover : Zero cost — old image, config, checkpoints intact.
Post-cutover, M steps on new framework : Rollback means either discard M steps or convert new weights back (optimizer state cannot revert). Irreversible — confirm with stakeholders before cutover.
Retain old framework image, config, last old-format checkpoint until new framework produces first checkpoint that passes resume drill.
Never mix frameworks within a single training job.
Common Pitfalls
DeepSpeed first launch hangs/times out : Multiple ranks JIT-compiling operators simultaneously. Pre-compile in image, verify with ds_report before launch.
ZeRO-3 saved weights "are empty" : Each rank holds only shard; torch.save(model.state_dict()) yields shard. Enable 16-bit weight aggregation in config or use zero_to_fp32.py offline merge.
FSDP2 memory doesn't drop : Check that fully_shard called on every layer, bottom-up order.
Megatron param validation fails : Attention heads must be divisible by tensor parallel degree; global batch size divisible by (micro-batch × data parallel degree). Errors surface at launch; adjust per messages.
Checkpoint saturates shared storage : All ranks write many files simultaneously. On NFS, metadata & bandwidth pressure spike. See "NFS Performance Optimization & Common Hang Debugging".
Multi-node launch on Kubernetes : Use torchrun uniformly; all pods same image, same NCCL env vars. Scheduling & GPU node config per "Kubernetes Best Practices for AI Workloads".
Verification Status
Syntax check only : fsdp2_bench.py and Python snippets compiled; JSON configs parsed; shell snippets statically checked (quotes, line continuations); no bash -n in authoring env.
Not executed : No GPU runs; Megatron param names not verified against core_v0.20.x --help — verify before use.
Memory numbers are formula-derived, not measured; zero throughput/MFU/speedup numbers provided.
References
ZeRO paper (memory & communication analysis): https://arxiv.org/abs/1910.02054
Megatron-LM large-scale training paper (pipeline bubble analysis): https://arxiv.org/abs/2104.04473
PyTorch fully_shard docs: https://docs.pytorch.org/docs/main/distributed/fsdp.fully_shard.html
PyTorch FSDP2 tutorial & FSDP1 migration: https://docs.pytorch.org/tutorials/intermediate/FSDP_tutorial.html
PyTorch 2.14 release notes: https://pytorch.org/blog/pytorch-2-14-release-blog/
DeepSpeed releases: https://github.com/deepspeedai/DeepSpeed/releases
DeepSpeed PyPI: https://pypi.org/project/deepspeed/
DeepSpeed core API update: https://github.com/deepspeedai/DeepSpeed/blob/master/blogs/core_api_update/README.md
Megatron-LM releases: https://github.com/NVIDIA/Megatron-LM/releases
Megatron Core release notes: https://docs.nvidia.com/megatron-core/developer-guide/nightly/get-started/releasenotes.html
For questions about attribution, corrections or content rights, please contactand we will review it promptly.