# /// script # requires-python = ">=3.11" # dependencies = ["huggingface-hub>=1.0", "psutil>=6", "nvidia-ml-py>=12.560", "numpy>=1.26", "onnxruntime>=1.20"] # /// from __future__ import annotations import argparse, atexit, json, os, statistics, threading, time from pathlib import Path import numpy as np, psutil from huggingface_hub import HfApi, snapshot_download def emit(percent, stage, message): print(json.dumps({"event":"progress","percent":percent,"stage":stage,"message":message}),flush=True) class Telemetry: def __init__(self): self.stop=threading.Event(); self.thread=threading.Thread(target=self.run,daemon=True) def start(self): psutil.cpu_percent(None); self.thread.start(); atexit.register(self.close) def close(self): self.stop.set() def run(self): while not self.stop.wait(1): m=psutil.virtual_memory(); p={"event":"telemetry","timestamp":time.time(),"cpu_percent":psutil.cpu_percent(None),"ram_percent":m.percent,"ram_used_gb":round((m.total-m.available)/1024**3,3),"ram_total_gb":round(m.total/1024**3,3),"gpu_count":0,"gpu_name":None,"gpu_util_percent":None,"vram_used_gb":None,"vram_total_gb":None,"vram_percent":None,"gpu_temperature_c":None} try: import pynvml; pynvml.nvmlInit(); c=pynvml.nvmlDeviceGetCount(); utils=[]; used=total=0; names=[]; temps=[] for i in range(c): h=pynvml.nvmlDeviceGetHandleByIndex(i); u=pynvml.nvmlDeviceGetUtilizationRates(h); mm=pynvml.nvmlDeviceGetMemoryInfo(h); n=pynvml.nvmlDeviceGetName(h) names.append(n.decode() if isinstance(n,bytes) else str(n)); utils.append(u.gpu); used+=mm.used; total+=mm.total try: temps.append(pynvml.nvmlDeviceGetTemperature(h,pynvml.NVML_TEMPERATURE_GPU)) except Exception: pass p.update(gpu_count=c,gpu_name=' + '.join(names) or None,gpu_util_percent=sum(utils)/len(utils) if utils else None,vram_used_gb=used/1024**3 if total else None,vram_total_gb=total/1024**3 if total else None,vram_percent=100*used/total if total else None,gpu_temperature_c=sum(temps)/len(temps) if temps else None); pynvml.nvmlShutdown() except Exception: pass print(json.dumps(p),flush=True) def resolve(source,token): local=Path('/cache')/source.lstrip('/') if local.exists(): return local if '/' in source: return Path(snapshot_download(source,token=token)) return local def main(): ap=argparse.ArgumentParser(); ap.add_argument('--source',required=True); ap.add_argument('--backend',default='onnxruntime'); ap.add_argument('--precision',default='fp16'); ap.add_argument('--warmup-runs',type=int,default=10); ap.add_argument('--measured-runs',type=int,default=50); ap.add_argument('--batch-sizes',default='1'); ap.add_argument('--input-sizes',default='512'); ap.add_argument('--output-repo',default=''); ap.add_argument('--private',action='store_true'); ap.add_argument('--dry-run',action='store_true'); a=ap.parse_args() token=os.environ['HF_TOKEN']; telemetry=Telemetry(); telemetry.start(); emit(5,'inspect',f'Inspecting {a.source}'); local=Path('/cache')/a.source.lstrip('/'); files=list(local.rglob('*.onnx')) if local.exists() else []; remote_files=[] if not local.exists() and '/' in a.source: try: remote_files=HfApi(token=token).list_repo_files(a.source,token=token) except Exception: remote_files=[] plan=vars(a)|{'local_source':str(local),'local_exists':local.exists(),'onnx_files':[str(x) for x in files],'remote_onnx':[x for x in remote_files if x.endswith('.onnx')]} out=Path('/cache/bench')/str(int(time.time())); out.mkdir(parents=True,exist_ok=True); (out/'benchmark_plan.json').write_text(json.dumps(plan,indent=2)) if a.dry_run: emit(100,'completed',f"BenchJob dry-run validated; {len(files)} local and {len(plan['remote_onnx'])} remote ONNX graph(s) found"); return root=resolve(a.source,token); files=list(root.rglob('*.onnx')) if root.exists() else [] if not files: raise SystemExit('No ONNX graph found for BenchJob') import onnxruntime as ort; graph=files[0]; providers=ort.get_available_providers(); session=ort.InferenceSession(str(graph),providers=providers); emit(25,'load',f'Loaded {graph.name} with {session.get_providers()}') inputs=session.get_inputs(); batch_values=[int(x) for x in a.batch_sizes.split(',') if x.strip()]; size_values=[int(x) for x in a.input_sizes.split(',') if x.strip()]; results=[] total_cases=max(1,len(batch_values)*len(size_values)); case=0 for batch in batch_values: for size in size_values: case+=1; feed={} for meta in inputs: shape=[] for i,d in enumerate(meta.shape): shape.append(batch if i==0 else size if i==1 and isinstance(d,str) else int(d) if isinstance(d,int) and d>0 else 1) dtype=np.int64 if 'int64' in meta.type else np.int32 if 'int32' in meta.type else np.float32 feed[meta.name]=np.zeros(shape,dtype=dtype) for _ in range(max(1,a.warmup_runs)): session.run(None,feed) samples=[] for _ in range(max(1,a.measured_runs)): start=time.perf_counter(); session.run(None,feed); samples.append((time.perf_counter()-start)*1000) mean=statistics.mean(samples); ordered=sorted(samples); p95=ordered[min(len(ordered)-1,int(.95*len(ordered)))] results.append({'batch':batch,'input_size':size,'latency_ms_mean':mean,'latency_ms_p50':statistics.median(samples),'latency_ms_p95':p95,'throughput_per_s':1000*batch/mean}) emit(25+65*case/total_cases,'benchmark',f'batch {batch}, size {size}: {mean:.2f} ms') report={'source':a.source,'backend':a.backend,'precision':a.precision,'providers':session.get_providers(),'results':results}; (out/'benchmark.json').write_text(json.dumps(report,indent=2)) if a.output_repo: api=HfApi(token=token); api.create_repo(a.output_repo,repo_type='model',private=a.private,exist_ok=True,token=token); api.upload_folder(folder_path=out,repo_id=a.output_repo,repo_type='model',path_in_repo='benchmarks',token=token,commit_message='Add BenchJob report') emit(100,'completed',f'BenchJob completed with {len(results)} measurement cases') if __name__=='__main__': main()