Core distributed

Process-group setup, context-parallel split/gather, model-parallel groups, rank-aware logging, EMA broadcast, and pipeline scheduling.

On this page

Distributed Core separates process-group topology from tensor movement. Initialization creates global and model-parallel groups. Rank/group queries expose that topology. Collective helpers then split, gather, broadcast, or synchronize tensors without forcing each model integration to reproduce edge cases.

Importing this package requires the distributed model runtime dependencies, including Torch and Loguru. dist_init additionally requires CUDA; the cp_group=None behavior shown below is a contract example, not a claim that the distributed package belongs to the minimal CLI environment.

Single-process behavior is intentional

The context-parallel data helpers accept None as “parallelism disabled.” This makes the same model code usable in one process and many processes without branching at every call site.

import torch

from worldfoundry.core.distributed import cat_outputs_cp, split_inputs_cp

x = torch.arange(24).reshape(2, 3, 4)
local = split_inputs_cp(x, seq_dim=1, cp_group=None)
restored = cat_outputs_cp(local, seq_dim=1, cp_group=None)

assert local is x
assert restored is x

With a real CP group, split_inputs_cp requires the sequence dimension to be divisible by the group size. cat_outputs_cp gathers equal-shaped local tensors in rank order. cat_outputs_cp_with_grad restores the local rank's autograd reference after gathering; use it only when gradients must flow through the local shard.

Typical context-parallel sequence

Rank zero or the minimum rank can load an input once, broadcast_split_tensor broadcasts its full shape/data and returns one shard per rank, the model computes locally, and cat_outputs_cp restores the global sequence. The split and gather must use the same seq_dim and process group.

broadcast supports tensors and Python objects, but object collectives serialize data and are inappropriate for high-volume model activations. find_split plans temporal/spatial CP dimensions for Megatron-compatible runtimes and mutates the compatibility parallel state; it is not a generic tensor chunker.

Initialization boundary

dist_init is the high-level CUDA inference initializer for runtimes whose config supplies backend, timeout, CP size, and PP size. It reads RANK and WORLD_SIZE, binds the local CUDA device, verifies cp_size * pp_size, initializes model-parallel groups, and creates a pipeline scheduler when needed.

Do not call model-parallel rank/group accessors before initialization. Pair lifecycle teardown with destroy_model_parallel in tests or long-lived workers that rebuild topology. print_rank_0 is safe outside distributed execution and is preferable for messages that should appear once.

Complete reference

The blocks below are the generated signatures for this category. Use the on-page symbol index to jump; source links open the defining implementation behind each lazy export.

20 public symbols

def broadcast(item: torch.Tensor | str | None,process_group: ProcessGroup | None = None) -> torch.Tensor | str | None
worldfoundry.core.distributedfrom worldfoundry.core.distributed import broadcast

Overview

Broadcast a tensor or object from the minimum rank in `process_group. Belongs to Core distributed helpers (collectives and context-parallel split/gather). Annotated return type: torch.Tensor | str | None`.

Parameters

itemtorch.Tensor | str | None
process_groupProcessGroup | Nonedefault None

Returns

torch.Tensor | str | None
def broadcast_dtensor_model_states(model: torch.nn.Module,mesh: DeviceMesh) -> None
worldfoundry.corefrom worldfoundry.core import broadcast_dtensor_model_states

Overview

Broadcast model parameters and buffers from the first rank in the replicate mesh. Belongs to Core distributed helpers (collectives and context-parallel split/gather). Annotated return type: None.

Parameters

modeltorch.nn.Module
meshDeviceMesh

Returns

None
def broadcast_split_tensor(tensor: torch.Tensor | None,seq_dim: int,process_group: ProcessGroup | None = None) -> torch.Tensor | None
worldfoundry.core.distributedfrom worldfoundry.core.distributed import broadcast_split_tensor

Overview

Broadcast a tensor from the minimum CP rank, then return this rank's shard. Belongs to Core distributed helpers (collectives and context-parallel split/gather). Annotated return type: torch.Tensor | None.

Parameters

tensortorch.Tensor | None
seq_dimint
process_groupProcessGroup | Nonedefault None

Returns

