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]}"