Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / distributed / expert_parallel / routing.py: 62%
159 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# ============================================================================
16"""expert_parallel.routing: MoE router adapters (05 §6.4.7, D-09).
18Routing semantics are model-specific (softmax/sigmoid, top-k normalization,
19scaling), while the expert MLP structure is uniform (SwiGLU). A factory picks
20an adapter from ``MOE_ROUTER_ADAPTERS`` BY NAME in its own code — the choice
21is explicit, never inferred. Each adapter maps
22``(module, hidden) -> (topk_idx [T,K] int64, topk_w [T,K] float)``.
24Benchmark-only balanced variants are derived from a real adapter with
25:func:`make_balanced_router` and registered as ``<adapter>_fixed``, so an
26archetype opts in with one flag (``fix_router``, see :func:`resolve_moe_router`)
27instead of carrying its own copy of the wrapper.
29Split out of components/distributed/ep_utils.py in stage 4e.
30"""
32import logging
33import math
34from typing import Optional
36import torch
38logger = logging.getLogger(__name__)
40# float32 represents every integer up to 2**24 exactly, so a smaller expert count
41# can use the AICore float sort.
42_SORT_KEY_FP32_LIMIT = 1 << 24
44_FP32_KEY_WARNED = False
47def _softmax_topk_router(module, hidden_states):
48 """default adapter: softmax -> topk -> normalize by sum (Mixtral/Qwen3 semantics).
50 top_k source: config.num_experts_per_tok / config.top_k / module.top_k (default 2);
51 normalization switch: config.norm_topk_prob (default True).
52 """
53 gate = getattr(module, "gate", None)
54 if gate is None:
55 gate = getattr(module, "router", None)
56 if gate is None:
57 raise AttributeError(
58 f"{type(module).__name__}: router not found (neither gate nor router "
59 "attribute exists); please register a custom MOE_ROUTER_ADAPTERS entry"
60 )
61 cfg = getattr(module, "config", None)
62 logits = gate(hidden_states)
63 logits = logits.view(-1, logits.shape[-1])
64 top_k = (getattr(cfg, "num_experts_per_tok", None)
65 or getattr(cfg, "top_k", None)
66 or getattr(module, "top_k", 2))
67 weights = logits.softmax(-1)
68 topk_w, topk_idx = weights.topk(int(top_k), dim=-1)
69 if getattr(cfg, "norm_topk_prob", True):
70 topk_w = topk_w / topk_w.sum(-1, keepdim=True).clamp_min(1e-20)
71 return topk_idx, topk_w
74def _topk_router_module(module, hidden_states):
75 """Adapt both tuple-returning TopKRouter and legacy linear gate modules."""
76 gate = getattr(module, "gate", None)
77 if gate is None:
78 gate = getattr(module, "router", None)
79 out = gate(hidden_states)
80 if isinstance(out, (tuple, list)) and len(out) == 3:
81 _, scores, indices = out
82 return indices, scores
83 if isinstance(out, torch.Tensor):
84 logits = out.reshape(-1, out.shape[-1])
85 config = getattr(module, "config", None)
86 top_k = (getattr(module, "top_k", None)
87 or getattr(config, "num_experts_per_tok", None)
88 or getattr(config, "top_k", None))
89 if top_k is None:
90 raise ValueError(f"{type(module).__name__}: linear router requires top_k")
91 weights = torch.softmax(logits, dim=-1, dtype=torch.float32)
92 scores, indices = weights.topk(int(top_k), dim=-1)
93 norm_topk_prob = getattr(module, "norm_topk_prob", None)
94 if norm_topk_prob is None:
95 norm_topk_prob = getattr(config, "norm_topk_prob", True)
96 if norm_topk_prob:
97 scores = scores / scores.sum(dim=-1, keepdim=True).clamp_min(1e-20)
98 return indices, scores.to(hidden_states.dtype)
99 raise TypeError(
100 f"{type(module).__name__}: router should return a Tensor or "
101 f"(logits, scores, indices), got {type(out).__name__}"
102 )
105def _mask_scores_by_group(scores, n_group, topk_group):
106 """Keep scores only in the highest-scoring expert groups."""
107 expert_count = scores.shape[-1]
108 group_scores = (
109 scores.view(-1, n_group, expert_count // n_group)
110 .topk(2, dim=-1)[0]
111 .sum(dim=-1)
112 )
113 group_indices = group_scores.topk(topk_group, dim=-1, sorted=False)[1]
114 group_mask = torch.zeros_like(group_scores)
115 group_mask.scatter_(1, group_indices, 1)
116 score_mask = (
117 group_mask.unsqueeze(-1)
118 .expand(-1, n_group, expert_count // n_group)
119 .reshape(-1, expert_count)
120 )
121 return scores.masked_fill(~score_mask.bool(), float("-inf"))
124def _sigmoid_group_router(module, hidden_states):
125 """deepseekv3/glm4moe adapter: sigmoid + e_score_correction_bias +
126 group-limited topk + (optional) normalization + routed_scaling_factor
127 (step-by-step consistent with HF DeepseekV3MoE.route_tokens_to_experts /
128 Glm4MoeMoE).
130 Parameter source: the module's own attributes take precedence
131 (n_group/topk_group/top_k/norm_topk_prob/routed_scaling_factor), falling
132 back to module.config; when n_group is missing or <=1, the group-limited
133 filter is skipped.
134 """
135 gate = getattr(module, "gate", None)
136 if gate is None:
137 gate = getattr(module, "router", None)
138 cfg = getattr(module, "config", None)
140 def _attr(name, default=None):
141 v = getattr(module, name, None)
142 if v is None and cfg is not None:
143 v = getattr(cfg, name, None)
144 return default if v is None else v
146 logits = gate(hidden_states)
147 if isinstance(logits, (tuple, list)):
148 logits = logits[0]
149 logits = logits.view(-1, logits.shape[-1]).float()
150 scores = logits.sigmoid()
151 bias = getattr(gate, "e_score_correction_bias", None)
152 scores_for_choice = scores + bias if bias is not None else scores
154 n_group = int(_attr("n_group", 0) or 0)
155 topk_group = int(_attr("topk_group", 0) or 0)
156 top_k = int(_attr("top_k", None) or _attr("num_experts_per_tok", 2))
157 if n_group > 1 and topk_group > 0:
158 scores_for_choice = _mask_scores_by_group(
159 scores_for_choice, n_group, topk_group
160 )
162 topk_idx = scores_for_choice.topk(top_k, dim=-1, sorted=False)[1]
163 topk_w = scores.gather(1, topk_idx)
164 if _attr("norm_topk_prob", False):
165 topk_w = topk_w / (topk_w.sum(dim=-1, keepdim=True) + 1e-20)
166 topk_w = topk_w * float(_attr("routed_scaling_factor", 1.0))
167 return topk_idx, topk_w
170def apply_capacity_limit(
171 topk_idx: "torch.Tensor",
172 capacity_factor: Optional[float],
173 num_experts: int,
174 weights: Optional["torch.Tensor"] = None,
175) -> tuple["torch.Tensor", "torch.Tensor"]:
176 """Capacity mask for a routed assignment (MoE token dropping).
178 Real routing is skewed: on the 2-SN benchmark the busiest rank has been measured at
179 **6x** the mean token count. A rank's expert buffers are sized by the rows it
180 receives, so that skew -- not the balanced case -- decides whether the step fits in
181 memory: at GBS 256 / seq 8192 the balanced peak is 41.5 GB while real routing reached
182 55.3 GiB and failed to allocate a 5.23 GiB expert output. Every *switch* that does not
183 change the routed row count (GBS, prefetch depth, ``swap_inputs``, ``overlap_shared_expert``,
184 even a 25% shorter sequence) bought at most 1.8 GB, because none of them bound the
185 busiest rank.
187 Capping each expert at ``capacity_factor x (T*K / E)`` slots bounds it directly, which is
188 the standard GShard/Switch/Megatron answer to routing skew. Tokens beyond capacity are
189 *dropped* (their contribution is removed), so this changes the model, exactly as it does
190 in those implementations; the returned drop rate is what makes the trade measurable.
192 Each expert keeps ``min(count_e, capacity)`` slots, prioritized by descending
193 routing weight. Without weights, the slots follow the expert-major order.
195 Args:
196 topk_idx: Routed expert per slot, shape ``[T, K]``.
197 capacity_factor: Multiplier on the mean load, or ``None`` to disable the cap.
198 num_experts: Total routed experts ``E``.
199 weights: Optional routing weights, shaped like ``topk_idx``.
201 Returns:
202 ``(keep, dropped)`` where ``keep`` is a bool tensor shaped like ``topk_idx`` and
203 ``dropped`` is the number of dropped slots as a 0-dim tensor on the plan's device.
205 Raises:
206 ValueError: If ``num_experts`` is not positive or the weights do not match the slots.
207 """
208 if capacity_factor is None or float(capacity_factor) <= 0:
209 return (
210 torch.ones_like(topk_idx, dtype=torch.bool),
211 torch.zeros((), dtype=torch.int64, device=topk_idx.device),
212 )
213 if num_experts <= 0:
214 raise ValueError(f"num_experts must be positive, got {num_experts}")
216 flat_expert = topk_idx.reshape(-1).to(torch.int64)
217 slots = flat_expert.numel()
218 capacity = int(math.ceil(float(capacity_factor) * slots / float(num_experts)))
219 keep_flat = torch.zeros_like(flat_expert, dtype=torch.bool)
220 if capacity > 0:
221 permutation = _slot_order(flat_expert, weights, num_experts)
222 counts = torch.bincount(flat_expert, minlength=num_experts)
223 starts = torch.cumsum(counts, dim=0) - counts
224 ranks = torch.arange(slots, device=flat_expert.device) - starts[flat_expert[permutation]]
225 keep_flat[permutation] = ranks < capacity
226 return keep_flat.view_as(topk_idx), (~keep_flat).sum()
229def _slot_order(
230 flat_expert: "torch.Tensor",
231 flat_weights: Optional["torch.Tensor"],
232 num_experts: int,
233) -> "torch.Tensor":
234 """Order slots by expert and by descending weight when available."""
235 if flat_weights is None:
236 return _expert_major_order(flat_expert, num_experts)
237 return _expert_score_order(flat_expert, flat_weights, num_experts)
240def _expert_score_order(
241 flat_expert: "torch.Tensor",
242 flat_weights: "torch.Tensor",
243 num_experts: int,
244) -> "torch.Tensor":
245 """Expert-major order that puts the heaviest slot of every expert first.
247 Both keys travel in ONE fp32 sort key: the integer part is the expert index and the
248 fractional part carries the inverted, normalized weight, so a heavier slot always sorts
249 earlier and the fraction can never carry into the next expert. The single key uses the
250 same AICore float sort as the expert-major order.
252 Resolution limit: fp32 spends the integer part's exponent on the expert index, so the
253 fractional step is about ``2**-15`` around ``num_experts = 2**8..2**9`` (and ``2**-11``
254 around ``2**12``). Weights closer together than that, relative to the plan's spread, tie
255 and their relative order is arbitrary -- the *count* kept per expert, which is what bounds
256 the busiest rank, remains exact.
258 Args:
259 flat_expert: Expert index of every routed slot, shape ``[T*K]``.
260 flat_weights: Routing weight of every slot, same shape.
261 num_experts: Size of the expert index space.
263 Returns:
264 An int64 permutation of ``range(flat_expert.numel())``.
266 Raises:
267 ValueError: If ``flat_weights`` does not carry exactly one weight per slot.
268 """
269 if flat_weights.numel() != flat_expert.numel():
270 raise ValueError(
271 f"weights must have one entry per slot: got {flat_weights.numel()} for "
272 f"{flat_expert.numel()} slots"
273 )
274 if not 0 < num_experts <= _SORT_KEY_FP32_LIMIT:
275 global _FP32_KEY_WARNED # pylint: disable=global-statement
276 if not _FP32_KEY_WARNED:
277 _FP32_KEY_WARNED = True
278 logger.warning(
279 "Capacity ranking needs the expert index to be exact in a float32 "
280 "key, but num_experts=%d is outside (0, 2**24]; keeping the expert-major order",
281 num_experts,
282 )
283 return _expert_major_order(flat_expert, num_experts)
284 weight = flat_weights.reshape(-1).to(torch.float32)
285 inverted = weight.max() - weight
286 # ``clamp_min`` rather than a host-side ``if span == 0``: reading the span would drain the
287 # device, and this runs once per MoE layer. A zero span leaves every ``inverted`` at zero,
288 # so the fraction stays zero and the expert-major order stands. ``0 * inf`` cannot happen:
289 # a zero span means ``inverted`` is exactly zero.
290 span = inverted.max().clamp_min(torch.finfo(weight.dtype).tiny)
291 # One multiply-add instead of three elementwise passes: ``expert + inverted * 0.5 / span``.
292 key = torch.addcmul(flat_expert.to(torch.float32), inverted, 0.5 / span)
293 return key.argsort()
296def _expert_major_order(flat_expert: "torch.Tensor", num_experts: int) -> "torch.Tensor":
297 """Return the permutation that groups slots by expert.
299 Integer ``argsort`` has no AICore kernel on this stack, so keys are cast to float32 when the
300 expert count is exactly representable. Ties inside one expert may then be ordered
301 arbitrarily rather than by token: the *count* kept per expert -- which is what bounds the
302 busiest rank's memory -- is unaffected, and the result is still deterministic for a given
303 input and backend.
305 Args:
306 flat_expert: Expert index of every routed slot, shape ``[T*K]``.
307 num_experts: Size of the expert index space.
309 Returns:
310 An int64 permutation of ``range(flat_expert.numel())`` ordering slots by expert.
311 """
312 if 0 < num_experts <= _SORT_KEY_FP32_LIMIT:
313 return flat_expert.to(torch.float32).argsort()
314 return torch.argsort(flat_expert, stable=True)
317def _global_expert_count(module):
318 """Model-level routed expert count (mirrors ``experts._get_global_expert_count``).
320 Kept local so this module stays a torch-only leaf (it is imported by
321 model adapters that do not want the expert compute machinery).
322 """
323 for owner in (getattr(module, "experts", None), module):
324 count = getattr(owner, "num_experts", None)
325 if count is not None:
326 return int(count)
327 cfg = getattr(module, "config", None)
328 for name in ("num_experts", "n_routed_experts"):
329 count = getattr(cfg, name, None)
330 if count is not None:
331 return int(count)
332 raise ValueError(
333 f"{type(module).__name__}: cannot determine the global routed expert count"
334 )
337def _balanced_expert_indices(
338 token_count: int,
339 experts_per_token: int,
340 expert_count: int,
341 local_count: int,
342 *,
343 device,
344) -> "torch.Tensor":
345 """Round-robin the ``T*K`` slots over the DESTINATION ranks.
347 Local slot ``i`` goes to one of the ``L`` experts owned by destination
348 ``i mod Q`` (``Q = E/L``), so every rank receives exactly ``T*K/Q`` slots
349 instead of a data-dependent count.
351 Spreading by *rank* rather than by expert is what makes this exact: the
352 per-expert token count cannot be made uniform at all when ``E`` does not
353 divide ``T*K``, and a per-expert round robin (``i mod E``) replays the same
354 residue pattern on every rank, so the leftover slots pile onto the same
355 fixed group of ranks (measured: 0.8% above the mean on the busiest rank,
356 2.4% spread between rank groups). Going through the destination first
357 absorbs that leftover per rank instead.
359 Args:
360 token_count: Local tokens ``T``.
361 experts_per_token: Routed experts per token ``K``.
362 expert_count: Global routed experts ``E``.
363 local_count: Experts this rank owns ``L``.
364 device: Device for the returned index tensor.
366 Returns:
367 ``[T, K]`` int64 indices naming the expert each slot is routed to.
369 Raises:
370 ValueError: If ``E`` is not divisible by ``L``.
371 """
372 if local_count <= 0 or expert_count % local_count != 0:
373 raise ValueError(
374 f"num_experts ({expert_count}) must be divisible by the local "
375 f"expert count ({local_count})"
376 )
377 destinations = expert_count // local_count
378 slots = torch.arange(token_count * experts_per_token, device=device)
379 indices = (slots % destinations) * local_count + (slots // destinations) % local_count
380 return indices.view(token_count, experts_per_token)
383def make_balanced_router(real_router):
384 """Wrap ``real_router`` in a benchmark-only variant with a uniform expert load.
386 The real adapter still runs -- so its weights stay differentiable and the
387 router GEMM stays in the compute profile -- but the chosen experts are
388 replaced by a round-robin assignment that spreads the local slots over the
389 **destination ranks** (see :func:`_balanced_expert_indices`). Every rank
390 therefore receives exactly ``T*K/Q`` tokens instead of a data-dependent
391 count, whatever routing semantics ``real_router`` implements.
393 Why: unbalanced routing is the dominant source of step-time jitter on MoE
394 training runs -- the slowest rank in a step is the one whose experts drew
395 the most tokens, so identical configurations can differ by tens of percent
396 step to step. Measured on the 293B/18-layer config, the real router put
397 **6.3x** the mean token count on the busiest rank (leaving some experts
398 empty) while the balanced one stayed at 1.00x. Flattening the load makes a
399 step-to-step comparison converge in 2-3 steps instead of needing a dozen,
400 which is what makes small (1-3%) kernel-level effects measurable at all.
402 **Benchmark-only.** The assignment ignores the gate scores, so:
404 - ``loss`` / ``grad_norm`` / any convergence signal is meaningless here;
405 - expert hit distributions and "effective MFU" are optimistic (the load is
406 artificially flat), so numbers from this mode must not be reported as an
407 efficiency result.
409 Correctness must be validated with the switch OFF (``fix_router: False``),
410 where ``real_router`` runs unchanged. The true ``topk_w`` are kept so the
411 gate still receives gradient.
413 Args:
414 real_router: A ``(module, hidden) -> (topk_idx, topk_w)`` adapter, e.g.
415 any entry of :data:`MOE_ROUTER_ADAPTERS`.
417 Returns:
418 A ``(module, hidden) -> (topk_idx, topk_w)`` adapter with a uniform
419 destination load; its ``__name__`` records the wrapped adapter.
420 """
422 def balanced_router(module, hidden_states):
423 """Run ``real_router`` and replace its destinations round-robin."""
424 topk_idx, topk_w = real_router(module, hidden_states)
425 token_count, experts_per_token = topk_idx.shape
426 balanced_idx = _balanced_expert_indices(
427 int(token_count),
428 int(experts_per_token),
429 _global_expert_count(module),
430 # Set by the EP binder (bind_local_expert_forward) before any forward; a
431 # missing value degrades to a plain per-expert round robin.
432 int(getattr(getattr(module, "experts", None),
433 "local_expert_count", None) or 1),
434 device=topk_idx.device,
435 )
436 return balanced_idx.to(topk_idx.dtype), topk_w
438 # A callable object or a functools.partial has no ``__name__``; its class name is
439 # then the most informative thing the log line can carry.
440 real_name = getattr(real_router, "__name__", None) or type(real_router).__name__
441 balanced_router.__name__ = f"balanced_{real_name}"
442 balanced_router.__doc__ = (
443 f"Benchmark-only variant of ``{real_name}`` with a uniform destination "
444 "load (see :func:`make_balanced_router`)."
445 )
446 return balanced_router
449MOE_ROUTER_ADAPTERS = {
450 "softmax_topk": _softmax_topk_router,
451 "topk_router_module": _topk_router_module,
452 "sigmoid_group": _sigmoid_group_router,
453 "default": _softmax_topk_router,
454 "qwen2moe": _topk_router_module,
455 "qwen2_moe": _topk_router_module,
456 "qwen3moe": _topk_router_module,
457 "qwen3_moe": _topk_router_module,
458 "mixtral": _topk_router_module,
459 "deepseekv3": _sigmoid_group_router,
460 "deepseek_v3": _sigmoid_group_router,
461 "glm4moe": _sigmoid_group_router,
462 "glm4_moe": _sigmoid_group_router,
463}
465# One balanced wrapper per distinct real adapter, published as ``<name>_fixed`` for
466# every alias: the convention ``fix_router`` resolves through.
467_BALANCED_VARIANTS = {
468 adapter: make_balanced_router(adapter)
469 for adapter in dict.fromkeys(MOE_ROUTER_ADAPTERS.values())
470}
471# The archived benchmark router: the balanced wrapper over the sigmoid-group adapter,
472# kept as a module-level name because the recipes' docs and the earlier 2-SN sweeps
473# refer to it.
474_balanced_router = _BALANCED_VARIANTS[_sigmoid_group_router]
475for _alias, _adapter in list(MOE_ROUTER_ADAPTERS.items()):
476 MOE_ROUTER_ADAPTERS[f"{_alias}_fixed"] = _BALANCED_VARIANTS[_adapter]
477del _alias, _adapter
480def resolve_moe_router(router, fix_router: bool = False):
481 """Resolve a router adapter, optionally to its benchmark-only balanced variant.
483 ``fix_router`` is the switch every archetype factory exposes; it has to mean the
484 same thing everywhere, so it is resolved here rather than re-implemented per
485 factory (see :func:`make_balanced_router` for what it does and why its numbers are
486 not efficiency results).
488 Args:
489 router: An adapter callable, or the name of an entry in
490 :data:`MOE_ROUTER_ADAPTERS`.
491 fix_router: When true, return the balanced variant: the ``<name>_fixed``
492 registry entry for a name, or ``make_balanced_router(router)`` for a
493 callable.
495 Returns:
496 A ``(module, hidden) -> (topk_idx, topk_w)`` adapter.
498 Raises:
499 KeyError: If ``router`` is a name that is not registered.
500 TypeError: If ``router`` is neither a registry name nor callable.
501 """
502 if isinstance(router, str):
503 key = f"{router}_fixed" if fix_router else router
504 return MOE_ROUTER_ADAPTERS[key]
505 if not callable(router):
506 raise TypeError(
507 "router must be a registry name or a callable, got "
508 f"{type(router).__name__}"
509 )
510 return make_balanced_router(router) if fix_router else router