Skip to content

vllm.distributed.weight_transfer.m2n_source

Trainer-side weight sources for the NCCL M2N backend.

M2N plans a transfer from both sides' layouts, so the trainer has to say how it holds each parameter — which the base WeightSource / ParamMeta pair does not express. Each parameter owns its source mesh and placements because dense and expert weights can use different factorizations over the same source-group ranks. A source topology separately routes each parameter to its owning rank group, including pipeline-parallel producers.

Classes:

Functions:

DTensorModuleSource

Bases: M2NWeightSource

M2NWeightSource over module.named_parameters().

Covers both the FSDP/DTensor trainer (placement read off each parameter, local shard yielded via to_local()) and the plain replicated trainer, with no special casing. Trainers with a custom producer (a Megatron export, MoE re-fusing) subclass M2NWeightSource instead.

Methods:

  • __init__ –

    Wrap module; num_trainer_ranks sizes the mesh for plain tensors.

  • __iter__ –

    Yield each parameter's local shard (to_local()), or the tensor itself.

  • metadata –

    Read each global shape and source layout without gathering shards.

Source code in vllm/distributed/weight_transfer/m2n_source.py
class DTensorModuleSource(M2NWeightSource):
    """`M2NWeightSource` over `module.named_parameters()`.

    Covers both the FSDP/DTensor trainer (placement read off each parameter,
    local shard yielded via `to_local()`) and the plain replicated trainer, with
    no special casing. Trainers with a custom producer (a Megatron export, MoE
    re-fusing) subclass `M2NWeightSource` instead.
    """

    def __init__(self, module: torch.nn.Module, num_trainer_ranks: int) -> None:
        """Wrap `module`; `num_trainer_ranks` sizes the mesh for plain tensors."""
        self._module = module
        self._num_trainer_ranks = num_trainer_ranks

    def metadata(self) -> list[M2NParamMeta]:  # type: ignore[override]
        """Read each global shape and source layout without gathering shards."""
        return [
            M2NParamMeta(
                name,
                p.dtype,
                tuple(p.shape),
                M2NLayout(
                    mesh_from_tensor(p, self._num_trainer_ranks),
                    placements_from_tensor(p),
                ),
            )
            for name, p in self._module.named_parameters()
        ]

    def __iter__(self) -> Iterator[tuple[str, torch.Tensor]]:
        """Yield each parameter's local shard (`to_local()`), or the tensor itself."""
        for name, param in self._module.named_parameters():
            to_local = getattr(param, "to_local", None)
            yield name, (to_local() if callable(to_local) else param)

__init__(module, num_trainer_ranks)

Wrap module; num_trainer_ranks sizes the mesh for plain tensors.

Source code in vllm/distributed/weight_transfer/m2n_source.py
def __init__(self, module: torch.nn.Module, num_trainer_ranks: int) -> None:
    """Wrap `module`; `num_trainer_ranks` sizes the mesh for plain tensors."""
    self._module = module
    self._num_trainer_ranks = num_trainer_ranks

__iter__()

Yield each parameter's local shard (to_local()), or the tensor itself.

Source code in vllm/distributed/weight_transfer/m2n_source.py
def __iter__(self) -> Iterator[tuple[str, torch.Tensor]]:
    """Yield each parameter's local shard (`to_local()`), or the tensor itself."""
    for name, param in self._module.named_parameters():
        to_local = getattr(param, "to_local", None)
        yield name, (to_local() if callable(to_local) else param)

metadata()

Read each global shape and source layout without gathering shards.

Source code in vllm/distributed/weight_transfer/m2n_source.py
def metadata(self) -> list[M2NParamMeta]:  # type: ignore[override]
    """Read each global shape and source layout without gathering shards."""
    return [
        M2NParamMeta(
            name,
            p.dtype,
            tuple(p.shape),
            M2NLayout(
                mesh_from_tensor(p, self._num_trainer_ranks),
                placements_from_tensor(p),
            ),
        )
        for name, p in self._module.named_parameters()
    ]

