Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / losses / aux_loss.py: 72%

119 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"""MoE load balancing and shared auxiliary-loss gradient scaling.""" 

16 

17from __future__ import annotations 

18 

19from collections.abc import Iterator 

20from contextlib import contextmanager 

21from contextvars import ContextVar 

22from dataclasses import dataclass, field 

23from typing import Any 

24 

25import torch 

26import torch.distributed as dist 

27from torch.nn import functional as F 

28 

29from hyper_parallel.core.dtensor.dtensor import DTensor, SkipDTensorDispatch 

30from hyper_parallel.core.utils.communication import differentiable_all_reduce 

31 

32 

33def sequence_load_balancing_loss( 

34 scores: torch.Tensor, 

35 selected_experts: torch.Tensor, 

36 sequence_ids: torch.Tensor, 

37 num_sequences: int, 

38 token_mask: torch.Tensor | None = None, 

39 sequence_partition_groups: tuple[Any, ...] = (), 

40) -> torch.Tensor: 

41 """Average ``E * sum_i(fraction_i * mean_probability_i)`` over sequences. 

42 

43 Args: 

44 scores: Nonnegative, unbiased scores for all experts, shaped ``[T, E]``. 

45 selected_experts: Expert IDs used for balancing assignment fractions, shaped ``[T, K]``. 

46 sequence_ids: Logical sample index of each token, shaped ``[T]``. 

47 num_sequences: Global number of samples shared by the token-partition ranks. 

48 token_mask: Optional boolean ``[T]`` mask; true tokens contribute. 

49 sequence_partition_groups: Independent axes partitioning the same 

50 sequences' tokens. Never include a data-parallel/expert-dispatch 

51 group. Probability sums use a differentiable SUM all-reduce; 

52 callers must account for replicated losses in gradient reduction. 

53 

54 Returns: 

55 Unweighted mean over nonempty sequences. Empty or fully masked inputs 

56 return a differentiable zero, including when a local shard is empty. 

57 """ 

58 if scores.ndim != 2 or selected_experts.ndim != 2 or scores.shape[0] != selected_experts.shape[0]: 

59 raise ValueError("scores and selected_experts must have shapes [T, E] and [T, K]") 

60 num_tokens, num_experts = scores.shape 

61 if num_sequences <= 0 or sequence_ids.shape != (num_tokens,) or sequence_ids.dtype != torch.long: 

62 raise ValueError("sequence_ids must be int64 [T] and num_sequences must be positive") 

63 top_k = selected_experts.shape[1] 

64 if not 0 < top_k <= num_experts: 

65 raise ValueError("top_k must be positive and no greater than num_experts") 

66 if token_mask is not None and (token_mask.shape != (num_tokens,) or token_mask.dtype != torch.bool): 

67 raise ValueError("token_mask must be a boolean tensor with shape [T]") 

68 scores = scores.float() 

69 probabilities = scores / scores.sum(dim=-1, keepdim=True).clamp_min(torch.finfo(torch.float32).tiny) 

70 valid = torch.ones(num_tokens, device=scores.device, dtype=torch.float32) 

71 if token_mask is not None: 

72 valid = token_mask.to(dtype=torch.float32) 

73 indices = sequence_ids.unsqueeze(-1) * num_experts + selected_experts 

74 counts = scores.new_zeros(num_sequences * num_experts).scatter_add( 

75 0, indices.reshape(-1), valid.unsqueeze(-1).expand(-1, top_k).reshape(-1), 

76 ).view(num_sequences, num_experts) 

77 probability_sum = scores.new_zeros(num_sequences, num_experts).index_add( 

78 0, sequence_ids, probabilities * valid.unsqueeze(-1), 

79 ) 

80 for group in sequence_partition_groups: 

81 dist.all_reduce(counts, group=group) 

82 probability_sum = differentiable_all_reduce(probability_sum, "sum", group) 

83 assignments = counts.sum(dim=-1, keepdim=True) 

84 token_count = (assignments / top_k).clamp_min(1.0) 

85 losses = num_experts * ((counts / assignments.clamp_min(1.0)) * (probability_sum / token_count)).sum(-1) 

