Skip to content

vllm.distributed.weight_transfer.m2n_plan ¶

Canonical destination-plan agreement for NCCL M2N.

Classes:

  • M2NWireDestination –

    JSON-safe, callback-free destination descriptor for one worker.

Functions:

M2NWireDestination dataclass ¶

JSON-safe, callback-free destination descriptor for one worker.

Methods:

  • from_destination –

    Strip live state from one worker-local destination plan.

Source code in vllm/distributed/weight_transfer/m2n_plan.py
@dataclass(frozen=True)
class M2NWireDestination:
    """JSON-safe, callback-free destination descriptor for one worker."""

    name: str
    mode: str
    dtype_name: str
    mesh_dims: tuple[int, int]
    placements: Placements | None
    local_shape: tuple[int, ...]
    semantic_id: str | None
    shard_dim: int | None
    shard_index: int
    num_shards: int
    staging_group: int | None = None
    staging_slot: int | None = None
    staging_group_size: int | None = None

    def __post_init__(self) -> None:
        if not isinstance(self.name, str) or not isinstance(self.dtype_name, str):
            raise TypeError("destination name and dtype must be strings")
        if not self.name or not self.dtype_name:
            raise ValueError("destination name and dtype must be non-empty")
        if not isinstance(self.mode, str):
            raise TypeError("destination mode must be a string")
        M2NDestinationMode(self.mode)
        mesh_dims = tuple(self.mesh_dims)
        M2NMesh(cast(tuple[int, int], mesh_dims), 0)
        object.__setattr__(self, "mesh_dims", mesh_dims)
        if self.placements is not None:
            object.__setattr__(self, "placements", tuple(self.placements))
            _check_destination_placements(
                self.placements, f"parameter '{self.name}' destination placements"
            )
        object.__setattr__(self, "local_shape", tuple(self.local_shape))
        if not self.local_shape or any(
            not isinstance(dim, int) or isinstance(dim, bool) or dim <= 0
            for dim in self.local_shape
        ):
            raise ValueError("destination local_shape must contain positive integers")
        for field, value in (
            ("shard_index", self.shard_index),
            ("num_shards", self.num_shards),
        ):
            if not isinstance(value, int) or isinstance(value, bool):
                raise TypeError(f"destination {field} must be an integer")
        if self.num_shards <= 0 or not 0 <= self.shard_index < self.num_shards:
            raise ValueError("destination shard coordinate is invalid")
        if self.shard_dim is not None and (
            not isinstance(self.shard_dim, int) or isinstance(self.shard_dim, bool)
        ):
            raise TypeError("destination shard_dim must be an integer or null")
        if self.shard_dim is not None and not (
            0 <= self.shard_dim < len(self.local_shape)
        ):
            raise ValueError("destination shard_dim is outside local_shape")
        staged = self.mode == M2NDestinationMode.SHARDED_STAGING.value
        staging_coordinates = (
            self.staging_group,
            self.staging_slot,
            self.staging_group_size,
        )
        if staged:
            if self.placements is None or self.shard_dim is None:
                raise ValueError("a staged destination must be sharded")
            if not isinstance(self.semantic_id, str) or not self.semantic_id:
                raise ValueError("a staged destination needs a semantic_id")
            if any(coordinate is None for coordinate in staging_coordinates):
                raise ValueError("a staged destination needs staging coordinates")
            for field, coordinate in (
                ("staging_group", self.staging_group),
                ("staging_slot", self.staging_slot),
                ("staging_group_size", self.staging_group_size),
            ):
                if (
                    not isinstance(coordinate, int)
                    or isinstance(coordinate, bool)
                    or coordinate < 0
                ):
                    raise ValueError(f"{field} must be a non-negative integer")
            assert self.staging_slot is not None
            assert self.staging_group_size is not None
            if self.staging_group_size == 0:
                raise ValueError("staging_group_size must be positive")
            if self.staging_slot >= self.staging_group_size:
                raise ValueError("staging_slot is outside its group")
        elif self.semantic_id is not None or any(
            coordinate is not None for coordinate in staging_coordinates
        ):
            raise ValueError(
                "only staged destinations carry a semantic_id or coordinates"
            )
        if self.placements is None:
            if (
                self.shard_dim is not None
                or self.shard_index != 0
                or self.num_shards != 1
            ):
                raise ValueError("a replicated destination has shard metadata")
        else:
            if self.shard_dim is None:
                raise ValueError("a sharded destination needs shard_dim")
            if self.num_shards != self.mesh_dims[DESTINATION_SHARD_AXIS]:
                raise ValueError(
                    "destination num_shards must match its mesh shard axis"
                )
        if (
            self.mode == M2NDestinationMode.FULL_FALLBACK.value
            and self.placements is not None
        ):
            raise ValueError("a full fallback must be replicated")

    @classmethod
    def from_dict(cls, value: Mapping[str, Any]) -> M2NWireDestination:
        fields = {
            "name",
            "mode",
            "dtype_name",
            "mesh_dims",
            "placements",
            "local_shape",
            "semantic_id",
            "shard_dim",
            "shard_index",
            "num_shards",
            "staging_group",
            "staging_slot",
            "staging_group_size",
        }
        missing = fields - value.keys()
        extra = value.keys() - fields
        if missing or extra:
            details = []
            if missing:
                details.append(f"missing {sorted(missing)}")
            if extra:
                details.append(f"unexpected {sorted(extra)}")
            raise ValueError(f"invalid M2N wire destination: {', '.join(details)}")
        return cls(**value)

    def to_dict(self) -> dict[str, Any]:
        return {
            "name": self.name,
            "mode": self.mode,
            "dtype_name": self.dtype_name,
            "mesh_dims": list(self.mesh_dims),
            "placements": (None if self.placements is None else list(self.placements)),
            "local_shape": list(self.local_shape),
            "semantic_id": self.semantic_id,
            "shard_dim": self.shard_dim,
            "shard_index": self.shard_index,
            "num_shards": self.num_shards,
            "staging_group": self.staging_group,
            "staging_slot": self.staging_slot,
            "staging_group_size": self.staging_group_size,
        }

    @classmethod
    def from_destination(
        cls,
        destination: M2NDestination,
        *,
        dtype_name: str,
        local_worker_rank: int,
    ) -> M2NWireDestination:
        """Strip live state from one worker-local destination plan."""
        placements = destination.placements
        shard_dim = None
        shard_index = 0
        num_shards = 1
        semantic_id = None
        if placements is not None:
            shard_dim = placements[DESTINATION_SHARD_AXIS]
            num_shards = destination.mesh_dims[DESTINATION_SHARD_AXIS]
            shard_index = local_worker_rank % num_shards
        if destination.mode is M2NDestinationMode.SHARDED_STAGING:
            assert destination.sharded_spec is not None
            spec = destination.sharded_spec
            semantic_id = spec.semantic_id
            shard_dim = spec.shard_dim
            shard_index = spec.shard_index
            num_shards = spec.num_shards
        return cls(
            name=destination.name,
            mode=destination.mode.value,
            dtype_name=dtype_name,
            mesh_dims=destination.mesh_dims,
            placements=placements,
            local_shape=destination.local_shape,
            semantic_id=semantic_id,
            shard_dim=shard_dim,
            shard_index=shard_index,
            num_shards=num_shards,
            staging_group=destination.staging_group,
            staging_slot=destination.staging_slot,
            staging_group_size=destination.staging_group_size,
        )