M2NManifestEntry dataclass

One immutable source descriptor with a lazy rank-local tensor view.

Attributes:

Source code in vllm/distributed/weight_transfer/m2n_source.py
@dataclass(frozen=True)
class M2NManifestEntry:
    """One immutable source descriptor with a lazy rank-local tensor view."""

    key: str
    dtype: torch.dtype
    global_shape: tuple[int, ...]
    source_layout: M2NLayout
    local_tensor: Callable[[], Any]
    allow_full_fallback: bool = True

    def __post_init__(self) -> None:
        object.__setattr__(self, "global_shape", tuple(self.global_shape))
        if not self.key:
            raise ValueError("M2N manifest key must not be empty")
        if not isinstance(self.dtype, torch.dtype):
            raise TypeError(
                f"manifest entry '{self.key}' has invalid dtype {self.dtype!r}"
            )
        if not isinstance(self.source_layout, M2NLayout):
            raise TypeError(
                f"manifest entry '{self.key}' source_layout must be an M2NLayout"
            )
        if not callable(self.local_tensor):
            raise TypeError(
                f"manifest entry '{self.key}' local_tensor must be callable"
            )
        if not isinstance(self.allow_full_fallback, bool):
            raise TypeError(
                f"manifest entry '{self.key}' allow_full_fallback must be a bool"
            )

    @property
    def metadata(self) -> M2NParamMeta:
        """Return the serializable portion consumed during initialization."""
        return M2NParamMeta(
            self.key,
            self.dtype,
            self.global_shape,
            self.source_layout,
            self.allow_full_fallback,
        )

metadata property

Return the serializable portion consumed during initialization.

M2NSourceTopology dataclass

Ordered source rank groups and each parameter's owning group.

Rank ids live in the global metadata-group namespace. Rank order within a group defines route-local source-mesh coordinates, so callers must not sort it. param_groups[i] selects the group that exports params[i]. Transfer-route identity is derived separately from this source ownership.

An empty topology represents an empty manifest and is also used as a lifecycle sentinel. A usable non-empty plan must pass :meth:validate. Source groups are non-empty, pairwise disjoint, and equal-sized, so a trainer rank belongs to at most one group. Each parameter selects exactly one canonical group.

Methods:

  • from_dict –

    Parse one strict JSON-decoded topology record.

  • single_group –

    Build the legacy topology: every trainer exports every parameter.

  • to_dict –

    Serialize this topology using JSON-compatible values.

  • validate –

    Validate this topology against one concrete source manifest.

