Select the top-k items inside every group without a Python loop
Why it matters Per-query top-k over flat candidate arrays is the last step of batched retrieval, re-ranking and MoE routing.
Retrieval systems score many candidates for many queries in one flat array and then keep the top k per query. Looping over queries in Python is slow; one lexsort plus a rank-within-group trick does it all at once.
Write topk_per_group(scores, groups, k). scores is a 1D float array, groups a 1D int array of the same length (group ids, any order, not necessarily contiguous). For each group keep the k highest-scoring indices (fewer if the group is smaller); ties go to the smaller index. Return a 1D int array of the kept indices ordered by group id ascending, then by score descending (ties by index).
def topk_per_group(scores, groups, k)Example
topk_per_group([0.1, 0.9, 0.5, 0.7, 0.3], [1, 0, 1, 0, 1], 2) is [1, 3, 2, 4].
Understand the idea
To take the top k inside many groups at once, sort everything so each group is contiguous and best-first, then number the rows inside each group and keep numbers below k.
Worked example: scores [0.1, 0.9, 0.5, 0.7, 0.3], groups [1, 0, 1, 0, 1], k = 2. Sorted by group, then score descending: group 0 gives indices 1 (0.9), 3 (0.7); group 1 gives 2 (0.5), 4 (0.3), 0 (0.1). Ranks inside groups: 0, 1, 0, 1, 2. Keeping rank < 2 gives [1, 3, 2, 4].
Rule: order = lexsort((index, -score, group)). start[i] = (group changes at i). first = running max of start positions. rank = position - first. keep rank < k.
Batched retrieval keeps the top documents per query this way, and MoE routers keep the top tokens per expert.
Shapes and data flow
scores, groups (N,) -> order (N,) -> rank (N,) -> kept indices (<= N,)