from_destination(destination, *, dtype_name, local_worker_rank) classmethod ¶

Strip live state from one worker-local destination plan.

Source code in vllm/distributed/weight_transfer/m2n_plan.py
@classmethod
def from_destination(
    cls,
    destination: M2NDestination,
    *,
    dtype_name: str,
    local_worker_rank: int,
) -> M2NWireDestination:
    """Strip live state from one worker-local destination plan."""
    placements = destination.placements
    shard_dim = None
    shard_index = 0
    num_shards = 1
    semantic_id = None
    if placements is not None:
        shard_dim = placements[DESTINATION_SHARD_AXIS]
        num_shards = destination.mesh_dims[DESTINATION_SHARD_AXIS]
        shard_index = local_worker_rank % num_shards
    if destination.mode is M2NDestinationMode.SHARDED_STAGING:
        assert destination.sharded_spec is not None
        spec = destination.sharded_spec
        semantic_id = spec.semantic_id
        shard_dim = spec.shard_dim
        shard_index = spec.shard_index
        num_shards = spec.num_shards
    return cls(
        name=destination.name,
        mode=destination.mode.value,
        dtype_name=dtype_name,
        mesh_dims=destination.mesh_dims,
        placements=placements,
        local_shape=destination.local_shape,
        semantic_id=semantic_id,
        shard_dim=shard_dim,
        shard_index=shard_index,
        num_shards=num_shards,
        staging_group=destination.staging_group,
        staging_slot=destination.staging_slot,
        staging_group_size=destination.staging_group_size,
    )

