File size: 1,715 Bytes
cfa2024
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
"""Hold the shared GPU for the VLR chain between its stages (never touches other jobs): the free memory is polled
every 0.5 s (no CUDA context meanwhile); once >= need MiB are free, all of it but 1 GB is allocated and kept until one
of our GPU processes calls gpu_take.take_gpu() right before its own allocation.
Files: /tmp/vlr_gpu_hold.pid (holder alive), /tmp/vlr_gpu_held (memory held), /tmp/vlr_gpu_release (handover asked).
Run (db): python gpu_hold.py [need_mib]
"""
import os
import subprocess
import sys
import time

import torch

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 main():
    need = int(sys.argv[1]) if len(sys.argv) > 1 else 12000
    open(PID, 'w').write(str(os.getpid()))
    try:
        while free_mib() < need:                       # no CUDA context before: it would take memory from the running job
            time.sleep(.5)
        f = free_mib()
        x = torch.empty(int((f - 1000) * 2 ** 20), dtype=torch.uint8, device='cuda')
        open(HELD, 'w').write(str(os.getpid()))
        print(time.strftime('%H:%M:%S'), f'holding {f - 1000} MiB', flush=True)
        while not os.path.exists(RELEASE):
            time.sleep(.1)
        del x
        torch.cuda.empty_cache()
        print(time.strftime('%H:%M:%S'), 'released', flush=True)
    finally:
        for p in (HELD, PID, RELEASE):
            if os.path.exists(p):
                os.remove(p)


if __name__ == '__main__':
    main()