Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / distributed / expert_parallel / experts.py: 80%
235 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 2025-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.experts: EP expert execution and binding.
18- Routed-experts pipeline (``ep_routed_forward``, 05 §6.4.8): router (local
19 chunk) -> a2a dispatch (extended EP group) -> local SwiGLU (complete
20 expert weights, no internal communication) -> a2a combine -> weighted
21 aggregation. SP-in -> SP-out, all communication cohesive inside. NO
22 shared-expert/gate branch — that composition is the caller's job.
23- Expert entry point (``bind_local_expert_forward`` /
24 ``resolve_swiglu_weights``): installs ``experts.forward`` (via the forward
25 rewriter's bound-forward install point, 05 §15.2.3) so nested FSDP hooks
26 unshard/reshard around the local SwiGLU.
27- Interface helpers (``require_attrs`` / ``describe_moe_module``):
28 build-time interface assertions with teaching errors, and a structural
29 diagnostic for mapping a concrete MoE module to an archetype.
31Nothing in this module probes model structure with getattr fallback chains.
32Split out of components/distributed/ep_utils.py in stage 4e.
33"""
35from dataclasses import dataclass
36from typing import Any, Callable, NamedTuple, Optional
37import torch
38import torch.distributed as dist
39import torch.nn.functional as F
41from hyper_parallel.components.functional.npu_grouped_swiglu import (
42 npu_grouped_swiglu,
43)
44from hyper_parallel.distributed.expert_parallel._tracing import expert_parallel_region
45from hyper_parallel.distributed._builder.forward_rewriter import (
46 _install_bound_forward,
47)
48from hyper_parallel.distributed.expert_parallel.routing import (
49 apply_capacity_limit,
50)
51from hyper_parallel.distributed.expert_parallel.collectives import (
52 ep_exchange_counts,
53 ep_all_to_all,
54 ep_all_to_all_async,
55 ep_split_sizes,
56)
59_SORT_KEY_FP32_LIMIT = 2**24
62@dataclass(frozen=True)
63class _EPDispatch:
64 """Prepared tensors and split sizes for one routed expert exchange."""
66 source_indices: torch.Tensor
67 expert_weights: torch.Tensor
68 dispatch_order: torch.Tensor
69 states: torch.Tensor
70 expert_indices: torch.Tensor
71 send_counts: list[int]
72 receive_counts: list[int]
73 unpermute_indices: Optional[torch.Tensor] = None
74 routing_weights: Optional[torch.Tensor] = None
77def resolve_swiglu_weights(
78 experts: Any,
79) -> tuple[torch.Tensor, Optional[torch.Tensor], torch.Tensor]:
80 """Resolve SwiGLU weights from the stacked holder (three layouts).
82 Returns (w_gate, w_up, w_down):
83 - Separate naming: gate_proj/up_proj/down_proj or w1/w3/w2 (all
84 [E, I, H]/[E, H, I]);
85 - **fused layout** (after the HF 2025 refactor, D-11): gate_up_proj
86 [E, 2I, H] + down_proj [E, H, I] -> returns (gate_up_proj, None,
87 down_proj); w_up=None marks the fused case (the compute side chunks
88 out gate/up).
89 """
90 w_fused = getattr(experts, "gate_up_proj", None)
91 if w_fused is None:
92 w_fused = getattr(experts, "gate_and_up_projs", None)
93 w_down = getattr(experts, "down_proj", None)
94 w_down = w_down if w_down is not None else getattr(experts, "down_projs", None)
95 w_down = w_down if w_down is not None else getattr(experts, "w2", None)
96 if w_fused is not None and w_down is not None:
97 return w_fused, None, w_down
99 w_gate = getattr(experts, "gate_proj", None)
100 w_gate = w_gate if w_gate is not None else getattr(experts, "w1", None)
101 w_up = getattr(experts, "up_proj", None)
102 w_up = w_up if w_up is not None else getattr(experts, "w3", None)
103 if w_gate is None or w_up is None or w_down is None:
104 raise NotImplementedError(
105 f"{type(experts).__name__}: only SwiGLU experts are supported "
106 "(fused gate_up_proj, or separate gate_proj/up_proj/down_proj, "
107 "w1/w2/w3 three-matrix layouts); use an EP-aware MoE module instead"
108 )
109 return w_gate, w_up, w_down
112def _argsort_keys(keys: torch.Tensor, *, bound: int) -> torch.Tensor:
113 """Sort nonnegative expert IDs below ``bound`` without losing precision."""
114 # Ascend can use an AICore sort when the integer IDs are exact in FP32.
115 if 0 < bound <= _SORT_KEY_FP32_LIMIT:
116 return keys.to(torch.float32).argsort()
117 return keys.argsort()
120def _expert_token_counts(indices: torch.Tensor, num_experts: int) -> torch.Tensor:
121 """Count routed tokens per expert with device ops only.
123 ``torch.bincount`` on NPU reads the input's min and max back to the host
124 (input validation and output sizing), so every call drains the device queue
125 and blocks the host. The counts here are consumed either fully on device
126 (grouped GEMM group list) or -- where the ragged all-to-all genuinely needs
127 them -- as a single host list, so accumulating them with ``scatter_add_``
128 keeps the same values at one device kernel and no host stall.
130 Args:
131 indices: Expert indices, any shape; values must be in ``[0, num_experts)``.
132 num_experts: Length of the returned histogram (``minlength``).
134 Returns:
135 int64 counts of shape ``[num_experts]`` on ``indices.device``.
136 """
137 flat = indices.to(torch.int64).reshape(-1)
138 counts = torch.zeros(num_experts, dtype=torch.int64, device=flat.device)
139 return counts.scatter_add_(0, flat, torch.ones_like(flat))
142def _local_swiglu_expert_forward(experts, dispatched_states, local_expert_indices):
143 """Compute dispatched tokens with the local stacked SwiGLU experts.
145 This function is installed as ``experts.forward`` for the HF-native EP
146 path. Calling the expert module, instead of indexing its parameters from
147 the parent MoE forward, allows nested FSDP forward hooks to unshard and
148 reshard expert parameters around the local computation.
149 """
150 token_order = _argsort_keys(local_expert_indices, bound=experts.local_expert_count)
151 sorted_states = dispatched_states[token_order]
152 local_expert_counts = _expert_token_counts(
153 local_expert_indices, experts.local_expert_count)
154 if getattr(experts, "_ep_use_grouped_gemm", False):
155 grouped_forward = getattr(experts, "forward_expert_major", None)
156 if callable(grouped_forward):
157 sorted_output = grouped_forward(sorted_states, local_expert_counts)
158 else:
159 gate_weight, up_weight, down_weight = resolve_swiglu_weights(experts)
160 if up_weight is not None:
161 raise ValueError(
162 "EP grouped GEMM currently requires packed gate_up_proj weights"
163 )
164 sorted_output = npu_grouped_swiglu(
165 sorted_states,
166 gate_weight,
167 down_weight,
168 local_expert_counts,
169 )
170 output = torch.empty_like(sorted_output)
171 output[token_order] = sorted_output
172 return output
174 gate_weight, up_weight, down_weight = resolve_swiglu_weights(experts)
175 # The eager path needs host ints: read them in one transfer rather than
176 # draining the queue once per local expert.
177 expert_token_counts = local_expert_counts.tolist()
178 sorted_outputs = []
179 token_start = 0
180 for local_expert_index in range(experts.local_expert_count):
181 expert_token_count = expert_token_counts[local_expert_index]
182 expert_states = sorted_states[token_start:token_start + expert_token_count]
183 if up_weight is None:
184 gate_up_states = F.linear( # pylint: disable=not-callable
185 expert_states,
186 gate_weight[local_expert_index],
187 )
188 apply_gate = getattr(experts, "_ep_apply_gate", None)
189 if apply_gate is None:
190 gate_states, up_states = gate_up_states.chunk(2, dim=-1)
191 activation = getattr(experts, "_ep_act_fn", F.silu)
192 activated_states = activation(gate_states) * up_states
193 else:
194 activated_states = apply_gate(gate_up_states)
195 else:
196 gate_states = F.linear( # pylint: disable=not-callable
197 expert_states, gate_weight[local_expert_index]
198 )
199 up_states = F.linear( # pylint: disable=not-callable
200 expert_states, up_weight[local_expert_index]
201 )
202 activation = getattr(experts, "_ep_act_fn", F.silu)
203 activated_states = activation(gate_states) * up_states
204 sorted_outputs.append(
205 F.linear( # pylint: disable=not-callable
206 activated_states,
207 down_weight[local_expert_index],
208 )
209 )
210 token_start += expert_token_count
212 sorted_output = torch.cat(sorted_outputs)
213 output = torch.empty_like(sorted_output)
214 output[token_order] = sorted_output
215 return output
218def _get_global_expert_count(module):
219 """Return the model-level routed expert count for an MoE module."""
220 if hasattr(module.experts, "num_experts"):
221 return module.experts.num_experts
222 if hasattr(module, "num_experts"):
223 return module.num_experts
224 if hasattr(module, "config") and hasattr(module.config, "num_experts"):
225 return module.config.num_experts
226 if hasattr(module, "config") and hasattr(module.config, "n_routed_experts"):
227 return module.config.n_routed_experts
228 raise ValueError(
229 f"{type(module).__name__}: cannot determine the global routed expert count"
230 )
233def bind_local_expert_forward(
234 module: Any,
235 ep_size: int,
236 use_grouped_gemm: bool = False,
237 apply_gate: Optional[Callable] = None,
238) -> None:
239 """Install the local expert compute entry used by TP-extend-EP.
241 Called by the EP compute factory (archetype or user-written) at apply
242 time: sets ``module.experts.local_expert_count`` and installs
243 ``experts.forward`` (via the forward rewriter's bound-forward install
244 point) so nested FSDP hooks unshard/reshard around the local SwiGLU
245 computation. ``apply_gate`` supplies model-specific fused gate/up
246 semantics when the default activation-times-up rule is insufficient.
247 """
248 if getattr(module.experts, "requires_ep_grouped_gemm", False) and not use_grouped_gemm:
249 raise ValueError(
250 f"{type(module.experts).__name__} requires use_grouped_gemm=True in the EP method replacement"
251 )
252 global_expert_count = _get_global_expert_count(module)
253 if global_expert_count % ep_size != 0:
254 raise ValueError(
255 f"num_experts ({global_expert_count}) must be divisible by ep_size ({ep_size})"
256 )
257 module.experts.local_expert_count = global_expert_count // ep_size
258 activation = getattr(module.experts, "act_fn", None)
259 if activation is None:
260 hidden_act = getattr(getattr(module, "config", None), "hidden_act", "silu")
261 activation = {
262 "gelu": F.gelu,
263 "relu": F.relu,
264 "silu": F.silu,
265 "swish": F.silu,
266 }.get(hidden_act)
267 if activation is None:
268 raise ValueError(
269 f"{type(module).__name__}: unsupported expert activation {hidden_act!r}; "
270 "provide experts.act_fn or extend the EP activation registry"
271 )
272 if apply_gate is not None and use_grouped_gemm:
273 raise ValueError("custom expert gate activation is not supported by grouped GEMM")
274 # ``_ep_*`` is the contract the local compute path reads back off the module's
275 # experts child; setting them here is the point of the binder.
276 # pylint: disable=protected-access
277 module.experts._ep_act_fn = activation
278 module.experts._ep_apply_gate = apply_gate
279 module.experts._ep_use_grouped_gemm = use_grouped_gemm
280 # The forward write itself lives in the forward rewriter (05 §15.2.3:
281 # the single MethodType/assignment site); this binder only sets the
282 # companion attributes above.
283 _install_bound_forward(module.experts, _local_swiglu_expert_forward)
286def _resolve_capacity_factor(module: Any) -> Optional[float]:
287 """Read the configured expert capacity multiplier."""
288 value = getattr(getattr(module, "experts", None), "capacity_factor", None)
289 if value is None:
290 return None
291 value = float(value)
292 return value if value > 0 else None
295def _routed_slot_token_ids(
296 token_count: int, experts_per_token: int, device: Any,
297) -> torch.Tensor:
298 """Return the source token of every routed slot, as an index tensor.
300 Slot ``token * K + i`` holds the source index ``token``.
302 Args:
303 token_count: Number of local tokens ``T`` in this dispatch.
304 experts_per_token: Routed experts per token ``K``.
305 device: Device to build the tensor on.
307 Returns:
308 Contiguous int64 tensor of shape ``[T * K]``.
310 """
311 # Make a contiguous buffer even for a single token with multiple slots.
312 return (
313 torch.arange(token_count, device=device)
314 .unsqueeze(1)
315 .expand(token_count, experts_per_token)
316 .reshape(-1)
317 .contiguous()
318 )
321def _prepare_ep_dispatch(
322 hidden_states: torch.Tensor,
323 topk_indices: torch.Tensor,
324 topk_weights: torch.Tensor,
325 *,
326 local_expert_count: int,
327 ep_size: int,
328 ep_group: Any,
329 keep: Optional[torch.Tensor] = None,
330 use_fused_moe_token_permute_and_unpermute: bool = False,
331) -> _EPDispatch:
332 """Sort routed tokens and exchange per-rank dispatch counts.
334 ``keep`` is an optional ``[T, K]`` bool mask (see
335 :func:`routing.apply_capacity_limit`). It compacts the routed slots *before* anything is
336 exchanged: dropped slots never become rows, which is the entire point of a capacity limit,
337 because a rank's expert buffers are sized by the rows it receives. The rest of the
338 pipeline is already ragged-safe -- the expert compute is row-based, and the combine
339 accumulates with ``index_add_`` over ``source_indices`` -- so a token with fewer than ``K``
340 surviving slots simply receives fewer contributions.
341 """
342 flattened_states = hidden_states.reshape(-1, hidden_states.shape[-1])
343 token_count = flattened_states.shape[0]
344 experts_per_token = topk_indices.shape[1]
345 if keep is None:
346 expert_indices = topk_indices.reshape(-1)
347 expert_weights = topk_weights.reshape(-1).to(dtype=flattened_states.dtype)
348 source_indices = _routed_slot_token_ids(
349 token_count, experts_per_token, flattened_states.device)
350 else:
351 flat_keep = keep.reshape(-1)
352 expert_indices = topk_indices.reshape(-1)[flat_keep]
353 expert_weights = topk_weights.reshape(-1)[flat_keep].to(dtype=flattened_states.dtype)
354 source_indices = _routed_slot_token_ids(
355 token_count, experts_per_token, flattened_states.device)[flat_keep]
356 use_fused_moe_token_permute_and_unpermute = (
357 use_fused_moe_token_permute_and_unpermute
358 and flattened_states.device.type == "npu" and keep is None
359 )
360 unpermute_indices = None
361 if use_fused_moe_token_permute_and_unpermute:
362 # Keep optional NPU dependencies out of the generic dispatch path.
363 from hyper_parallel.components.functional.moe_token_permute import ( # pylint: disable=C0415
364 moe_token_permute,
365 )
367 dispatched_states, unpermute_indices = moe_token_permute(
368 flattened_states, topk_indices.to(torch.int32),
369 )
370 dispatch_order = torch.empty_like(unpermute_indices, dtype=torch.int64)
371 dispatch_order.scatter_(
372 0, unpermute_indices.to(torch.int64),
373 torch.arange(unpermute_indices.numel(), device=unpermute_indices.device),
374 )
375 else:
376 # Global IDs are contiguous across destination ranks.
377 dispatch_order = _argsort_keys(expert_indices, bound=local_expert_count * ep_size)
378 dispatched_states = flattened_states[source_indices[dispatch_order]].contiguous()
379 dispatched_indices = expert_indices[dispatch_order].unsqueeze(-1).contiguous()
380 destination_ranks = torch.div(expert_indices, local_expert_count, rounding_mode="floor")
381 send_counts_tensor = _expert_token_counts(destination_ranks, ep_size)
382 receive_counts_tensor = ep_exchange_counts(send_counts_tensor, ep_group)
383 send_counts = ep_split_sizes(send_counts_tensor, dispatched_states.shape[0])
384 receive_counts = ep_split_sizes(receive_counts_tensor)
385 return _EPDispatch(
386 source_indices=source_indices,
387 expert_weights=expert_weights,
388 dispatch_order=dispatch_order,
389 states=dispatched_states,
390 expert_indices=dispatched_indices,
391 send_counts=send_counts,
392 receive_counts=receive_counts,
393 unpermute_indices=unpermute_indices,
394 routing_weights=topk_weights if use_fused_moe_token_permute_and_unpermute else None,
395 )
398def _run_ep_local_experts(
399 module: Any,
400 dispatched_states: torch.Tensor,
401 dispatched_indices: torch.Tensor,
402 send_counts: list[int],
403 receive_counts: list[int],
404 ep_group: Any,
405 expert_offset: int,
406) -> torch.Tensor:
407 """Dispatch tokens, run local experts, and return combined expert outputs."""
408 received_states = ep_all_to_all(dispatched_states, send_counts, receive_counts, ep_group)
409 received_indices = ep_all_to_all(
410 dispatched_indices, send_counts, receive_counts, ep_group
411 ).squeeze(-1)
412 local_outputs = module.experts(received_states, received_indices - expert_offset)
413 return ep_all_to_all(local_outputs.contiguous(), receive_counts, send_counts, ep_group)
416def _aggregate_ep_outputs(
417 combined_outputs: torch.Tensor,
418 expert_weights: torch.Tensor,
419 source_indices: torch.Tensor,
420 dispatch_order: torch.Tensor,
421 output_shape: tuple[int, int, int],
422 unpermute_indices: Optional[torch.Tensor] = None,
423 routing_weights: Optional[torch.Tensor] = None,
424) -> torch.Tensor:
425 """Undo expert-major routing and aggregate weighted top-k outputs."""
426 if unpermute_indices is not None:
427 # Keep optional NPU dependencies out of the generic aggregation path.
428 from hyper_parallel.components.functional.moe_token_unpermute import ( # pylint: disable=C0415
429 moe_token_unpermute,
430 )
432 return moe_token_unpermute(combined_outputs, unpermute_indices, routing_weights).view(*output_shape)
433 weighted_outputs = combined_outputs * expert_weights[dispatch_order].unsqueeze(-1)
434 output = torch.zeros(
435 output_shape[0] * output_shape[1],
436 output_shape[-1],
437 dtype=weighted_outputs.dtype,
438 device=weighted_outputs.device,
439 )
440 output.index_add_(0, source_indices[dispatch_order], weighted_outputs)
441 return output.view(*output_shape)
444def ep_routed_forward(
445 module: Any,
446 hidden_states: torch.Tensor,
447 *,
448 router_fn: Callable,
449 ep_group: Any,
450 use_fused_moe_token_permute_and_unpermute: bool = True,
451) -> torch.Tensor:
452 """Routed-experts pipeline: SP-in (local chunk) -> all communication
453 inside -> SP-out. **Routed branch only.**
455 This primitive deliberately does NOT handle shared experts / scalar
456 gates / branch merging — that composition is model semantics and belongs
457 to the caller (an ep_compute.py archetype or a user-written factory,
458 accuracy_fix_plan.md §3). There is no ``tp_group`` parameter: if the
459 caller invokes a nested-boundary submodule (e.g. ``module.shared_expert``),
460 that submodule's own boundary performs its TP communication — the
461 **nested-boundary call contract**: the nested boundary receives the
462 parent's local layout, exclusively owns its parameter layout and TP
463 communication, and returns its declared out_dst layout. The caller MUST
464 NOT repeat a compensating collective over the nested boundary's mesh.
466 Communication flow (isomorphic to Megatron token_dispatcher.py
467 MoEAlltoAllTokenDispatcher):
468 router (local chunk, no communication) -> a2a dispatch (extended EP
469 group, including TP ranks) -> local SwiGLU (complete expert weights, no
470 internal communication, no Partial) -> a2a combine (returns over the
471 same group) -> weighted aggregation.
473 Input hidden [B, S/tp, H] (local sequence chunk, boundary identity);
474 output [B, S/tp, H] (complete, boundary identity).
476 ``router_fn`` is supplied BY THE CALLER (explicit choice, e.g. an entry
477 of MOE_ROUTER_ADAPTERS picked by name in the factory code).
479 ``use_fused_moe_token_permute_and_unpermute`` replaces the generic sort/index-add routing
480 with NPU token permute/unpermute. It defaults to enabled on NPU and does
481 not require grouped GEMM. CPU/GPU and capacity-limited dispatch use the
482 generic permutation path.
484 Extended EP group = the ep axis of the derived expert mesh (flatten
485 ep_size consecutive ranks: first span the TP group, then extend to
486 adjacent dp/cp ranks; MindSpeed TP-extend-EP / Megatron etp=1 + ep
487 homogeneous across TP). Expert weights are only Shard(0) along the
488 expert dim -- each rank holds num_experts/ep_size complete experts, so
489 there is no all_gather/reduce_scatter pair.
490 """
491 ep_size = ep_group.size()
492 ep_rank = dist.get_rank(group=ep_group)
493 local_expert_count = module.experts.local_expert_count
494 expert_offset = ep_rank * local_expert_count
495 output_shape = tuple(hidden_states.shape)
496 dispatch = _plan_routed_slots(
497 module, hidden_states, router_fn, ep_size, ep_group,
498 fused_permute=use_fused_moe_token_permute_and_unpermute,
499 )
500 with expert_parallel_region():
501 combined_expert_outputs = _run_ep_local_experts(
502 module,
503 dispatch.states,
504 dispatch.expert_indices,
505 dispatch.send_counts,
506 dispatch.receive_counts,
507 ep_group,
508 expert_offset,
509 )
510 return _aggregate_ep_outputs(
511 combined_expert_outputs,
512 dispatch.expert_weights,
513 dispatch.source_indices,
514 dispatch.dispatch_order,
515 output_shape,
516 unpermute_indices=dispatch.unpermute_indices,
517 routing_weights=dispatch.routing_weights,
518 )
521class EPRoutedState(NamedTuple):
522 """Pending routed-experts state between dispatch and experts+combine.
524 Produced by :func:`ep_routed_dispatch` and consumed by
525 :func:`ep_routed_experts_and_combine`. ``received_states`` /
526 ``received_indices`` may still be in flight until their first non-view use.
527 """
529 source_token_indices: torch.Tensor
530 flattened_expert_weights: torch.Tensor
531 dispatch_order: torch.Tensor
532 received_states: torch.Tensor
533 received_indices: torch.Tensor
534 send_counts: list[int]
535 receive_counts: list[int]
536 output_shape: tuple[int, int, int]
539def _plan_routed_slots(
540 module: Any,
541 hidden_states: torch.Tensor,
542 router_fn: Callable,
543 ep_size: int,
544 ep_group: Any,
545 fused_permute: bool = False,
546) -> _EPDispatch:
547 """Route once and compact the same capacity-limited slots for all schedules."""
548 local_expert_count = module.experts.local_expert_count
549 global_expert_count = local_expert_count * ep_size
550 topk_indices, topk_weights = router_fn(module, hidden_states)
551 # Keep the router capturable while marking dynamic dispatch and expert rows.
552 with expert_parallel_region():
553 capacity_factor = _resolve_capacity_factor(module)
554 keep = None
555 if capacity_factor is not None:
556 keep, _ = apply_capacity_limit(
557 topk_indices, capacity_factor, global_expert_count, topk_weights,
558 )
559 return _prepare_ep_dispatch(
560 hidden_states, topk_indices, topk_weights,
561 local_expert_count=local_expert_count,
562 ep_size=ep_size,
563 ep_group=ep_group,
564 keep=keep,
565 use_fused_moe_token_permute_and_unpermute=fused_permute,
566 )
569@expert_parallel_region()
570def ep_routed_dispatch(
571 module: Any,
572 hidden_states: torch.Tensor,
573 *,
574 router_fn: Callable,
575 ep_group: Any,
576) -> EPRoutedState:
577 """Route locally and **launch** the token exchange without waiting.
579 Same routing/dispatch preparation as :func:`ep_routed_forward`, but the two
580 token exchanges are issued through :func:`ep_all_to_all_async`, whose wait
581 is deferred to the first non-view consumer. A caller that runs independent
582 work between this call and :func:`ep_routed_experts_and_combine` (for
583 DeepSeek-V3 style blocks: the shared-expert MLP, which depends only on
584 ``hidden_states``) therefore overlaps that work with the in-flight
585 exchange instead of serializing behind it.
587 Args:
588 module: MoE block exposing ``experts`` (with ``local_expert_count``).
589 hidden_states: Local sequence chunk, shape ``[B, S, H]``.
590 router_fn: Router adapter, called as ``router_fn(module, hidden_states)``.
591 ep_group: Extended EP process group.
593 Returns:
594 The pending :class:`EPRoutedState` to hand to
595 :func:`ep_routed_experts_and_combine`.
596 """
597 batch_size, sequence_length, hidden_size = hidden_states.shape
598 dispatch = _plan_routed_slots(module, hidden_states, router_fn, ep_group.size(), ep_group)
599 send_counts = dispatch.send_counts
600 receive_counts = dispatch.receive_counts
601 received_states = ep_all_to_all_async(dispatch.states, send_counts, receive_counts, ep_group)
602 received_indices = ep_all_to_all_async(
603 dispatch.expert_indices, send_counts, receive_counts, ep_group,
604 ).squeeze(-1)
605 return EPRoutedState(
606 dispatch.source_indices,
607 dispatch.expert_weights,
608 dispatch.dispatch_order,
609 received_states,
610 received_indices,
611 send_counts,
612 receive_counts,
613 (batch_size, sequence_length, hidden_size),
614 )
617@expert_parallel_region()
618def ep_routed_experts_and_combine(
619 module: Any,
620 state: EPRoutedState,
621 ep_group: Any,
622) -> torch.Tensor:
623 """Run the local experts on a dispatched state and exchange the outputs back.
625 The dispatch exchange reached ``state`` from :func:`ep_routed_dispatch` and
626 is waited here -- at the first expert read, i.e. after whatever work the
627 caller ran in between -- and the combine exchange is issued asynchronously
628 as well, so its wait lands on the weighted aggregation instead of blocking
629 right after the local experts.
631 Args:
632 module: MoE block exposing ``experts`` (with ``local_expert_count``).
633 state: State returned by :func:`ep_routed_dispatch`.
634 ep_group: Extended EP process group.
636 Returns:
637 The routed branch output, shape ``state.output_shape``.
638 """
639 expert_offset = dist.get_rank(group=ep_group) * module.experts.local_expert_count
640 local_outputs = module.experts(
641 state.received_states,
642 state.received_indices - expert_offset)
643 combined_expert_outputs = ep_all_to_all_async(
644 local_outputs.contiguous(), state.receive_counts, state.send_counts, ep_group,
645 )
646 return _aggregate_ep_outputs(
647 combined_expert_outputs,
648 state.flattened_expert_weights,
649 state.source_token_indices,
650 state.dispatch_order,
651 state.output_shape,
652 )
655def _merge_shared_none(
656 module: Any,
657 hidden_states: torch.Tensor,
658 routed: torch.Tensor,
659) -> torch.Tensor:
660 """Routed branch only (no shared expert)."""
661 del module, hidden_states
662 return routed
665# Shared-branch merges used by model adapters and native EP recipes.
666SHARED_MERGE_MODES: dict[str, Callable[[Any, torch.Tensor, torch.Tensor], torch.Tensor]] = {
667 "none": _merge_shared_none,
668}
671def require_attrs(module: Any, *names: str, owner: str = "") -> None:
672 """Assert that ``module`` has every attribute in ``names``; raise a
673 teaching ValueError listing the module's ACTUAL children otherwise.
675 Used by EP compute factories (archetype or user-written) at apply time:
676 the factory body runs ONCE at apply time (before the wrapped forward
677 ever executes), so an interface mismatch fails the model build in
678 seconds instead of surfacing as a runtime AttributeError at step N.
679 The check is structural (the names the implementation will call exist);
680 it does not prove semantic correctness — that is vouched by numeric
681 verification.
682 """
683 missing = [n for n in names if not hasattr(module, n)]
684 if not missing:
685 return
686 children = [n for n, _ in module.named_children()]
687 who = f"{owner} " if owner else ""
688 raise ValueError(
689 f"{who}expects MoE module attribute(s) {missing} on "
690 f"{type(module).__name__}, but they do not exist; the module's "
691 f"actual children are {children}. Pick the matching EP archetype "
692 f"(see the archetype table in ep_compute.py), or write your own "
693 f"factory (reference: examples/distributed/ep_factories.py) — the "
694 f"names your compute_fn calls on module.<child> must match the "
695 f"model's actual attribute names"
696 )
699def describe_moe_module(module: Any) -> str:
700 """Structural diagnostic for a MoE module: child submodules, direct
701 parameter shapes, and expert-related attributes — the facts needed to
702 pick an EP archetype or write a custom factory. Returns the report;
703 also logged at INFO."""
704 lines = [f"MoE module: {type(module).__name__}"]
705 children = list(module.named_children())
706 lines.append(f"children ({len(children)}):")
707 for name, child in children:
708 lines.append(f" - {name}: {type(child).__name__}")
709 direct_params = list(module.named_parameters(recurse=False))
710 if direct_params:
711 lines.append("direct parameters:")
712 for name, p in direct_params:
713 lines.append(f" - {name}: shape={tuple(p.shape)}")
714 experts = getattr(module, "experts", None)
715 if experts is not None:
716 lines.append(
717 f"experts: {type(experts).__name__}, "
718 f"local_expert_count={getattr(experts, 'local_expert_count', '<unset>')}"
719 )
720 report = "\n".join(lines)
721 return report