File size: 5,063 Bytes
36b714d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
"""Small, dependency-free persistence and whole-device NVML telemetry helpers."""
import ctypes
import json
import os
from pathlib import Path
import threading
import time
import subprocess
import sys

ROOT = Path(__file__).resolve().parents[1]


def save_json(path, value):
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    temporary = path.with_suffix(path.suffix + '.tmp')
    durable = os.environ.get('EVAL_DURABLE_WRITES') == '1'
    with temporary.open('w') as stream:
        stream.write(json.dumps(value, indent=2, ensure_ascii=False, default=str) + '\n')
        if durable:
            stream.flush()
            os.fsync(stream.fileno())
    os.replace(temporary, path)
    if durable:
        directory = os.open(str(path.parent), os.O_RDONLY | os.O_DIRECTORY)
        try:
            os.fsync(directory)
        finally:
            os.close(directory)


def append_json(path, value):
    with Path(path).open('a') as f:
        f.write(json.dumps(value, ensure_ascii=False, default=str) + '\n')


class MemoryInfo(ctypes.Structure):
    _fields_ = [(name, ctypes.c_ulonglong) for name in ('total', 'free', 'used')]


def nvml_device(nvml):
    """Select the allocation UUID explicitly; CUDA masks do not remap NVML."""
    handle = ctypes.c_void_p()
    uuid = os.environ.get('EVAL_GPU_UUID')
    if uuid:
        if not uuid.startswith('GPU-') or ',' in uuid:
            raise ValueError('EVAL_GPU_UUID must identify exactly one physical GPU')
        code = nvml.nvmlDeviceGetHandleByUUID(uuid.encode(), ctypes.byref(handle))
    else:
        code = nvml.nvmlDeviceGetHandleByIndex_v2(0, ctypes.byref(handle))
    if code:
        raise RuntimeError(f'NVML device selection error {code}')
    return handle


class Telemetry:
    def __init__(self, path):
        self.path = Path(path)
        self.nvml = ctypes.CDLL('libnvidia-ml.so.1')
        self.check(self.nvml.nvmlInit_v2())
        self.handle = nvml_device(self.nvml)
        self.rows = []
        self.lock = threading.Lock()
        self.sample()
        # A Python thread misses samples while simulator extensions hold the
        # GIL during setup. A separate sampler process keeps a true 1 s cadence.
        self.process = subprocess.Popen([sys.executable, str(Path(__file__).resolve()),
                                         '--sample', str(self.path.resolve())],
                                        stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)

    @staticmethod
    def check(code):
        if code:
            raise RuntimeError(f'NVML error {code}')

    def sample(self):
        with self.lock:
            info = MemoryInfo()
            code = self.nvml.nvmlDeviceGetMemoryInfo(self.handle, ctypes.byref(info))
            row = {'monotonic': time.monotonic(), 'timestamp': time.time(), 'error': code}
            if os.environ.get('EVAL_GPU_UUID'):
                row['gpu_uuid'] = os.environ['EVAL_GPU_UUID']
            if code == 0:
                row['used_mib'] = info.used / 1024**2
                row['total_mib'] = info.total / 1024**2
            self.rows.append(row)
            append_json(self.path, row)
            return row

    def summary(self, start, end):
        if hasattr(self, 'path'):
            sampled = []
            for line in self.path.read_text().splitlines():
                try:
                    sampled.append(json.loads(line))
                except json.JSONDecodeError:
                    pass  # The only allowable partial line is the newest write.
        else:
            sampled = self.rows
        rows = sorted([r for r in sampled if start <= r['monotonic'] <= end], key=lambda r:r['monotonic'])
        integral = covered = 0.0
        for a, b in zip(rows, rows[1:]):
            dt = b['monotonic'] - a['monotonic']
            if a['error'] or b['error'] or dt > 2.5:
                continue
            integral += (a['used_mib'] + b['used_mib']) * 0.5 * dt
            covered += dt
        good = [r['used_mib'] for r in rows if not r['error']]
        return {'memory_integral_mib_seconds': integral,
                'memory_covered_seconds': covered,
                'memory_coverage': covered / (end-start) if end > start else 0,
                'mean_memory_mib': integral / covered if covered else None,
                'peak_memory_mib': max(good) if good else None,
                'memory_samples': len(good)}

    def close(self):
        self.process.terminate()
        self.process.wait(timeout=5)
        self.sample()


if __name__ == '__main__' and len(sys.argv) == 3 and sys.argv[1] == '--sample':
    # Construct only the NVML reader, without recursively spawning a sampler.
    reader = Telemetry.__new__(Telemetry)
    reader.path = Path(sys.argv[2])
    reader.nvml = ctypes.CDLL('libnvidia-ml.so.1')
    reader.check(reader.nvml.nvmlInit_v2())
    reader.handle = nvml_device(reader.nvml)
    reader.rows = []
    reader.lock = threading.Lock()
    while True:
        reader.sample()
        reader.rows.clear()
        time.sleep(1)