Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / distributed / expert_parallel / recipes.py: 82%
88 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# ============================================================================
15"""expert_parallel.recipes: built-in EP compute factories, organized as EXPLICIT archetypes
16(accuracy_fix_plan.md §3 E2).
18Since the explicit-injection rework the planner only SHARDS the expert
19parameters (``{EP: Shard(0)}`` + stacking metadata); the EP compute is never
20injected automatically — a factory must be referenced explicitly from YAML:
22.. code-block:: yaml
24 plan_overrides:
25 - match: "*.mlp.forward"
26 when: ep
27 replace:
28 kind: method
29 implementation: hyper_parallel.distributed.expert_parallel.recipes.qwen2moe_ep_compute_fn
31Archetype table (each factory is a COMPLETE semantic implementation —
32router / dispatch / experts / combine / shared expert / gate / merge are
33all inside; the framework never fills in any branch for you):
35=============================== ====================== =========================== =========================
36archetype key router shared expert representative models
37=============================== ====================== =========================== =========================
38routed_only_softmax_topk softmax top-k none legacy linear routers
39mixtral_topk_router TopKRouter tuple none Mixtral
40qwen2moe_shared_expert_gate TopKRouter tuple shared_expert + sigmoid gate Qwen2-MoE
41deepseekv3_sigmoid_group_shared sigmoid group routing shared_experts DeepSeek-V3 / GLM-4-MoE
42=============================== ====================== =========================== =========================
44Model-family archetypes live at their model-adapter homes (adjust doc §5.1):
45the Qwen3-MoE ``qwen3moe_topk_router`` archetype is
46``models/qwen3_moe/adapter/distributed/expert_parallel.qwen3moe_ep_compute_fn``.
48Three hard constraints on every archetype (accuracy_fix_plan.md §3.2):
501. **Explicitly keyed, zero runtime probing** — the user names the factory
51 in YAML; the implementation accesses ``module.experts`` /
52 ``module.shared_expert`` etc. directly. There are no getattr fallback
53 chains anywhere (a half-found branch is a SILENT numeric error — see
54 accuracy_problem.md 10.2).
552. **Apply-time interface assertion** — the factory runs ONCE at apply time
56 with the real module; it first asserts every attribute it will call and
57 fails the build with a teaching error (listing the module's actual
58 children) on mismatch. The assertion proves structural match, not
59 semantic correctness (that is vouched by numeric verification).
603. **Complete semantics** — nothing is left for the framework to guess.
62Not sure which archetype fits? ``describe_moe_module(module)`` (expert_parallel.experts)
63prints the module's children/param shapes; ``EP_ARCHETYPE_SUGGESTIONS``
64maps the planner's canonical arch name to a likely archetype (a SUGGESTION
65shown in error messages — selection stays explicit; a wrong suggestion is
66caught by constraint 2). Non-typical MoE: copy
67``examples/distributed/ep_factories.py`` and write your own factory with
68the same contract.
70Nested-boundary call contract (inside every compute_fn): calling a
71planned nested-boundary submodule (e.g. ``module.shared_expert(...)``)
72returns its out_dst layout with TP communication already sealed inside —
73the caller MUST NOT apply compensating collectives to the return value:
75.. code-block:: python
77 dist.all_reduce(shared, group=tp_group) # FORBIDDEN — the nested
78 # boundary already reduced
80Factory contract: decorated ``@local_compute`` (injection discipline —
81undecorated factories fail fast in the resolution chain). The mesh family
82``mesh`` / ``tp_mesh`` / ``cp_mesh`` / ``ep_mesh`` is MANDATORY context,
83ALL filled by the framework at apply time (None for inactive axes;
84``ep_mesh`` is the same object the expert parameters were sharded on).
85The factory must RETURN the compute fn
86``fn(module, *local_args, **local_kwargs) -> Tensor`` executed on local
87tensors inside the local-region skeleton.
88"""
90import math
91from typing import Any, Callable, Optional
93import torch
95from hyper_parallel.distributed._builder.rule_resolver import (
96 _check_target_config_keys,
97 _is_delayed_target,
98 fill_context_kwargs,
99)
100from hyper_parallel.distributed.expert_parallel.routing import (
101 resolve_moe_router,
102)
103from hyper_parallel.distributed.expert_parallel.experts import (
104 bind_local_expert_forward,
105 ep_routed_dispatch,
106 ep_routed_experts_and_combine,
107 ep_routed_forward,
108 require_attrs,
109)
110from hyper_parallel.distributed.recipe_spec import (
111 LOCAL_COMPUTE,
112 local_compute,
113 require_injection_meta,
114)
117# {canonical arch name (ShardingPlanner._get_architecture): archetype key} —
118# a SUGGESTION shown in preflight error messages and describe_moe_module
119# output, never an automatic selection (accuracy_fix_plan.md §3 E2).
120EP_ARCHETYPE_SUGGESTIONS = {
121 "qwen2moe": "qwen2moe_shared_expert_gate",
122 "qwen2_moe": "qwen2moe_shared_expert_gate",
123 "mixtral": "mixtral_topk_router",
124 "deepseekv3": "deepseekv3_sigmoid_group_shared",
125 "deepseek_v3": "deepseekv3_sigmoid_group_shared",
126 "glm4moe": "deepseekv3_sigmoid_group_shared",
127 "glm4_moe": "deepseekv3_sigmoid_group_shared",
128}
131def _require_ep_group(ep_mesh: Any, factory_name: str):
132 """Validate the expert mesh context and return the EP process group."""
133 if ep_mesh is None:
134 raise ValueError(
135 f"{factory_name} was built without an ep_mesh — this factory must "
136 "be injected on an EP-sharded MoE boundary (ep_size > 1 so the "
137 "framework-derived expert mesh exists). If you meant TP-only "
138 "expert sharding, do not use an EP compute factory."
139 )
140 return ep_mesh.get_group("ep")
143def _require_moe_interface(module: Any, expected_attrs, archetype_key: str) -> None:
144 """Apply-time structural assertion for an archetype (constraint 2)."""
145 require_attrs(module, *expected_attrs, owner=f"archetype '{archetype_key}'")
148def build_ep_compute(
149 module: Any,
150 ep_mesh: Any,
151 *,
152 router_fn: Callable,
153 archetype_key: str,
154 expected_attrs,
155 combine: Callable,
156 use_grouped_gemm: bool = False,
157 fix_router: bool = False,
158 capacity_factor: Optional[float] = None,
159 overlap_fn: Optional[Callable] = None,
160) -> Callable:
161 """Shared skeleton for archetype factories: validate context, assert the
162 interface, bind the local expert entry point, and close over the
163 archetype-specific ``combine`` (the branch composition — the ONLY part
164 that differs between archetypes).
166 ``combine(module, hidden_states, routed) -> Tensor`` receives the routed
167 branch output and returns the MoE block output.
169 When ``overlap_fn`` is given the routed branch is split into dispatch and
170 experts+combine, and ``overlap_fn(module, hidden_states)`` runs in between:
171 the token exchange is issued asynchronously there, so the overlapped work
172 (for DeepSeek-V3 style blocks the shared-expert MLP, which depends only on
173 ``hidden_states``) proceeds while it is in flight. ``combine`` then
174 receives that value as a fourth argument.
176 Public since M3 (adjust doc §5.4): model adapters (e.g.
177 ``models/qwen3_moe/adapter/distributed/expert_parallel.py``) compose
178 their EP archetype on top of this skeleton while the router adapters and
179 dispatch primitives stay in this generic layer.
180 ``fix_router`` is the archetype-independent benchmark switch: it swaps the chosen
181 router for its balanced variant -- the ``<name>_fixed`` registry entry when
182 ``router_fn`` names one, else
183 :func:`~hyper_parallel.distributed.expert_parallel.routing.make_balanced_router`
184 around the given callable -- so a family gets the uniform-load comparison mode
185 without carrying its own copy of the router. See that factory for what it does and
186 why its numbers must not be reported as an efficiency result.
187 """
188 router_fn = resolve_moe_router(router_fn, fix_router)
189 ep_group = _require_ep_group(ep_mesh, f"archetype '{archetype_key}'")
190 _require_moe_interface(module, expected_attrs, archetype_key)
191 if use_grouped_gemm:
192 bind_local_expert_forward(
193 module,
194 ep_mesh["ep"].size(),
195 use_grouped_gemm=True,
196 )
197 else:
198 # Keep the established call contract unchanged for every reference
199 # archetype and for Qwen3 when grouped GEMM is disabled.
200 bind_local_expert_forward(module, ep_mesh["ep"].size())
202 if capacity_factor is not None:
203 # Read back by ``experts._resolve_capacity_factor``; bounds each expert's routed slots
204 # so the busiest rank's buffers cannot blow up under a skewed real router.
205 module.experts.capacity_factor = float(capacity_factor)
207 if overlap_fn is None:
208 def compute_fn(module: Any, hidden_states: torch.Tensor) -> torch.Tensor:
209 """Run the routed branch and compose the MoE block output."""
210 routed = ep_routed_forward(
211 module, hidden_states, router_fn=router_fn, ep_group=ep_group)
212 return combine(module, hidden_states, routed)
213 else:
214 def compute_fn(module: Any, hidden_states: torch.Tensor) -> torch.Tensor:
215 """Dispatch, run ``overlap_fn`` against the in-flight exchange, then finish."""
216 state = ep_routed_dispatch(
217 module, hidden_states, router_fn=router_fn, ep_group=ep_group)
218 overlapped = overlap_fn(module, hidden_states)
219 routed = ep_routed_experts_and_combine(module, state, ep_group)
220 return combine(module, hidden_states, routed, overlapped)
222 return compute_fn
225@local_compute
226def ep_compute_with_dispatch_options(
227 *,
228 module: Any,
229 mesh: Any,
230 tp_mesh: Any,
231 cp_mesh: Any,
232 ep_mesh: Any,
233 compute: Any,
234 capacity_factor: Optional[float] = None,
235) -> Callable:
236 """Apply an optional capacity limit around an existing EP compute factory.
238 Args:
239 module: MoE boundary containing the routed experts.
240 mesh: Boundary device mesh.
241 tp_mesh: Framework-provided tensor-parallel mesh.
242 cp_mesh: Framework-provided context-parallel mesh.
243 ep_mesh: Framework-provided expert-parallel mesh.
244 compute: Nested YAML target for the existing MoE compute factory.
245 capacity_factor: Optional positive per-source capacity multiplier.
247 Returns:
248 The local compute callable from the nested factory.
249 """
250 source = "ep_compute_with_dispatch_options.compute"
251 if not _is_delayed_target(compute):
252 raise TypeError(f"{source} requires a nested _target_ for an EP local compute factory")
253 _require_ep_group(ep_mesh, source)
254 _check_target_config_keys(compute, source)
255 meta = require_injection_meta(compute.callable, LOCAL_COMPUTE, source=source)
256 context = {"module": module, "mesh": mesh, "tp_mesh": tp_mesh, "cp_mesh": cp_mesh, "ep_mesh": ep_mesh}
257 configured = compute._kwargs # pylint: disable=protected-access
258 compute_fn = compute.build(**fill_context_kwargs(meta, context, configured, source=source))
259 experts = getattr(module, "experts", None)
260 if not hasattr(experts, "_ep_use_grouped_gemm"):
261 raise ValueError(f"{source} must bind the routed experts with bind_local_expert_forward")
262 if capacity_factor is not None:
263 if not math.isfinite(capacity_factor) or capacity_factor <= 0:
264 raise ValueError("capacity_factor must be finite and positive")
265 experts.capacity_factor = capacity_factor
266 return compute_fn
269@local_compute
270def routed_only_ep_compute_fn(
271 *,
272 module: Any,
273 mesh: Any,
274 tp_mesh: Any,
275 cp_mesh: Any,
276 ep_mesh: Any,
277 fix_router: bool = False,
278) -> Callable:
279 """Archetype ``routed_only_softmax_topk``: softmax top-k router, no
280 shared expert (Mixtral-style). Output = routed branch only.
282 Expected module interface: ``gate`` (router Linear), ``experts``.
284 ``fix_router`` selects the benchmark-only balanced variant of the router
285 (``routing.make_balanced_router``); correctness runs keep it ``False``.
286 """
287 del mesh, tp_mesh, cp_mesh
288 return build_ep_compute(
289 module,
290 ep_mesh,
291 router_fn=resolve_moe_router("default", fix_router),
292 archetype_key="routed_only_softmax_topk",
293 expected_attrs=["gate", "experts"],
294 combine=lambda module, hidden_states, routed: routed,
295 )
298@local_compute
299def mixtral_ep_compute_fn(
300 *,
301 module: Any,
302 mesh: Any,
303 tp_mesh: Any,
304 cp_mesh: Any,
305 ep_mesh: Any,
306 fix_router: bool = False,
307) -> Callable:
308 """Archetype ``mixtral_topk_router`` with training-time router jitter.
310 Transformers 5.12 Mixtral uses a TopKRouter returning
311 ``(logits, scores, indices)``. When configured, the original block also
312 perturbs hidden states before both routing and expert computation.
314 ``fix_router`` selects the benchmark-only balanced variant of the router
315 (``routing.make_balanced_router``); correctness runs keep it ``False``.
316 """
317 del mesh, tp_mesh, cp_mesh
318 router_fn = resolve_moe_router("mixtral", fix_router)
319 ep_group = _require_ep_group(ep_mesh, "archetype 'mixtral_topk_router'")
320 _require_moe_interface(module, ["gate", "experts"], "mixtral_topk_router")
321 bind_local_expert_forward(module, ep_mesh["ep"].size())
323 def compute_fn(module: Any, hidden_states: torch.Tensor) -> torch.Tensor:
324 """Apply router jitter when training, then run the routed branch."""
325 jitter_noise = float(getattr(module, "jitter_noise", 0.0))
326 if module.training and jitter_noise > 0.0:
327 noise = torch.empty_like(hidden_states).uniform_(
328 1.0 - jitter_noise,
329 1.0 + jitter_noise,
330 )
331 hidden_states = hidden_states * noise
332 return ep_routed_forward(
333 module,
334 hidden_states,
335 router_fn=router_fn,
336 ep_group=ep_group,
337 )
339 return compute_fn
342@local_compute
343def qwen2moe_ep_compute_fn(
344 *,
345 module: Any,
346 mesh: Any,
347 tp_mesh: Any,
348 cp_mesh: Any,
349 ep_mesh: Any,
350 fix_router: bool = False,
351) -> Callable:
352 """Archetype ``qwen2moe_shared_expert_gate``: TopKRouter tuple +
353 shared_expert + sigmoid scalar gate (Qwen2-MoE):
354 ``routed + sigmoid(shared_expert_gate(x)) * shared_expert(x)``.
356 Expected module interface: ``gate``, ``experts``, ``shared_expert``,
357 ``shared_expert_gate``.
359 ``module.shared_expert(...)`` is a planned nested TP boundary: its exit
360 already performs the RowWise Partial TP reduction (nested-boundary call
361 contract) — do NOT all-reduce its return value.
362 """
363 del mesh, tp_mesh, cp_mesh
365 def combine(
366 module: Any,
367 hidden_states: torch.Tensor,
368 routed: torch.Tensor,
369 ) -> torch.Tensor:
370 """Merge the routed branch with the gated shared-expert branch."""
371 shared = module.shared_expert(hidden_states) # nested boundary
372 gate = torch.sigmoid(module.shared_expert_gate(hidden_states))
373 return routed + gate * shared
375 return build_ep_compute(
376 module,
377 ep_mesh,
378 router_fn="qwen2moe",
379 fix_router=fix_router,
380 archetype_key="qwen2moe_shared_expert_gate",
381 expected_attrs=["gate", "experts", "shared_expert", "shared_expert_gate"],
382 combine=combine,
383 )
386@local_compute
387def deepseekv3_ep_compute_fn(
388 *,
389 module: Any,
390 mesh: Any,
391 tp_mesh: Any,
392 cp_mesh: Any,
393 ep_mesh: Any,
394 use_grouped_gemm: bool = False,
395 overlap_shared_expert: bool = False,
396 fix_router: bool = False,
397 capacity_factor: Optional[float] = None,
398) -> Callable:
399 """Archetype ``deepseekv3_sigmoid_group_shared``: sigmoid group-limited
400 routing (with e_score_correction_bias / routed_scaling_factor, already
401 folded into the router adapter's topk weights) + shared_experts
402 (DeepSeek-V3 / GLM-4-MoE): ``routed + shared_experts(x)``.
404 Expected module interface: ``gate``, ``experts``, ``shared_experts``.
406 ``module.shared_experts(...)`` is a planned nested TP boundary — its
407 exit already performs the TP reduction (nested-boundary call contract).
409 ``use_grouped_gemm=True`` runs the local experts through the packed
410 ``gate_up_proj`` grouped GEMM path (``npu_grouped_swiglu``) instead of
411 the eager per-expert loop; the default keeps the eager path.
413 ``overlap_shared_expert=True`` issues the token exchange asynchronously
414 and evaluates ``shared_experts`` while it is in flight — the shared branch
415 reads only ``hidden_states``, so it hides communication instead of
416 serializing behind the routed branch. The math is unchanged either way.
418 ``fix_router=True`` swaps the adapter for ``deepseekv3_fixed``, a
419 BENCHMARK-ONLY variant that hands every rank the same token count
420 (round-robin over the K slots by destination rank instead of the gate's
421 top-k) so that per-rank step time stops depending on how the data
422 happened to route. Loss / grad_norm / expert-load metrics are meaningless
423 in that mode and it must not be used to report an efficiency number —
424 see ``routing.make_balanced_router``. Correctness runs keep it off.
425 """
426 del mesh, tp_mesh, cp_mesh
428 def combine(
429 module: Any,
430 hidden_states: torch.Tensor,
431 routed: torch.Tensor,
432 overlapped: Optional[torch.Tensor] = None,
433 ) -> torch.Tensor:
434 """Merge the routed branch with the shared-experts branch."""
435 shared = module.shared_experts(hidden_states) if overlapped is None else overlapped
436 return routed + shared # nested boundary
438 def overlap_shared(module: Any, hidden_states: torch.Tensor) -> torch.Tensor:
439 """Shared-experts branch, evaluated while the dispatch exchange is in flight."""
440 return module.shared_experts(hidden_states) # nested boundary
442 return build_ep_compute(
443 module,
444 ep_mesh,
445 router_fn="deepseekv3",
446 fix_router=fix_router,
447 archetype_key="deepseekv3_sigmoid_group_shared",
448 expected_attrs=["gate", "experts", "shared_experts"],
449 combine=combine,
450 use_grouped_gemm=use_grouped_gemm,
451 capacity_factor=capacity_factor,
452 overlap_fn=overlap_shared if overlap_shared_expert else None,
453 )
456# {archetype key: factory} — introspection registry (the YAML _target_
457# points at a factory directly; this registry exists for
458# describe/preflight messaging).
459EP_ARCHETYPES = {
460 "routed_only_softmax_topk": routed_only_ep_compute_fn,
461 "mixtral_topk_router": mixtral_ep_compute_fn,
462 "qwen2moe_shared_expert_gate": qwen2moe_ep_compute_fn,
463 "deepseekv3_sigmoid_group_shared": deepseekv3_ep_compute_fn,
464}