Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / high_availability / replica_topology.py: 90%
88 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
1# Copyright 2026 Huawei Technologies Co., Ltd
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ============================================================================
15"""Infer actual equivalent device replicas from parameter layouts."""
17from dataclasses import dataclass
18import os
19from typing import Any
21import numpy as np
22import torch.distributed as dist
24from hyper_parallel.high_availability.group_registry import GroupRegistry
27def device_replica_ranks(parameter: Any, rank: int) -> set[int]:
28 """Vary replicated mesh axes only; TP/EP shard coordinates must stay fixed."""
29 mesh = getattr(parameter, "device_mesh", None)
30 placements = getattr(parameter, "placements", None)
31 if mesh is None or placements is None:
32 return {rank}
33 shape = tuple(mesh.mesh_shape)
34 ranks = tuple(int(value) for value in mesh.rank_list)
35 own = tuple(np.unravel_index(ranks.index(rank), shape))
36 result = set()
37 for index, coordinate in enumerate(np.ndindex(shape)):
38 if all(placement.is_replicate() or coordinate[axis] == own[axis]
39 for axis, placement in enumerate(placements)):
40 result.add(ranks[index])
41 return result
44def model_replica_candidates(state: Any, rank: int, world: int) -> tuple[int, ...]:
45 """Intersect declared device-shard equivalence across every model parameter."""
46 candidates = set(range(world))
47 external = getattr(state, "external_state", None)
48 host_names = external.parameters if external is not None else {}
49 host_peers = external.recovery_replica_ranks(rank) if host_names else set()
50 for name, parameter in state.parameters.items():
51 peers = host_peers if name in host_names else device_replica_ranks(parameter, rank)
52 candidates.intersection_update(peers)
53 return tuple(sorted(candidates))
56@dataclass(frozen=True)
57class ReplicaTopology:
58 """A partition of equivalent full local device states, never arbitrary backup pairs."""
60 replica_groups: tuple[tuple[int, ...], ...]
62 @classmethod
63 def from_profiles(cls, profiles: list[dict[str, Any]]) -> "ReplicaTopology":
64 """Intersect model equivalence with actual optimizer-state ownership."""
65 groups = set()
66 for rank, profile in enumerate(profiles):
67 peers = tuple(profile["candidates"])
68 if len(peers) < 2 or rank not in peers:
69 raise ValueError(f"rank {rank} has no equivalent device replica; unique TP/EP shards cannot recover "
70 "and worker recovery cannot be enabled")
71 for peer in peers:
72 if not 0 <= peer < len(profiles):
73 raise ValueError("replica rank is outside the training world")
74 other = profiles[peer]
75 if tuple(other["candidates"]) != peers or other["schema"] != profile["schema"]:
76 raise ValueError("device replica layout or optimizer ownership is inconsistent")
77 complete = tuple(peer for peer in peers
78 if profiles[peer]["optimizer_ownership"] == profile["optimizer_ownership"])
79 if len(complete) < 2:
80 raise ValueError(f"rank {rank} has no complete device replica for model and optimizer state; "
81 f"worker recovery cannot be enabled (model replicas={peers}). "
82 "Check Muon hsdp_replica_count and its actual state-owner assignments.")
83 groups.add(complete)
84 if len({len(group) for group in groups}) != 1:
85 raise ValueError("MindIO recovery requires uniform replica counts across these device domains")
86 return cls(tuple(sorted(groups)))
88 @classmethod
89 def discover(cls, state: Any, rank: int, world: int, reboot: bool) -> "ReplicaTopology":
90 """Derive equivalent owners locally; validate original workers once without caching.
92 Args:
93 state: Bound model and optimizer state with the local ownership plan.
94 rank: Current global worker rank.
95 world: Number of workers in the training world.
96 reboot: Whether this replacement must avoid global descriptor exchange.
98 Returns:
99 Complete local-state replicas containing this worker.
100 """
101 candidates = model_replica_candidates(state, rank, world)
102 if len(candidates) < 2:
103 raise ValueError(f"rank {rank} has no equivalent device replica; worker recovery cannot be enabled")
104 ownership = {peer: state.replica_ownership(peer) for peer in candidates}
105 if ownership.get(rank) != state.optimizer_ownership:
106 raise ValueError("local Muon owner inference differs from its actual optimizer assignment")
107 members = tuple(peer for peer in candidates if ownership[peer] == state.optimizer_ownership)
108 if len(members) < 2:
109 raise ValueError(f"rank {rank} has no complete device replica for model and optimizer state; "
110 "check Muon hsdp_replica_count and its actual state-owner assignments")
111 if not reboot:
112 own = {"candidates": candidates, "schema": state.schema,
113 "optimizer_ownership": state.optimizer_ownership}
114 profiles = [None] * world
115 dist.all_gather_object(profiles, own)
116 if cls.from_profiles(profiles).members(rank) != members:
117 raise ValueError("derived optimizer replicas disagree with original workers")
118 return cls((members,))
120 def members(self, rank: int) -> tuple[int, ...]:
121 """Return the complete equivalent device-replica domain for this rank."""
122 for group in self.replica_groups:
123 if rank in group:
124 return group
125 raise ValueError(f"rank {rank} is outside the device replica topology")
127 def get_metadata_group(self, rank: int, registry: GroupRegistry) -> Any:
128 """Reuse the first exact registered HCCL group or construct a lazy local handle.
130 Args:
131 rank: Global rank whose complete replicas exchange metadata.
132 registry: Recovery catalog that preserves handles across communication rebuild.
134 Returns:
135 An existing or newly registered HCCL group with exactly the replica members.
136 """
137 ranks = tuple(sorted(self.members(rank)))
138 group = next((descriptor.group for descriptor in registry.groups
139 if tuple(sorted(descriptor.ranks)) == ranks), None)
140 if group is None:
141 if ranks == tuple(range(dist.get_world_size())):
142 group = dist.group.WORLD
143 else:
144 if os.getenv("TORCH_DIST_INIT_BARRIER", "0") != "0":
145 raise ValueError("metadata group bootstrap requires TORCH_DIST_INIT_BARRIER=0")
146 if getattr(dist.group.WORLD, "bound_device_id", None) is not None:
147 raise ValueError("metadata group bootstrap requires a default group without bound device_id")
148 # Hashed names depend on members, not the creation count of other
149 # replica domains. No device_id keeps replacement HCCL setup lazy.
150 group = registry.call_original_new_group(
151 ranks=list(ranks),
152 backend="hccl",
153 use_local_synchronization=True,
154 group_desc="recovery_metadata",
155 )
156 if group is not dist.group.WORLD:
157 registry.register(group, purpose="recovery_metadata")
158 return group