Source code in vllm/distributed/weight_transfer/m2n_common.py
@dataclass(frozen=True)
class M2NSourceTopology:
    """Ordered source rank groups and each parameter's owning group.

    Rank ids live in the global metadata-group namespace. Rank order within a
    group defines route-local source-mesh coordinates, so callers must not sort
    it. ``param_groups[i]`` selects the group that exports ``params[i]``.
    Transfer-route identity is derived separately from this source ownership.

    An empty topology represents an empty manifest and is also used as a
    lifecycle sentinel. A usable non-empty plan must pass :meth:`validate`.
    Source groups are non-empty, pairwise disjoint, and equal-sized, so a
    trainer rank belongs to at most one group. Each parameter selects exactly
    one canonical group.
    """

    groups: tuple[tuple[int, ...], ...]
    param_groups: tuple[int, ...]

    def __post_init__(self) -> None:
        groups = tuple(tuple(ranks) for ranks in self.groups)
        param_groups = tuple(self.param_groups)
        object.__setattr__(self, "groups", groups)
        object.__setattr__(self, "param_groups", param_groups)

        seen_ranks: set[int] = set()
        for group_index, ranks in enumerate(groups):
            if not ranks:
                raise ValueError(f"source group {group_index} must not be empty")
            if any(
                not isinstance(rank, int) or isinstance(rank, bool) or rank < 0
                for rank in ranks
            ):
                raise ValueError(
                    f"source group {group_index} ranks must be non-negative integers"
                )
            if len(set(ranks)) != len(ranks):
                raise ValueError(
                    f"source group {group_index} contains duplicate trainer ranks"
                )
            overlap = seen_ranks.intersection(ranks)
            if overlap:
                raise ValueError(
                    f"source group {group_index} overlaps an earlier group at "
                    f"trainer rank {min(overlap)}"
                )
            seen_ranks.update(ranks)

        for param_index, group_index in enumerate(param_groups):
            if not isinstance(group_index, int) or isinstance(group_index, bool):
                raise TypeError(
                    f"parameter {param_index} source group must be an integer"
                )
            if not 0 <= group_index < len(groups):
                raise ValueError(
                    f"parameter {param_index} references source group "
                    f"{group_index}, but there are {len(groups)} groups"
                )

    @classmethod
    def single_group(
        cls, num_trainer_ranks: int, num_params: int
    ) -> "M2NSourceTopology":
        """Build the legacy topology: every trainer exports every parameter."""
        if (
            not isinstance(num_trainer_ranks, int)
            or isinstance(num_trainer_ranks, bool)
            or num_trainer_ranks <= 0
        ):
            raise ValueError("num_trainer_ranks must be a positive integer")
        if (
            not isinstance(num_params, int)
            or isinstance(num_params, bool)
            or num_params < 0
        ):
            raise ValueError("num_params must be a non-negative integer")
        if num_params == 0:
            return cls((), ())
        return cls(
            (tuple(range(num_trainer_ranks)),),
            (0,) * num_params,
        )

    @classmethod
    def from_dict(cls, value: Mapping[str, Any]) -> "M2NSourceTopology":
        """Parse one strict JSON-decoded topology record."""
        fields = {"groups", "param_groups"}
        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 source topology: {', '.join(details)}")
        raw_groups = value["groups"]
        raw_param_groups = value["param_groups"]
        if not isinstance(raw_groups, list):
            raise TypeError("source topology groups must be a list")
        if not isinstance(raw_param_groups, list):
            raise TypeError("source topology param_groups must be a list")
        if any(not isinstance(ranks, list) for ranks in raw_groups):
            raise TypeError("each source topology group must be a list")
        return cls(
            tuple(tuple(ranks) for ranks in raw_groups),
            tuple(raw_param_groups),
        )

    def to_dict(self) -> dict[str, Any]:
        """Serialize this topology using JSON-compatible values."""
        return {
            "groups": [list(ranks) for ranks in self.groups],
            "param_groups": list(self.param_groups),
        }

    def validate(self, *, num_trainer_ranks: int, num_params: int) -> None:
        """Validate this topology against one concrete source manifest."""
        if (
            not isinstance(num_trainer_ranks, int)
            or isinstance(num_trainer_ranks, bool)
            or num_trainer_ranks <= 0
        ):
            raise ValueError("num_trainer_ranks must be a positive integer")
        if (
            not isinstance(num_params, int)
            or isinstance(num_params, bool)
            or num_params < 0
        ):
            raise ValueError("num_params must be a non-negative integer")
        if len(self.param_groups) != num_params:
            raise ValueError(
                f"source topology maps {len(self.param_groups)} parameters, "
                f"expected {num_params}"
            )
        if num_params == 0:
            if self.groups:
                raise ValueError("an empty source manifest must not declare groups")
            return
        if not self.groups:
            raise ValueError("a non-empty source manifest needs a source group")
        group_size = len(self.groups[0])
        if any(len(ranks) != group_size for ranks in self.groups):
            raise ValueError("all source groups must have the same size")
        for group_index, ranks in enumerate(self.groups):
            invalid = [rank for rank in ranks if rank >= num_trainer_ranks]
            if invalid:
                raise ValueError(
                    f"source group {group_index} rank {invalid[0]} is outside "
                    f"trainer ranks [0, {num_trainer_ranks})"
                )
        used = set(self.param_groups)
        unused = sorted(set(range(len(self.groups))) - used)
        if unused:
            raise ValueError(f"source topology contains unused groups {unused}")

