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
    self._nbytes = 0
    self._disabled_reason: str | None = None

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

Run one collective on an already-armed context.

Source code in fastvideo/distributed/device_communicators/ulysses_a2a.py
def run_armed(self, x: torch.Tensor, mode: int) -> torch.Tensor:
    """Run one collective 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)
    comm_ops.all_to_all(self._handle, x, out, B, S_local, H, D, mode)
    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[-2]
    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)

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 == "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})"

    vote = torch.tensor([int(helper is not None)], dtype=torch.int32)
    dist.all_reduce(vote, op=dist.ReduceOp.MIN, group=cpu_group)
    if not bool(vote.item()):
        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