Skip to content

ulysses_a2a

Fused NVLink all-to-all for Ulysses sequence parallelism.

Drop-in replacement for DistributedAutograd.AllToAll4D when the group is a load-store accessible NVLink mesh: same layout, byte-identical results, fewer passes over local memory. Anything else falls back to the NCCL path.

Classes

fastvideo.distributed.device_communicators.ulysses_a2a.UlyssesA2AHelper

UlyssesA2AHelper(cpu_group: ProcessGroup, device_group: ProcessGroup, world_size: int, device: device, pynccl_comm)

Owns the fused all-to-all context for one sequence-parallel group.

Group capability is agreed during construction; the NCCL window is registered on first use, once an operand size is known.

Source code in fastvideo/distributed/device_communicators/ulysses_a2a.py
def __init__(self, cpu_group: ProcessGroup, device_group: ProcessGroup, world_size: int, device: torch.device,
             pynccl_comm):
    self.cpu_group = cpu_group
    self.device_group = device_group
    self.world_size = world_size
    self.device = device
    self.pynccl_comm = pynccl_comm

    self._handle: int | None = None
    # Reuse storage, but exchange the current contract on every call. A
    # rank-local cache hit cannot establish what peers are doing now.
    self._local_contract = array("q", [0] * _CONTRACT_SIZE)
    self._local_tensor = torch.frombuffer(self._local_contract, dtype=torch.int64)
    self._gathered_tensor = torch.empty(world_size * _CONTRACT_SIZE, dtype=torch.int64, device="cpu")
    self._nbytes = 0
    self._disabled_reason: str | None = None
    self._h3_tuning_available: bool | None = None
    self._contract_mismatch_logged = False

    if world_size not in SUPPORTED_WORLD_SIZES:
        self._disabled_reason = (f"world size {world_size} is not one of "
                                 f"{SUPPORTED_WORLD_SIZES}")

Methods:

fastvideo.distributed.device_communicators.ulysses_a2a.UlyssesA2AHelper.close
close() -> bool

Collectively destroy the device communicator and its window.

Returns whether all ranks completed teardown. An armed/unarmed split cannot safely enter NCCL window deregistration, so that exceptional state is leaked until process exit and permanently disabled instead of risking a distributed deadlock.

Source code in fastvideo/distributed/device_communicators/ulysses_a2a.py
def close(self) -> bool:
    """Collectively destroy the device communicator and its window.

    Returns whether all ranks completed teardown. An armed/unarmed split
    cannot safely enter NCCL window deregistration, so that exceptional
    state is leaked until process exit and permanently disabled instead of
    risking a distributed deadlock.
    """
    handle = self._handle
    all_armed = self._agree(handle is not None)
    all_unarmed = self._agree(handle is None)
    if all_unarmed:
        self._nbytes = 0
        return True
    if not all_armed:
        self._handle = None
        self._nbytes = 0
        self._disable("ranks disagreed on whether a fused window was armed during teardown")
        return False

    assert handle is not None
    synchronize_ok = True
    try:
        torch.cuda.synchronize(self.device)
    except Exception:  # noqa: BLE001 - converted to a group verdict below
        synchronize_ok = False
        logger.warning("Ulysses pre-teardown synchronization failed", exc_info=True)
    if not self._agree(synchronize_ok):
        self._disable("a peer rank could not synchronize before fused-window teardown")
        return False

    dispose_ok = True
    try:
        self._dispose(handle, synchronize=False)
    except Exception:  # noqa: BLE001 - teardown must not mask a real error
        dispose_ok = False
        logger.warning("Ulysses window deregistration failed", exc_info=True)

    group_ok = self._agree(dispose_ok)
    # The native disposer consumes the handle even when a cleanup call
    # reports an error, so never retry a potentially dangling pointer.
    self._handle = None
    self._nbytes = 0
    if not group_ok:
        self._disable("fused-window teardown failed on a peer rank")
    return group_ok
fastvideo.distributed.device_communicators.ulysses_a2a.UlyssesA2AHelper.run_armed
run_armed(x: Tensor, mode: int, chunked: bool, blocks: int) -> Tensor

Run one call's collective(s) on an already-armed context.

