patdev commited on
Commit
89fa464
verified
1 Parent(s): a85db6e

Fix PublishJob dependency resolution

Browse files
Files changed (1) hide show
  1. publish_job.py +48 -91
publish_job.py CHANGED
@@ -1,101 +1,58 @@
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
- if not (Path(a.source).exists() or (Path('/cache')/a.source.lstrip('/')).exists()):
62
- remote_info=api.model_info(a.source,token=token)
63
- if a.dry_run:
64
- emit(100,"completed",f"PublishJob dry-run valid 路 source={'Hub' if remote_info else 'cache'} 路 target={a.output_repo}")
65
- return
66
- with tempfile.TemporaryDirectory() as tmp:
67
- root=Path(tmp); src=source_path(a.source,token,root,False); assert src is not None
68
- out=root/"onnx"; out.mkdir(parents=True)
69
- existing=list(src.rglob("*.onnx"))
70
- if existing:
71
- emit(25,"collect",f"Copying {len(existing)} existing ONNX graph(s)")
72
- for file in existing:
73
- target=out/file.name; shutil.copy2(file,target)
74
- data=file.with_name(file.name+"_data")
75
- if data.exists(): shutil.copy2(data,out/data.name)
76
- else:
77
- emit(20,"export",f"Exporting with Optimum 路 task={a.task} 路 opset={a.opset}")
78
- command=["optimum-cli","export","onnx","--model",str(src),"--opset",str(a.opset)]
79
- if a.task and a.task!="auto": command += ["--task",a.task]
80
- command.append(str(out))
81
- process=subprocess.Popen(command,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True)
82
- assert process.stdout is not None
83
- for line in process.stdout:
84
- print(line.rstrip(),flush=True)
85
- if process.wait(): raise RuntimeError("Optimum ONNX export failed")
86
- graphs=list(out.glob("*.onnx"))
87
- if not graphs: raise RuntimeError("No ONNX graph was produced")
88
- if a.quantization in {"dynamic","weight-only"} or a.precision=="int8":
89
- emit(62,"quantize","Applying ONNX Runtime dynamic INT8 quantization")
90
- from onnxruntime.quantization import QuantType, quantize_dynamic
91
- for graph in list(graphs):
92
- quantized=graph.with_name(graph.stem+"-int8.onnx"); quantize_dynamic(str(graph),str(quantized),weight_type=QuantType.QInt8)
93
- graphs=list(out.glob("*.onnx"))
94
- 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]}
95
- (out/"publish_manifest.json").write_text(json.dumps(manifest,indent=2),encoding="utf-8")
96
- emit(82,"upload",f"Uploading {len(graphs)} graph(s)")
97
- api.create_repo(a.output_repo,repo_type="model",private=a.private,exist_ok=True,token=token)
98
- api.upload_folder(folder_path=out,repo_id=a.output_repo,repo_type="model",token=token,commit_message="Publish ONNX runtime package")
99
- emit(100,"completed",f"Published ONNX package to {a.output_repo}")
100
- finally: telemetry.close()
101
- 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"]
 
 
 
 
 
 
 
 
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
  class Telemetry:
13
+ def __init__(self): self.stop=threading.Event(); self.t=threading.Thread(target=self.run,daemon=True)
14
+ def start(self): psutil.cpu_percent(None); self.t.start(); atexit.register(self.stop.set)
15
+ def run(self):
16
+ while not self.stop.wait(1):
17
+ m=psutil.virtual_memory(); print(json.dumps({'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}),flush=True)
18
+ def resolve(source,token):
19
+ p=Path('/cache')/source.lstrip('/')
20
+ if p.exists(): return p
21
+ return Path(snapshot_download(source,token=token)) if '/' in source else p
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  def main():
23
+ 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)
24
+ local=Path('/cache')/a.source.lstrip('/'); existing=list(local.rglob('*.onnx')) if local.exists() else []
25
+ remote_files=[]
26
+ if not local.exists() and '/' in a.source:
27
+ try: remote_files=HfApi(token=token).list_repo_files(a.source,token=token)
28
+ except Exception: remote_files=[]
29
+ 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))
30
+ 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
31
+ source=resolve(a.source,token)
32
+ if existing:
33
+ emit(25,'copy','Copying existing ONNX package')
34
+ for f in existing: shutil.copy2(f,out/f.name)
35
+ else:
36
+ emit(20,'export','Exporting model to ONNX with Optimum')
37
+ cmd=['optimum-cli','export','onnx','--model',str(source),'--task',a.task,'--opset',str(a.opset),str(out)]; subprocess.run(cmd,check=True)
38
+ files=list(out.rglob('*.onnx'))
39
+ if not files: raise SystemExit('PublishJob produced no ONNX graph')
40
+ if a.precision=='fp16':
41
+ emit(58,'precision','Converting ONNX weights to FP16')
42
+ import onnx
43
+ from onnxconverter_common import float16
44
+ for f in files:
45
+ model=onnx.load(str(f)); model=float16.convert_float_to_float16(model,keep_io_types=True); onnx.save(model,str(f))
46
+ if a.quantization=='dynamic':
47
+ emit(68,'quantize','Applying dynamic INT8 quantization')
48
+ from onnxruntime.quantization import quantize_dynamic, QuantType
49
+ for f in list(out.rglob('*.onnx')):
50
+ target=f.with_name(f.stem+'-int8.onnx'); quantize_dynamic(str(f),str(target),weight_type=QuantType.QInt8)
51
+ emit(82,'validate','Validating exported ONNX sessions')
52
+ import onnxruntime as ort
53
+ validated=[]
54
+ for f in out.rglob('*.onnx'): ort.InferenceSession(str(f),providers=['CPUExecutionProvider']); validated.append(f.name)
55
+ (out/'publish_manifest.json').write_text(json.dumps({'source':a.source,'backend':a.backend,'precision':a.precision,'quantization':a.quantization,'files':validated},indent=2))
56
+ 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')
57
+ emit(100,'completed',f'Published {len(validated)} ONNX graph(s) to {a.output_repo}')
58
+ if __name__=='__main__': main()