Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / modules / moe / moe_utils.py: 95%

63 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"""Model-independent router load accounting, bias updates and statistics resources.""" 

16 

17from __future__ import annotations 

18 

19from typing import Any, Optional 

20 

21import torch 

22import torch.distributed as dist 

23from torch import nn 

24 

25from hyper_parallel.core.dtensor.dtensor import DTensor, SkipDTensorDispatch, distribute_tensor 

26from hyper_parallel.core.dtensor.placement_types import Replicate 

27from hyper_parallel.distributed.recipe_spec import ModuleShardingSpec 

28 

29 

30def local_router_metadata( 

31 tensor: torch.Tensor | None, states: torch.Tensor, tp_mesh: Any, 

32) -> torch.Tensor | None: 

33 """Align masks or logical sample IDs with the router's actual TP token slice. 

34 

35 Args: 

36 tensor: Local metadata or metadata before the TP token slice. 

37 states: Router input ending in the hidden dimension. 

38 tp_mesh: Existing token-partition TP mesh, or None for replicated tokens. 

39 

40 Returns: 

41 Metadata matching exactly the router input token dimensions. 

42 """ 

43 if tensor is None or tensor.shape == states.shape[:-1]: 

44 return tensor 

45 length = states.shape[-2] 

46 expected = (*states.shape[:-2], length * tp_mesh.size()) if tp_mesh is not None else None 

47 if expected is None or tuple(tensor.shape) != expected: 

48 raise ValueError("router metadata must match local or TP-gathered token dimensions") 

49 return tensor.narrow(-1, tp_mesh.get_local_rank() * length, length) 

50 

51 

52def router_sharding(*, module: nn.Module, module_fqn: str, member: Any, context: Any) -> ModuleShardingSpec: 

53 """Declare complete replicated router state without another token boundary. 

54 

55 Args: 

56 module: Actual router member. 

57 module_fqn: Diagnostic path supplied by the family builder. 

58 member: Resolved family member. 

59 context: Existing logical topology. 

60 """ 

61 del module_fqn, member, context 

62 return ModuleShardingSpec(params={name: {} for name, _ in module.named_parameters()}, 

63 in_src={}, in_dst={}, is_boundary=False) 

64 

65 

66def validate_router_layout(*, module: nn.Module, sharding: ModuleShardingSpec, context: Any) -> None: 

67 """Reject parameter sharding or token redistribution inside a replicated router. 

68 

69 Args: 

70 module: Router owning projection and optional correction state. 

71 sharding: Final family layout after user overrides. 

72 context: Existing logical topology. 

73 """ 

74 del context 

75 if set(sharding.params) != {name for name, _ in module.named_parameters()}: 

76 raise ValueError("router requires complete parameter ownership") 

77 if any(value != Replicate() for axes in sharding.params.values() for value in axes.values()): 

78 raise ValueError("router parameters must be replicated across computation axes") 

79 if sharding.is_boundary or sharding.in_src or sharding.in_dst or sharding.out_src or sharding.out_dst: 

80 raise ValueError("router token redistribution belongs to the containing MoE") 

81 

82 

83class _AccumulateRouterLoad(torch.autograd.Function): 

84 """Count a training microbatch once, even when its forward is recomputed.""" 

85 

86 @staticmethod 

87 def forward(ctx: Any, weights: torch.Tensor, counts: torch.Tensor, accumulator: torch.Tensor) -> torch.Tensor: 

88 """Keep the forward unchanged; only a consumed backward records loads. 

89 

90 Args: 

91 ctx: Autograd context holding the accumulator reference. 

92 weights: Routing-weight gradient carrier. 

93 counts: Immutable local microbatch counts. 

94 accumulator: Integer step-level expert counts. 

95 """ 

96 ctx.save_for_backward(counts) 

97 ctx.accumulator = accumulator 

98 return weights 

99 

100 @staticmethod 

101 def backward(ctx: Any, gradient: torch.Tensor) -> tuple[torch.Tensor, None, None]: 

102 """Accumulate integer counts without retaining the model graph. 

103 

104 Args: 

105 ctx: Context saved by forward. 

106 gradient: Unchanged gradient for the routing weights. 

107 """ 

108 with SkipDTensorDispatch(), torch.no_grad(): 

109 ctx.accumulator.add_(ctx.saved_tensors[0]) 

110 return gradient, None, None 

111 

112 

113 

114def accumulate_router_load( 

115 weights: torch.Tensor, 

116 selected_experts: torch.Tensor, 

117 token_mask: torch.Tensor | None, 

118 accumulator: torch.Tensor, 

119) -> torch.Tensor: 

120 """Attach expert load accumulation to the router's backward path. 

121 

122 Args: 

123 weights: Routing weights used by expert combination. 

124 selected_experts: Actual selected indices, shaped [T, K]. 

125 token_mask: Boolean token mask; true tokens contribute. 

126 accumulator: Integer [E] step counter. 

127 """ 

128 selected_experts = selected_experts.to(torch.int64) 

