)
num_local_rows = padded_num_embeddings // ep_size
row_start = ep_rank * num_local_rows
flat_ids = hash_ids.reshape(-1)
torch._check_index( # pylint: disable=protected-access
((flat_ids >= 0) & (flat_ids < padded_num_embeddings)).all().item(),
lambda: "Engram hash requested a row outside the padded table",
)
owner = torch.div(flat_ids, num_local_rows, rounding_mode="floor").long()
# A fixed-size histogram keeps the peer counts in the graph even when
# an owner receives no rows. The exchange only needs one count per peer.
local_counts = owner.new_zeros(ep_size).scatter_add_(0, owner, torch.ones_like(owner))
received_counts = ep_exchange_counts(local_counts, ep_group)
send_counts = ep_split_sizes(local_counts, flat_ids.numel())
recv_counts = ep_split_sizes(received_counts)
# Ascend ArgSort executes integer inputs on AiCPU. The owner range is
# bounded by ep_size, so float32 preserves it exactly and stays on AiCore.
sort_indices = torch.argsort(owner.float(), stable=True)