from_dict(value) classmethod

Parse one strict JSON-decoded topology record.

Source code in vllm/distributed/weight_transfer/m2n_common.py
@classmethod
def from_dict(cls, value: Mapping[str, Any]) -> "M2NSourceTopology":
    """Parse one strict JSON-decoded topology record."""
    fields = {"groups", "param_groups"}
    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 source topology: {', '.join(details)}")
    raw_groups = value["groups"]
    raw_param_groups = value["param_groups"]
    if not isinstance(raw_groups, list):
        raise TypeError("source topology groups must be a list")
    if not isinstance(raw_param_groups, list):
        raise TypeError("source topology param_groups must be a list")
    if any(not isinstance(ranks, list) for ranks in raw_groups):
        raise TypeError("each source topology group must be a list")
    return cls(
        tuple(tuple(ranks) for ranks in raw_groups),
        tuple(raw_param_groups),
    )

single_group(num_trainer_ranks, num_params) classmethod

Build the legacy topology: every trainer exports every parameter.

Source code in vllm/distributed/weight_transfer/m2n_common.py
@classmethod
def single_group(
    cls, num_trainer_ranks: int, num_params: int
) -> "M2NSourceTopology":
    """Build the legacy topology: every trainer exports every parameter."""
    if (
        not isinstance(num_trainer_ranks, int)
        or isinstance(num_trainer_ranks, bool)
        or num_trainer_ranks <= 0
    ):
        raise ValueError("num_trainer_ranks must be a positive integer")
    if (
        not isinstance(num_params, int)
        or isinstance(num_params, bool)
        or num_params < 0
    ):
        raise ValueError("num_params must be a non-negative integer")
    if num_params == 0:
        return cls((), ())
    return cls(
        (tuple(range(num_trainer_ranks)),),
        (0,) * num_params,
    )

to_dict()

Serialize this topology using JSON-compatible values.

Source code in vllm/distributed/weight_transfer/m2n_common.py
def to_dict(self) -> dict[str, Any]:
    """Serialize this topology using JSON-compatible values."""
    return {
        "groups": [list(ranks) for ranks in self.groups],
        "param_groups": list(self.param_groups),
    }

validate(*, num_trainer_ranks, num_params)

Validate this topology against one concrete source manifest.

Source code in vllm/distributed/weight_transfer/m2n_common.py
def validate(self, *, num_trainer_ranks: int, num_params: int) -> None:
    """Validate this topology against one concrete source manifest."""
    if (
        not isinstance(num_trainer_ranks, int)
        or isinstance(num_trainer_ranks, bool)
        or num_trainer_ranks <= 0
    ):
        raise ValueError("num_trainer_ranks must be a positive integer")
    if (
        not isinstance(num_params, int)
        or isinstance(num_params, bool)
        or num_params < 0
    ):
        raise ValueError("num_params must be a non-negative integer")
    if len(self.param_groups) != num_params:
        raise ValueError(
            f"source topology maps {len(self.param_groups)} parameters, "
            f"expected {num_params}"
        )
    if num_params == 0:
        if self.groups:
            raise ValueError("an empty source manifest must not declare groups")
        return
    if not self.groups:
        raise ValueError("a non-empty source manifest needs a source group")
    group_size = len(self.groups[0])
    if any(len(ranks) != group_size for ranks in self.groups):
        raise ValueError("all source groups must have the same size")
    for group_index, ranks in enumerate(self.groups):
        invalid = [rank for rank in ranks if rank >= num_trainer_ranks]
        if invalid:
            raise ValueError(
                f"source group {group_index} rank {invalid[0]} is outside "
                f"trainer ranks [0, {num_trainer_ranks})"
            )
    used = set(self.param_groups)
    unused = sorted(set(range(len(self.groups))) - used)
    if unused:
        raise ValueError(f"source topology contains unused groups {unused}")