86 return losses.sum() / (assignments > 0).sum().clamp_min(1) 

87 

88 

89def token_choice_load_balancing_loss( 

90 router_logits: tuple[torch.Tensor, ...], num_experts: int, top_k: int, attention_mask: torch.Tensor | None = None 

91) -> torch.Tensor: 

92 """Compute the token-choice objective used by Qwen3-MoE chunked loss in PR #1652. 

93 

94 Pool statistics across router layers and valid tokens. Probabilities retain 

95 the source logit dtype, and counts and probability sums accumulate in FP32. 

96 

97 Args: 

98 router_logits: Per-layer router logits of shape [tokens, num_experts]. 

99 num_experts: Number of routed experts per layer. 

100 top_k: Number of experts selected per token. 

101 attention_mask: Optional [batch, sequence] mask with 1 for valid tokens. 

102 

103 Returns: 

104 Scalar auxiliary loss before applying the model's coefficient. 

105 """ 

106 if not isinstance(router_logits, tuple) or not router_logits: 

107 raise ValueError("router_logits must contain at least one layer") 

108 if not 0 < top_k <= num_experts: 

109 raise ValueError("top_k must be positive and no larger than num_experts") 

110 device = router_logits[0].device 

111 assignments = torch.zeros(num_experts, dtype=torch.float32, device=device) 

112 probability_sum = torch.zeros_like(assignments) 

113 rows = 0.0 

114 valid = None 

115 if attention_mask is not None: 

116 if attention_mask.ndim != 2: 

117 raise ValueError("padding mask must have shape [batch, sequence]") 

118 valid = attention_mask.reshape(-1).to(device=device, dtype=torch.float32) 

119 for logits in router_logits: 

120 if logits.ndim != 2 or logits.shape[1] != num_experts: 

121 raise ValueError("router logits must have shape [tokens, num_experts]") 

122 if valid is not None and valid.numel() != logits.shape[0]: 

123 raise ValueError("padding mask must cover every token in each router layer") 

124 probabilities = F.softmax(logits.to(device), dim=-1) 

125 selected = probabilities.topk(top_k, dim=-1).indices 

126 if valid is None: 

127 counts = torch.bincount(selected.reshape(-1), minlength=num_experts).float() 

128 probability_sum = probability_sum + probabilities.float().sum(dim=0) 

129 rows = rows + logits.shape[0] 

130 else: 

131 counts = torch.zeros_like(assignments).scatter_add_(0, selected.reshape(-1), valid.repeat_interleave(top_k)) 

132 probability_sum = probability_sum + (probabilities.float() * valid[:, None]).sum(dim=0) 

133 rows = rows + valid.sum() 

134 assignments = assignments + counts 

135 rows = torch.as_tensor(rows, dtype=torch.float32, device=device).clamp_min(1.0) 

136 return ((assignments / rows) * (probability_sum / rows)[None, :]).sum() * num_experts 

137 

138 

139@dataclass 

140class _AuxLossScaleState: 

141 """Per-forward scale, shared with its backward and recomputation.""" 

142 

143 scale: torch.Tensor | float = 1.0 

144 active: bool = False 

145 handles: list[Any] = field(default_factory=list) 

146 

147 

148_AUX_LOSS_STATE: ContextVar[_AuxLossScaleState | None] = ContextVar("aux_loss_state", default=None) 

149 

150 

151@contextmanager 

152def aux_loss_scale_context(scale: torch.Tensor | float = 1.0) -> Iterator[None]: 

153 """Isolate auxiliary gradient scaling for one forward/backward microstep. 

154 

155 Call :func:`bind_aux_loss_scale` on the local scalar task loss before 

156 weighting it. Keep this context active through backward so checkpoint 

157 recomputation observes the same scale. Nested contexts are independent. 

158 

159 Args: 

160 scale: Initial gradient multiplier for stages that do not compute the task loss. 

161 """ 

162 state = _AuxLossScaleState(scale=scale) 

163 token = _AUX_LOSS_STATE.set(state) 

164 try: 

165 yield 

166 finally: 

167 for handle in state.handles: 

168 handle.remove() 

169 _AUX_LOSS_STATE.reset(token) 

