File size: 8,691 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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
"""Local capacity telemetry: one NVML GPU and owned Linux process trees.

CPU percentages use one logical CPU as 100%. RSS sums count shared pages once
per process and are not unique physical memory. Host MemAvailable is separate.
"""
import ctypes
import os
from pathlib import Path
import time

from eval_common import MemoryInfo

GIB = 1024 ** 3


class Utilization(ctypes.Structure):
    _fields_ = [('gpu', ctypes.c_uint), ('memory', ctypes.c_uint)]


def read_process(pid, proc_root=Path('/proc')):
    """PID plus start ticks is the identity; comm can contain spaces/parens."""
    try:
        text = (Path(proc_root) / str(pid) / 'stat').read_text()
        suffix = text[text.rfind(')') + 2:].split()
        return {'pid': int(pid), 'start_ticks': int(suffix[19]),
                'ppid': int(suffix[1]), 'pgrp': int(suffix[2]), 'session': int(suffix[3]),
                'state': suffix[0], 'cpu_ticks': int(suffix[11]) + int(suffix[12]),
                'rss_bytes': max(0, int(suffix[21])) * os.sysconf('SC_PAGE_SIZE')}
    except (OSError, ValueError, IndexError):
        return None


def process_snapshot(proc_root=Path('/proc')):
    records = {}
    for path in Path(proc_root).iterdir():
        if path.name.isdigit():
            row = read_process(int(path.name), proc_root)
            if row is not None:
                records[row['pid']] = row
    return records


def identity(row):
    return row['pid'], row['start_ticks']


def owned_processes(snapshot, roots, remembered=()):
    """Follow parent links only from matching identities; retain observed orphans."""
    known = set(roots) | set(remembered)
    selected = {pid for pid, row in snapshot.items() if identity(row) in known}
    while True:
        extra = {pid for pid, row in snapshot.items() if row['ppid'] in selected}
        if extra <= selected:
            break
        selected |= extra
    return [snapshot[pid] for pid in sorted(selected)]


class NvmlGpu:
    def __init__(self, uuid):
        if not uuid or not uuid.startswith('GPU-') or any(x.isspace() for x in uuid) or ',' in uuid:
            raise ValueError('Select one physical GPU UUID explicitly')
        self.uuid = uuid
        self.lib = ctypes.CDLL('libnvidia-ml.so.1')
        self.check(self.lib.nvmlInit_v2())
        self.handle = ctypes.c_void_p()
        self.check(self.lib.nvmlDeviceGetHandleByUUID(uuid.encode(), ctypes.byref(self.handle)))
        actual = ctypes.create_string_buffer(96)
        self.check(self.lib.nvmlDeviceGetUUID(self.handle, actual, len(actual)))
        if actual.value.decode() != uuid:
            raise RuntimeError('NVML GPU UUID mismatch')

    @staticmethod
    def check(code):
        if code:
            raise RuntimeError('NVML error ' + str(code))

    def sample(self):
        memory, utilization, power = MemoryInfo(), Utilization(), ctypes.c_uint()
        self.check(self.lib.nvmlDeviceGetMemoryInfo(self.handle, ctypes.byref(memory)))
        utilization_code = self.lib.nvmlDeviceGetUtilizationRates(self.handle, ctypes.byref(utilization))
        power_code = self.lib.nvmlDeviceGetPowerUsage(self.handle, ctypes.byref(power))
        return {'gpu_uuid': self.uuid, 'memory_used_bytes': memory.used,
                'memory_total_bytes': memory.total,
                'utilization_percent': utilization.gpu if utilization_code == 0 else None,
                'power_watts': power.value / 1000 if power_code == 0 else None,
                'optional_metric_errors': {'utilization': utilization_code, 'power': power_code}}

    def close(self):
        self.lib.nvmlShutdown()


