Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / tools / dryrun / patches / trainer / optimizer.py: 92%

96 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"""Training-flow optimizer patches for FakeTensor dry-run.""" 

16 

17from contextvars import ContextVar 

18from itertools import product 

19from typing import Any 

20 

21import torch 

22import torch.distributed as dist 

23 

24from hyper_parallel.core.dtensor.layout import Layout, infer_slice_area_by_layout 

25from hyper_parallel.core.optimizer import muon, muon_shard, optimizer as optimizer_module 

26from hyper_parallel.core.optimizer.dtensor_compat import to_local_if_dtensor 

27from hyper_parallel.core.optimizer.optimizer import BaseDistributedOptimizer 

28 

29_MUON_LAYOUT_STAGE_STATE: ContextVar[Any] = ContextVar( 

30 "dryrun_muon_layout_stage_state", 

31 default=None, 

32) 

33 

34 

35def install_fake_subgroup_patch() -> None: 

36 """Create optimizer replica subgroups directly on PyTorch's fake backend.""" 

37 if getattr(BaseDistributedOptimizer, "_dryrun_subgroup_patched", False): 

38 return 

39 original = BaseDistributedOptimizer._get_or_create_sub_pg 

40 

41 def get_or_create_sub_pg( 

42 self: Any, 

43 parent_pg: dist.ProcessGroup, 

44 sub_size: int, 

45 ) -> dist.ProcessGroup: 

46 """Create optimizer replica subgroups directly on the fake backend.""" 

47 if optimizer_module.dist.get_backend(parent_pg) != "fake": 

48 return original(self, parent_pg, sub_size) 

49 parent_ranks = tuple(sorted(optimizer_module.dist.get_process_group_ranks(parent_pg))) 

50 cache_key = (parent_ranks, sub_size) 

51 cached = self._split_sub_pg_cache.get(cache_key) 

52 if cached is not None: 

53 for subgroup in cached.values(): 

54 if subgroup is not None: 

55 return subgroup 

56 

57 rank = optimizer_module.dist.get_rank() 

58 subgroups = {} 

59 local_group = None 

