test_gc.py 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. #!/usr/bin/env python
  2. import gc
  3. import unittest
  4. import numpy as np
  5. from tinygrad.tensor import Tensor
  6. def tensors_allocated():
  7. return sum([isinstance(x, Tensor) for x in gc.get_objects()])
  8. class TestGC(unittest.TestCase):
  9. def test_gc(self):
  10. a = Tensor.rand(4, 4, requires_grad=True)
  11. b = Tensor.zeros(4, 4, requires_grad=True)
  12. (a*b).mean().backward()
  13. assert(tensors_allocated() > 0)
  14. del a,b
  15. assert(tensors_allocated() == 1) # one for Tensor._rng_counter
  16. def test_gc_complex(self):
  17. a = Tensor(np.zeros((4, 4), dtype=np.float32), requires_grad=True)
  18. b = Tensor.rand(4, 4, requires_grad=True)
  19. assert(tensors_allocated() == 3)
  20. (a*b).mean().backward()
  21. assert(tensors_allocated() == 5)
  22. del b
  23. assert(tensors_allocated() == 3)
  24. b = Tensor(np.zeros((4, 4), dtype=np.float32), requires_grad=True)
  25. print(tensors_allocated())
  26. (a*b).mean().backward()
  27. print(tensors_allocated())
  28. assert(tensors_allocated() == 5)
  29. del b
  30. assert(tensors_allocated() == 3)
  31. if __name__ == '__main__':
  32. unittest.main()