M2NWeightSource

Bases: WeightSource

A WeightSource that also describes how the trainer holds its weights.

Unlike ModuleSource, iteration yields each rank's local shard, not a materialized full tensor: gathering is exactly the cost m2n removes.

Methods:

  • __iter__ –

    Yield (name, local buffer) pairs in metadata order.

  • iter_group –

    Iterate one source group in its global manifest subsequence order.

  • metadata –

    Name, dtype, full shape, and source layout for each parameter.

  • source_topology –

    Return explicit source groups, or None for the legacy single group.

Source code in vllm/distributed/weight_transfer/m2n_source.py
class M2NWeightSource(WeightSource):
    """A `WeightSource` that also describes how the trainer holds its weights.

    Unlike `ModuleSource`, iteration yields each rank's **local shard**, not a
    materialized full tensor: gathering is exactly the cost m2n removes.
    """

    def metadata(self) -> list[M2NParamMeta]:  # type: ignore[override]
        """Name, dtype, full shape, and source layout for each parameter."""
        raise NotImplementedError

    def __iter__(self) -> Iterator[tuple[str, Any]]:  # type: ignore[override]
        """Yield `(name, local buffer)` pairs in metadata order.

        Providers must enqueue materialization on the caller's current CUDA
        stream, or return a buffer whose writes are already visible to it.
        Buffers may be torch tensors, CUDA Array Interface objects, or raw
        device pointers accepted by nccl4py. Providers own correct
        communicator-device placement. Raw-pointer providers additionally own
        allocation lifetime, dtype, and shape correctness.
        """
        raise NotImplementedError

    def source_topology(self) -> M2NSourceTopology | None:
        """Return explicit source groups, or ``None`` for the legacy single group.

        Group ranks use global trainer-rank ids in source-mesh coordinate order.
        The trainer engine converts ``None`` into one group containing every
        trainer rank and assigning every parameter to it. Pipeline-parallel or
        otherwise partitioned producers override this together with
        :meth:`iter_group`; vLLM never infers trainer ownership from parameter
        names or inference topology.
        """
        return None

    def iter_group(self, group_index: int) -> Iterator[tuple[str, Any]]:
        """Iterate one source group in its global manifest subsequence order.

        Legacy sources expose one group and keep their existing ``__iter__``
        implementation. Explicit multi-group sources must override this method
        so ranks materialize only parameters belonging to the requested group.
        """
        if (
            not isinstance(group_index, int)
            or isinstance(group_index, bool)
            or group_index != 0
        ):
            raise ValueError(
                "legacy M2N source only supports source group 0; explicit "
                "multi-group sources must override iter_group()"
            )
        return iter(self)

__iter__()

Yield (name, local buffer) pairs in metadata order.

Providers must enqueue materialization on the caller's current CUDA stream, or return a buffer whose writes are already visible to it. Buffers may be torch tensors, CUDA Array Interface objects, or raw device pointers accepted by nccl4py. Providers own correct communicator-device placement. Raw-pointer providers additionally own allocation lifetime, dtype, and shape correctness.

Source code in vllm/distributed/weight_transfer/m2n_source.py
def __iter__(self) -> Iterator[tuple[str, Any]]:  # type: ignore[override]
    """Yield `(name, local buffer)` pairs in metadata order.

    Providers must enqueue materialization on the caller's current CUDA
    stream, or return a buffer whose writes are already visible to it.
    Buffers may be torch tensors, CUDA Array Interface objects, or raw
    device pointers accepted by nccl4py. Providers own correct
    communicator-device placement. Raw-pointer providers additionally own
    allocation lifetime, dtype, and shape correctness.
    """
    raise NotImplementedError

iter_group(group_index)

Iterate one source group in its global manifest subsequence order.

Legacy sources expose one group and keep their existing __iter__ implementation. Explicit multi-group sources must override this method so ranks materialize only parameters belonging to the requested group.

Source code in vllm/distributed/weight_transfer/m2n_source.py
def iter_group(self, group_index: int) -> Iterator[tuple[str, Any]]:
    """Iterate one source group in its global manifest subsequence order.

    Legacy sources expose one group and keep their existing ``__iter__``
    implementation. Explicit multi-group sources must override this method
    so ranks materialize only parameters belonging to the requested group.
    """
    if (
        not isinstance(group_index, int)
        or isinstance(group_index, bool)
        or group_index != 0
    ):
        raise ValueError(
            "legacy M2N source only supports source group 0; explicit "
            "multi-group sources must override iter_group()"
        )
    return iter(self)

metadata()

Name, dtype, full shape, and source layout for each parameter.

Source code in vllm/distributed/weight_transfer/m2n_source.py
def metadata(self) -> list[M2NParamMeta]:  # type: ignore[override]
    """Name, dtype, full shape, and source layout for each parameter."""
    raise NotImplementedError

source_topology()

Return explicit source groups, or None for the legacy single group.

Group ranks use global trainer-rank ids in source-mesh coordinate order. The trainer engine converts None into one group containing every trainer rank and assigning every parameter to it. Pipeline-parallel or otherwise partitioned producers override this together with :meth:iter_group; vLLM never infers trainer ownership from parameter names or inference topology.

Source code in vllm/distributed/weight_transfer/m2n_source.py
def source_topology(self) -> M2NSourceTopology | None:
    """Return explicit source groups, or ``None`` for the legacy single group.

    Group ranks use global trainer-rank ids in source-mesh coordinate order.
    The trainer engine converts ``None`` into one group containing every
    trainer rank and assigning every parameter to it. Pipeline-parallel or
    otherwise partitioned producers override this together with
    :meth:`iter_group`; vLLM never infers trainer ownership from parameter
    names or inference topology.
    """
    return None

ManifestM2NWeightSource

Bases: M2NWeightSource

An ordered M2N source backed by lazy, rank-local manifest entries.

The provider callable is invoked on every iteration, so it can return a current parameter view or perform rank-local conversion and LoRA merging. Callable identities and tensors remain local and never enter the wire plan. Callbacks run synchronously and must honor M2NWeightSource.__iter__'s current-stream readiness contract.

Methods:

  • __iter__ –

    Materialize one rank-local buffer at a time.

  • metadata –

    Return a fresh list while preserving the immutable manifest order.

Source code in vllm/distributed/weight_transfer/m2n_source.py
class ManifestM2NWeightSource(M2NWeightSource):
    """An ordered M2N source backed by lazy, rank-local manifest entries.

    The provider callable is invoked on every iteration, so it can return a
    current parameter view or perform rank-local conversion and LoRA merging.
    Callable identities and tensors remain local and never enter the wire plan.
    Callbacks run synchronously and must honor `M2NWeightSource.__iter__`'s
    current-stream readiness contract.
    """

    def __init__(self, entries: Sequence[M2NManifestEntry]) -> None:
        self._entries = tuple(entries)
        self._metadata = tuple(entry.metadata for entry in self._entries)

    def metadata(self) -> list[M2NParamMeta]:  # type: ignore[override]
        """Return a fresh list while preserving the immutable manifest order."""
        return list(self._metadata)

    def __iter__(self) -> Iterator[tuple[str, Any]]:  # type: ignore[override]
        """Materialize one rank-local buffer at a time."""
        for entry in self._entries:
            yield entry.key, entry.local_tensor()

__iter__()

Materialize one rank-local buffer at a time.