60 for index in range(len(parent_ranks) // sub_size): 

61 ranks = list(parent_ranks[index * sub_size:(index + 1) * sub_size]) 

62 if rank not in ranks: 

63 subgroups[index] = None 

64 continue 

65 local_group = optimizer_module.dist.new_group(ranks=ranks, use_local_synchronization=True) 

66 subgroups[index] = local_group 

67 self._split_sub_pg_cache[cache_key] = subgroups 

68 if local_group is None: 

69 raise RuntimeError(f"Rank {rank} is absent from optimizer subgroup {parent_ranks}") 

70 return local_group 

71 

72 BaseDistributedOptimizer._get_or_create_sub_pg = get_or_create_sub_pg 

73 BaseDistributedOptimizer._dryrun_subgroup_patched = True 

74 

75 

76def _infer_gather_rank_shapes( 

77 layout: Layout, 

78 global_shape: tuple[int, ...], 

79 coordinate: tuple[int, ...], 

80 shard_axes: tuple[tuple[int, int], ...], 

81) -> tuple[tuple[tuple[int, ...], ...], ...]: 

82 """Derive successive all-gather shapes purely from DTensor slice geometry.""" 

83 shapes = {} 

84 for rank, mesh_coordinate in enumerate( 

85 product(*(range(size) for size in layout.mesh_shape)) 

86 ): 

87 area = infer_slice_area_by_layout(layout, rank, global_shape) 

88 shapes[mesh_coordinate] = tuple(end - start for start, end in area) 

89 result = [] 

90 for mesh_dim, tensor_dim in shard_axes: 

91 group_size = layout.mesh_shape[mesh_dim] 

92 peers = [ 

93 coordinate[:mesh_dim] + (rank,) + coordinate[mesh_dim + 1:] 

94 for rank in range(group_size) 

95 ] 

96 result.append(tuple(shapes[peer] for peer in peers)) 

97 next_shapes = {} 

98 for key, shape in shapes.items(): 

99 group_peers = [ 

100 key[:mesh_dim] + (rank,) + key[mesh_dim + 1:] 

101 for rank in range(group_size) 

102 ] 

103 output = list(shape) 

104 output[tensor_dim] = sum(shapes[peer][tensor_dim] for peer in group_peers) 

105 next_shapes[key] = tuple(output) 

106 shapes = next_shapes 

107 return tuple(result) 

108 

109 

110def install_muon_metadata_patch() -> None: 

111 """Supply FakeTensor Muon shard metadata without modifying optimizer code.""" 

112 if getattr(muon_shard, "_dryrun_metadata_patched", False): 

113 return 

114 original_build = muon_shard.build_param_shard_metadata_for_group 

115 original_all_gather = muon_shard._allgather_shapes_for_group 

116 

117 def all_gather_shapes_for_group( 

118 local_shapes: list[tuple[int, ...]], 

119 shard_pg: Any, 

120 shard_size: int, 

121 device: torch.device, 

122 ) -> list[list[tuple[int, ...]]]: 

123 """Answer Muon gather shapes from the staged layout geometry.""" 

124 state = _MUON_LAYOUT_STAGE_STATE.get() 

125 if state is None: 

126 return original_all_gather(local_shapes, shard_pg, shard_size, device) 

127 layout_shapes, stage = state 

128 _MUON_LAYOUT_STAGE_STATE.set((layout_shapes, stage + 1)) 

129 return [ 

130 [stages[stage][rank] for stages in layout_shapes] 

131 for rank in range(shard_size) 

132 ] 

133 

134 def build_param_shard_metadata_for_group(hsdp_group: Any) -> dict[Any, Any]: 

135 """Derive Muon gather metadata from parameter layouts, including empty shards.""" 

136 layout_spec = hsdp_group.layout_spec 

137 if ( 

138 layout_spec is None 

139 or not layout_spec.shard_axes 

140 or not hsdp_group.records 

141 or not all( 

142 isinstance(getattr(record.param, "layout", None), Layout) 

143 for record in hsdp_group.records 

144 ) 

145 ): 

146 return original_build(hsdp_group) 

147 layout_shapes = [] 

148 for record in hsdp_group.records: 

149 parameter = record.param 

150 coordinate = tuple(parameter.device_mesh.get_coordinate()) 

151 stages = _infer_gather_rank_shapes( 

152 parameter.layout, 

153 tuple(parameter.shape), 

154 coordinate, 

155 layout_spec.shard_axes, 

156 ) 

157 inferred = stages[0][coordinate[layout_spec.shard_axes[0][0]]] 

158 local_shape = tuple(to_local_if_dtensor(parameter.data).shape) 

159 if inferred != local_shape: 

160 raise ValueError( 

161 f"Muon shard shape disagrees with layout: inferred={inferred}, " 

162 f"local={local_shape}, global={tuple(parameter.shape)}" 

163 ) 

164 layout_shapes.append(stages) 

165 token = _MUON_LAYOUT_STAGE_STATE.set((layout_shapes, 0)) 

166 try: 

167 return original_build(hsdp_group) 

168 finally: 

169 _MUON_LAYOUT_STAGE_STATE.reset(token) 

170 

171 muon_shard.build_param_shard_metadata_for_group = build_param_shard_metadata_for_group 

172 muon.build_param_shard_metadata_for_group = build_param_shard_metadata_for_group 

173 muon_shard._allgather_shapes_for_group = all_gather_shapes_for_group 

174 muon_shard._dryrun_metadata_patched = True 

175 

176 

177def install_optimizer_patches() -> None: 

178 """Install all optimizer-related training-flow patches for dry-run.""" 

179 install_fake_subgroup_patch() 

180 install_muon_metadata_patch() 

181 

182 

183__all__ = [ 

184 "install_fake_subgroup_patch", 

185 "install_muon_metadata_patch", 

186 "install_optimizer_patches", 

187]