jax.clear_backends() does not release device memory
Description
jax.clear_backends() does not release device memory allocated by BFC allocator. For example, running jax ut TF_CPP_MIN_LOG_LEVEL=0 python tests/clear_backends_test.py on A100 40G, you can see infos like I external/xla/xla/stream_executor/cuda/cuda_driver.cc:1571] failed to allocate 29.67GiB (31861358592 bytes) from device: CUDA_ERROR_OUT_OF_MEMORY: out of memory after Clearing JAX backend caches. The reason is that xla first allocate 0.75*40G in BFC at the first call of g, then after clear_backends() and call g again, it will try to Extend the BFC Allocator by 9G instead of release or use the previous 29G.
Here's a test case that can pass without clear_backends() but OOM with it.
from absl.testing import absltest
import jax
from jax import config
from jax._src import test_util as jtu
from jax._src import xla_bridge as xb
config.parse_flags_with_absl()
class ClearBackendsTest(jtu.JaxTestCase):
def test_clear_backends(self):
g = jax.jit(lambda x: x+1.)
a = jax.numpy.zeros((1024,1024,512,4),dtype=jax.numpy.float32)
a = g(a)
print(a)
jax.clear_backends() #skip this line to pass
b = jax.numpy.ones((1024,1024,512,4),dtype=jax.numpy.float32)
b = g(b)
print(b)
if __name__ == "__main__":
absltest.main(testLoader=jtu.JaxTestLoader())
System info (python version, jaxlib version, accelerator, etc.)
I'm running jax compiled from main on A100 40G.
jax: 0.4.26.dev20240229+58f898b36 jaxlib: 0.4.26.dev20240229 numpy: 1.26.4 python: 3.10.13 (main, Sep 11 2023, 13:44:35) [GCC 11.2.0] jax.devices (1 total, 1 local): [cuda(id=0)] process_count: 1 platform: uname_result(system='Linux', node='milan-01', release='5.4.0-169-generic', version='#187-Ubuntu SMP Thu Nov 23 14:52:28 UTC 2023', machine='x86_64')
Thanks for reporting this. This jax.clear_backends() API is a big footgun and it is actually not doing what we intend it to do. Our plan is to deprecate it. I am curious what's your use case here? In most cases, jax.clear_caches() is a safer API.
Thanks. I just run the UT and found this weird behavior on intel platform. I'm fine if jax.clear_backends() is deprecated. I didn't see similar issues on jax.clear_caches() .