"""
Clear GPU memory and stop any GPU processes.
"""

import torch
import subprocess
import os

print("Clearing GPU memory...")

# Clear PyTorch cache
if torch.cuda.is_available():
    torch.cuda.empty_cache()
    print("[OK] Cleared PyTorch GPU cache")
    
    # Try to see what's using GPU
    try:
        result = subprocess.run(['nvidia-smi', '--query-compute-apps=pid,process_name,used_memory', '--format=csv'], 
                              capture_output=True, text=True, timeout=5)
        if result.stdout.strip():
            print("\nCurrent GPU processes:")
            print(result.stdout)
            print("\nIf you see Python processes above, they're using GPU memory.")
            print("You may want to stop them manually if they're old training runs.")
    except:
        pass
    
    print(f"\nGPU Memory Status:")
    print(f"  Total: {torch.cuda.get_device_properties(0).total_memory / 1e9:.2f} GB")
    print(f"  Allocated: {torch.cuda.memory_allocated(0) / 1e9:.2f} GB")
    print(f"  Cached: {torch.cuda.memory_reserved(0) / 1e9:.2f} GB")
    print(f"\n[OK] GPU ready for new training!")

