Distributed¶
Torch-native distributed helpers. AgileRL is single-device by default;
multi-GPU LLM training initialises torch.distributed from the standard
launcher environment variables set by torchrun (or an orchestration layer
such as Ray), and these helpers no-op on a single device.
How to launch, when to use data parallel vs FSDP2, and every
FSDPConfig field: Multi-GPU LLM training.
- agilerl.distributed.init_distributed(timeout_seconds: int = 1800) bool¶
Initialise
torch.distributedfrom launcher env vars.No-op (returns
False) on a single device with no launcher env. Safe to call repeatedly; if a process group already exists it is reused.
- agilerl.distributed.get_world_size() int¶
Number of processes (launcher
WORLD_SIZE, or 1 on a single device).
- agilerl.distributed.is_main_process() bool¶
Whether this is rank 0 (always
Trueon a single device).
- agilerl.distributed.broadcast_object_list(objects: list, src: int = 0) list¶
Broadcast a list of picklable objects from
srcto all ranks.Mutates
objectsin place on non-source ranks and returns it. No-op on a single device.
- agilerl.distributed.gather_tensor(tensor: Tensor | ndarray | float) Tensor¶
Gather a tensor from every rank (identity on a single device).
- Parameters:
tensor – Tensor (or array/scalar convertible to one) to gather.
- Returns:
Stacked / concatenated tensors from all ranks.
- agilerl.distributed.gather_objects(objects: list) list¶
Flatten object lists gathered from every rank.
Identity on a single device. Each rank contributes a picklable list; the result is concatenation in rank order.
- agilerl.distributed.allreduce_minmax_int(value: int) tuple[int, int]¶
Return
(min, max)ofvalueacross ranks ((value, value)locally).
- agilerl.distributed.aggregate_metrics_across_gpus(metric_tensor: Tensor | ndarray | float) float¶
Average a metric across ranks (local mean on a single device).
- agilerl.distributed.aggregate_metrics_dict(metrics: Mapping[str, Tensor | ndarray | float], excluded: Collection[str] = (), maximized: Collection[str] = (), minimized: Collection[str] = ()) dict[str, float]¶
Reduce every metric across ranks in one all-reduce: the mean, or the max / min for
maximized/minimized.Every rank must pass the same keys in the same order. On a single device each metric is its local mean.
- Parameters:
metrics (Mapping[str, torch.Tensor | np.ndarray | float]) – Metric values on this rank, by name.
excluded (Collection[str]) – Metrics this rank leaves out of their cross-rank mean. A metric every rank excludes averages to NaN.
maximized (Collection[str]) – Metrics reduced to their largest value on any rank;
excludeddoes not apply to them.minimized (Collection[str]) – Metrics reduced to their smallest value on any rank;
excludeddoes not apply to them.
- Returns:
Mean of each metric across the ranks that count it, or its max / min across ranks for
maximized/minimized.- Return type:
- agilerl.distributed.sync_grads(params: Sequence[Parameter], cp: int = 1) None¶
Average gradients across data-parallel ranks.
One coalesced all-reduce of every
.gradinparams(SUM, then divide by world size /cpso Gloo works). Seeall_reduce_grads()for params without a grad. No-op on a single device.- Parameters:
params – Optimizer parameters whose
.gradshould be averaged.cp – Context-parallel degree. CP ranks hold slices of one sequence’s grad, so they sum rather than average.
- agilerl.distributed.materialize_dtensors(t0: torch.Tensor, t1: torch.Tensor | None, /) _GeneratorContextManager[tuple[torch.Tensor, torch.Tensor | None], None, None]¶
- agilerl.distributed.materialize_dtensors(*tensors: torch.Tensor | None) _GeneratorContextManager[list[torch.Tensor | None], None, None]
All-gather
DTensorshards to dense locals without swapping module params.Prefer this for ephemeral matmuls (fused lm_head logprobs, Liger). Use
gather_params()when in-module reads must see dense weights (state_dict/ PEFTsave_pretrained). All ranks must enter and exit together. Yields a list parallel totensors.- Parameters:
tensors (torch.Tensor | None) – Tensors to densify;
Nonepasses through.
- agilerl.distributed.gather_params(root: Module, params: Sequence[Tensor | None]) Generator[list[Tensor | None], None, None]¶
Materialize full (unsharded) views of
paramsfor the duration of the context.Plain tensors are left unchanged. For FSDP2
DTensorparameters, each tensor is all-gathered withfull_tensor()and temporarily installed on its owning module so in-module reads (e.g.state_dict/ PEFTsave_pretrained) see dense weights. Original shards are restored on exit.Yields a list parallel to
params: dense locals for any gatheredDTensor, and the original handles otherwise. Callers that hold pre-gather tensor references must use the yielded list for math — those references still point at the shard. For matmul-only gathers prefermaterialize_dtensors()(no module Parameter install).Gathered parameters are read-only: writes are discarded when the sharded
DTensoris restored. Write into a sharded model withset_full_model_state_dict(). All ranks must enter and exit together.- Parameters:
root (nn.Module) – Module whose submodules own
params.params (Sequence[torch.Tensor | None]) – Parameters to gather;
Noneentries pass through.
- agilerl.distributed.full_shape_views(root: Module, params: Sequence[Tensor | None]) Generator[None, None, None]¶
Expose global-shape views on FSDP2
DTensorparams for shape-only reads.Each sharded param is temporarily replaced on its owning module with a zero-storage view (a scalar expanded to the DTensor global shape) so shape, dtype and device reads see the full tensor without
full_tensor(). Values must not be read inside the block; the originalDTensoris restored on exit when the installed view is still the live parameter. Plain tensors pass through untouched. Duplicate references are processed once (by identity).- Parameters:
root (nn.Module) – Module whose submodules own
params.params (Sequence[torch.Tensor | None]) – Parameters to expose;
Noneentries are skipped.
- agilerl.distributed.resolve_device(requested: str | device | None = None) str¶
Pick the training device.
Distributed runs are pinned to
cuda:<local_rank>, or CPU without CUDA; otherwise the requested device (or the best available) is used.
- class agilerl.distributed.FSDPConfig(reshard_after_forward: Annotated[bool | None, FieldInfo(annotation=NoneType, required=True, description="Free gathered parameters after each module's forward. False keeps them gathered: faster, more VRAM. Picked from the memory estimate; manifests cannot set it. None picks False when the estimated training peak fits with the underprediction buffer at every other fastest choice, else True; off CUDA it picks True.")] | None = None, cpu_offload: Annotated[bool | None, FieldInfo(annotation=NoneType, required=True, description='Offload sharded parameters and gradients to CPU. Needs colocated vLLM generation: no async rollout engines. Mutually exclusive with optim_cpu_offload. Picked from the memory estimate; manifests cannot set it. None picks True only when vLLM is colocated and the training peak is over the GPU at every other lightest choice, activation offload and the micro-batch floor; off CUDA it picks False.')] | None = None, optim_cpu_offload: Annotated[bool | None, FieldInfo(annotation=NoneType, required=True, description='Keep Adam state on CPU and step it there with the default AdamW kernel. Parameters and gradients stay on GPU. False keeps Adam on GPU and steps it with fused AdamW. Picked from the memory estimate; manifests cannot set it. None picks GPU when the estimated training peak fits with the underprediction buffer, else CPU; off CUDA it picks CPU.')] | None = None, param_dtype: Annotated[str, FieldInfo(annotation=NoneType, required=True, description="Mixed-precision parameter dtype, e.g. 'bfloat16'. A torch.dtype is accepted and stored by name.")] = 'bfloat16', reduce_dtype: Annotated[str, FieldInfo(annotation=NoneType, required=True, description='Dtype for gradient reduce-scatter and all-reduce.')] = 'float32', checkpoint_every_n_blocks: Annotated[int | None, FieldInfo(annotation=NoneType, required=True, description='Checkpoint one in every n transformer blocks. 1 checkpoints all of them. Picked from the memory estimate with gradient_checkpointing; manifests cannot set it. Must be set before training with gradient_checkpointing on.', metadata=[Ge(ge=1)])] | None = None, ep: Annotated[int, FieldInfo(annotation=NoneType, required=True, description='Expert-parallel degree: packed MoE experts per layer are split across this many GPUs. 1 keeps data parallel plus FSDP sharding with no expert split.', metadata=[Ge(ge=1)])] = 1, ep_token_blocks: Annotated[int, FieldInfo(annotation=NoneType, required=True, description="Token blocks per routed MoE layer under expert parallel. Each block runs dispatch, experts, and combine; on GPU the next block's all-to-all overlaps this block's experts. 1 moves every token in one all-to-all.", metadata=[Ge(ge=1)])] = 1, routed_expert_chunk_mib: Annotated[int | None, FieldInfo(annotation=NoneType, required=True, description='MiB of the widest activation of one routed-expert row chunk under expert LoRA, of one fp32 chunk of the expert-parallel combine, and of one grouped LoRA GEMM output. Bigger chunks launch fewer kernels per MoE layer; on Super-VL the learn peak grows ~0.37 GiB per GiB of chunk. Picked from the memory estimate; manifests cannot set it. None picks the largest of 512/256/128/64 whose estimated training peak fits, else 64; off CUDA it picks 64.', metadata=[Ge(ge=1)])] | None = None, activation_offload: Annotated[bool | None, FieldInfo(annotation=NoneType, required=True, description='Offload backward-saved activations to host memory between forward and backward. Saves GPU memory at the cost of PCIe traffic. Picked from the memory estimate; manifests cannot set it. None picks True only when the training peak is over the GPU at every other lightest choice and a micro-batch of 1; off CUDA it picks False.')] | None = None, tp: Annotated[int, FieldInfo(annotation=NoneType, required=True, description='Tensor-parallel degree for dense layers. Ranks in one TP group share a batch shard. 1 gives every rank its own batch.', metadata=[Ge(ge=1)])] = 1, shard_frozen_tp: Annotated[bool | None, FieldInfo(annotation=NoneType, required=True, description="FSDP-shard frozen tensor-parallel weights over dp_shard x cp and all-gather them per unit. False keeps each rank's 1/tp of them resident outside FSDP: no gathers, more VRAM. Trainable weights always shard. Picked from the memory estimate; manifests cannot set it. None shards; the search picks False when the estimated training peak fits with the underprediction buffer, else True.")] | None = None, save_moe_collectives: Annotated[bool | None, FieldInfo(annotation=NoneType, required=True, description='Activation checkpointing saves the expert-parallel token all-to-alls and the tensor-parallel reduces and gathers inside each checkpointed MoE block, so its recompute communicates nothing. Holds those outputs from forward to backward: 2 x tokens x top_k / tp routed rows per MoE layer under expert parallel. Picked from the memory estimate; manifests cannot set it. None recomputes them; the search picks True on MoE models with expert parallel or a MoE tensor-parallel plan when the estimated training peak fits with the underprediction buffer, else False.')] | None = None, cp: Annotated[int, FieldInfo(annotation=NoneType, required=True, description='Context-parallel degree. Consecutive ranks hold the same batch rows and one slice of each sequence. 1 keeps full sequences on every rank.', metadata=[Ge(ge=1)])] = 1, cp_style: Annotated[Literal['ulysses'], FieldInfo(annotation=NoneType, required=True, description="How context parallel redistributes sequence shards. Only 'ulysses' is supported: two all-to-alls around local flash attention, head-parallel all-to-alls around Mamba, and sequence-sharded Gated DeltaNet.")] = 'ulysses', shard_group_size: Annotated[int | None, FieldInfo(annotation=NoneType, required=True, description='Ranks that shard weights between them; groups replicate (HSDP). Set to GPUs per node so weight gathers stay inside a node. An ep that is a multiple of it spans whole groups and holds each expert once per ep ranks. None shards across all trainer ranks.', metadata=[Ge(ge=1)])] | None = None, parallel_pins: Annotated[frozenset[str] | None, SkipJsonSchema(), FieldInfo(annotation=NoneType, required=True, exclude=True)] | None = None)¶
Settings for sharding the LLM actor with PyTorch FSDP2 (
fully_shard).
- agilerl.distributed.apply_fsdp2(model: Module, config: FSDPConfig | None = None, mesh: DeviceMesh | None = None, expert_mesh: DeviceMesh | None = None, gradient_checkpointing: bool = False) Module¶
Shard
modelwith FSDP2: experts, blocks, embed / untied lm_head, PLE, root, prefetch.Parameters become DTensors in place, so any optimizer must be (re)built after this call. Callers must not pass a dense full-model replica on CUDA — use
materialize_fsdp2_from_cpu_state()so weights stay on CPU/meta until only local shards are allocated on the compute device.When
meshis provided, non-expertfully_sharduses that mesh; whenNone, FSDP uses the default process group (flat path). Packed expert modules are sharded onexpert_meshwhen that is provided.Each transformer block is one FSDP unit. When
gradient_checkpointingis on, everyconfig.checkpoint_every_n_blocks-th block is wrapped withcheckpoint_wrapperbeforefully_shardso the checkpoint boundary sits inside the FSDP unit. Blocks holding packed experts reuse their forward routing in the recompute; their listed routers (ROUTER_FORWARDS) get out-of-place top-k renormalization.- Parameters:
model (nn.Module) – Model to shard (CPU or meta parameters).
config (FSDPConfig | None) – Sharding settings; defaults to
FSDPConfig’s defaults.mesh (DeviceMesh | None) – Optional FSDP device mesh for non-expert units. Ignored when
None.expert_mesh (DeviceMesh | None) – Optional FSDP mesh for packed-expert modules (the leftover data-parallel axis). Ignored when
None.gradient_checkpointing (bool) – Wrap the transformer blocks selected by
config.checkpoint_every_n_blockswith non-reentrant activation checkpointing before sharding.
- Returns:
The sharded model (same object).
- Return type:
nn.Module
- Raises:
ValueError – If
config.cp > 1andmeshisNone.