patdev commited on
Commit
47ea533
verified
1 Parent(s): 3e09c82

Add GPU telemetry to publish_job.py

Browse files
Files changed (1) hide show
  1. publish_job.py +57 -92
publish_job.py CHANGED
@@ -1,103 +1,68 @@
1
  # /// script
2
  # requires-python = ">=3.11"
3
- # dependencies = [
4
- # "huggingface-hub>=1.0",
5
- # "optimum[onnxruntime]>=2.0",
6
- # "transformers>=5.0",
7
- # "torch>=2.6",
8
- # "onnx>=1.17",
9
- # "onnxruntime>=1.21",
10
- # "psutil>=6",
11
- # ]
12
  # ///
13
  from __future__ import annotations
14
- import argparse, json, os, shutil, subprocess, tempfile, threading, time
15
  from pathlib import Path
16
- from typing import Any
17
  import psutil
18
  from huggingface_hub import HfApi, snapshot_download
19
 
20
-
21
- def emit(percent:int, stage:str, message:str):
22
- print(json.dumps({"event":"progress","percent":percent,"stage":stage,"message":message}),flush=True)
 
 
 
 
 
 
 
23
 
24
  class Telemetry:
25
- def __init__(self): self.stop=threading.Event(); self.thread=threading.Thread(target=self.run,daemon=True)
26
- def start(self): self.thread.start(); return self
27
- def close(self): self.stop.set(); self.thread.join(timeout=2)
28
- def run(self):
29
- psutil.cpu_percent(None)
30
- while not self.stop.wait(2):
31
- m=psutil.virtual_memory(); p:dict[str,Any]={"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}
32
- try:
33
- import pynvml
34
- pynvml.nvmlInit(); n=pynvml.nvmlDeviceGetCount(); used=total=0; utils=[]; names=[]
35
- for i in range(n):
36
- h=pynvml.nvmlDeviceGetHandleByIndex(i); mem=pynvml.nvmlDeviceGetMemoryInfo(h); used+=mem.used; total+=mem.total; utils.append(pynvml.nvmlDeviceGetUtilizationRates(h).gpu); name=pynvml.nvmlDeviceGetName(h); names.append(name.decode() if isinstance(name,bytes) else str(name))
37
- p.update(gpu_count=n,gpu_name=" + ".join(names) or None,gpu_util_percent=sum(utils)/len(utils) if utils else None,vram_used_gb=round(used/1024**3,3) if total else None,vram_total_gb=round(total/1024**3,3) if total else None,vram_percent=100*used/total if total else None)
38
- pynvml.nvmlShutdown()
39
- except Exception: pass
40
- print(json.dumps(p),flush=True)
41
-
42
- def parse_args():
43
- ap=argparse.ArgumentParser(description="Export, optimize and publish an ONNX model")
44
- ap.add_argument("--source",required=True); ap.add_argument("--output-repo",required=True); ap.add_argument("--task",default="auto"); ap.add_argument("--backend",default="onnxruntime"); ap.add_argument("--precision",default="fp16"); ap.add_argument("--quantization",default="none"); ap.add_argument("--opset",type=int,default=18); ap.add_argument("--opt-level",default="all"); ap.add_argument("--dynamic-shapes",action="store_true"); ap.add_argument("--external-data",action="store_true"); ap.add_argument("--private",action="store_true"); ap.add_argument("--dry-run",action="store_true")
45
- return ap.parse_args()
46
-
47
- def source_path(source:str, token:str, root:Path, dry_run:bool)->Path|None:
48
- candidate=Path(source)
49
- if candidate.is_absolute() and candidate.exists(): return candidate
50
- cached=Path("/cache")/source.lstrip("/")
51
- if cached.exists(): return cached
52
- if dry_run: return None
53
- return Path(snapshot_download(source,repo_type="model",token=token,local_dir=root/"source"))
54
-
55
  def main():
56
- a=parse_args(); token=os.environ["HF_TOKEN"]; telemetry=Telemetry().start()
57
- try:
58
- emit(3,"inspect",f"Inspecting {a.source}")
59
- api=HfApi(token=token)
60
- remote_info=None
61
- source_status="cache"
62
- if not (Path(a.source).exists() or (Path('/cache')/a.source.lstrip('/')).exists()):
63
- try: remote_info=api.model_info(a.source,token=token); source_status="Hub"
64
- except Exception: source_status="planned output"
65
- if a.dry_run:
66
- emit(100,"completed",f"PublishJob dry-run valid 路 source={source_status} 路 target={a.output_repo}")
67
- return
68
- with tempfile.TemporaryDirectory() as tmp:
69
- root=Path(tmp); src=source_path(a.source,token,root,False); assert src is not None
70
- out=root/"onnx"; out.mkdir(parents=True)
71
- existing=list(src.rglob("*.onnx"))
72
- if existing:
73
- emit(25,"collect",f"Copying {len(existing)} existing ONNX graph(s)")
74
- for file in existing:
75
- target=out/file.name; shutil.copy2(file,target)
76
- data=file.with_name(file.name+"_data")
77
- if data.exists(): shutil.copy2(data,out/data.name)
78
- else:
79
- emit(20,"export",f"Exporting with Optimum 路 task={a.task} 路 opset={a.opset}")
80
- command=["optimum-cli","export","onnx","--model",str(src),"--opset",str(a.opset)]
81
- if a.task and a.task!="auto": command += ["--task",a.task]
82
- command.append(str(out))
83
- process=subprocess.Popen(command,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True)
84
- assert process.stdout is not None
85
- for line in process.stdout:
86
- print(line.rstrip(),flush=True)
87
- if process.wait(): raise RuntimeError("Optimum ONNX export failed")
88
- graphs=list(out.glob("*.onnx"))
89
- if not graphs: raise RuntimeError("No ONNX graph was produced")
90
- if a.quantization in {"dynamic","weight-only"} or a.precision=="int8":
91
- emit(62,"quantize","Applying ONNX Runtime dynamic INT8 quantization")
92
- from onnxruntime.quantization import QuantType, quantize_dynamic
93
- for graph in list(graphs):
94
- quantized=graph.with_name(graph.stem+"-int8.onnx"); quantize_dynamic(str(graph),str(quantized),weight_type=QuantType.QInt8)
95
- graphs=list(out.glob("*.onnx"))
96
- manifest={"source":a.source,"output_repo":a.output_repo,"task":a.task,"backend":a.backend,"precision":a.precision,"quantization":a.quantization,"opset":a.opset,"opt_level":a.opt_level,"dynamic_shapes":a.dynamic_shapes,"external_data":a.external_data,"graphs":[g.name for g in graphs]}
97
- (out/"publish_manifest.json").write_text(json.dumps(manifest,indent=2),encoding="utf-8")
98
- emit(82,"upload",f"Uploading {len(graphs)} graph(s)")
99
- api.create_repo(a.output_repo,repo_type="model",private=a.private,exist_ok=True,token=token)
100
- api.upload_folder(folder_path=out,repo_id=a.output_repo,repo_type="model",token=token,commit_message="Publish ONNX runtime package")
101
- emit(100,"completed",f"Published ONNX package to {a.output_repo}")
102
- finally: telemetry.close()
103
- if __name__=="__main__": main()
 
1
  # /// script
2
  # requires-python = ">=3.11"
3
+ # dependencies = ["huggingface-hub>=0.34,<1.0", "transformers>=4.56,<4.58", "optimum[onnxruntime]>=2.1,<2.3", "onnx>=1.17", "onnxruntime>=1.20", "onnxconverter-common>=1.14", "psutil>=6", "nvidia-ml-py>=12.560"]
 
 
 
 
 
 
 
 
4
  # ///
5
  from __future__ import annotations
6
+ import argparse, atexit, json, os, shutil, subprocess, threading, time
7
  from pathlib import Path
 
8
  import psutil
9
  from huggingface_hub import HfApi, snapshot_download
10
 
11
+ def emit(p,s,m): print(json.dumps({'event':'progress','percent':p,'stage':s,'message':m}),flush=True)
12
+ def gpu_sample():
13
+ try:
14
+ import pynvml; pynvml.nvmlInit(); count=pynvml.nvmlDeviceGetCount(); names=[]; utils=[]; used=total=0; temps=[]
15
+ for i in range(count):
16
+ h=pynvml.nvmlDeviceGetHandleByIndex(i); n=pynvml.nvmlDeviceGetName(h); names.append(n.decode() if isinstance(n,bytes) else str(n)); u=pynvml.nvmlDeviceGetUtilizationRates(h); utils.append(float(u.gpu)); m=pynvml.nvmlDeviceGetMemoryInfo(h); used+=m.used; total+=m.total
17
+ try: temps.append(float(pynvml.nvmlDeviceGetTemperature(h,pynvml.NVML_TEMPERATURE_GPU)))
18
+ except Exception: pass
19
+ pynvml.nvmlShutdown(); return {'gpu_count':count,'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}
20
+ except Exception:return {'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}
21
 
22
  class Telemetry:
23
+ def __init__(self): self.stop=threading.Event(); self.t=threading.Thread(target=self.run,daemon=True)
24
+ def start(self): psutil.cpu_percent(None); self.t.start(); atexit.register(self.stop.set)
25
+ def run(self):
26
+ while not self.stop.wait(1):
27
+ m=psutil.virtual_memory(); payload={'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)}; payload.update(gpu_sample()); print(json.dumps(payload),flush=True)
28
+ def resolve(source,token):
29
+ p=Path('/cache')/source.lstrip('/')
30
+ if p.exists(): return p
31
+ return Path(snapshot_download(source,token=token)) if '/' in source else p
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  def main():
33
+ ap=argparse.ArgumentParser(); ap.add_argument('--source',required=True); ap.add_argument('--output-repo',required=True); ap.add_argument('--task',default='auto'); ap.add_argument('--backend',default='onnxruntime'); ap.add_argument('--precision',default='fp16'); ap.add_argument('--quantization',default='none'); ap.add_argument('--opset',type=int,default=18); ap.add_argument('--dynamic-shapes',action='store_true'); ap.add_argument('--external-data',action='store_true'); ap.add_argument('--opt-level',default='all'); 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().start(); emit(5,'inspect',f'Inspecting {a.source}'); out=Path('/cache/publish')/a.output_repo.replace('/','__'); out.mkdir(parents=True,exist_ok=True)
34
+ local=Path('/cache')/a.source.lstrip('/'); existing=list(local.rglob('*.onnx')) if local.exists() else []
35
+ remote_files=[]
36
+ if not local.exists() and '/' in a.source:
37
+ try: remote_files=HfApi(token=token).list_repo_files(a.source,token=token)
38
+ except Exception: remote_files=[]
39
+ plan=vars(a)|{'local_source':str(local),'local_exists':local.exists(),'existing_onnx':[str(x) for x in existing],'remote_onnx':[x for x in remote_files if x.endswith('.onnx')]}; (out/'publish_plan.json').write_text(json.dumps(plan,indent=2))
40
+ if a.dry_run: emit(100,'completed',f"PublishJob dry-run validated; {len(existing)} local and {len(plan['remote_onnx'])} remote ONNX file(s) found"); return
41
+ source=resolve(a.source,token)
42
+ if existing:
43
+ emit(25,'copy','Copying existing ONNX package')
44
+ for f in existing: shutil.copy2(f,out/f.name)
45
+ else:
46
+ emit(20,'export','Exporting model to ONNX with Optimum')
47
+ cmd=['optimum-cli','export','onnx','--model',str(source),'--task',a.task,'--opset',str(a.opset),str(out)]; subprocess.run(cmd,check=True)
48
+ files=list(out.rglob('*.onnx'))
49
+ if not files: raise SystemExit('PublishJob produced no ONNX graph')
50
+ if a.precision=='fp16':
51
+ emit(58,'precision','Converting ONNX weights to FP16')
52
+ import onnx
53
+ from onnxconverter_common import float16
54
+ for f in files:
55
+ model=onnx.load(str(f)); model=float16.convert_float_to_float16(model,keep_io_types=True); onnx.save(model,str(f))
56
+ if a.quantization=='dynamic':
57
+ emit(68,'quantize','Applying dynamic INT8 quantization')
58
+ from onnxruntime.quantization import quantize_dynamic, QuantType
59
+ for f in list(out.rglob('*.onnx')):
60
+ target=f.with_name(f.stem+'-int8.onnx'); quantize_dynamic(str(f),str(target),weight_type=QuantType.QInt8)
61
+ emit(82,'validate','Validating exported ONNX sessions')
62
+ import onnxruntime as ort
63
+ validated=[]
64
+ for f in out.rglob('*.onnx'): ort.InferenceSession(str(f),providers=['CPUExecutionProvider']); validated.append(f.name)
65
+ (out/'publish_manifest.json').write_text(json.dumps({'source':a.source,'backend':a.backend,'precision':a.precision,'quantization':a.quantization,'files':validated},indent=2))
66
+ 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',token=token,commit_message='Publish ONNX runtime package')
67
+ emit(100,'completed',f'Published {len(validated)} ONNX graph(s) to {a.output_repo}')
68
+ if __name__=='__main__': main()