PyTorch torch.cuda.empty_cache function
PyTorch torch reference manual
torch.cuda.empty_cache is a PyTorch function for clearing the CUDA cache. It frees unused cached memory so it can be reallocated.
Function definition
torch.cuda.empty_cache()
Usage examples
Example
import
torch
Clear the CUDA cache
if
torch.
cuda
.
is_available
(
)
:
Create some tensors
x
=
torch.
randn
(
1000
,
1000
)
.
cuda
(
)
y
=
torch.
randn
(
1000
,
1000
)
.
cuda
(
)
Clear the cache
torch.
cuda
.
empty_cache
(
)
(
"CUDA cache cleared"
)
Check memory
(
f
"Memory allocated: {torch.cuda.memory_allocated() / 1024**2:.2f} MB"
)
else
:
(
"CUDA not available"
)