# GPU- clear variable after use

**URL:** <https://discuss.pytorch.org/t/gpu-clear-variable-after-use/166702>\
**Category:** Uncategorized\
**Created:** [November 23, 2022, 9:58am UTC](https://discuss.pytorch.org/t/gpu-clear-variable-after-use/166702 "2022-11-23T09:58:38Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![nstrek](https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/n/53a042/32.png) [@nstrek](https://discuss.pytorch.org/u/nstrek)\
**Post date:** [November 7, 2023, 11:31pm UTC](https://discuss.pytorch.org/t/gpu-clear-variable-after-use/166702/2 "2023-11-07T23:31:25Z")

</div>

You can try this snippet:

```auto
import gc
gc.collect()

with torch.no_grad():
    torch.cuda.empty_cache()

```

and read:

> [@How can we release GPU memory cache?](https://discuss.pytorch.org/t/how-can-we-release-gpu-memory-cache/14530/18):
>
> This works only some of the times. Even when I clear out all the variables, restart the kernel, and execute torch.cuda.empty\_cache() as the first line in my code, I still get a ‘CUDA out of memory’ error.

> <https://stackoverflow.com/questions/57858433/how-to-clear-gpu-memory-after-pytorch-model-training-without-restarting-kernel>

---

_[View the full topic](https://discuss.pytorch.org/t/gpu-clear-variable-after-use/166702)._
