PyTorch equivalent of index_add_ that takes the maximum instead
In PyTorch, the index_add_ method of a Tensor does a summation using a provided index tensor:

idx = torch.LongTensor([0,0,0,0,1,1])
child = torch.FloatTensor([1, 3, 5, 10, 8, 1])
parent = torch.FloatTensor([0, 0])
parent.index_add_(0, idx, child)


The first four child values sum into parent[0] and the next two go into parent[1], so the result is tensor([ 19.,   9.])

However, I need to do index_max_ instead, which doesn't exist in the API. Is there a way to do it efficiently (without having to loop or allocate more memory)? One (bad) loop solution would be:

for i in range(max(idx)+1):
    parent[i] = torch.max(child[idx == i])


This produces the desired result of tensor([ 10.,   8.]), but very slowly.

A solution playing with the indices:

def index_max(child, idx, num_partitions): 
    # Building a num_partition x num_samples matrix `idx_tiled`:
    partition_idx = torch.range(0, num_partitions - 1, dtype=torch.long)
    partition_idx = partition_idx.view(-1, 1).expand(num_partitions, idx.shape[0])
    idx_tiled = idx.view(1, -1).repeat(num_partitions, 1)
    idx_tiled = (idx_tiled == partition_idx).float()
    # i.e. idx_tiled[i,j] == 1 if idx[j] == i, else 0

    parent = idx_tiled * child
    parent, _ = torch.max(parent, dim=1)
    return parent


Benchmarking:

import timeit

setup = '''
import torch

def index_max_v0(child, idx, num_partitions):
    parent = torch.zeros(num_partitions)
    for i in range(max(idx) + 1):
        parent[i] = torch.max(child[idx == i])
    return parent

def index_max(child, idx, num_partitions):

    # Building a num_partition x num_samples matrix `idx_tiled` 
    # containing for each row indices of
    partition_idx = torch.range(0, num_partitions - 1, dtype=torch.long)
    partition_idx = partition_idx.view(-1, 1).expand(num_partitions, idx.shape[0])
    idx_tiled = idx.view(1, -1).repeat(num_partitions, 1)
    idx_tiled = (idx_tiled == partition_idx).float()

    parent = idx_tiled * child
    parent, _ = torch.max(parent, dim=1)
    return parent

idx = torch.LongTensor([0,0,0,0,1,1])
child = torch.FloatTensor([1, 3, 5, 10, 8, 1])
num_partitions = torch.unique(idx).shape[0]

'''
print(min(timeit.Timer('index_max_v0(child, idx, num_partitions)', setup=setup).repeat(5, 1000)))
# &gt; 0.05308796599274501
print(min(timeit.Timer('index_max(child, idx, num_partitions)', setup=setup).repeat(5, 1000)))
# &gt; 0.024736385996220633

