Skip to content

Commit

Permalink
iter(TensorProxy) lookaside (#718)
Browse files Browse the repository at this point in the history
  • Loading branch information
nikitaved authored Jul 5, 2024
1 parent 0d80444 commit 415b485
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
9 changes: 9 additions & 0 deletions thunder/core/proxies.py
Original file line number Diff line number Diff line change
Expand Up @@ -1316,6 +1316,15 @@ def __getattr__(self, attr: str, /):

return method_or_value

def __iter__(self):
# NOTE: this implementation is equivalent to torch.Tensor.__iter__

if self.ndim == 0:
raise TypeError("iteration over a 0-dim tensor")

unbound_tuple = self.unbind(0)
return iter(unbound_tuple)

#
# Default attribute
#
Expand Down
44 changes: 44 additions & 0 deletions thunder/tests/test_interpreter.py
Original file line number Diff line number Diff line change
Expand Up @@ -1082,6 +1082,50 @@ def f(a, b, c):
# }


def test_tensor_proxy_iter_lookaside(jit):
t0 = torch.rand(3, 3)
t1 = torch.rand(0, 3)
t2 = torch.rand(())

for x in (t0, t1):

def f(x):
for i, xi in enumerate(x):
pass
return x

jf = jit(f)

assert f(x) is jf(x)

def f(x):
res = 0
for i, xi in enumerate(x):
res = xi
return res

jf = jit(f)

assert_close(jf(x), f(x))

with pytest.raises(TypeError, match="iteration over a 0-d tensor"):
jf(t2)

with pytest.raises(TypeError, match="iteration over a 0-d tensor"):
f(t2)

def f(x):
res = x
for xi in x:
res = res + xi.unsqueeze(0)
return res

jf = jit(f)

for x in (t0, t1):
assert_close(jf(x), f(x))


def test_calling_methods(jit):
jitting = False

Expand Down

0 comments on commit 415b485

Please sign in to comment.