Add TrainingJob ONNX benchmark runtime
Browse files- benchmark_job.py +61 -59
benchmark_job.py
CHANGED
|
@@ -1,70 +1,72 @@
|
|
| 1 |
# /// script
|
| 2 |
# requires-python = ">=3.11"
|
| 3 |
-
# dependencies = ["huggingface-hub>=1.0", "
|
| 4 |
# ///
|
| 5 |
from __future__ import annotations
|
| 6 |
-
import argparse,
|
| 7 |
from pathlib import Path
|
| 8 |
-
import numpy as np
|
| 9 |
from huggingface_hub import HfApi, snapshot_download
|
| 10 |
|
| 11 |
|
| 12 |
-
def emit(percent,
|
| 13 |
-
class Telemetry:
|
| 14 |
-
def __init__(self): self.stop=threading.Event(); self.thread=threading.Thread(target=self.run,daemon=True)
|
| 15 |
-
def start(self): psutil.cpu_percent(None); self.thread.start(); atexit.register(self.close)
|
| 16 |
-
def close(self): self.stop.set()
|
| 17 |
-
def run(self):
|
| 18 |
-
while not self.stop.wait(1):
|
| 19 |
-
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}
|
| 20 |
-
try:
|
| 21 |
-
import pynvml; pynvml.nvmlInit(); c=pynvml.nvmlDeviceGetCount(); utils=[]; used=total=0; names=[]; temps=[]
|
| 22 |
-
for i in range(c):
|
| 23 |
-
h=pynvml.nvmlDeviceGetHandleByIndex(i); u=pynvml.nvmlDeviceGetUtilizationRates(h); mm=pynvml.nvmlDeviceGetMemoryInfo(h); n=pynvml.nvmlDeviceGetName(h)
|
| 24 |
-
names.append(n.decode() if isinstance(n,bytes) else str(n)); utils.append(u.gpu); used+=mm.used; total+=mm.total
|
| 25 |
-
try: temps.append(pynvml.nvmlDeviceGetTemperature(h,pynvml.NVML_TEMPERATURE_GPU))
|
| 26 |
-
except Exception: pass
|
| 27 |
-
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()
|
| 28 |
-
except Exception: pass
|
| 29 |
-
print(json.dumps(p),flush=True)
|
| 30 |
|
| 31 |
-
def
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
def main():
|
| 38 |
-
ap=argparse.ArgumentParser(
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
for
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
if __name__=='__main__':
|
|
|
|
| 1 |
# /// script
|
| 2 |
# requires-python = ">=3.11"
|
| 3 |
+
# dependencies = ["huggingface-hub>=1.0", "onnxruntime>=1.21", "numpy>=1.26", "psutil>=6"]
|
| 4 |
# ///
|
| 5 |
from __future__ import annotations
|
| 6 |
+
import argparse, json, os, statistics, tempfile, time
|
| 7 |
from pathlib import Path
|
| 8 |
+
import numpy as np
|
| 9 |
from huggingface_hub import HfApi, snapshot_download
|
| 10 |
|
| 11 |
|
| 12 |
+
def emit(percent:int,stage:str,message:str): print(json.dumps({"event":"progress","percent":percent,"stage":stage,"message":message}),flush=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
+
def parse_csv(text:str)->list[int]: return [int(x.strip()) for x in text.split(',') if x.strip()]
|
| 15 |
+
|
| 16 |
+
def resolve_source(source:str,token:str,root:Path,dry_run:bool)->Path|None:
|
| 17 |
+
direct=Path(source)
|
| 18 |
+
if direct.is_absolute() and direct.exists(): return direct
|
| 19 |
+
cached=Path('/cache')/source.lstrip('/')
|
| 20 |
+
if cached.exists(): return cached
|
| 21 |
+
if dry_run:return None
|
| 22 |
+
return Path(snapshot_download(source,repo_type='model',token=token,local_dir=root/'source',allow_patterns=['*.onnx','**/*.onnx','*.json','**/*.json','*.data','**/*.data']))
|
| 23 |
+
|
| 24 |
+
def dtype(name:str):
|
| 25 |
+
return {'tensor(float)':np.float32,'tensor(float16)':np.float16,'tensor(double)':np.float64,'tensor(int64)':np.int64,'tensor(int32)':np.int32,'tensor(bool)':np.bool_}.get(name,np.float32)
|
| 26 |
+
|
| 27 |
+
def make_inputs(session,batch:int,size:int):
|
| 28 |
+
values={}
|
| 29 |
+
for item in session.get_inputs():
|
| 30 |
+
shape=[]
|
| 31 |
+
for index,dim in enumerate(item.shape):
|
| 32 |
+
if isinstance(dim,int) and dim>0: shape.append(dim)
|
| 33 |
+
elif index==0: shape.append(batch)
|
| 34 |
+
else: shape.append(size)
|
| 35 |
+
if not shape: shape=[batch]
|
| 36 |
+
values[item.name]=np.zeros(shape,dtype=dtype(item.type))
|
| 37 |
+
return values
|
| 38 |
|
| 39 |
def main():
|
| 40 |
+
ap=argparse.ArgumentParser(description='Benchmark an ONNX runtime package')
|
| 41 |
+
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()
|
| 42 |
+
token=os.environ['HF_TOKEN'];emit(5,'inspect',f'Inspecting {a.source}')
|
| 43 |
+
if a.dry_run:
|
| 44 |
+
if not (Path(a.source).exists() or (Path('/cache')/a.source.lstrip('/')).exists()): HfApi(token=token).model_info(a.source,token=token)
|
| 45 |
+
emit(100,'completed','BenchJob dry-run validated');return
|
| 46 |
+
with tempfile.TemporaryDirectory() as tmp:
|
| 47 |
+
root=Path(tmp);source=resolve_source(a.source,token,root,False);assert source is not None
|
| 48 |
+
graphs=list(source.rglob('*.onnx'))
|
| 49 |
+
if not graphs:raise RuntimeError('No ONNX graph found in benchmark source')
|
| 50 |
+
import onnxruntime as ort
|
| 51 |
+
providers=['CPUExecutionProvider']
|
| 52 |
+
if a.backend=='tensorrt' and 'TensorrtExecutionProvider' in ort.get_available_providers():providers=['TensorrtExecutionProvider','CUDAExecutionProvider','CPUExecutionProvider']
|
| 53 |
+
elif 'CUDAExecutionProvider' in ort.get_available_providers() and a.backend=='onnxruntime':providers=['CUDAExecutionProvider','CPUExecutionProvider']
|
| 54 |
+
graph=max(graphs,key=lambda p:p.stat().st_size);emit(20,'load',f'Loading {graph.name} with {providers[0]}')
|
| 55 |
+
session=ort.InferenceSession(str(graph),providers=providers)
|
| 56 |
+
results=[];batches=parse_csv(a.batch_sizes) or [1];sizes=parse_csv(a.input_sizes) or [512];total=len(batches)*len(sizes);done=0
|
| 57 |
+
for batch in batches:
|
| 58 |
+
for size in sizes:
|
| 59 |
+
feed=make_inputs(session,batch,size)
|
| 60 |
+
for _ in range(max(0,a.warmup_runs)):session.run(None,feed)
|
| 61 |
+
samples=[]
|
| 62 |
+
for _ in range(max(1,a.measured_runs)):
|
| 63 |
+
start=time.perf_counter();session.run(None,feed);samples.append((time.perf_counter()-start)*1000)
|
| 64 |
+
samples.sort();mean=statistics.mean(samples);p50=statistics.median(samples);p95=samples[min(len(samples)-1,int(len(samples)*.95))]
|
| 65 |
+
results.append({'batch_size':batch,'input_size':size,'runs':len(samples),'latency_ms_mean':mean,'latency_ms_p50':p50,'latency_ms_p95':p95,'throughput_per_s':1000*batch/mean,'provider':session.get_providers()[0]})
|
| 66 |
+
done+=1;emit(20+int(70*done/total),'benchmark',f'batch={batch} size={size} mean={mean:.2f} ms')
|
| 67 |
+
report={'source':a.source,'graph':graph.name,'backend':a.backend,'precision':a.precision,'results':results,'generated_at':time.time()}
|
| 68 |
+
output=root/'report';output.mkdir();(output/'benchmark.json').write_text(json.dumps(report,indent=2),encoding='utf-8')
|
| 69 |
+
if a.output_repo:
|
| 70 |
+
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=output,repo_id=a.output_repo,repo_type='model',token=token,commit_message='Add runtime benchmark report')
|
| 71 |
+
emit(100,'completed',f'Benchmarked {len(results)} configuration(s)')
|
| 72 |
+
if __name__=='__main__':main()
|