torch.Tensor | None
def cat_outputs_cp(x: Tensor,seq_dim: int,cp_group: ProcessGroup | None = None) -> Tensor
worldfoundry.core.distributedfrom worldfoundry.core.distributed import cat_outputs_cp

Gather and concatenate per-rank tensors along `seq_dim. Belongs to Core distributed helpers (collectives and context-parallel split/gather). Annotated return type: Tensor`.

Parameters

xTensor
This rank's local tensor.
seq_dimint
Concatenation dimension.
cp_groupProcessGroup | Nonedefault None
CP process group; `None returns x` unchanged.

Returns

TensorTensor with the gathered shards concatenated along `seq_dim`.

Raises

RuntimeError
`all_gather` failed.
def cat_outputs_cp_with_grad(x: Tensor,seq_dim: int,cp_group: ProcessGroup | None = None) -> Tensor
worldfoundry.core.distributedfrom worldfoundry.core.distributed import cat_outputs_cp_with_grad

Overview

Gather CP shards while preserving the local rank's autograd graph. Belongs to Core distributed helpers (collectives and context-parallel split/gather). Annotated return type: Tensor.

Parameters

xTensor
seq_dimint
cp_groupProcessGroup | Nonedefault None

Returns

Tensor
def destroy_model_parallel(destroy_process_groups: bool = True) -> None
worldfoundry.corefrom worldfoundry.core import destroy_model_parallel

Overview

Tear down model-parallel process groups by clearing the stored group handles.

Source docstring

Destroy owned subgroups and clear all model-parallel state.

The default process group is deliberately left alive; its lifecycle is owned by the distributed launcher. Set `destroy_process_groups=False` only when an external framework has already destroyed the subgroups.

Parameters

destroy_process_groupsbooldefault True

Returns

None
def dist_init(config)
worldfoundry.corefrom worldfoundry.core import dist_init

Initialize torch.distributed plus WorldFoundry CP/PP groups. Belongs to Core distributed helpers (collectives and context-parallel split/gather).

Parameters

config
Runtime config whose `engine_config provides distributed_backend, distributed_timeout_minutes, cp_size, and pp_size`.

Notes

Rank and world size come from `RANK and WORLD_SIZE. The function requires CUDA, binds each rank to a local device, verifies cp_size * pp_size == world_size, and initializes the pipeline scheduler when pipeline parallelism is active. CC-17 WONTFIX: not a wrapper of init_torch_distributed. Backend and timeout come from config, device binding is rank % device_count (not LOCAL_RANK`), and this function also creates CP/PP groups plus the PP scheduler.

worldfoundry.corefrom worldfoundry.core import DTensorFastEmaModelUpdater

Foreach-based EMA updater that operates on local DTensor shards. Belongs to Core distributed helpers (collectives and context-parallel split/gather).

Methods

methcopy_to(src_model: torch.nn.Module,tgt_model: torch.nn.Module) -> NoneSource

Overwrite target local shards with source local shards (no broadcast).

Parameters

src_modeltorch.nn.Module
tgt_modeltorch.nn.Module

Returns

None
methupdate_average(src_model: torch.nn.Module,tgt_model: torch.nn.Module,beta: float = 0.9999) -> NoneSource

Overview

In-place EMA on local FP32 shards: `tgt = beta * tgt + (1 - beta) * src`.

Source docstring

In-place EMA on local FP32 shards: `tgt = beta * tgt + (1 - beta) * src`.

EMA in a lower dtype silently underflows the `1 - beta` term, so the target must already be FP32.

Parameters

src_modeltorch.nn.Module
tgt_modeltorch.nn.Module
betafloatdefault 0.9999

Returns

None
methcache(parameters: Any,is_cpu: bool = False) -> NoneSource

Overview

Snapshot local shards before a temporary overwrite (eval / checkpoint).

Source docstring

Snapshot local shards before a temporary overwrite (eval / checkpoint).

Nested :meth:cache without :meth:restore is refused so a later restore cannot apply the wrong generation of weights.

Parameters

parametersAny
is_cpubooldefault False

Returns

None
methrestore(parameters: Any) -> NoneSource

Write cached local shards back; `strict=False` zip matches FSDP holes.

Parameters

parametersAny

Returns