_check_destination_placements(placements, context) ¶

Validate the per-parameter replica/shard destination convention.

Source code in vllm/distributed/weight_transfer/m2n_plan.py
def _check_destination_placements(placements: Placements, context: str) -> None:
    """Validate the per-parameter replica/shard destination convention."""
    if len(placements) != 2:
        raise ValueError(f"{context} must have 2 entries")
    if any(not isinstance(code, int) or isinstance(code, bool) for code in placements):
        raise TypeError(f"{context} must contain integer placement codes")
    if placements[0] != REPLICATE or placements[1] < 0:
        raise ValueError(
            f"{context} must replicate axis 0 and shard axis 1 by a tensor dimension"
        )

_validate_staging_groups(plan, worker_rank) ¶

Require complete, contiguous semantic groups in canonical order.

Source code in vllm/distributed/weight_transfer/m2n_plan.py
def _validate_staging_groups(
    plan: Sequence[M2NWireDestination], worker_rank: int
) -> None:
    """Require complete, contiguous semantic groups in canonical order."""
    closed: set[int] = set()
    active_group: int | None = None
    active_slots: list[int] = []
    active_size = 0

    def close() -> None:
        nonlocal active_group, active_size
        if active_group is None:
            return
        if active_slots != list(range(active_size)):
            raise ValueError(
                f"worker rank {worker_rank} has incomplete staging group "
                f"{active_group}: slots {active_slots}, expected "
                f"{list(range(active_size))}"
            )
        closed.add(active_group)
        active_group = None
        active_slots.clear()
        active_size = 0

    for destination in plan:
        group = destination.staging_group
        if group is None:
            close()
            continue
        assert destination.staging_slot is not None
        assert destination.staging_group_size is not None
        if group != active_group:
            close()
            if group in closed:
                raise ValueError(
                    f"worker rank {worker_rank} reopens staging group {group}"
                )
            active_group = group
            active_size = destination.staging_group_size
        elif destination.staging_group_size != active_size:
            raise ValueError(
                f"worker rank {worker_rank} staging group {group} "
                "disagrees on its required size"
            )
        active_slots.append(destination.staging_slot)
    close()
    if closed and closed != set(range(len(closed))):
        raise ValueError(
            f"worker rank {worker_rank} staging groups are not densely numbered"
        )

agree_destination_plan(group, *, source_digest, params, source_topology=None, metas, dst_mesh, dst_mesh_constraint, local_plan, local_error) ¶

Agree one complete source-to-destination plan before NCCL init.

