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 xWith 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 | NoneOverview
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 | Noneprocess_groupProcessGroup | Nonedefault NoneReturns
def broadcast_dtensor_model_states(model: torch.nn.Module,mesh: DeviceMesh) -> NoneOverview
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.ModulemeshDeviceMeshReturns
broadcast_split_tensor
def broadcast_split_tensor(tensor: torch.Tensor | None,seq_dim: int,process_group: ProcessGroup | None = None) -> torch.Tensor | NoneOverview
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 | Noneseq_dimintprocess_groupProcessGroup | Nonedefault NoneReturns
cat_outputs_cp
def cat_outputs_cp(x: Tensor,seq_dim: int,cp_group: ProcessGroup | None = None) -> TensorGather and concatenate per-rank tensors along `seq_dim. Belongs to Core distributed helpers (collectives and context-parallel split/gather). Annotated return type: Tensor`.
Parameters
xTensorseq_dimintcp_groupProcessGroup | Nonedefault NoneNone returns x` unchanged.Returns
seq_dim`.Raises
RuntimeError- `
all_gather` failed.
cat_outputs_cp_with_grad
def cat_outputs_cp_with_grad(x: Tensor,seq_dim: int,cp_group: ProcessGroup | None = None) -> TensorOverview
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
xTensorseq_dimintcp_groupProcessGroup | Nonedefault NoneReturns
destroy_model_parallel
def destroy_model_parallel(destroy_process_groups: bool = True) -> NoneOverview
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 TrueReturns
def dist_init(config)Initialize torch.distributed plus WorldFoundry CP/PP groups. Belongs to Core distributed helpers (collectives and context-parallel split/gather).
Parameters
configengine_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.
class DTensorFastEmaModelUpdater()Foreach-based EMA updater that operates on local DTensor shards. Belongs to Core distributed helpers (collectives and context-parallel split/gather).
Methods
Overwrite target local shards with source local shards (no broadcast).
Parameters
src_modeltorch.nn.Moduletgt_modeltorch.nn.ModuleReturns
update_average(src_model: torch.nn.Module,tgt_model: torch.nn.Module,beta: float = 0.9999) -> NoneSourceOverview
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.Moduletgt_modeltorch.nn.Modulebetafloatdefault 0.9999Returns
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
parametersAnyis_cpubooldefault FalseReturns
Write cached local shards back; `strict=False` zip matches FSDP holes.
Parameters
parametersAnyReturns
find_split
def find_split(shape_tensor: torch.Size,cp_size: int,patch_values: tuple[int, int, int] = (1, 2, 2),view_factor: int = 1) -> torch.SizeOverview
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.Sizecp_sizeintpatch_valuestuple[int, int, int]default (1, 2, 2)view_factorintdefault 1Returns
def get_local_tensor_if_dtensor(tensor)Return the local shard for DTensor inputs; leave regular tensors unchanged. Belongs to Core distributed helpers (collectives and context-parallel split/gather).
Parameters
tensorinit_pp_scheduler
def init_pp_scheduler()Initialize the pipeline-parallel scheduler singleton used by PP runs.
Raises
AssertionError- If the PPScheduler is already initialized.
initialize_model_parallel
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') -> NoneInitialize model data parallel groups. Belongs to Core distributed helpers (collectives and context-parallel split/gather). Annotated return type: None.
Parameters
tp_sizeintdefault 1pp_sizeintdefault 1cp_sizeintdefault 1nccl_communicator_config_pathOptional[str]default Nonemin_ctas, max_ctas, and cga_cluster_size can be set for each communicator.distributed_timeout_minutesintdefault 30orderstrdefault 'tp-cp-pp-dp'Returns
is_last_rank
def 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).
is_last_tp_cp_rank
def 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).
Check if model and data parallel groups are initialized. Belongs to Core distributed helpers (collectives and context-parallel split/gather).
pp_scheduler
def pp_scheduler() -> PPSchedulerReturn the current pipeline-parallel scheduler instance.
Returns
Raises
AssertionError- If the PPScheduler has not been initialized.
PPScheduler
class 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
Asynchronously send a tensor to the next pipeline and return the send handle.
Parameters
tensortorch.TensorReturns
Asynchronously receive a tensor from the previous pipeline and return the receive handle.
Parameters
buffertorch.TensorReturns
Receive data from the previous pipeline and return the received tensor.
Parameters
shapetorch.Sizedtypetorch.dtypeReturns
Put the asynchronously received tensor and handle into the receive queue.
Parameters
shapetorch.Sizedtypetorch.dtypeReturns
Get a tensor from the receive queue and wait for the receive operation to complete.
Returns
print_per_rank
def print_per_rank(message: object) -> NoneEmit one informational log record from every calling rank. Belongs to Core distributed helpers (collectives and context-parallel split/gather). Annotated return type: None.
Parameters
messageobjectReturns
print_rank_0
def print_rank_0(message: object) -> NoneOverview
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
messageobjectReturns
split_inputs_cp
def split_inputs_cp(x: Tensor,seq_dim: int,cp_group: ProcessGroup | None = None) -> TensorSlice 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
xTensorseq_dimintcp_groupProcessGroup | Nonedefault NoneNone returns x` unchanged.Returns
x.shape[seq_dim] // cp_size`.Raises
AssertionError- `
seq_dim` is not divisible by the CP size.