"""Resource measurements inside the dispatched model process.""" import os import threading def measured(execute, request): import psutil import pynvml import torch proc = psutil.Process() stop = threading.Event() peak_host = 0 peak_device = 0 samples = 0 pynvml.nvmlInit() try: handle = pynvml.nvmlDeviceGetHandleByUUID(os.environ["LLM_GPU_UUID"]) def sample(): nonlocal peak_host, peak_device, samples pids = set() rss = 0 for child in [proc, *proc.children(recursive=True)]: try: rss += child.memory_info().rss pids.add(child.pid) except psutil.NoSuchProcess: continue used = sum( p.usedGpuMemory for p in pynvml.nvmlDeviceGetComputeRunningProcesses(handle) if p.pid in pids and isinstance(p.usedGpuMemory, int) and 0 <= p.usedGpuMemory < 2**60 ) peak_host = max(peak_host, rss) peak_device = max(peak_device, used) samples += 1 def poll(): while not stop.wait(0.5): sample() sample() thread = threading.Thread(target=poll, daemon=True) thread.start() try: paths, meta = execute(request) sample() finally: stop.set() thread.join(timeout=5) finally: pynvml.nvmlShutdown() torch_peak = torch.cuda.max_memory_reserved() return paths, { **meta, "resource_metrics": { "peak_gpu_mib": round(max(torch_peak, peak_device) / 2**20, 2), "peak_host_mib": round(peak_host / 2**20, 2), "torch_reserved_peak_mib": round(torch_peak / 2**20, 2), "cpu_threads": torch.get_num_threads(), "nvml_samples": samples, }, }