Source code in vllm/distributed/weight_transfer/m2n_plan.py
def agree_destination_plan(
    group: StatelessProcessGroup,
    *,
    source_digest: str,
    params: Sequence[M2NWireParam],
    source_topology: M2NSourceTopology | None = None,
    metas: Sequence[M2NParamMeta],
    dst_mesh: M2NMesh,
    dst_mesh_constraint: tuple[int, int] | None,
    local_plan: Sequence[M2NWireDestination] | None,
    local_error: str | None,
) -> tuple[list[M2NWireDestination], str]:
    """Agree one complete source-to-destination plan before NCCL init."""
    prepared_error = local_error
    serialized_plan: list[dict[str, Any]] | None = None
    if prepared_error is None:
        try:
            if not isinstance(source_digest, str) or not source_digest:
                raise ValueError("source_digest must be a non-empty string")
            if not params:
                raise ValueError("source parameter manifest must not be empty")
            if source_plan_digest(params, source_topology) != source_digest:
                raise ValueError("source_digest does not match local parameters")
            if group.world_size != dst_mesh.start_rank + dst_mesh.size:
                raise ValueError(
                    "destination mesh does not cover the tail of the group"
                )
            if dst_mesh_constraint is not None:
                constraint_mesh = M2NMesh(dst_mesh_constraint, dst_mesh.start_rank)
                if constraint_mesh != dst_mesh:
                    raise ValueError(
                        "fixed destination mesh constraint does not match the "
                        "destination rank interval"
                    )
            if local_plan is not None:
                serialized_plan = [item.to_dict() for item in local_plan]
        except Exception as exc:
            prepared_error = f"{type(exc).__name__}: {exc}"
    envelope = {
        "ok": prepared_error is None,
        "error": prepared_error,
        "plan": serialized_plan,
        "source_digest": source_digest,
        "dst_mesh_dims": (
            None if dst_mesh_constraint is None else list(dst_mesh_constraint)
        ),
        "dst_mesh_start_rank": dst_mesh.start_rank,
    }
    gathered = group.all_gather_obj(envelope)
    errors: list[str] = []
    declarations: list[tuple[int, str, int, tuple[int, int] | None]] = []
    expected_fields = {
        "ok",
        "error",
        "plan",
        "source_digest",
        "dst_mesh_dims",
        "dst_mesh_start_rank",
    }
    if len(gathered) != group.world_size:
        errors.append(
            "control-plane all-gather returned "
            f"{len(gathered)} records for world size {group.world_size}"
        )
    for rank, item in enumerate(gathered):
        if not isinstance(item, Mapping):
            errors.append(f"rank {rank}: invalid preflight envelope")
            continue
        if set(item) != expected_fields:
            errors.append(f"rank {rank}: invalid preflight envelope fields")
            continue
        if not isinstance(item["ok"], bool):
            errors.append(f"rank {rank}: invalid preflight status")
            continue
        error = item["error"]
        if item["ok"] != (error is None) or (
            error is not None and (not isinstance(error, str) or not error)
        ):
            errors.append(f"rank {rank}: invalid preflight error")
            continue
        if item["ok"] is not True:
            errors.append(f"rank {rank}: {error}")
            continue
        try:
            declared_digest = item["source_digest"]
            if not isinstance(declared_digest, str) or not declared_digest:
                raise ValueError("source_digest must be a non-empty string")
            start_rank = item["dst_mesh_start_rank"]
            if (
                not isinstance(start_rank, int)
                or isinstance(start_rank, bool)
                or not 0 < start_rank < group.world_size
            ):
                raise ValueError("destination mesh start rank is invalid")
            raw_constraint = item["dst_mesh_dims"]
            declared_constraint = None
            if raw_constraint is not None:
                constraint_mesh = M2NMesh(tuple(raw_constraint), start_rank)
                if constraint_mesh.size != group.world_size - start_rank:
                    raise ValueError(
                        "fixed destination mesh does not cover the group tail"
                    )
                declared_constraint = constraint_mesh.dims
            declarations.append(
                (rank, declared_digest, start_rank, declared_constraint)
            )
        except Exception as exc:
            errors.append(f"rank {rank}: {type(exc).__name__}: {exc}")
    if errors:
        raise RuntimeError(
            "nccl_m2n destination preflight rejected before NCCL init: "
            + "; ".join(errors)
        )

    _, canonical_digest, canonical_start_rank, canonical_constraint = declarations[0]
    for rank, declared_digest, declared_start_rank, declared_constraint in declarations[
        1:
    ]:
        if declared_digest != canonical_digest:
            errors.append(f"rank {rank}: source_digest disagrees with rank 0")
        if declared_start_rank != canonical_start_rank:
            errors.append(f"rank {rank}: destination mesh start disagrees with rank 0")
        if declared_constraint != canonical_constraint:
            errors.append(
                f"rank {rank}: destination mesh constraint disagrees with rank 0"
            )
    canonical_mesh = M2NMesh(
        (group.world_size - canonical_start_rank, 1), canonical_start_rank
    )
    if errors:
        raise RuntimeError(
            "nccl_m2n destination preflight rejected before NCCL init: "
            + "; ".join(errors)
        )

    worker_plans: list[tuple[int, list[M2NWireDestination]]] = []
    for rank, item in enumerate(gathered):
        raw_plan = item["plan"]
        if rank < canonical_mesh.start_rank:
            if raw_plan is not None:
                errors.append(f"trainer rank {rank} published a destination plan")
            continue
        try:
            plan = _parse_worker_plan(raw_plan, rank=rank, params=params)
            worker_plans.append((rank, plan))
        except Exception as exc:
            errors.append(f"rank {rank}: {type(exc).__name__}: {exc}")
    if errors:
        raise RuntimeError(
            "nccl_m2n destination preflight rejected before NCCL init: "
            + "; ".join(errors)
        )
    canonical_plan = worker_plans[0][1]
    commit_digest: str | None = None
    commit_error: str | None = None
    try:
        _validate_plan_set(worker_plans, params, canonical_mesh)
        if canonical_constraint is not None:
            for destination in canonical_plan:
                if (
                    destination.placements is not None
                    and destination.mesh_dims != canonical_constraint
                ):
                    raise ValueError(
                        f"sharded destination for {destination.name!r} uses mesh "
                        f"{destination.mesh_dims}, expected fixed destination "
                        f"mesh {canonical_constraint}"
                    )
        if len(metas) != len(params) or any(
            meta.name != param.name for meta, param in zip(metas, params)
        ):
            raise ValueError("source metadata does not match the wire plan")
        resolved_topology = source_topology or M2NSourceTopology.single_group(
            canonical_mesh.start_rank,
            len(params),
        )
        resolved_topology.validate(
            num_trainer_ranks=canonical_mesh.start_rank,
            num_params=len(params),
        )
        source_group_size = len(resolved_topology.groups[0])
        destination_layouts = [
            M2NLayout(
                M2NMesh(destination.mesh_dims, source_group_size),
                destination.placements,
            )
            for destination in canonical_plan
        ]
        validate_transfer_plan(metas, destination_layouts)
        route_mesh_dims = canonical_constraint or canonical_mesh.dims
        transfer_routes = build_m2n_transfer_routes(
            resolved_topology,
            num_trainer_ranks=canonical_mesh.start_rank,
            world_size=group.world_size,
            dst_mesh_dims=route_mesh_dims,
        )
        payload = {
            "schema_version": M2N_WIRE_SCHEMA_VERSION,
            "source_digest": canonical_digest,
            "source_topology": resolved_topology.to_dict(),
            "dst_mesh_constraint": (
                None if canonical_constraint is None else list(canonical_constraint)
            ),
            "dst_mesh_start_rank": canonical_mesh.start_rank,
            "transfer_routes": [
                {
                    "source_group_index": transfer_route.source_group_index,
                    "members": list(transfer_route.members),
                    "param_indices": list(transfer_route.param_indices),
                    "dst_mesh_dims": list(transfer_route.dst_mesh.dims),
                    "dst_mesh_start_rank": transfer_route.dst_mesh.start_rank,
                }
                for transfer_route in transfer_routes
            ],
            "workers": [
                {
                    "rank": rank,
                    "plan": [destination.to_dict() for destination in plan],
                }
                for rank, plan in worker_plans
            ],
        }
        commit_digest = hashlib.sha256(
            json.dumps(payload, sort_keys=True, separators=(",", ":")).encode()
        ).hexdigest()
    except Exception as exc:
        commit_error = f"{type(exc).__name__}: {exc}"

    committed = group.all_gather_obj(
        {
            "phase": "destination_commit",
            "digest": commit_digest,
            "error": commit_error,
        }
    )
    errors = []
    digests: list[tuple[int, str]] = []
    expected_fields = {"phase", "digest", "error"}
    if len(committed) != group.world_size:
        errors.append(
            "control-plane all-gather returned "
            f"{len(committed)} records for world size {group.world_size}"
        )
    for rank, item in enumerate(committed):
        if (
            not isinstance(item, Mapping)
            or set(item) != expected_fields
            or item.get("phase") != "destination_commit"
        ):
            errors.append(f"rank {rank}: invalid destination-commit envelope")
            continue
        error = item["error"]
        if error is not None:
            if not isinstance(error, str) or not error:
                errors.append(f"rank {rank}: invalid destination-commit error")
            else:
                errors.append(f"rank {rank}: {error}")
            continue
        digest = item["digest"]
        if not isinstance(digest, str) or not digest:
            errors.append(f"rank {rank}: invalid destination-commit digest")
            continue
        digests.append((rank, digest))
    if not errors:
        canonical_commit_digest = digests[0][1]
        for rank, digest in digests[1:]:
            if digest != canonical_commit_digest:
                errors.append(
                    f"rank {rank}: destination-commit digest disagrees with rank 0"
                )
    if errors:
        raise RuntimeError(
            "nccl_m2n complete-plan preflight rejected before NCCL init: "
            + "; ".join(errors)
        )
    return canonical_plan, f"m2n-plan:{digests[0][1]}"