Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / distributed / expert_parallel / ep_context.py: 87%
163 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# ============================================================================
15"""Routed-slot transport, independent of routing and expert computation."""
17from __future__ import annotations
19from contextvars import ContextVar
20from weakref import ref
21from typing import Any
23import torch
24from torch import Tensor, nn
25from torch.distributed import _functional_collectives
27from hyper_parallel.distributed.expert_parallel.collectives import (
28 ep_all_to_all, ep_all_to_all_async, ep_exchange_counts, ep_split_sizes,
29)
30from hyper_parallel.core.activation_memory.recompute_state import get_recompute_state
33def _validate_slot_inputs(hidden: Tensor, ids: Tensor, weights: Tensor | None) -> None:
34 """Validate resource-free source slots before entering any collective."""
35 if hidden.ndim != 2 or hidden.shape[1] < 1 or not hidden.is_floating_point():
36 raise ValueError("slot hidden_states must be floating-point [slots,H] with H>0")
37 if ids.shape != (hidden.shape[0],) or ids.dtype not in (torch.int32, torch.int64):
38 raise ValueError("expert_ids must have integer dtype and shape [slots]")
39 if ids.device != hidden.device:
40 raise ValueError("slot activations and expert IDs must share the same device")
41 if weights is not None:
42 if weights.shape != ids.shape or not weights.is_floating_point() or weights.device != hidden.device:
43 raise ValueError("slot routing_weights must be floating-point [slots] on the activation device")
46class EPContext:
47 """Contiguous expert ownership, slot transport and optional shared-expert overlap."""
49 def __init__(self, mesh: Any, *, num_experts: int, overlap_shared_expert: bool = True) -> None:
50 """Borrow the EP mesh; never create a group or reduce parameter gradients.
52 Args:
53 mesh: Existing one-dimensional expert ownership mesh.
54 num_experts: Global expert count divisible by the mesh size.
55 overlap_shared_expert: Schedule bound shared stages during token exchange.
56 """
57 if mesh is None or mesh.ndim != 1:
58 raise ValueError("EPContext requires an existing one-dimensional HP mesh")
59 if num_experts < 1 or num_experts % mesh.size():
60 raise ValueError("num_experts must be positive and divisible by EP size")
61 if not isinstance(overlap_shared_expert, bool):
62 raise ValueError("overlap_shared_expert must be bool")
63 self.overlap_shared_expert = overlap_shared_expert
64 self._shared_expert = None
65 self._shared_state: ContextVar | None = None
66 self.mesh = mesh
67 self.num_experts = num_experts
68 self.local_experts = num_experts // mesh.size()
69 self.rank = mesh.get_local_rank()
71 def _exchange(self, tensor: Tensor, send: list[int], receive: list[int], *, async_op: bool = False) -> Tensor:
72 """Share one synchronous/lazy exchange entry between dispatch and combine."""
73 if self.mesh.size() == 1:
74 return tensor
75 if async_op:
76 return ep_all_to_all_async(tensor, send, receive, self.mesh.get_group())
77 return ep_all_to_all(tensor, send, receive, self.mesh.get_group())
79 def bind_shared_expert(self, owner: nn.Module, shared: nn.Module, experts: nn.Module) -> None:
80 """Bind shared stages without changing the containing MoE's forward.
82 Args:
83 owner: MoE whose first activation input also feeds its shared expert.
84 shared: SharedExpert member with the existing FC1/FC2 module-call protocol.
85 experts: Routed expert member whose checkpoint replay needs the same shared stages.
86 """
87 if self._shared_state is not None:
88 raise ValueError("EP context already has a shared-expert owner")
89 shared.bind_ep_context(self)
90 self._shared_expert = ref(shared)
91 self._shared_state = ContextVar("ep_shared_expert", default=None)
92 owner.register_forward_pre_hook(self._capture_shared_input, prepend=True, with_kwargs=True)
93 owner.register_forward_hook(self._release_shared_state, with_kwargs=True, always_call=True)
94 experts.register_forward_pre_hook(self._capture_expert_input, prepend=True, with_kwargs=True)
96 def _capture_shared_input(self, module: nn.Module, args: tuple, kwargs: dict) -> None:
97 """Keep original token shape and invocation-local state across both communication windows."""
98 del module
99 if not self.overlap_shared_expert or self.mesh.size() == 1:
100 return
101 hidden = args[0] if args else kwargs.get("hidden_states", kwargs.get("x"))
102 if not isinstance(hidden, Tensor):
103 raise ValueError("shared-expert overlap requires the MoE activation as its first input")
104 state = {"hidden": hidden, "shared_called": False, "started": False,
105 "grad_enabled": torch.is_grad_enabled()}
106 state["token"] = self._shared_state.set(state)
108 def _release_shared_state(self, module: nn.Module, args: tuple, kwargs: dict, output: Any) -> None:
109 """Release graph references on normal exit, checkpoint replay and exceptions."""
110 del module, args, kwargs, output
111 state = self._shared_state.get()
112 if state:
113 token = state.pop("token")
114 self._shared_state.reset(token)
115 state.clear()
117 def take_shared_output(self, hidden_states: Tensor) -> Any:
118 """Consume the prepared result at the model's unchanged shared-expert call.
120 Args:
121 hidden_states: Original activation supplied to the shared module.
123 Returns:
124 Prepared shared output, or None to execute the ordinary shared forward.
125 """
126 state = self._shared_state.get() if self._shared_state is not None else None
127 if not state or not isinstance(hidden_states, Tensor):
128 return None
129 if hidden_states is not state["hidden"] and not hidden_states.is_set_to(state["hidden"]):
130 return None
131 state["shared_called"] = True
132 return state.pop("output", None)
134 def _capture_expert_input(self, module: nn.Module, args: tuple, kwargs: dict) -> None:
135 """Keep only shared shape metadata; replay uses the restored expert input tensor."""
136 del module
137 state = self._shared_state.get()
138 hidden = args[0] if args else kwargs.get("hidden_states")
139 if state and not state["started"] and not state["shared_called"]:
140 # Use the containing MoE's post-FSDP activation and gradient hooks,
141 # rather than the raw tensor seen before its forward pre-hooks.
142 state["hidden"] = hidden.reshape(state["hidden"].shape)
143 recompute = get_recompute_state()
144 if not self.overlap_shared_expert or recompute is None:
145 return
146 saved = recompute.get_resource(self, dict)
147 if state:
148 if not state["shared_called"] and (not state["grad_enabled"] or torch.is_grad_enabled()):
149 saved.setdefault("shape", tuple(state["hidden"].shape))
150 elif recompute.is_recomputing and saved:
151 saved.update(hidden=hidden.reshape(saved["shape"]), shared_called=False, started=False, grad_enabled=True)
152 self._shared_state.set(saved)
154 def _overlap_ready(self, stage: str) -> bool:
155 """Only an active, unconsumed invocation can schedule shared work."""
156 state = self._shared_state.get() if self._shared_state is not None else None
157 if not self.overlap_shared_expert or not state or state["shared_called"]:
158 return False
159 # Reentrant experts-only checkpointing must not move the shared branch
160 # into its no-grad forward; its ordinary model call still needs autograd.
161 if state["grad_enabled"] and not torch.is_grad_enabled() and state["hidden"].requires_grad:
162 return False
163 return not state["started"] if stage == "fc1" else "intermediate" in state
165 def _run_overlap(self, stage: str, *payloads: Tensor | None) -> None:
166 """Run a bound shared stage and drain outstanding exchanges if it fails."""
167 state = self._shared_state.get()
168 shared = self._shared_expert()
169 try:
170 if stage == "fc1":
171 state["started"] = True
172 state["intermediate"] = shared(state["hidden"], stage="fc1")
173 else:
174 state["output"] = shared(state.pop("intermediate"), stage="fc2")
175 except Exception:
176 for payload in payloads:
177 if payload is not None:
178 _functional_collectives.wait_tensor(payload)
179 raise
181 def combine(
182 self, values: Tensor, send_splits: list[int], recv_splits: list[int], recv_inverse: Tensor,
183 ) -> Tensor:
184 """Return outputs to source prepared-slot order, without weighting or reduction.
186 Args:
187 values: Local expert-major outputs [received_slots,H].
188 send_splits: Original per-peer send sizes from this call's dispatch.
189 recv_splits: Original per-peer receive sizes, reversed for combine.
190 recv_inverse: Mapping from peer-major rows to local expert-major rows [R].
192 Returns:
193 Source-side slot outputs; the Experts algorithm restores original tokens.
194 """
195 if len(send_splits) != self.mesh.size() or len(recv_splits) != self.mesh.size():
196 raise ValueError("slot split lists must follow the current EP group's rank order")
197 if values.ndim != 2 or values.shape[0] != sum(recv_splits):
198 raise ValueError("slot output must have one row per received slot")
199 if recv_inverse.shape != (values.shape[0],) or recv_inverse.dtype != torch.int32:
200 raise ValueError("recv_inverse must have dtype int32 and one index per received slot")
201 if recv_inverse.device != values.device:
202 raise ValueError("slot outputs and recv_inverse must be on the same device")
203 if values.shape[0] and values.device.type == "npu":
204 # Keep the optional torch_npu dependency inside the NPU path.
205 from hyper_parallel.components.functional.moe_token_unpermute import ( # pylint: disable=C0415
206 moe_token_unpermute,
207 )
209 values = moe_token_unpermute(values.contiguous(), recv_inverse)
210 elif values.shape[0]:
211 values = values.index_select(0, recv_inverse)
212 asynchronous = self._overlap_ready("fc2")
213 returned = self._exchange(values, recv_splits, send_splits, async_op=asynchronous)
214 if asynchronous:
215 self._run_overlap("fc2", returned)
216 return returned
218 def _slot_split_sizes(self, counts: Tensor, weighted: bool) -> tuple[list[int], list[int]]:
219 """Exchange counts and verify optional probability transport agrees across peers."""
220 metadata = torch.stack((counts, torch.full_like(counts, int(weighted))), dim=1)
221 received = (ep_exchange_counts(metadata, self.mesh.get_group())
222 if self.mesh.size() > 1 else metadata)
223 fields = ep_split_sizes(received.reshape(-1))
224 if any(flag != int(weighted) for flag in fields[1::2]):
225 raise ValueError("all EP ranks must agree on whether slot routing_weights are transported")
226 return ep_split_sizes(counts), fields[::2]
228 def dispatch(
229 self, hidden_states: Tensor, expert_ids: Tensor, routing_weights: Tensor | None = None,
230 ) -> tuple[Tensor, Tensor, Tensor | None, list[int], list[int], Tensor]:
231 """Transport prepared slots and group received rows by local expert.
233 Args:
234 hidden_states: Source expert-major slot activations [S,H].
235 expert_ids: Matching global expert IDs [S], sorted in ascending order.
236 routing_weights: Optional differentiable per-slot probabilities [S].
238 Returns:
239 Owner-local hidden [R,H], counts [E_local], optional weights [R],
240 send/receive split lists and the inverse mapping from received rows to
241 owner-local expert-major rows [R]. The caller retains them for combine.
242 """
243 _validate_slot_inputs(hidden_states, expert_ids, routing_weights)
244 ids = expert_ids.to(torch.int64)
245 # Fixed-size counting rejects invalid/drop IDs on device and retains empty experts.
246 global_counts = ids.new_zeros(self.num_experts).scatter_add_(0, ids, torch.ones_like(ids))
247 counts = global_counts.reshape(self.mesh.size(), self.local_experts).sum(dim=1)
248 send, receive = self._slot_split_sizes(counts, routing_weights is not None)
249 # Ascending global IDs already group rows by rank under contiguous expert ownership.
250 asynchronous = self._overlap_ready("fc1")
251 hidden = self._exchange(hidden_states.contiguous(), send, receive, async_op=asynchronous)
252 global_ids = self._exchange(ids[:, None].contiguous(), send, receive, async_op=asynchronous).reshape(-1)
253 weights = None
254 if routing_weights is not None:
255 weights = self._exchange(routing_weights[:, None].contiguous(), send, receive,
256 async_op=asynchronous).reshape(-1)
257 if asynchronous:
258 self._run_overlap("fc1", hidden, global_ids, weights)
259 # AsyncCollectiveTensor inserts the wait at these first non-view consumers.
260 local_ids = global_ids - self.rank * self.local_experts
261 local_counts = local_ids.new_zeros(self.local_experts).scatter_add_(
262 0, local_ids, torch.ones_like(local_ids),
263 )
264 if not hidden.shape[0]:
265 return hidden, local_counts, weights, send, receive, local_ids.to(torch.int32)
267 if hidden.device.type == "npu":
268 # Keep the optional torch_npu dependency inside the NPU path.
269 from hyper_parallel.components.functional.moe_token_permute import ( # pylint: disable=C0415
270 moe_token_permute,
271 )
273 # One expert per received slot keeps this a one-to-one rearrangement.
274 hidden, recv_inverse = moe_token_permute(hidden.contiguous(), local_ids.to(torch.int32).view(-1, 1))
275 else:
276 order = local_ids.argsort(stable=True)
277 hidden = hidden.index_select(0, order)
278 rows = torch.arange(order.numel(), dtype=torch.int32, device=order.device)
279 recv_inverse = torch.empty_like(rows).scatter_(0, order, rows)
280 if weights is not None:
281 weights = torch.empty_like(weights).scatter_(0, recv_inverse.to(torch.int64), weights)
282 return hidden, local_counts, weights, send, receive, recv_inverse