Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / distributed / expert_parallel / moonep_context.py: 71%

56 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"""Collective MoonEP transport with invocation-local plans and fixed home ownership.""" 

16 

17from __future__ import annotations 

18 

19from numbers import Integral 

20from typing import Any 

21 

22import torch 

23import torch.distributed as dist 

24from torch import Tensor 

25 

26from hyper_parallel.distributed.expert_parallel.ep_context import EPContext 

27from hyper_parallel.distributed.expert_parallel.moonep_planner import compile_plan, select_allocation 

28 

29 

30class MoonEPContext(EPContext): 

31 """Reuse EP collectives while dynamically balancing execution, without prefetch caches.""" 

32 

33 def __init__(self, mesh: Any, *, num_experts: int, replica_capacity: int | None = None, 

34 overlap_shared_expert: bool = True) -> None: 

35 """Borrow the existing mesh and bound the number of remote experts per rank. 

36 

37 Args: 

38 mesh: Existing one-dimensional TP-extend-EP mesh. 

39 num_experts: Global number of home experts, divisible by the mesh size. 

40 replica_capacity: Maximum distinct remote experts per rank; None means E/EP. 

41 overlap_shared_expert: Run bound shared FC1/FC2 during token exchanges. 

42 """ 

43 super().__init__(mesh, num_experts=num_experts, overlap_shared_expert=overlap_shared_expert) 

44 capacity = self.local_experts if replica_capacity is None else replica_capacity 

45 if isinstance(capacity, bool) or not isinstance(capacity, Integral) or capacity < 0: 

46 raise ValueError("moonep_replica_capacity must be a nonnegative integer or None") 

47 self.replica_capacity = int(capacity) 

48 

49 def plan(self, expert_ids: Tensor) -> dict: 

50 """Compile a deterministic plan from all sources' prepared slot counts. 

51 

52 Args: 

53 expert_ids: Global integer expert IDs [S], in source expert-major order. 

54 

55 Returns: 

56 Per-call transport splits, permutations and compute-table counts. 

57 """ 

58 ids = expert_ids.to(torch.int64) 

59 counts = ids.new_zeros(self.num_experts).scatter_add_(0, ids, torch.ones_like(ids)) 

60 gathered = [torch.empty_like(counts) for _ in range(self.mesh.size())] 

61 if self.mesh.size() > 1: 

62 dist.all_gather(gathered, counts, group=self.mesh.get_group()) 

63 else: 

64 gathered[0] = counts 

65 # The collective baseline plans on small integer histograms, like PR #1485. 

66 # This eager synchronization is not the official fused device planner. 

67 global_counts = torch.stack(gathered).cpu().numpy() 

68 allocation = select_allocation(global_counts, self.replica_capacity) 

69 return compile_plan(global_counts, allocation, ids, self.rank) 

70 

71 # MoonEP deliberately keeps the plan-based entry point while inheriting EP runtime state. 

72 def dispatch( # pylint: disable=arguments-differ 

73 self, hidden_states: Tensor, routing_weights: Tensor | None = None, 

74 *, plan: dict, 

75 ) -> tuple[Tensor, Tensor, Tensor | None, Tensor]: 

76 """Send source slots to planned execution ranks, then perform the second permute. 

77 

78 Args: 

79 hidden_states: Prepared expert-major slots [S,H]. 

80 routing_weights: Optional differentiable before-FC2 probabilities [S]. 

81 plan: Invocation-local result of plan(). 

82 

83 Returns: 

84 Compute-major activations [R,H], counts [C], optional probabilities [R], 

85 and the receiver inverse permutation [R]. C includes home and remote rows. 

86 """ 

87 send, receive, order = plan["token_send"], plan["token_recv"], plan["source_order"] 

88 asynchronous = self._overlap_ready("fc1") 

89 hidden = self._exchange(hidden_states.index_select(0, order), send, receive, async_op=asynchronous) 

90 weights = None 

91 if routing_weights is not None: 

92 weights = self._exchange(routing_weights.index_select(0, order).unsqueeze(-1), send, receive, 

93 async_op=asynchronous).reshape(-1) 

94 if asynchronous: 

95 self._run_overlap("fc1", hidden, weights) 

96 counts, receive_order = plan["counts"], plan["receive_order"] 

97 if hidden.shape[0] and hidden.device.type == "npu": 

98 # torch_npu is optional for CPU import and planning tests. 

99 from hyper_parallel.components.functional.moe_token_permute import ( # pylint: disable=C0415 

100 moe_token_permute, 

101 ) 

102 

103 rows = torch.arange(counts.numel(), device=counts.device).repeat_interleave( 

104 counts, output_size=hidden.shape[0], 

105 ) 

106 ids = torch.empty_like(rows).scatter_(0, receive_order, rows) 

107 hidden, inverse = moe_token_permute(hidden.contiguous(), ids.to(torch.int32).unsqueeze(-1)) 

108 else: 

109 hidden = hidden.index_select(0, receive_order) 

110 inverse = torch.empty_like(receive_order, dtype=torch.int32).scatter_( 

111 0, receive_order, torch.arange(receive_order.numel(), device=receive_order.device, dtype=torch.int32), 

112 ) 

113 if weights is not None: 

114 weights = weights.index_select(0, receive_order) 

115 return hidden, counts, weights, inverse 

116 

117 def expert_weights(self, gate_up: Tensor, down: Tensor, plan: dict) -> tuple[Tensor, Tensor]: 

118 """Exchange only needed replicas using differentiable all-to-all. 

119 

120 Args: 

121 gate_up: Materialized home FC1 weights [E/EP,2I,H]. 

122 down: Materialized home FC2 weights [E/EP,H,I]. 

123 plan: This invocation's remote expert requests and split sizes. 

124 

125 Returns: 

126 Home rows followed by temporary remote rows. The collective adjoint 

127 returns replica gradients to home before the original Parameters' hooks. 

128 No Parameter, FSDP storage state or process group is created here. 

129 """ 

130 if not plan["weight_exchange"]: 

131 return gate_up, down 

132 indices = plan["send_experts"] 

133 packet = torch.cat((gate_up.index_select(0, indices).flatten(1), 

134 down.index_select(0, indices).flatten(1)), dim=1) 

135 remote = self._exchange(packet, plan["weight_send"], plan["weight_recv"]) 

136 first, second = remote.split((gate_up[0].numel(), down[0].numel()), dim=1) 

137 return (torch.cat((gate_up, first.reshape(-1, *gate_up.shape[1:]))), 

138 torch.cat((down, second.reshape(-1, *down.shape[1:])))) 

139 

140 # The forward plan owns the split sizes and source order required by MoonEP combine. 

141 def combine( # pylint: disable=arguments-differ 

142 self, values: Tensor, plan: dict, recv_inverse: Tensor, 

143 ) -> Tensor: 

144 """Unpermute at the compute owner and return source expert-major slots. 

145 

146 Args: 

147 values: Compute-major expert outputs [R,H]. 

148 plan: Saved forward transport and source inverse mapping. 

149 recv_inverse: Receiver permutation returned by dispatch(). 

150 

151 Returns: 

152 Source expert-major outputs [S,H], before the algorithm's final unpermute. 

153 """ 

154 values = super().combine(values, plan["token_send"], plan["token_recv"], recv_inverse) 

155 return values.index_select(0, plan["source_inverse"].to(torch.int64))