None
def find_split(shape_tensor: torch.Size,cp_size: int,patch_values: tuple[int, int, int] = (1, 2, 2),view_factor: int = 1) -> torch.Size
worldfoundry.core.distributedfrom worldfoundry.core.distributed import find_split

Overview

Find the post-context-parallel temporal/spatial split shape. Belongs to Core distributed helpers (collectives and context-parallel split/gather). Annotated return type: torch.Size.

Parameters

shape_tensortorch.Size
cp_sizeint
patch_valuestuple[int, int, int]default (1, 2, 2)
view_factorintdefault 1

Returns

torch.Size
worldfoundry.corefrom worldfoundry.core import get_local_tensor_if_dtensor

Return the local shard for DTensor inputs; leave regular tensors unchanged. Belongs to Core distributed helpers (collectives and context-parallel split/gather).

Parameters

tensor
worldfoundry.corefrom worldfoundry.core import init_pp_scheduler

Initialize the pipeline-parallel scheduler singleton used by PP runs.

Raises

AssertionError
If the PPScheduler is already initialized.
def initialize_model_parallel(tp_size: int = 1,pp_size: int = 1,cp_size: int = 1,nccl_communicator_config_path: Optional[str] = None,distributed_timeout_minutes: int = 30,order: str = 'tp-cp-pp-dp') -> None
worldfoundry.corefrom worldfoundry.core import initialize_model_parallel

Initialize model data parallel groups. Belongs to Core distributed helpers (collectives and context-parallel split/gather). Annotated return type: None.

Parameters

tp_sizeintdefault 1
The number of GPUs to split individual tensors across.
pp_sizeintdefault 1
The number of tensor parallel GPU groups to split the Transformer layers across. For example, if tp_size is 4 and pp_size is 2, the model will be split into 2 groups of 4 GPUs.
cp_sizeintdefault 1
The number of tensor parallel GPU groups to split the network input sequence length across. Compute of attention module requires tokens of full sequence length, so GPUs in a context parallel group need to communicate with each other to exchange information of other sequence chunks. Each GPU and its counterparts in other tensor parallel groups compose a context parallel group. For example, assume we have 8 GPUs, if tensor model parallel size is 4 and context parallel size is 2, the network input will be split into two sequence chunks, which are processed by 2 different groups of 4 GPUs. One chunk is processed by GPU0-3, the other chunk is processed by GPU4-7. Four groups are build to do context parallel communications: [GPU0, GPU4], [GPU1, GPU5], [GPU2, GPU6], and [GPU3, GPU7]. Context parallelism partitions sequence length, so it has no impact on weights, which means weights are duplicated among GPUs in a context parallel group. Hence, weight gradients all-reduce is required in backward. For simplicity, we piggyback GPUs of context parallelism on data parallel group for weight gradient all-reduce.
nccl_communicator_config_pathOptional[str]default None
Path to the yaml file of NCCL communicator configurations. min_ctas, max_ctas, and cga_cluster_size can be set for each communicator.
distributed_timeout_minutesintdefault 30
Timeout, in minutes,for operations executed against distributed process groups. See PyTorch documentation at
orderstrdefault 'tp-cp-pp-dp'
The rank initialization order of parallelism. Now we support tp-dp-pp and tp-pp-dp orders. Let's say we have a total of 16 GPUs denoted by g0 ... g15 and we use 2 GPUs to parallelize the model tensor, and 4 GPUs to parallelize the model pipeline. The present function will create 8 tensor model-parallel groups, 4 pipeline model-parallel groups and 8 data-parallel groups as: 8 data_parallel groups: [g0, g2], [g1, g3], [g4, g6], [g5, g7], [g8, g10], [g9, g11], [g12, g14], [g13, g15] 8 tensor model-parallel groups: [g0, g1], [g2, g3], [g4, g5], [g6, g7], [g8, g9], [g10, g11], [g12, g13], [g14, g15] 4 pipeline model-parallel groups: [g0, g4, g8, g12], [g1, g5, g9, g13], [g2, g6, g10, g14], [g3, g7, g11, g15] Note that for efficiency, the caller should make sure adjacent ranks are on the same DGX box. For example if we are using 2 DGX-1 boxes with a total of 16 GPUs, rank 0 to 7 belong to the first box and ranks 8 to 15 belong to the second box.

Returns

