patdev commited on
Commit
61bd87f
·
verified ·
1 Parent(s): 89fa464

Add TrainingJob ONNX benchmark runtime

Browse files
Files changed (1) hide show
  1. 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", "psutil>=6", "numpy>=1.26", "onnxruntime>=1.20"]
4
  # ///
5
  from __future__ import annotations
6
- import argparse, atexit, json, os, statistics, threading, time
7
  from pathlib import Path
8
- import numpy as np, psutil
9
  from huggingface_hub import HfApi, snapshot_download
10
 
11
 
12
- def emit(percent, stage, message): print(json.dumps({"event":"progress","percent":percent,"stage":stage,"message":message}),flush=True)
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 resolve(source,token):
32
- local=Path('/cache')/source.lstrip('/')
33
- if local.exists(): return local
34
- if '/' in source: return Path(snapshot_download(source,token=token))
35
- return local
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
  def main():
38
- 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()
39
- 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=[]
40
- if not local.exists() and '/' in a.source:
41
- try: remote_files=HfApi(token=token).list_repo_files(a.source,token=token)
42
- except Exception: remote_files=[]
43
- 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')]}
44
- 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))
45
- 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
46
- root=resolve(a.source,token); files=list(root.rglob('*.onnx')) if root.exists() else []
47
- if not files: raise SystemExit('No ONNX graph found for BenchJob')
48
- 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()}')
49
- 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=[]
50
- total_cases=max(1,len(batch_values)*len(size_values)); case=0
51
- for batch in batch_values:
52
- for size in size_values:
53
- case+=1; feed={}
54
- for meta in inputs:
55
- shape=[]
56
- 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)
57
- dtype=np.int64 if 'int64' in meta.type else np.int32 if 'int32' in meta.type else np.float32
58
- feed[meta.name]=np.zeros(shape,dtype=dtype)
59
- for _ in range(max(1,a.warmup_runs)): session.run(None,feed)
60
- samples=[]
61
- for _ in range(max(1,a.measured_runs)):
62
- start=time.perf_counter(); session.run(None,feed); samples.append((time.perf_counter()-start)*1000)
63
- mean=statistics.mean(samples); ordered=sorted(samples); p95=ordered[min(len(ordered)-1,int(.95*len(ordered)))]
64
- 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})
65
- emit(25+65*case/total_cases,'benchmark',f'batch {batch}, size {size}: {mean:.2f} ms')
66
- 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))
67
- if a.output_repo:
68
- 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')
69
- emit(100,'completed',f'BenchJob completed with {len(results)} measurement cases')
70
- if __name__=='__main__': 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()