Skip to content

torch.Tensor reverse operators (__rmul__) should return NotImplemented for unsupported types #26333

@yaroslavvb

Description

@yaroslavvb

Currently if the the argument of __rmatmul__ is not a Tensor, PyTorch throws *** TypeError: matmul(): argument 'other' (position 1) must be Tensor, not Vec

Python data model asks that it return NotImplemented in such case. This allows interpreter to dispatch op to the proper implementation.
(ie see https://docs.python.org/3/library/numbers.html#implementing-the-arithmetic-operations)

Current behavior makes it hard to implement custom types. IE

class FactoredMatrix:
  def __init__(self, mat):
    self.mat = mat
  def __matmul__(self, other):
    return 0
  def __rmatmul__(self, other):
    return 1
x = torch.ones((2,2))
print(FactoredMatrix(x) @ x)  # works
print(x @ FactoredMatrix(x))  # fails

cc @ezyang @gchanan @zou3519

Metadata

Metadata

Assignees

Labels

enhancementNot as big of a feature, but technically not a bug. Should be easy to fixfeatureA request for a proper, new feature.high prioritytriagedThis issue has been looked at a team member, and triaged and prioritized into an appropriate module

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions