Download scripts/eval_common.py from ar-mine/e5-c3-code: direct link, hf CLI and curl.
- Browser
- Download file 5.06 kB
-
https://huggingface.co/datasets/ar-mine/e5-c3-code/resolve/main/scripts/eval_common.py
- Command line
-
hf download hf://datasets/ar-mine/e5-c3-code/scripts/eval_common.py
-
curl -L -o eval_common.py https://huggingface.co/datasets/ar-mine/e5-c3-code/resolve/main/scripts/eval_common.py
5.06 kB
| """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) | |
| 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) | |