170 

171 

172def bind_aux_loss_scale(loss: torch.Tensor) -> None: 

173 """Make injected losses follow the scalar task loss's backward multiplier. 

174 

175 This is a no-op outside :func:`aux_loss_scale_context` or when no auxiliary 

176 loss was attached. The hook runs before upstream model backward, including 

177 checkpoint recomputation, and never changes the task-loss gradient. 

178 

179 Args: 

180 loss: Unweighted scalar foundation loss connected to the model output. 

181 """ 

182 state = _AUX_LOSS_STATE.get() 

183 if state is None or not state.active or not loss.requires_grad: 

184 return 

185 if loss.numel() != 1: 

186 raise ValueError("Auxiliary gradient scaling requires a scalar task loss") 

187 

188 def save_scale(gradient: torch.Tensor) -> None: 

189 """Capture the actual multiplier after token and parallel weighting. 

190 

191 Args: 

192 gradient: Upstream scalar loss multiplier, possibly a DTensor. 

193 """ 

194 with SkipDTensorDispatch(): 

195 local_gradient = gradient.to_local() if isinstance(gradient, DTensor) else gradient 

196 state.scale = local_gradient.detach() 

197 

198 state.handles.append(loss.register_hook(save_scale)) 

199 

200 

201class _AuxLossAutoScaler(torch.autograd.Function): 

202 """Inject auxiliary-loss gradients without changing the forward loss value.""" 

203 

204 main_loss_backward_scale = torch.tensor(1.0) 

205 

206 @staticmethod 

207 def forward(ctx: Any, output: torch.Tensor, aux_loss: torch.Tensor) -> torch.Tensor: 

208 """Save the auxiliary loss and return the output unchanged. 

209 

210 Args: 

211 ctx: Autograd context for the auxiliary loss and scale state. 

212 output: Forward tensor carrying the injected gradient. 

213 aux_loss: Scalar objective whose gradient is injected in backward. 

214 """ 

215 ctx.save_for_backward(aux_loss) 

216 ctx.scale_state = _AUX_LOSS_STATE.get() 

217 return output 

218 

219 @staticmethod 

220 def backward(ctx: Any, grad_output: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: 

221 """Pass through the output gradient and inject the auxiliary-loss gradient. 

222 

223 Args: 

224 ctx: Context saved by forward. 

225 grad_output: Unchanged gradient returned to the forward tensor. 

226 """ 

227 (aux_loss,) = ctx.saved_tensors 

228 scale = ( 

229 ctx.scale_state.scale if ctx.scale_state is not None 

230 else _AuxLossAutoScaler.main_loss_backward_scale 

231 ) 

232 if isinstance(scale, torch.Tensor): 

233 scale = scale.to(device=aux_loss.device, dtype=aux_loss.dtype) 

234 aux_loss_grad = torch.ones_like(aux_loss) * scale 

235 return grad_output, aux_loss_grad 

236 

237 @staticmethod 

238 def set_loss_scale(scale: torch.Tensor) -> None: 

239 """Set the auxiliary-loss gradient scale.""" 

240 _AuxLossAutoScaler.main_loss_backward_scale = scale 

241 

242 

243def aux_loss_auto_scale(output: torch.Tensor, aux_loss: torch.Tensor) -> torch.Tensor: 

244 """Attach an auxiliary-loss gradient to an unchanged forward tensor. 

245 

246 Args: 

247 output: Main forward output. 

248 aux_loss: Scalar auxiliary loss whose gradient should be injected. 

249 

250 Returns: 

251 ``output`` unchanged in value, with an autograd edge to ``aux_loss``. 

252 """ 

253 state = _AUX_LOSS_STATE.get() 

254 if state is not None: 

255 state.active = True 

256 return _AuxLossAutoScaler.apply(output, aux_loss) 

257 

258 

259def set_aux_loss_scale(scale: torch.Tensor) -> None: 

260 """Set the gradient multiplier used by :func:`aux_loss_auto_scale`. 

261 

262 Args: 

263 scale: Tensor used to scale the injected auxiliary-loss gradient. 

264 """ 

265 _AuxLossAutoScaler.set_loss_scale(scale)