Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / distributed / expert_parallel / moonep_planner.py: 99%
87 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"""MoonEP collective placement compiled from route histograms.
18Adapted from HyperParallel PR #1485. The whole-deficit fallback matches the
19MoonEP official planning reference; the partial-fill pass minimizes moved rows
20when it fits the requested replica capacity. Planning is eager CPU metadata;
21no token activation or expert parameter is copied to the CPU.
22"""
24from __future__ import annotations
26import numpy as np
27import torch
30def _allocate(totals: np.ndarray, targets: np.ndarray, fill_deficit: bool) -> np.ndarray:
31 """Split sender/receiver quotas across experts in descending load order."""
32 ranks = targets.size
33 home = totals.reshape(ranks, -1)
34 balance = home.sum(axis=1) - targets
35 quotas = np.zeros((ranks, ranks), dtype=np.int64)
36 for _ in range(ranks - 1):
37 source, target = balance.argmax(), balance.argmin()
38 amount = -balance[target]
39 if not fill_deficit:
40 amount = min(balance[source], amount)
41 quotas[source, target] += amount
42 balance[source] -= amount
43 balance[target] += amount
45 allocation = np.zeros((totals.size, ranks), dtype=np.int64)
46 for owner in range(ranks):
47 remaining = home[owner].copy()
48 allocation[owner * home.shape[1]:(owner + 1) * home.shape[1], owner] = remaining
49 experts = np.argsort(-remaining, kind="stable")
50 position = 0
51 for destination in np.argsort(-quotas[owner], kind="stable"):
52 quota = quotas[owner, destination]
53 while quota > 0:
54 expert = experts[position]
55 amount = min(remaining[expert], quota)
56 logical_id = owner * home.shape[1] + expert
57 allocation[logical_id, destination] += amount
58 allocation[logical_id, owner] -= amount
59 remaining[expert] -= amount
60 quota -= amount
61 if remaining[expert] == 0:
62 position += 1
63 return allocation
66def select_allocation(counts: np.ndarray, replica_capacity: int | None = None) -> np.ndarray:
67 """Apply the moonep_with_fsdp partial-fill policy with the whole-deficit fallback.
69 Args:
70 counts: Global route counts in [source rank, logical expert] order.
71 replica_capacity: Maximum distinct remote experts per rank; defaults to E/EP.
73 Returns:
74 Real row allocation in [logical expert, execution rank] order.
75 """
76 ranks, experts = counts.shape
77 local = experts // ranks
78 capacity = local if replica_capacity is None else replica_capacity
79 totals = counts.sum(axis=0)
80 total = totals.sum()
81 targets = total // ranks + (np.arange(ranks) < total % ranks)
82 allocation = _allocate(totals, targets, fill_deficit=False)
83 remote = np.arange(experts)[:, None] // local != np.arange(ranks)
84 minimum = np.maximum(totals.reshape(ranks, local).sum(axis=1) - targets, 0).sum()
85 if (allocation[remote].sum() == minimum and np.all(allocation.sum(axis=0) == targets)
86 and np.all(((allocation > 0) & remote).sum(axis=0) <= capacity)):
87 return allocation
88 allocation = _allocate(totals, targets, fill_deficit=True)
89 valid = (not np.any(allocation < 0), np.array_equal(allocation.sum(axis=1), totals),
90 np.array_equal(allocation.sum(axis=0), targets),
91 np.all(((allocation > 0) & remote).sum(axis=0) <= capacity))
92 if not all(valid):
93 raise RuntimeError(f"MoonEP cannot balance routes within replica capacity {capacity}")
94 return allocation
97def compile_plan(counts: np.ndarray, allocation: np.ndarray, ids: torch.Tensor, rank: int) -> dict:
98 """Compile source and receiver permutations without copying token IDs to the host.
100 Args:
101 counts: Global counts [source rank, expert].
102 allocation: Conserved route allocation [expert, execution rank].
103 ids: This source's prepared expert-major slot IDs.
104 rank: Source rank in the existing EP group.
106 Returns:
107 Invocation-local split lists, compute counts and permutation tensors.
108 """
109 ranks, experts = counts.shape
110 local = experts // ranks
111 source_ends = counts.cumsum(axis=0)
112 target_ends = allocation.cumsum(axis=1)
113 overlap = np.maximum(
114 np.minimum(source_ends[:, :, None], target_ends[None])
115 - np.maximum((source_ends - counts)[:, :, None], (target_ends - allocation)[None]),
116 0,
117 )
118 recv_rows = overlap[:, :, rank]
119 token_send = overlap[rank].sum(axis=0).tolist()
120 token_recv = recv_rows.sum(axis=1).tolist()
122 expert_ids = np.arange(experts)
123 owners = expert_ids // local
124 remote = (allocation > 0) & (owners[:, None] != np.arange(ranks))
125 weight_send = remote[owners == rank].sum(axis=0).tolist()
126 weight_recv = remote[:, rank].reshape(ranks, local).sum(axis=1).tolist()
127 send_experts = np.nonzero(remote[owners == rank].T)[1]
128 received_experts = expert_ids[remote[:, rank]]
129 home_experts = expert_ids[owners == rank]
130 active = np.concatenate((home_experts, received_experts))
131 boundaries = allocation[active, rank].cumsum()
133 # Sender packets are destination-major, with ascending expert IDs per peer.
134 # Receiver packets are source-major; expand one offset per (expert, source) segment.
135 recv_starts = (recv_rows.flatten().cumsum() - recv_rows.flatten()).reshape(recv_rows.shape)
136 lengths = recv_rows[:, active].T.flatten()
137 recv_offsets = recv_starts[:, active].T.flatten() - (lengths.cumsum() - lengths)
138 offset = (source_ends - counts)[rank] - (counts[rank].cumsum() - counts[rank])
139 rows = (offset, target_ends.flatten(), recv_offsets, lengths, send_experts, boundaries)
140 metadata = torch.from_numpy(np.concatenate(rows)).to(ids.device)
141 offset, ends, recv_offsets, lengths, send, boundaries = metadata.split([row.size for row in rows])
143 positions = torch.arange(ids.numel(), device=ids.device)
144 ordinals = positions + offset[ids]
145 destinations = (ordinals[:, None] >= ends.view(experts, ranks)[ids]).sum(dim=1)
146 # Inputs are already expert-major; stable destination sorting retains that order per peer.
147 source_order = destinations.float().argsort(stable=True)
148 source_inverse = torch.empty_like(source_order, dtype=torch.int32)
149 source_inverse.scatter_(0, source_order, positions.int())
150 received = sum(token_recv)
151 receive_order = torch.arange(received, device=ids.device) + torch.repeat_interleave(
152 recv_offsets, lengths, output_size=received,
153 )
154 return {
155 "token_send": token_send, "token_recv": token_recv,
156 "weight_send": weight_send, "weight_recv": weight_recv, "weight_exchange": bool(remote.any()),
157 "send_experts": send, "source_order": source_order, "source_inverse": source_inverse,
158 "receive_order": receive_order, "counts": torch.diff(boundaries, prepend=boundaries.new_zeros(1)),
159 }