Source code in vllm/distributed/weight_transfer/m2n_source.py
def __iter__(self) -> Iterator[tuple[str, Any]]:  # type: ignore[override]
    """Materialize one rank-local buffer at a time."""
    for entry in self._entries:
        yield entry.key, entry.local_tensor()

metadata()

Return a fresh list while preserving the immutable manifest order.

Source code in vllm/distributed/weight_transfer/m2n_source.py
def metadata(self) -> list[M2NParamMeta]:  # type: ignore[override]
    """Return a fresh list while preserving the immutable manifest order."""
    return list(self._metadata)

_placement_code(placement)

Map a torch.distributed placement onto an m2n placement code.

Source code in vllm/distributed/weight_transfer/m2n_source.py
def _placement_code(placement: Any) -> int:
    """Map a `torch.distributed` placement onto an m2n placement code."""
    name = type(placement).__name__
    if name == "Replicate":
        return REPLICATE
    if name == "Shard":
        return int(placement.dim)
    raise ValueError(
        f"nccl_m2n cannot express the {name} placement; only Replicate and "
        "Shard are supported"
    )

mesh_from_tensor(tensor, num_trainer_ranks)

The mesh a parameter lives on, as an M2NMesh.

This adapter treats tensors without DeviceMesh metadata as replicated. Implicitly sharded tensors, such as Megatron parameters, require a custom M2NWeightSource with an explicit source layout.

Megatron integrations must use ManifestM2NWeightSource or another custom M2NWeightSource that explicitly supplies TP/EP layouts. Megatron parameters must not be passed to DTensorModuleSource.

Source code in vllm/distributed/weight_transfer/m2n_source.py
def mesh_from_tensor(tensor: torch.Tensor, num_trainer_ranks: int) -> M2NMesh:
    """The mesh a parameter lives on, as an `M2NMesh`.

    This adapter treats tensors without DeviceMesh metadata as replicated.
    Implicitly sharded tensors, such as Megatron parameters, require a custom
    `M2NWeightSource` with an explicit source layout.

    Megatron integrations must use `ManifestM2NWeightSource` or another custom
    `M2NWeightSource` that explicitly supplies TP/EP layouts. Megatron parameters
    must not be passed to `DTensorModuleSource`.
    """
    device_mesh = getattr(tensor, "device_mesh", None)
    if device_mesh is None:
        return M2NMesh((num_trainer_ranks, 1), 0)

    grid = device_mesh.mesh
    ranks = grid.flatten().tolist()
    if ranks != list(range(len(ranks))):
        raise ValueError(
            "nccl_m2n requires the trainer's device mesh to cover the "
            f"contiguous rank interval [0, {len(ranks)}); got {ranks}"
        )
    if grid.ndim > 2:
        raise ValueError(
            f"nccl_m2n supports 1-D and 2-D device meshes, got {grid.ndim}-D"
        )
    dims = tuple(grid.shape)
    return M2NMesh(dims if len(dims) == 2 else (dims[0], 1), 0)

placements_from_tensor(tensor)

How a parameter is placed over its mesh, or REPLICATED.

REPLICATED is returned rather than a (REPLICATE, REPLICATE) pair so vLLM has one canonical fully replicated representation. resolve_layout later converts it to the equivalent size-1-axis encoding.

Source code in vllm/distributed/weight_transfer/m2n_source.py
def placements_from_tensor(tensor: torch.Tensor) -> Placements | None:
    """How a parameter is placed over its mesh, or `REPLICATED`.

    `REPLICATED` is returned rather than a `(REPLICATE, REPLICATE)` pair so
    vLLM has one canonical fully replicated representation. `resolve_layout`
    later converts it to the equivalent size-1-axis encoding.
    """
    placements = getattr(tensor, "placements", None)
    if placements is None:
        return REPLICATED
    codes = [_placement_code(p) for p in placements]
    if all(code == REPLICATE for code in codes):
        return REPLICATED
    if len(codes) == 1:
        return (codes[0], REPLICATE)
    return (codes[0], codes[1])