Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / high_availability / group_registry.py: 92%

110 statements  

« 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"""Track process groups through scoped Torch hooks during worker recovery.""" 

16 

17import inspect 

18import os 

19from contextvars import ContextVar 

20from dataclasses import dataclass 

21from typing import Any 

22 

23import torch.distributed as dist 

24 

25_ACTIVE_REGISTRY = ContextVar("hp_recovery_groups", default=None) 

26_NEW_GROUP_SIGNATURE = inspect.signature(dist.new_group) 

27 

28 

29def is_recovery_enabled() -> bool: 

30 """Return whether the current execution context belongs to a recovery session.""" 

31 return _ACTIVE_REGISTRY.get() is not None 

32 

33 

34def is_recovery_reboot() -> bool: 

35 """Return whether the current session belongs to a replacement worker.""" 

36 registry = _ACTIVE_REGISTRY.get() 

37 return registry is not None and registry.reboot 

38 

39 

40def is_recovery_bootstrapping() -> bool: 

41 """Return whether a replacement is still constructing objects before attach.""" 

42 registry = _ACTIVE_REGISTRY.get() 

43 return registry is not None and registry.reboot and not registry.sealed 

44 

45 

46@dataclass(frozen=True) 

47class GroupDescriptor: 

48 """One creation-ordered process group, including its backend and purpose.""" 

49 

50 ranks: tuple[int, ...] 

51 backend: str 

52 purpose: str 

53 group: Any 

54 

55 

56def recovery_optimizer_subgroup(parent: Any, sub_size: int) -> Any: 

57 """Split recorded mesh groups without a world collective during worker reboot. 

58 

59 Return None outside recovery so normal optimizer construction is unchanged. 

60 All ranks have the canonical mesh-group catalog, including nonmember groups. 

61 

62 Args: 

63 parent: Recorded parent process group to split. 

64 sub_size: Number of ranks in each optimizer subgroup. 

65 

66 Returns: 

67 The local optimizer subgroup, or None when recovery is inactive. 

68 """ 

69 registry = _ACTIVE_REGISTRY.get() 

70 if registry is None: 

71 return None 

72 parent_ranks = tuple(sorted(dist.get_process_group_ranks(parent))) 

73 parents = {descriptor.ranks for descriptor in registry.groups 

74 if len(descriptor.ranks) == len(parent_ranks) and descriptor.purpose != "recovery_backup"} 

75 if len(parent_ranks) == dist.get_world_size(): 

76 parents.add(tuple(range(dist.get_world_size()))) 

77 if parent_ranks not in parents: 

78 raise ValueError("register the optimizer's parent mesh groups before recovery subgroup construction") 

79 key = (tuple(sorted(parents)), sub_size) 

80 if key not in registry.optimizer_subgroups: 

81 groups = {} 

82 for ranks in key[0]: 

83 if len(ranks) % sub_size: 

84 raise ValueError("optimizer subgroup size must divide each recorded parent group") 

85 for start in range(0, len(ranks), sub_size): 

86 members = ranks[start:start + sub_size] 

87 group = dist.new_group( 

88 ranks=list(members), 

89 backend="hccl", 

90 group_desc="recovery_optimizer", 

91 ) 

92 groups[members] = group 

93 registry.optimizer_subgroups[key] = groups 

94 rank = dist.get_rank() 

