"""Hand the GPU from gpu_hold.py to the calling process, right before that process allocates: wait until the holder holds the memory, ask it to release, wait until it has exited. Without a holder, wait for need MiB free (0.5 s polls). Then cuBLAS is initialised and all free memory but 1.5 GB is reserved in PyTorch's caching allocator, so no other job can take it while the calling process warms up (the cache is reused by its own allocations).""" import os import subprocess import time PID, HELD, RELEASE = '/tmp/vlr_gpu_hold.pid', '/tmp/vlr_gpu_held', '/tmp/vlr_gpu_release' def _free_mib(): o = subprocess.run(['nvidia-smi', '--query-gpu=memory.total,memory.used', '--format=csv,noheader,nounits'], capture_output=True, text=True).stdout.split(',') return int(o[0]) - int(o[1]) def take_gpu(need): if os.path.exists(PID): while os.path.exists(PID) and not os.path.exists(HELD): time.sleep(.5) if os.path.exists(HELD): open(RELEASE, 'w').close() while os.path.exists(PID): time.sleep(.05) print(time.strftime('%H:%M:%S'), 'GPU taken over from gpu_hold', flush=True) _reserve() return while _free_mib() < need: time.sleep(.5) print(time.strftime('%H:%M:%S'), 'GPU free -> run', flush=True) _reserve() def _reserve(): import torch a = torch.ones(64, 64, device='cuda') # cuBLAS handles and workspaces live outside the cache: (a @ a).sum().item() # create them before reserving with torch.autocast('cuda', dtype=torch.bfloat16): (a @ a).sum().item() f = _free_mib() x = torch.empty(int((f - 1500) * 2 ** 20), dtype=torch.uint8, device='cuda') del x # stays reserved in the cache for this process print(time.strftime('%H:%M:%S'), f'reserved {f - 1500} MiB', flush=True)