Returns:
Compute-major activations [R,H], counts [C], optional probabilities [R],
and the receiver inverse permutation [R]. C includes home and remote rows.
"""
send, receive, order = plan["token_send"], plan["token_recv"], plan["source_order"]
asynchronous = overlap_compute is not None
hidden = self._exchange(hidden_states.index_select(0, order), send, receive, async_op=asynchronous)
weights = None
if routing_weights is not None:
weights = self._exchange(routing_weights.index_select(0, order).unsqueeze(-1), send, receive,
async_op=asynchronous).reshape(-1)
self._run_overlap(overlap_compute, hidden, weights)
counts, receive_order = plan["counts"], plan["receive_order"]
if hidden.shape[0] and hidden.device.type == "npu":
# torch_npu is optional for CPU import and planning tests.
from hyper_parallel.components.functional.moe_token_permute import ( # pylint: disable=C0415
moe_token_permute,
)
rows = torch.arange(counts.numel(), device=counts.device).repeat_interleave(
counts, output_size=hidden.shape[0],
)
ids = torch.empty_like(rows).scatter_(0, receive_order, rows)
hidden, inverse = moe_token_permute(hidden.contiguous(), ids.to(torch.int32).unsqueeze(-1))
else:
hidden = hidden.index_select(0, receive_order)
inverse = torch.empty_like(receive_order, dtype=torch.int32).scatter_(
0, receive_order, torch.arange(receive_order.numel(), device=receive_order.device, dtype=torch.int32),
)
if weights is not None:
weights = weights.index_select(0, receive_order)
return hidden, counts, weights, inverse
def expert_weights(self, gate_up: Tensor, down: Tensor, plan: dict) -> tuple[Tensor, Tensor]:
"""Exchange only needed replicas using differentiable all-to-all.