PyTorch torch.cuda.empty_cache Function


Pytorch torch 参考手册PyTorch torch Reference Manual

torch.cuda.empty_cacheIt is a function in PyTorch used to clear the CUDA cache. It releases unused cached memory so that it can be reallocated.

Function Definition

torch.cuda.empty_cache()

Usage Example

Example

import torch

# Clear 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 参考手册PyTorch torch Reference Manual

Other Extensions