None
worldfoundry.corefrom worldfoundry.core import is_last_rank

Return whether this worker is the final rank in the global process group. Belongs to Core distributed helpers (collectives and context-parallel split/gather).

worldfoundry.corefrom worldfoundry.core import is_last_tp_cp_rank

Return whether this worker is last in the combined tensor/context group. Belongs to Core distributed helpers (collectives and context-parallel split/gather).

worldfoundry.corefrom worldfoundry.core import model_parallel_is_initialized

Check if model and data parallel groups are initialized. Belongs to Core distributed helpers (collectives and context-parallel split/gather).

worldfoundry.corefrom worldfoundry.core import pp_scheduler

Return the current pipeline-parallel scheduler instance.

Returns

PPSchedulerPPScheduler: The current PPScheduler instance.

Raises

AssertionError
If the PPScheduler has not been initialized.
class PPScheduler()
worldfoundry.corefrom worldfoundry.core import PPScheduler

Overview

Minimal point-to-point scheduler for adjacent pipeline stages. Belongs to Core distributed helpers (collectives and context-parallel split/gather).

Source docstring

Minimal point-to-point scheduler for adjacent pipeline stages.

The scheduler owns a CUDA receive buffer queue and exposes synchronous and asynchronous helpers around the model-parallel pipeline group. Initialize the process-wide instance with `init_pp_scheduler and retrieve it with pp_scheduler`.

Methods

methisend_next(tensor: torch.Tensor) -> torch.distributed.WorkSource

Asynchronously send a tensor to the next pipeline and return the send handle.

Parameters

tensortorch.Tensor
The tensor to be sent.

Returns

torch.distributed.Worktorch.distributed.Work: The handle for the send operation.
methirecv_prev(buffer: torch.Tensor) -> torch.distributed.WorkSource

Asynchronously receive a tensor from the previous pipeline and return the receive handle.

Parameters

buffertorch.Tensor
The buffer tensor for receiving data.

Returns

torch.distributed.Worktorch.distributed.Work: The handle for the receive operation.
methrecv_prev_data(shape: torch.Size,dtype: torch.dtype) -> torch.TensorSource

Receive data from the previous pipeline and return the received tensor.

Parameters

shapetorch.Size
The shape of the tensor to receive.
dtypetorch.dtype
The data type of the tensor to receive.

Returns

torch.Tensortorch.Tensor: The received tensor.
methqueue_irecv_prev(shape: torch.Size,dtype: torch.dtype) -> NoneSource

Put the asynchronously received tensor and handle into the receive queue.

Parameters

shapetorch.Size
The shape of the tensor to receive.
dtypetorch.dtype
The data type of the tensor to receive.

Returns

None
methqueue_irecv_prev_data() -> torch.TensorSource

Get a tensor from the receive queue and wait for the receive operation to complete.

Returns

torch.Tensortorch.Tensor: The received tensor obtained from the queue.
def print_per_rank(message: object) -> None
worldfoundry.corefrom worldfoundry.core import print_per_rank

Emit one informational log record from every calling rank. Belongs to Core distributed helpers (collectives and context-parallel split/gather). Annotated return type: None.

Parameters

messageobject

Returns

None
def print_rank_0(message: object) -> None
worldfoundry.corefrom worldfoundry.core import print_rank_0

Overview

Emit one informational record on rank zero, or in a non-distributed process. Belongs to Core distributed helpers (collectives and context-parallel split/gather). Annotated return type: None.

Parameters

messageobject

Returns

None
def split_inputs_cp(x: Tensor,seq_dim: int,cp_group: ProcessGroup | None = None) -> Tensor
worldfoundry.core.distributedfrom worldfoundry.core.distributed import split_inputs_cp

Slice a tensor along `seq_dim to this rank's CP shard. Belongs to Core distributed helpers (collectives and context-parallel split/gather). Annotated return type: Tensor`.

Parameters

xTensor
Input tensor.
seq_dimint
Dimension to split along (negative indexing supported).
cp_groupProcessGroup | Nonedefault None
CP process group; `None returns x` unchanged.

Returns

TensorContiguous slice of length `x.shape[seq_dim] // cp_size`.

Raises

AssertionError
`seq_dim` is not divisible by the CP size.