2020-12-06 11:34:40 -07:00
|
|
|
#!/usr/bin/env python
|
2020-12-08 15:18:45 -07:00
|
|
|
import gc
|
2020-12-06 11:34:40 -07:00
|
|
|
import unittest
|
2021-01-01 07:19:03 -07:00
|
|
|
from tinygrad.tensor import Tensor
|
2020-12-06 11:34:40 -07:00
|
|
|
|
2020-12-08 15:18:45 -07:00
|
|
|
def tensors_allocated():
|
2020-12-09 03:52:28 -07:00
|
|
|
return sum([isinstance(x, Tensor) for x in gc.get_objects()])
|
2020-12-17 15:37:31 -07:00
|
|
|
|
2020-12-06 11:34:40 -07:00
|
|
|
class TestGC(unittest.TestCase):
|
2020-12-08 15:18:45 -07:00
|
|
|
|
2020-12-06 11:34:40 -07:00
|
|
|
def test_gc(self):
|
2022-09-21 09:16:02 -06:00
|
|
|
a = Tensor.zeros(4, 4, requires_grad=True)
|
|
|
|
b = Tensor.zeros(4, 4, requires_grad=True)
|
2020-12-06 11:34:40 -07:00
|
|
|
(a*b).mean().backward()
|
2020-12-08 15:18:45 -07:00
|
|
|
assert(tensors_allocated() > 0)
|
2020-12-06 11:34:40 -07:00
|
|
|
del a,b
|
2020-12-08 15:18:45 -07:00
|
|
|
assert(tensors_allocated() == 0)
|
2020-12-06 11:34:40 -07:00
|
|
|
|
|
|
|
def test_gc_complex(self):
|
2022-09-21 09:16:02 -06:00
|
|
|
a = Tensor.zeros(4, 4, requires_grad=True)
|
|
|
|
b = Tensor.zeros(4, 4, requires_grad=True)
|
2020-12-08 15:18:45 -07:00
|
|
|
assert(tensors_allocated() == 2)
|
2020-12-06 11:34:40 -07:00
|
|
|
(a*b).mean().backward()
|
2020-12-08 15:18:45 -07:00
|
|
|
assert(tensors_allocated() == 4)
|
2020-12-06 11:34:40 -07:00
|
|
|
del b
|
2020-12-08 15:18:45 -07:00
|
|
|
assert(tensors_allocated() == 2)
|
2022-09-21 09:16:02 -06:00
|
|
|
b = Tensor.zeros(4, 4, requires_grad=True)
|
2020-12-08 15:18:45 -07:00
|
|
|
print(tensors_allocated())
|
2020-12-06 11:34:40 -07:00
|
|
|
(a*b).mean().backward()
|
2020-12-08 15:18:45 -07:00
|
|
|
print(tensors_allocated())
|
|
|
|
assert(tensors_allocated() == 4)
|
2020-12-06 11:34:40 -07:00
|
|
|
del b
|
2020-12-08 15:18:45 -07:00
|
|
|
assert(tensors_allocated() == 2)
|
2020-12-06 11:34:40 -07:00
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
unittest.main()
|