Last active
January 31, 2024 19:34
-
-
Save 0x00b1/f5b44e576652337f5d8a5f61f04d87e1 to your computer and use it in GitHub Desktop.
PyTorch `segment_sum` operator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import Optional | |
import math | |
from torch import Tensor | |
import torch | |
def segment_sum(input: Tensor, indexes: Tensor, n: Optional[int] = None, **kwargs) -> Tensor: | |
if indexes.ndim == 1: | |
indexes = torch.repeat_interleave(indexes, math.prod([*input.shape[1:]])).view(*[indexes.shape[0], *input.shape[1:]]) | |
if n is None: | |
n = max([*indexes]) + 1 | |
return torch.zeros(n, *input.shape[1:]).scatter_add(0, indexes, input.to(torch.float32)).to(**kwargs) |
Author
0x00b1
commented
Jan 31, 2024
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment