**Megatron-FSDP** is an NVIDIA-developed PyTorch extension that provides a high-performance implementation of Fully Sharded Data Parallelism (FSDP)
Project description
✨ What is Megatron-FSDP?
Megatron-FSDP is an NVIDIA-developed distributed parallelism library written in native PyTorch that provides a high-performance implementation of Fully Sharded Data Parallelism (FSDP). It offers seamless cross-compatibility with various deep learning frameworks and parallelism libraries such as Megatron-Core, and is performance-optimized to support training and inference of extremely large PyTorch models at data-center scale on NVIDIA GPUs.
For comprehensive information about Megatron-FSDP, refer to: Megatron-FSDP | Megatron-Core Developer Guide
🧩 Compatibility
- PyTorch DeviceMesh, DTensor, and Distributed Checkpoint (DCP)
- Megatron Core
- TransformerEngine
- NVIDIA NeMo Framework Container
📦 Installation
pip install megatron-fsdp
- PyPI: https://pypi.org/project/megatron-fsdp/
- Source Code: https://github.com/NVIDIA/Megatron-LM/tree/main/megatron/core/distributed/fsdp/src
🚀 Quick Start
import torch
from megatron_fsdp import (
fully_shard_model,
fully_shard_optimizer,
)
# Initialize Torch Distributed.
torch.distributed.init_process_group()
torch.cuda.set_device(torch.distributed.get_rank())
# Fully-shard the model.
model = torch.nn.Transformer()
fsdp_model = fully_shard_model(
module=model,
fsdp_unit_modules=[
torch.nn.TransformerEncoder,
torch.nn.TransformerDecoder
]
)
# Fully-shard the optimizer.
toy_adam = torch.optim.AdamW(params=fsdp_model.parameters(), lr=0.01)
optimizer = fully_shard_optimizer(optimizer=toy_adam)
# Forward pass.
inp = torch.randn(1, 512, 512).to("cuda")
tgt = torch.randn(1, 512, 512).to("cuda")
output = fsdp_model(inp, inp)
# Backward pass.
torch.nn.functional.mse_loss(output, tgt).backward()
# Optimizer step.
optimizer.step()
optimizer.zero_grad()
# Checkpoint the model and optimizer.
torch.distributed.checkpoint.save({
"model": fsdp_model.state_dict(),
"optimizer": optimizer.state_dict(),
}, checkpoint_id="ckpt/")
# Load the saved checkpoint.
ckpt = {
"model": fsdp_model.state_dict(),
"optimizer": optimizer.state_dict(),
}
torch.distributed.checkpoint.load(state_dict=ckpt, checkpoint_id="ckpt/")
fsdp_model.load_state_dict(ckpt["model"], strict=False)
optimizer.load_state_dict(ckpt["optimizer"])
⚙️ fully_shard / MegatronFSDP API - Advanced Features
Megatron-FSDP's fully_shard_* API has a comprehensive set of arguments for fine-tuning your model's performance.
fsdp_unit_modulesis a list of sub-module classes orstrimport-paths associated with modules that you wantMegatronFSDPto fully-shard.- Required if
1,2, or3are specified as the sharding strategy. Defaults toNone, in which case Megatron-FSDP will replicate the parameters similar to DDP.
- Required if
zero_dp_strategy(andouter_dp_sharding_strategy) configure different degrees of zero-redundancy data parallelism as described in ZeRO (Zero Redundancy Optimizer). It reduces CUDA memory utilization during model training by distributing model parameters, gradients, and optimizer states across multiple devices in the DPProcessGroup, and collectively communicating subsets of parameters and gradients to specific devices when needed for computation or differentiation. More aggressive sharding strategies will entail more communication overhead, withno_shardbeing the least memory efficient but most communication efficient, andoptim_grads_paramsbeing the most memory efficient but least communication efficient. Additionally,outer_dp_sharding_strategysupportsno_shard(Hybrid-Sharded Data Parallelism (HSDP)) andoptim(HFSDP= Fully-Sharded Optimizer State + HSDP, requireszero_dp_strategy='optim_grads_params'), after specifying the "outer" DP group (dp_outer_dim/hybrid_fsdp_group).- Default:
optim_grads_paramsor3forzero_dp_strategyandno_shardor0forouter_dp_sharding_strategy 0orno_shardimplies that your model is not sharded. Similar memory usage toDDP.1oroptimimplies that your optimizer state is sharded for distributed optimization. Similar to optimizer state sharding inZeRO-DP.2oroptim_gradsimplies that your optimizer state and gradients are sharded. Similar toZeRO-2.3oroptim_grads_paramsimplies that your optimizer state, gradients, and training parameters are sharded. Similar toZeRO-3.
- Default:
device_meshis atorch.distributed.DeviceMeshthat informsMegatronFSDPof your distributed environment for sharding in conjunction with hardware configuration and other parallelisms. If not provided,megatron_fsdp.fully_shard(_model)will build an FSDP DeviceMesh for you automatically.dp_shard_dimis the name of the sub-mesh required for FSDP sharding, and is commonly the flattened combination of the data parallel (DP) and context parallel (CP) sub-meshes.- When model parameters are replicated across DP-CP during the backward pass, resultant gradients across DP and CP ranks are reduced simultaneously, normalized by the DP-CP world size. For more information about how ring attention shards the sequence dimension through the attention and non-attention layers of the Transformer, refer to: Ring Attention with Blockwise Transformers for Near-Infinite Context.
dp_outer_dimis the name of the sub-mesh corresponding to the "outer" DP group, which is required for replication or sharding in HSDP.fully_shardwill perform HSDP ifdp_outer_dimis specified.tp_dimis the name of the sub-mesh used for tensor parallelism (TP), which is required for(FSDP, TP)-strided sharding when using Megatron-LM or Torch-nativeDTensorTP.- For more information about tensor parallelism, refer to: Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism.
hybrid_fsdp_groupis theProcessGroupwhich contains all ranks in the flatteneddp_shard_dimanddp_outer_dimsub-meshes utilized to specify the(DP-Outer, DP-Shard)sharded mesh coordinates for the weight and gradient buffers. Required for HSDP.hybrid_fsdp_expt_groupdefines the data-parallel communication group for expert parameters. It is required for HSDP.
expt_device_meshis anothertorch.distributed.DeviceMeshtailored for the expert parallel (EP) modules inMegatronFSDP.dp_shard_dimis the name of the sub-mesh required for FSDP sharding of the EP modules, enabling expert data parallelism (EDP).tp_dimis the name of the sub-mesh used for expert tensor parallelism (ETP), which is required for(FSDP, ETP)-strided sharding when using Megatron-LM or Torch-nativeDTensorETP.
init_model_with_meta_devicehasMegatronFSDPinitialize yourmeta-device model in shards on every CUDA device to avoid OOM when initializing extremely large models that cannot fit on a single device. Users can initialize their model on ameta-device (with torch.device('meta'): ...), andMegatronFSDPwill further shard and initialize the model parameters layer-by-layer adhering to the customizablemodule.reset_parametersmethod, which prevents the entire model from being allocated in memory at any point during runtime.- Defaults to
False. - Note that the
deviceargument which installs your model on a specific device or rank will be deactivated wheninit_model_with_meta_device=True.
- Defaults to
mixed_precision_policytakes amegatron_fsdp.MixedPrecisionPolicythat configures mixed-precision compute and communication for Megatron-FSDP. Configuration options include:main_params_dtypecontrols the data-type for parameters responsible for distributed checkpointing, distributed optimization, and quantization.- Defaults to
torch.float32. - If set to
None, the native model compute parameter data-type will be utilized. - Requires specification (cannot be
None) when using quantized parameters with Megatron-FSDP.
- Defaults to
main_grads_dtypecontrols the data-type for gradients used in distributed optimization.- Defaults to
None, in which the model native gradient data-type will be utilized. - While
torch.float32(or higher) is recommended for accuracy at scale, asmain_grads_dtypecontrols the data-type for gradient accumulation,Noneis more flexible and uses pre-determined parameter gradient logic in mixed-precision scenarios, such asBF16forFP8/FP4parameters quantized via TransformerEngine.
- Defaults to
grad_comm_dtypecontrols the data-type for gradient communications when reducing gradients. Lower precisiongrad_comm_dtypeimproves (communication) performance, but may increase memory utilization or sacrifice gradient precision in certain cases.- Defaults to
None, in which themain_grads_dtypedata-type will be utilized. No additional memory is allocated whengrad_comm_dtype == main_grads_dtype. - If using HSDP (either DP-Replicate or DP-Outer in
outer_dp_sharding_strategy),no_shard, oroptim, allocatingdtype-custom gradient communication buffers may increase per-unit memory overhead, so users should consider the performance-memory trade-off when using this feature. - If using NCCL user buffer registration
v2.27+, gradient reduction may be performed in high-precision depending on the network domain (NVLink or IB), and can enable mixed-precision communication and accumulation, e.g. setting grad_comm_dtype toBF16can supportFP32reduction even though we haveBF16input and output communication buffers. Otherwise, gradients will be reduced ingrad_comm_dtype(and accumulated inmain_grads_dtype) as usual.
- Defaults to
overlap_grad_reduceandoverlap_param_gatherwill overlap gradientreduce-scatterand parameterall-gathergroup communications with backward and forward compute with asynchronous calls and pre-fetching. (In the case ofno_shard, parameters are not gathered but gradientall-reduceis overlapped.)- Both default to
True.
- Both default to
sync_model_each_microbatchwill trigger await(MegatronFSDP.finish_grad_sync()) on gradient reduction, parameter de-allocation, and optimizer parameter / gradient installation (in preparation foroptimizer.step()) after every forward-backward pass. When using HSDP, parameters and gradients will be all-gathered and reduced respectively on the "outer" DP group each training step instead of each optimization cycle. This behavior is desirable for a transparent and user-friendly sharded training loop where post-backward transformations on the gradient and a clean compute / memory state are necessary within and between training iterations, but damages performance in situations where optimization is delayed (e.g. gradient accumulation) when the communications of the previous training iteration can be overlapped with the compute of the next training iteration. Will also overrideis_last_microbatch/microbatch_countlogic inMegatronFSDP.- Defaults to
Trueforfully_shard, but defaults toFalsewhen using theMegatronFSDPclass directly. - Can also be controlled with the
MegatronFSDP.sync()context manager, or through invokingMegatronFSDP.set_model_auto_sync(bool). - WARNING: When this synchronization feature is activated in conjunction with
no_shard/0oroptim/1sharding strategies, the user is responsible for callingMegatronFSDP.zero_grad_buffer()oroptimizer.zero_grad()after the subsequent forward-backward pass. This is because un-sharded gradients are all-reduced directly into the gradient accumulation buffer, and this buffer should not be all-reduced more than once per optimization cycle! Analogous to the justification for theno_sync()API for PyTorch DistributedDataParallel.
- Defaults to
enable_fine_grained_param_gathermodifies FSDP to all-gather parameters with per-Module granularity instead of collectively unsharding all sub-modules of a unit module in Megatron-FSDP.- Defaults to
False.
- Defaults to
keep_fp8_transpose_cachewill keep the fp8 transpose cache when usingMegatronFSDP. This option will cause (number of parameter $\times$ 1 Byte) of memory overhead, but can skip the weight transpose operation in the backward propagation. This feature will not give any benefit from the Blackwell architecture.- Defaults to
False.
- Defaults to
use_decoupled_gradinstalls the reduced gradient into a separate buffer:Parameter.decoupled_grad. This buffer is utilized by specific optimizers, such as TransformerEngine'sFusedAdam, and can be used to temporarily store your gradient for customtorch.nn.Optimizer(s).- Defaults to
False. - Required for
transformer_engine.pytorch.optimizers.FusedAdam.
- Defaults to
nccl_ubwill allocate and register the NCCL userbuffer for param and grad buffers. This option enables an SM-efficient NCCL algorithm that could improve the performance of overlapped computations. This flag will be much more effective when used together with SHARP if the FSDP communication includes both NVL and IB domains. Enabling this option will cause additional memory overhead due to the requirement to enable thefsdp_double_bufferoption.- Only effective when using with Megatron-Core.
- Defaults to
False. - By default we try to use NCCL window (symmetric) registration if it is available. If not it falls back to conventional local registration.
fsdp_manual_registrationwill manually register the FSDP communication buffers with the NCCL user buffer. For symmetric registration with large models, the registration itself can take a significant amount of time. This option minimizes the number of registration calls to reduce the registration time. However, with this option enabled, you need to manually call theParamAndGradBuffer.manual_buffer_registration()function after the first iteration. This is already implemented in the Megatron-LM training loop. In other use cases, users are expected to call this function themselves.- This is an example of required modification in the training loop.
def train(...): ... # After the first iteration, user need to call the # ParamAndGradBuffer.manual_buffer_registration() function in the training loop if (iteration == start_iteration + 1): if isinstance(model, megatron_FSDP) and model.ddp_config.fsdp_manual_registration: param_and_grad_buffer = getattr(model, "param_and_grad_buffer", None) if param_and_grad_buffer is not None: param_and_grad_buffer.manual_buffer_registration()
- Only effective when using with Megatron-Core.
- This option is only effective when
nccl_ubis enabled. - Defaults to
False, but will be automatically enabled in Megatron-LM.
- This is an example of required modification in the training loop.
disable_symmetric_registrationwill disable NCCL window (i.e. symmetric) registration when usingnccl_ub.- Defaults to
False.
- Defaults to
fsdp_double_bufferwill use persistently allocated double buffers for temporarily-defined memory needed inMegatronFSDPcommunications. Having persistent double buffers may increase peak VRAM utilization, but is required to register NCCL user buffers (nccl_ub=True) forMegatronFSDP. Currently, this is only supported for simple repetitive model structures such as GPT.- Defaults to
False. Automatically overridden toTruewhennccl_ubis enabled.
- Defaults to
preproc_state_dict_for_dcp_ckptaddsmodel.state_dict()andoptimizer.state_dict()post-hooks that modify the model and optimizer state in preparation fortorch.distributed.checkpoint.{save,load}(Torch DCP) checkpointing. Specifically, it adds__create_write_items__and__create_chunk_list__methods to Tensors utilized by Torch DCP to redistribute parameters when saving and loading model and optimizer checkpoints. Can be deactivated should the user need a custom distributed checkpointing strategy.- Defaults to
True.
- Defaults to
🧮 Using Megatron-FSDP with TransformerEngine
Megatron-FSDP natively supports mixed-precision activations and parameter sharding in conjunction with TransformerEngine.
- Within the
transformer_engine.pytorch.autocast(recipe: transformer_engine.common.recipe.Recipe)context, model activations are converted based on the recipe. - Within the
transformer_engine.pytorch.quantized_model_init(recipe: transformer_engine.common.recipe.Recipe)context, TransformerEngine native modules (e.g.transformer_engine.pytorch.TransformerLayer) have their parameters converted based on the recipe.- Requires quantized model activations, i.e.
transformer_engine.pytorch.autocast.
- Requires quantized model activations, i.e.
# FP8 Recipe
fp8_recipe = transformer_engine.common.recipe.MXFP8BlockScaling(
fp8_format=transformer_engine.common.recipe.Format.HYBRID,
)
# Construct TransformerEngine model with FP8 parameters.
with transformer_engine.pytorch.quantized_model_init(
recipe=fp8_recipe,
# Needed for FP8 parameters with Megatron-FSDP.
preserve_high_precision_init_val=True,
):
te_model = transformer_engine.pytorch.TransformerLayer(...)
# Fully-shard the model.
mfsdp_model = fully_shard_model(
module=te_model,
fsdp_unit_modules=[te.pytorch.TransformerLayer],
# Only FSDP / ZeRO-3 supports FP8 parameters.
zero_dp_strategy=3,
# FP32 main weights needed for FP8 parameters.
mixed_precision_policy=MixedPrecisionPolicy(
main_params_dtype=torch.float32
),
# Needed for select FP8 recipes.
keep_fp8_transpose_cache=True,
)
# Evaluate and differentiate the model with FP8 activations.
with transformer_engine.pytorch.autocast(recipe=fp8_recipe):
mfsdp_model(x).sum().backward()
ℹ️ TransformerEngine kernels have various constraints related to quantized Tensors, such as using fused QKV parameters or defining activations and parameters with shapes compatible to CuBLAS kernels on supported hardware from NVIDIA. To properly initialize TransformerLayer, you can refer to the example model used in our unit tests: Megatron-LM/tests/unit_tests/distributed/fsdp/test_mfsdp_fully_shard.py::TestMegatronFsdpFullyShard::test_fully_shard_te_quantized.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file megatron_fsdp-0.5.0.tar.gz.
File metadata
- Download URL: megatron_fsdp-0.5.0.tar.gz
- Upload date:
- Size: 106.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
345a470620430a479e172a8dabda34bfa9f737f7aeec63e41f50f5b248cf9adc
|
|
| MD5 |
c446800957aad1a0949426dd8655e882
|
|
| BLAKE2b-256 |
0fb57d347b3dc00f06f98a4d2767e05fbd1cd4fbb181c6e25a5a0de118c3717a
|
File details
Details for the file megatron_fsdp-0.5.0-py3-none-any.whl.
File metadata
- Download URL: megatron_fsdp-0.5.0-py3-none-any.whl
- Upload date:
- Size: 106.6 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
e45474f048eb634a8a0b52989e2edfc104893ad21671c66d8e7fbd720964b962
|
|
| MD5 |
32b70d7c26cc88010a5ab528ee96ada0
|
|
| BLAKE2b-256 |
a59b9da4ede7fc8268386657356764b5af0b0389df239ba0d326a0f6711f395b
|