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.distributed from 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.

Parameters:

timeout_seconds (int) – Collective timeout for the process group.

Returns:

True when distributed training is active.

Return type:

bool

agilerl.distributed.is_distributed() → bool

Whether torch.distributed is available and initialised.

agilerl.distributed.get_rank() → int

Global rank (launcher RANK, or 0 on a single device).

agilerl.distributed.get_local_rank() → int

Rank within the node, used for device selection.

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 True on a single device).

agilerl.distributed.barrier() → None

Synchronise all processes; no-op on a single device.

agilerl.distributed.broadcast_object_list(objects: list, src: int = 0) → list

Broadcast a list of picklable objects from src to all ranks.

Mutates objects in place on non-source ranks and returns it. No-op on a single device.

Parameters:
  • objects (list) – Objects to broadcast (same length on every rank).

  • src (int) – Source rank.

Returns:

The broadcast list.

Return type:

list

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.

Parameters:

objects (list) – Local objects to gather.

Returns:

Flattened objects from all ranks.

Return type:

list

agilerl.distributed.allreduce_minmax_int(value: int) → tuple[int, int]

Return (min, max) of value across ranks ((value, value) locally).

Parameters:

value (int) – This rank’s value.

Returns:

(min, max) across ranks.

Return type:

tuple[int, int]

agilerl.distributed.aggregate_metrics_across_gpus(metric_tensor: Tensor | ndarray | float) → float

Average a metric across ranks (local mean on a single device).

Parameters:

metric_tensor (torch.Tensor | np.ndarray | float) – Metric values on this rank.

Returns:

Mean across all ranks.

Return type:

float

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; excluded does not apply to them.

  • minimized (Collection[str]) – Metrics reduced to their smallest value on any rank; excluded does 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:

dict[str, float]

agilerl.distributed.sync_grads(params: Sequence[Parameter], cp: int = 1) → None

Average gradients across data-parallel ranks.

One coalesced all-reduce of every .grad in params (SUM, then divide by world size / cp so Gloo works). See all_reduce_grads() for params without a grad. No-op on a single device.

Parameters:
  • params – Optimizer parameters whose .grad should 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 DTensor shards 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 / PEFT save_pretrained). All ranks must enter and exit together. Yields a list parallel to tensors.

Parameters:

tensors (torch.Tensor | None) – Tensors to densify; None passes through.

agilerl.distributed.gather_params(root: Module, params: Sequence[Tensor | None]) → Generator[list[Tensor | None], None, None]

Materialize full (unsharded) views of params for the duration of the context.

Plain tensors are left unchanged. For FSDP2 DTensor parameters, each tensor is all-gathered with full_tensor() and temporarily installed on its owning module so in-module reads (e.g. state_dict / PEFT save_pretrained) see dense weights. Original shards are restored on exit.

Yields a list parallel to params: dense locals for any gathered DTensor, 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 prefer materialize_dtensors() (no module Parameter install).

Gathered parameters are read-only: writes are discarded when the sharded DTensor is restored. Write into a sharded model with set_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; None entries pass through.

agilerl.distributed.full_shape_views(root: Module, params: Sequence[Tensor | None]) → Generator[None, None, None]

Expose global-shape views on FSDP2 DTensor params 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 original DTensor is 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; None entries 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.

Parameters:

requested (str | torch.device | None) – Device requested by the caller, if any.

Returns:

Device string.

Return type:

str

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).

property frozen_tp_resident: bool

Whether frozen tensor-parallel weights stay resident outside FSDP.

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 model with 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 mesh is provided, non-expert fully_shard uses that mesh; when None, FSDP uses the default process group (flat path). Packed expert modules are sharded on expert_mesh when that is provided.

Each transformer block is one FSDP unit. When gradient_checkpointing is on, every config.checkpoint_every_n_blocks-th block is wrapped with checkpoint_wrapper before fully_shard so 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_blocks with non-reentrant activation checkpointing before sharding.

Returns:

The sharded model (same object).

Return type:

nn.Module

Raises:

ValueError – If config.cp > 1 and mesh is None.