129 num_tokens, top_k = selected_experts.shape 

130 valid = selected_experts.new_ones(num_tokens) if token_mask is None else token_mask.reshape(-1).long() 

131 counts = torch.zeros_like(accumulator).scatter_add( 

132 0, selected_experts.reshape(-1), valid.unsqueeze(-1).expand(-1, top_k).reshape(-1), 

133 ) 

134 if torch.is_grad_enabled() and not weights.requires_grad: 

135 weights = weights.detach().requires_grad_() 

136 return _AccumulateRouterLoad.apply(weights, counts, accumulator) 

137 

138 

139 

140@torch.no_grad() 

141def update_router_bias(bias: torch.Tensor, counts: torch.Tensor, update_rate: float) -> None: 

142 """Update expert correction bias, including a sharded parameter. 

143 

144 Counts must already include all DP and token partitions. All-zero counts 

145 produce no update. Bias affects selection only. 

146 

147 Args: 

148 bias: Expert correction parameter [E], possibly sharded. 

149 counts: Global int64 expert assignment counts [E]. 

150 update_rate: Nonnegative step size for the sign update. 

151 """ 

152 num_experts = counts.shape[-1] 

153 total = counts.sum(dim=-1, keepdim=True) 

154 # Compare in integer arithmetic so rounding cannot erase small load 

155 # differences before the sign update. 

156 direction = (total - counts * num_experts).sign() 

157 delta = (update_rate * direction.float()).to(device=bias.device, dtype=bias.dtype) 

158 if isinstance(bias, DTensor): 

159 delta = distribute_tensor(delta, bias.device_mesh, bias.placements) 

160 bias.add_(delta) 

161 

162 

163def sync_and_update_expert_bias( 

164 moe: nn.Module, 

165 lr: float = 1e-3, 

166 tp_group: Optional[Any] = None, 

167 cp_group: Optional[Any] = None, 

168 dp_group: Optional[Any] = None, 

169 num_recomputations: int = 1, 

170) -> None: 

171 """Synchronize tokens_per_expert across distributed ranks, then update expert bias. 

172 

173 This function handles distributed synchronization for expert bias updates in 

174 MoE (Mixture of Experts) models. It should be called after optimizer.step() in 

175 the training loop. 

176 

177 The synchronization is needed because: 

178 - **DP**: Different ranks process different samples, need to aggregate global batch stats 

179 - **TP+SP**: Standard TP does not need sync (all ranks see same input). 

180 Only needed when TP is combined with sequence parallelism (TP+SP), 

181 where activations are sequence-sharded across TP ranks. 

182 - **CP**: Sequence dimension is sharded across ranks 

183 

184 For pure EP scenario (no DP/TP/CP), call moe.update_expert_bias() directly. 

185 

186 Args: 

187 moe: The MoE module whose expert bias should be updated. 

188 lr: Step size for the bias update. Defaults to ``1e-3``. 

189 tp_group: Tensor parallel process group (ProcessGroup or GroupInfo). 

190 Only needed when TP is combined with sequence parallelism (TP+SP), 

191 where activations are sequence-sharded across TP ranks. 

192 Standard TP (weight-only sharding) does not need this. 

193 cp_group: Context parallel process group (ProcessGroup or GroupInfo). 

194 Sync across sequence shards dimension. 

195 dp_group: Data parallel process group (ProcessGroup or GroupInfo). 

196 Sync across different samples to get global batch statistics. 

197 num_recomputations: Number of forward executions per optimizer step. 

198 Default ``1`` (normal training). Set to ``2`` when activation 

199 checkpoint is enabled. 

200 

201 Example: 

202 >>> # DP scenario 

203 >>> sync_and_update_expert_bias(moe_layer, lr=1e-3, dp_group=dp_group_info) 

204 >>> 

205 >>> # TP×CP×DP scenario (reference: Megatron-LM) 

206 >>> sync_and_update_expert_bias( 

207 ... moe_layer, 

208 ... lr=1e-3, 

209 ... tp_group=tp_group_info, 

210 ... cp_group=cp_group_info, 

211 ... dp_group=dp_group_info, 

212 ... ) 

213 

214 Note: 

215 Reference implementation: Megatron-LM megatron/core/transformer/moe/moe_utils.py 

216 uses TP×CP×DP group synchronization for global batch statistics. 

217 Model adapters may provide ``expert_bias_update_groups`` and 

218 ``expert_bias_update_rate`` to override generic groups and update speed. 

219 """ 

220 groups = getattr(moe, "expert_bias_update_groups", None) 

221 if groups is None: 

222 groups = (tp_group, cp_group, dp_group) 

223 for group in groups: 

224 if group is not None: 

225 dist.all_reduce(moe.tokens_per_expert, group=getattr(group, "group", group)) 

226 

227 moe.update_expert_bias( 

228 lr=getattr(moe, "expert_bias_update_rate", lr), 

229 num_recomputations=num_recomputations, 

230 )