1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
| from typing import Tuple, Optional
import torch
from sglang.srt.utils import get_bool_env_var
_REBALANCE_CALL_COUNT = 0
def balanced_packing( weight: torch.Tensor, num_packs: int ) -> Tuple[torch.Tensor, torch.Tensor]: """ Pack n weighted objects to m packs, such that each bin contains exactly n/m objects and the weights of all packs are as balanced as possible. Parameters: weight: [X, n], the weight of each item num_packs: number of packs Returns: pack_index: [X, n], the pack index of each item rank_in_pack: [X, n], the rank of the item in the pack """ num_layers, num_groups = weight.shape assert num_groups % num_packs == 0 groups_per_pack = num_groups // num_packs
if groups_per_pack == 1: pack_index = torch.arange( weight.size(-1), dtype=torch.int64, device=weight.device ).expand(weight.shape) rank_in_pack = torch.zeros_like(weight, dtype=torch.int64) return pack_index, rank_in_pack
indices = weight.float().sort(-1, descending=True).indices.cpu() pack_index = torch.full_like(weight, fill_value=-1, dtype=torch.int64, device="cpu") rank_in_pack = torch.full_like(pack_index, fill_value=-1) for i in range(num_layers): pack_weights = [0] * num_packs pack_items = [0] * num_packs for group in indices[i]: pack = min( (i for i in range(num_packs) if pack_items[i] < groups_per_pack), key=pack_weights.__getitem__, ) assert pack_items[pack] < groups_per_pack pack_index[i, group] = pack rank_in_pack[i, group] = pack_items[pack] pack_weights[pack] += weight[i, group] pack_items[pack] += 1 return pack_index, rank_in_pack
def balanced_packing_vectorized( weight: torch.Tensor, num_packs: int ) -> Tuple[torch.Tensor, torch.Tensor]: num_layers, num_groups = weight.shape assert num_groups % num_packs == 0 groups_per_pack = num_groups // num_packs
if groups_per_pack == 1: pack_index = torch.arange( weight.size(-1), dtype=torch.int64, device=weight.device ).expand(weight.shape) rank_in_pack = torch.zeros_like(weight, dtype=torch.int64) return pack_index, rank_in_pack
indices = weight.float().sort(-1, descending=True).indices
pack_index = torch.full_like(weight, fill_value=-1, dtype=torch.int64) rank_in_pack = torch.full_like(weight, fill_value=-1, dtype=torch.int64)
pack_weights = torch.zeros(num_layers, num_packs, dtype=weight.dtype, device=weight.device) pack_items = torch.zeros(num_layers, num_packs, dtype=torch.int64, device=weight.device)
for j in range(num_groups): groups = indices[:, j]
available_mask = (pack_items < groups_per_pack)
masked_pack_weights = torch.where(available_mask, pack_weights, torch.inf) packs = torch.argmin(masked_pack_weights, dim=1)
rank_in_pack_current = pack_items[torch.arange(num_layers), packs] pack_index[torch.arange(num_layers), groups] = packs rank_in_pack[torch.arange(num_layers), groups] = rank_in_pack_current
pack_weights.scatter_add_(1, packs.unsqueeze(1), weight[torch.arange(num_layers), groups].unsqueeze(1)) pack_items[torch.arange(num_layers), packs] += 1
return pack_index, rank_in_pack
def balanced_packing_vectorized_with_comm( weight: torch.Tensor, num_packs: int, phy2mlog: Optional[torch.Tensor] = None, comm_penalty: Optional[torch.Tensor] = None, ) -> Tuple[torch.Tensor, torch.Tensor]: """ Pack n weighted objects to m packs, such that each bin contains exactly n/m objects and the weights of all packs are as balanced as possible. Parameters: weight: [X, n], the weight of each item num_packs: number of packs comm_penalty: [X, n, num_packs], communication penalty for placing item j in pack k for layer i Returns: pack_index: [X, n], the pack index of each item rank_in_pack: [X, n], the rank of the item in the pack """ num_layers, num_groups = weight.shape assert num_groups % num_packs == 0 groups_per_pack = num_groups // num_packs
if groups_per_pack == 1: pack_index = torch.arange( weight.size(-1), dtype=torch.int64, device=weight.device ).expand(weight.shape) rank_in_pack = torch.zeros_like(weight, dtype=torch.int64) return pack_index, rank_in_pack
indices = weight.float().sort(-1, descending=True).indices
pack_index = torch.full_like(weight, fill_value=-1, dtype=torch.int64) rank_in_pack = torch.full_like(weight, fill_value=-1, dtype=torch.int64)
pack_weights = torch.zeros(num_layers, num_packs, dtype=weight.dtype, device=weight.device) pack_items = torch.zeros(num_layers, num_packs, dtype=torch.int64, device=weight.device)
for j in range(num_groups): groups = indices[:, j]
available_mask = (pack_items < groups_per_pack)
base_costs = pack_weights.clone()
if comm_penalty is not None and _REBALANCE_CALL_COUNT >= 3: logical_expert_ids = phy2mlog[torch.arange(num_layers), groups]
current_penalties = comm_penalty[ torch.arange(num_layers), logical_expert_ids, : ].view(num_layers, num_packs, groups_per_pack)[:, :, 0]
penalty_factor = 1.0 + current_penalties
adjusted_costs = base_costs * penalty_factor else: adjusted_costs = base_costs
masked_adjusted_costs = torch.where(available_mask, adjusted_costs, torch.inf) packs = torch.argmin(masked_adjusted_costs, dim=1)
rank_in_pack_current = pack_items[torch.arange(num_layers), packs] pack_index[torch.arange(num_layers), groups] = packs rank_in_pack[torch.arange(num_layers), groups] = rank_in_pack_current
pack_weights.scatter_add_(1, packs.unsqueeze(1), weight[torch.arange(num_layers), groups].unsqueeze(1)) pack_items[torch.arange(num_layers), packs] += 1
return pack_index, rank_in_pack
def replicate_experts( weight: torch.Tensor, num_phy: int ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """ Replicate `num_log` experts to `num_phy` replicas, such that the maximum load of all replicas is minimized. Parameters: weight: [X, num_log] num_phy: total number of experts after replication Returns: phy2log: [X, num_phy], logical expert id of each physical expert rank: [X, num_phy], the replica rank logcnt: [X, num_log], number of replicas for each logical expert """ n, num_log = weight.shape num_redundant = num_phy - num_log assert num_redundant >= 0 device = weight.device phy2log = torch.arange(num_phy, dtype=torch.int64, device=device).repeat(n, 1) rank = torch.zeros(n, num_phy, dtype=torch.int64, device=device) logcnt = torch.ones(n, num_log, dtype=torch.int64, device=device) arangen = torch.arange(n, dtype=torch.int64, device=device) for i in range(num_log, num_phy): redundant_indices = (weight / logcnt).max(dim=-1).indices phy2log[:, i] = redundant_indices rank[:, i] = logcnt[arangen, redundant_indices] logcnt[arangen, redundant_indices] += 1 return phy2log, rank, logcnt
def rebalance_experts_hierarchical( weight: torch.Tensor, num_physical_experts: int, num_groups: int, num_nodes: int, num_gpus: int, comm_penalty: Optional[torch.Tensor] = None, ): """ Parameters: weight: [num_moe_layers, num_logical_experts] num_physical_experts: number of physical experts after replication num_groups: number of expert groups num_nodes: number of server nodes, where the intra-node network (e.g, NVLink) is faster num_gpus: number of GPUs, must be a multiple of `num_nodes` Returns: physical_to_logical_map: [num_moe_layers, num_physical_experts] logical_to_physical_map: [num_moe_layers, num_logical_experts, X] logical_count: [num_moe_layers, num_logical_experts] """ num_layers, num_logical_experts = weight.shape assert num_logical_experts % num_groups == 0 group_size = num_logical_experts // num_groups assert num_groups % num_nodes == 0 groups_per_node = num_groups // num_nodes assert num_gpus % num_nodes == 0 assert num_physical_experts % num_gpus == 0 phy_experts_per_gpu = num_physical_experts // num_gpus
def inverse(perm: torch.Tensor) -> torch.Tensor: inv = torch.empty_like(perm) inv.scatter_( 1, perm, torch.arange(perm.size(1), dtype=torch.int64, device=perm.device).expand( perm.shape ), ) return inv
tokens_per_group = weight.unflatten(-1, (num_groups, group_size)).sum(-1) group_pack_index, group_rank_in_pack = balanced_packing(tokens_per_group, num_nodes) log2mlog = ( ( (group_pack_index * groups_per_node + group_rank_in_pack) * group_size ).unsqueeze(-1) + torch.arange(group_size, dtype=torch.int64, device=group_pack_index.device) ).flatten(-2) mlog2log = inverse(log2mlog)
tokens_per_mlog = weight.gather(-1, mlog2log).view( -1, num_logical_experts // num_nodes ) phy2mlog, phyrank, mlogcnt = replicate_experts( tokens_per_mlog, num_physical_experts // num_nodes )
tokens_per_phy = (tokens_per_mlog / mlogcnt).gather(-1, phy2mlog) pack_index, rank_in_pack = balanced_packing_vectorized_with_comm(tokens_per_phy, num_gpus // num_nodes, phy2mlog, comm_penalty) phy2pphy = pack_index * phy_experts_per_gpu + rank_in_pack pphy2phy = inverse(phy2pphy)
pphy2mlog = phy2mlog.gather( -1, pphy2phy ) pphy2mlog = ( pphy2mlog.view(num_layers, num_nodes, -1) + torch.arange( 0, num_logical_experts, num_logical_experts // num_nodes, device=group_pack_index.device, ).view(1, -1, 1) ).flatten(-2) pphy2log = mlog2log.gather(-1, pphy2mlog) pphyrank = phyrank.gather(-1, pphy2phy).view(num_layers, -1) logcnt = mlogcnt.view(num_layers, -1).gather(-1, log2mlog) return pphy2log, pphyrank, logcnt
def rebalance_experts( weight: torch.Tensor, num_replicas: int, num_gpus: int, comm_penalty: Optional[torch.Tensor] = None, ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """ Entry point for expert-parallelism load balancer. Parameters: weight: [layers, num_logical_experts], the load statistics for all logical experts num_replicas: number of physical experts, must be a multiple of `num_gpus` num_groups: number of expert groups num_nodes: number of server nodes, where the intra-node network (e.g, NVLink) is faster num_gpus: number of GPUs, must be a multiple of `num_nodes` Returns: physical_to_logical_map: [layers, num_replicas], the expert index of each replica logical_to_physical_map: [layers, num_logical_experts, X], the replica indices for each expert expert_count: [layers, num_logical_experts], number of physical replicas for each logical expert """ global _REBALANCE_CALL_COUNT if _REBALANCE_CALL_COUNT < 3: _REBALANCE_CALL_COUNT += 1
num_layers, num_logical_experts = weight.shape weight = weight.float().cpu() phy2log, phyrank, logcnt = rebalance_experts_hierarchical( weight, num_replicas, 1, 1, num_gpus, comm_penalty ) maxlogcnt = logcnt.max().item() log2phy: torch.Tensor = torch.full( (num_layers, num_logical_experts, maxlogcnt), -1, dtype=torch.int64, device=logcnt.device, ) log2phy.view(num_layers, -1).scatter_( -1, phy2log * maxlogcnt + phyrank, torch.arange(num_replicas, dtype=torch.int64, device=log2phy.device).expand( num_layers, -1 ), ) return phy2log, log2phy, logcnt
__all__ = ["rebalance_experts"]
|