Source code in fastvideo/distributed/device_communicators/ulysses_a2a.py
def run_armed(self, x: torch.Tensor, mode: int, chunked: bool, blocks: int) -> torch.Tensor:
    """Run one call's collective(s) on an already-armed context."""
    assert self._handle is not None, "run_armed called on an unarmed helper"
    from fastvideo_kernel import comm_ops

    w = self.world_size
    if mode == 0:
        B, S_local, H, D = x.shape
        out = torch.empty(B, S_local * w, H // w, D, dtype=x.dtype, device=x.device)
    else:
        B, S_global, H_local, D = x.shape
        S_local, H = S_global // w, H_local * w
        out = torch.empty(B, S_local, H, D, dtype=x.dtype, device=x.device)
    if chunked:
        # Each copy completes on this stream before the next plane reuses
        # the registered window. The full result owns its storage; saved
        # activations never alias the reusable window.
        for plane in range(B):
            comm_ops.all_to_all(self._handle,
                                x[plane:plane + 1],
                                out[plane:plane + 1],
                                1,
                                S_local,
                                H,
                                D,
                                mode,
                                blocks=blocks)
    else:
        comm_ops.all_to_all(self._handle, x, out, B, S_local, H, D, mode, blocks=blocks)
    return out
fastvideo.distributed.device_communicators.ulysses_a2a.UlyssesA2AHelper.try_all_to_all_4D
try_all_to_all_4D(x: Tensor, scatter_dim: int, gather_dim: int) -> Tensor | None

Fused collective, or None to let the caller use the NCCL path.

Source code in fastvideo/distributed/device_communicators/ulysses_a2a.py
def try_all_to_all_4D(self, x: torch.Tensor, scatter_dim: int, gather_dim: int) -> torch.Tensor | None:
    """Fused collective, or None to let the caller use the NCCL path."""
    if self._disabled_reason is not None:
        return None

    # Python lifecycle checks, votes, and pybind calls are not valid inside
    # a fullgraph region. The inherited NCCL path is compiler-visible, so
    # regional compile stays fullgraph by declining before any tensor read.
    if torch.compiler.is_compiling():
        return None

    signature, reason = self._call_signature(x, scatter_dim, gather_dim)
    use_fused, permanently_unavailable, lifecycle_consistent = self._agree_call(signature)
    if not use_fused:
        if not lifecycle_consistent:
            self.close()
            self._disable("ranks disagreed on the fused-window lifecycle")
        if permanently_unavailable:
            self._disable(reason or "a peer rank cannot use the fused path")
        return None

    mode = signature[2]
    nbytes = signature[8]
    if self._handle is None:
        if not self._build(nbytes):
            return None
    elif nbytes > self._nbytes:
        logger.info("Ulysses window grow: %d -> %d bytes", self._nbytes, nbytes)
        if not self.close():
            return None
        if not self._build(nbytes):
            return None

    return _FusedUlyssesA2A.apply(self, x, mode, bool(signature[10]), signature[11])

Functions:

fastvideo.distributed.device_communicators.ulysses_a2a.is_enabled

is_enabled() -> bool

Whether the fused path is opted in via FASTVIDEO_ULYSSES_A2A.

Source code in fastvideo/distributed/device_communicators/ulysses_a2a.py
def is_enabled() -> bool:
    """Whether the fused path is opted in via FASTVIDEO_ULYSSES_A2A."""
    return envs.FASTVIDEO_ULYSSES_A2A.get() == "auto"

fastvideo.distributed.device_communicators.ulysses_a2a.maybe_create_helper

maybe_create_helper(cpu_group: ProcessGroup | None, device_group: ProcessGroup | None, world_size: int, device: device | None, pynccl_comm) -> UlyssesA2AHelper | None

Collectively create a helper only when every rank can use it.

Source code in fastvideo/distributed/device_communicators/ulysses_a2a.py
def maybe_create_helper(cpu_group: ProcessGroup | None, device_group: ProcessGroup | None, world_size: int,
                        device: torch.device | None, pynccl_comm) -> UlyssesA2AHelper | None:
    """Collectively create a helper only when every rank can use it."""
    if (world_size <= 1 or cpu_group is None or device_group is None or device is None or device.type != "cuda"):
        return None
    if not dist.is_initialized():
        return None

    helper = None
    reason = ""
    if not is_enabled():
        reason = "FASTVIDEO_ULYSSES_A2A is not auto"
    elif world_size not in SUPPORTED_WORLD_SIZES:
        reason = f"world size {world_size} is not one of {SUPPORTED_WORLD_SIZES}"
    elif pynccl_comm is None or pynccl_comm.disabled:
        reason = "the group has no usable PyNccl communicator"
    else:
        try:
            candidate = UlyssesA2AHelper(cpu_group, device_group, world_size, device, pynccl_comm)
            can_attempt, reason = candidate._can_attempt()
            if can_attempt:
                helper = candidate
        except Exception as e:  # noqa: BLE001 - converted to a group verdict below
            reason = f"helper construction failed ({type(e).__name__}: {e})"

    # Every rank reaches the same exchange, including configuration, constructor,
    # and backend failures. LSA covers addressability, not single-host locality.
    gathered: list[tuple[str, bool]] = [("", False)] * world_size
    dist.all_gather_object(gathered, (_host_identity(), helper is not None), group=cpu_group)
    host_ids = {identity for identity, _ in gathered}
    if len(host_ids) != 1:
        reason = f"ranks do not share one host (host identities differ: {sorted(host_ids)})"
    if len(host_ids) != 1 or not all(ok for _, ok in gathered):
        if dist.get_rank(cpu_group) == 0:
            logger.info("Ulysses fused all-to-all unavailable: %s", reason or "a peer rank declined")
        return None
    return helper