Skip to content

Add index_add_ #99

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions namedtensor/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -424,6 +424,19 @@ def test_takes():
)


def test_index_add():

base = ntorch.zeros(3, 5, names=("beta", "alpha"))
vals = ntorch.randn(3, 4, names=("beta", "time"))
index = ntorch.randint(0, 5, (4,), names=("time"))

result = base.index_add_("alpha", index, vals)
expected_result = base.values.index_add_(1, index.values, vals.values)

assert (result._tensor == expected_result).all()
assert result.shape == OrderedDict([("beta", 3), ("alpha", 5)])


def test_narrow():
base1 = torch.randn(10, 2, 50)

Expand Down
13 changes: 13 additions & 0 deletions namedtensor/torch_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,19 @@ def index_select(self, dim, index):
new_names,
)

@staticmethod
def index_add_(self, dim, index, tensor):
"""Accumulate the elements of 'tensor' into the self tensor
by adding to the indices in the order given in 'index'."""
name = dim
dim = self._schema.get(name)
tensor_names = [i for i in self._schema._names]
tensor_names[dim] = index._schema._names[0]
self._tensor.index_add_(
dim, index._tensor, tensor._force_order(tensor_names)._tensor
)
return self

@staticmethod
def index_fill_(self, dim, index, val):
"Index into dimension names with the `index` named tensors."
Expand Down
1 change: 1 addition & 0 deletions namedtensor/torch_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -457,6 +457,7 @@ def __dir__(self):
"masked_scatter",
"masked_fill_",
"index_select",
"index_add_",
"index_copy_",
"index_fill_",
"topk",
Expand Down