Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PyTorch torch.cuda.empty_cache function

PyTorch torch.cuda.empty_cache function


PyTorch torch reference manual 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

(

)

   

print

(

"CUDA cache cleared"

)

   

Check memory

   

print

(

f

"Memory allocated: {torch.cuda.memory_allocated() / 1024**2:.2f} MB"

)

else

:

   

print

(

"CUDA not available"

)


PyTorch torch reference manual PyTorch torch reference manual