1
0
Fork 0
tinygrab/test/test_gc.py

40 lines
1.1 KiB
Python
Raw Permalink Normal View History

2020-12-06 11:34:40 -07:00
#!/usr/bin/env python
import gc
2020-12-06 11:34:40 -07:00
import unittest
2023-02-27 07:53:18 -07:00
import numpy as np
from tinygrad.tensor import Tensor
2020-12-06 11:34:40 -07:00
2023-12-04 22:01:04 -07:00
def tensors_allocated():
2023-12-04 22:01:04 -07:00
return sum([isinstance(x, Tensor) for x in gc.get_objects()])
2020-12-06 11:34:40 -07:00
class TestGC(unittest.TestCase):
2023-12-04 22:01:04 -07:00
def test_gc(self):
a = Tensor.zeros(4, 4, requires_grad=True)
b = Tensor.zeros(4, 4, requires_grad=True)
(a * b).mean().backward()
assert tensors_allocated() > 0
del a, b
assert tensors_allocated() == 0
2023-12-04 22:01:04 -07:00
def test_gc_complex(self):
a = Tensor(np.zeros((4, 4), dtype=np.float32), requires_grad=True)
b = Tensor(np.zeros((4, 4), dtype=np.float32), requires_grad=True)
assert tensors_allocated() == 2
(a * b).mean().backward()
assert tensors_allocated() == 4
del b
assert tensors_allocated() == 2
b = Tensor(np.zeros((4, 4), dtype=np.float32), requires_grad=True)
print(tensors_allocated())
(a * b).mean().backward()
print(tensors_allocated())
assert tensors_allocated() == 4
del b
assert tensors_allocated() == 2
2020-12-06 11:34:40 -07:00
2023-12-04 22:01:04 -07:00
if __name__ == "__main__":
unittest.main()