class CapacityTelemetry:
    def __init__(self, gpu_uuid, gpu_reader=None, proc_root=Path('/proc')):
        self.gpu = gpu_reader if gpu_reader is not None else NvmlGpu(gpu_uuid)
        self.proc_root = Path(proc_root)
        self.previous = {}
        self.previous_time = None
        self.remembered = set()
        self.ticks_per_second = os.sysconf('SC_CLK_TCK')

    def sample(self, roots):
        now = time.monotonic()
        snapshot = process_snapshot(self.proc_root)
        rows = owned_processes(snapshot, roots, self.remembered)
        self.remembered = {identity(row) for row in rows}
        elapsed = None if self.previous_time is None else now - self.previous_time
        for row in rows:
            previous = self.previous.get(identity(row))
            row['cpu_percent'] = (100 * (row['cpu_ticks'] - previous) / self.ticks_per_second / elapsed
                                  if previous is not None and elapsed and elapsed > 0 else None)
        self.previous = {identity(row): row['cpu_ticks'] for row in rows}
        self.previous_time = now
        meminfo = {}
        for line in (self.proc_root / 'meminfo').read_text().splitlines():
            key, value = line.split(':', 1)
            if key in ('MemTotal', 'MemAvailable', 'SwapTotal', 'SwapFree'):
                meminfo[key + '_bytes'] = int(value.split()[0]) * 1024
        if 'MemAvailable_bytes' not in meminfo:
            raise RuntimeError('Host MemAvailable is unavailable')
        return {'monotonic': now, 'timestamp': time.time(), 'gpu': self.gpu.sample(),
                'host': meminfo, 'processes': rows,
                'process_tree_rss_bytes': sum(row['rss_bytes'] for row in rows),
                'process_tree_cpu_percent': sum(row['cpu_percent'] or 0 for row in rows),
                'cpu_sample_has_baseline': elapsed is not None,
                'rss_scope': 'Sum of RSS; shared pages can be counted repeatedly across processes.',
                'gpu_scope': 'Whole selected physical GPU, including unrelated existing workloads.'}

    def close(self):
        self.gpu.close()


def summarize_samples(rows, start, end, interval=1.0):
    scoped = [row for row in rows if start <= row['monotonic'] <= end]
    valid = [row for row in scoped if row.get('status') == 'ok']
    covered = integral = 0.0
    metrics = {'gpu_utilization_percent': ('gpu', 'utilization_percent'),
               'gpu_power_watts': ('gpu', 'power_watts'),
               'process_tree_cpu_percent': (None, 'process_tree_cpu_percent')}
    totals = {name: [0.0, 0.0] for name in metrics}
    def value(row, name):
        parent, key = metrics[name]
        if parent is None:
            return row.get(key) if row.get('cpu_sample_has_baseline') else None
        return row[parent].get(key)
    for left, right in zip(scoped, scoped[1:]):
        delta = right['monotonic'] - left['monotonic']
        if left.get('status') == right.get('status') == 'ok' and 0 < delta <= 2.5 * interval:
            integral += delta * (left['gpu']['memory_used_bytes'] + right['gpu']['memory_used_bytes']) / 2
            covered += delta
            for name in metrics:
                a, b = value(left, name), value(right, name)
                # CPU percentage is itself a rate over the preceding interval.
                if name == 'process_tree_cpu_percent' and b is not None:
                    totals[name][0] += delta * b
                    totals[name][1] += delta
                elif a is not None and b is not None:
                    totals[name][0] += delta * (a + b) / 2
                    totals[name][1] += delta
    span = end - start
    summary = {'samples': len(valid), 'failed_samples': len(scoped) - len(valid),
            'gpu_mean_memory_bytes': integral / covered if covered else None,
            'gpu_peak_memory_bytes': max((r['gpu']['memory_used_bytes'] for r in valid), default=None),
            'process_tree_peak_rss_bytes': max((r['process_tree_rss_bytes'] for r in valid), default=None),
            'host_min_available_bytes': min((r['host']['MemAvailable_bytes'] for r in valid), default=None),
            'covered_seconds': covered, 'coverage': covered / span if span > 0 else 0,
            'scope': 'One-second samples over the whole condition, not sums of overlapping episode GPU-hours.',
            'rss_note': 'Shared RSS can be counted in multiple processes; host available memory is independent.',
            'cpu_note': 'One logical CPU is 100%; first samples without a baseline are excluded. Process creation/exit between samples can omit CPU work; this is not exact cumulative CPU time.',
            'peak_note': 'Sampled peak only; gaps over 2.5 sample intervals are excluded from the mean.'}
    for name, (total, duration) in totals.items():
        observed = [value(row, name) for row in valid if value(row, name) is not None]
        summary['mean_' + name] = total / duration if duration else None
        summary['peak_' + name] = max(observed, default=None)
        summary[name + '_covered_seconds'] = duration
    return summary