95 start = (parent_ranks.index(rank) // sub_size) * sub_size 

96 return registry.optimizer_subgroups[key][parent_ranks[start:start + sub_size]] 

97 

98 

99class GroupRegistry: 

100 """Preserve process group identities retained by mesh, buckets and optimizer. 

101 

102 This context patches Torch's public group factories process-wide during 

103 construction and training. Previously bound aliases and private factories 

104 require explicit ``register`` calls. Only fixed-topology HCCL is supported. 

105 """ 

106 

107 def __init__(self) -> None: 

108 """Start a fresh deterministic construction catalog.""" 

109 self.groups: list[GroupDescriptor] = [] 

110 self._token = None 

111 self._original_new_group = None 

112 self._original_c10d_new_group = None 

113 self.reboot = False 

114 self.sealed = False 

115 self.optimizer_subgroups: dict[Any, Any] = {} 

116 

117 def __enter__(self) -> "GroupRegistry": 

118 """Record process groups created in the current execution context.""" 

119 if (_ACTIVE_REGISTRY.get() is not None 

120 or isinstance(getattr(dist.new_group, "__self__", None), GroupRegistry)): 

121 raise RuntimeError("nested recovery group registries are not supported") 

122 self._original_new_group = dist.new_group 

123 self._original_c10d_new_group = dist.distributed_c10d.new_group 

124 dist.new_group = self.new_group 

125 dist.distributed_c10d.new_group = self.new_group 

126 self._token = _ACTIVE_REGISTRY.set(self) 

127 return self 

128 

129 def __exit__(self, *exc: Any) -> None: 

130 """Restore the caller's construction context.""" 

131 dist.new_group = self._original_new_group 

132 dist.distributed_c10d.new_group = self._original_c10d_new_group 

133 self._original_new_group = None 

134 self._original_c10d_new_group = None 

135 _ACTIVE_REGISTRY.reset(self._token) 

136 

137 def new_group(self, *args: Any, **kwargs: Any) -> Any: 

138 """Validate and record native group creation for this recovery registry. 

139 

140 Args: 

141 *args: Native positional group arguments. 

142 **kwargs: Native keyword group arguments. 

143 

144 Returns: 

145 The native process group or nonmember sentinel. 

146 """ 

147 options = _NEW_GROUP_SIGNATURE.bind(*args, **kwargs).arguments 

148 if options.get("use_local_synchronization", False) or options.get("device_id") is not None: 

149 raise ValueError("recovery groups require lazy init and no local synchronization") 

150 if getattr(dist.group.WORLD, "bound_device_id", None) is not None: 

151 raise ValueError("recovery groups require a default group without bound device_id") 

152 if self.sealed: 

153 raise RuntimeError("materialize every recovery process group during bootstrap, before attach") 

154 if options.get("pg_options") is not None: 

155 raise ValueError("custom HCCL process-group options are not supported by worker recovery") 

156 backend = str(options.get("backend") or dist.get_backend()) 

157 if backend != "hccl" or os.getenv("TORCH_DIST_INIT_BARRIER", "0") != "0": 

158 raise ValueError("worker reboot construction requires lazy HCCL and TORCH_DIST_INIT_BARRIER=0") 

159 group = self.call_original_new_group(*args, **kwargs) 

160 ranks = tuple(sorted(options.get("ranks") or range(dist.get_world_size()))) 

161 self.groups.append(GroupDescriptor(ranks, backend, options.get("group_desc") or "", group)) 

162 return group 

163 

164 def call_original_new_group(self, *args: Any, **kwargs: Any) -> Any: 

165 """Call the saved group factory without reentering the recovery hook. 

166 

167 Args: 

168 *args: Native positional group arguments. 

169 **kwargs: Native keyword group arguments. 

170 

171 Returns: 

172 A native group requiring explicit registration or caller-owned teardown. 

173 """ 

174 create = self._original_new_group if self._original_new_group is not None else dist.new_group 

175 return create(*args, **kwargs) 

176 

177 def register(self, group: Any, purpose: str = "external") -> None: 

178 """Record a caller-owned group used by the protected model.""" 

179 if self.sealed: 

180 raise RuntimeError("register process groups before attaching recovery state") 

181 if any(descriptor.group is group for descriptor in self.groups): 

182 return 

183 backend = str(dist.get_backend(group)) 

184 if backend != "hccl": 

185 raise ValueError("only HCCL process groups support this worker reboot path") 

186 self.groups.append(GroupDescriptor(tuple(dist.get_process_group_ranks(group)), backend, purpose, group)) 

187 

188 def rebuild(self) -> None: 

189 """Reinitialize member groups locally; MindIO fences completion before repair.""" 

190 reinit = getattr(dist, "reinit_process_group", None) 

191 if not callable(reinit): 

192 raise RuntimeError("torch-npu reinit_process_group is required for process recovery") 

193 reinit(group=None, rebuild_link=True) 

194 rank = dist.get_rank() 

195 seen = {id(dist.group.WORLD)} 

196 for descriptor in self.groups: 

197 if rank in descriptor.ranks and id(descriptor.group) not in seen: 

198 reinit(group=descriptor.group, rebuild_link=True) 

199 seen.add(id(descriptor.group))