Add GPU telemetry to eval_job.py
Browse files- eval_job.py +52 -34
eval_job.py
CHANGED
|
@@ -1,43 +1,61 @@
|
|
| 1 |
# /// script
|
| 2 |
# requires-python = ">=3.11"
|
| 3 |
-
# dependencies = ["huggingface-hub>=1.0", "datasets>=4.0", "psutil>=6"]
|
| 4 |
# ///
|
| 5 |
from __future__ import annotations
|
| 6 |
-
import argparse, json, os,
|
| 7 |
from pathlib import Path
|
|
|
|
| 8 |
from datasets import load_dataset
|
| 9 |
-
from huggingface_hub import HfApi
|
| 10 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
-
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
def main():
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
if
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
# /// script
|
| 2 |
# requires-python = ">=3.11"
|
| 3 |
+
# dependencies = ["huggingface-hub>=1.0", "datasets>=4.0", "transformers>=5.0", "torch>=2.6", "pillow>=11", "psutil>=6", "nvidia-ml-py>=12.560", "jiwer>=4.0"]
|
| 4 |
# ///
|
| 5 |
from __future__ import annotations
|
| 6 |
+
import argparse, atexit, json, os, threading, time
|
| 7 |
from pathlib import Path
|
| 8 |
+
import psutil
|
| 9 |
from datasets import load_dataset
|
| 10 |
+
from huggingface_hub import HfApi, hf_hub_download
|
| 11 |
|
| 12 |
+
def emit(p,s,m): print(json.dumps({'event':'progress','percent':p,'stage':s,'message':m}),flush=True)
|
| 13 |
+
def gpu_sample():
|
| 14 |
+
try:
|
| 15 |
+
import pynvml; pynvml.nvmlInit(); count=pynvml.nvmlDeviceGetCount(); names=[]; utils=[]; used=total=0; temps=[]
|
| 16 |
+
for i in range(count):
|
| 17 |
+
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
|
| 18 |
+
try: temps.append(float(pynvml.nvmlDeviceGetTemperature(h,pynvml.NVML_TEMPERATURE_GPU)))
|
| 19 |
+
except Exception: pass
|
| 20 |
+
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}
|
| 21 |
+
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}
|
| 22 |
|
| 23 |
+
class Telemetry:
|
| 24 |
+
def __init__(self): self.stop=threading.Event(); self.t=threading.Thread(target=self.run,daemon=True)
|
| 25 |
+
def start(self): psutil.cpu_percent(None); self.t.start(); atexit.register(self.stop.set)
|
| 26 |
+
def run(self):
|
| 27 |
+
while not self.stop.wait(1):
|
| 28 |
+
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)
|
| 29 |
def main():
|
| 30 |
+
ap=argparse.ArgumentParser(); ap.add_argument('--source',required=True); ap.add_argument('--dataset-id',required=True); ap.add_argument('--split',default='validation'); ap.add_argument('--metric',default='auto'); ap.add_argument('--max-samples',type=int,default=128); ap.add_argument('--prompt-column',default='prompt'); ap.add_argument('--reference-column',default='text'); ap.add_argument('--prediction-column',default='prediction'); ap.add_argument('--image-column',default='image'); 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().start()
|
| 31 |
+
emit(5,'dataset',f'Loading {a.dataset_id}:{a.split}')
|
| 32 |
+
try:
|
| 33 |
+
ds=load_dataset(a.dataset_id,split=a.split,token=token)
|
| 34 |
+
except Exception:
|
| 35 |
+
files=HfApi(token=token).list_repo_files(a.dataset_id,repo_type='dataset',token=token)
|
| 36 |
+
wanted=[f for f in files if f.lower().endswith(('.jsonl','.json')) and a.split.lower() in f.lower()]
|
| 37 |
+
if not wanted: wanted=[f for f in files if f.lower().endswith(('.jsonl','.json')) and 'validation' in f.lower()]
|
| 38 |
+
if not wanted: wanted=[f for f in files if f.lower().endswith(('.jsonl','.json')) and 'train' in f.lower()]
|
| 39 |
+
if not wanted: raise
|
| 40 |
+
local=hf_hub_download(a.dataset_id,wanted[0],repo_type='dataset',token=token)
|
| 41 |
+
ds=load_dataset('json',data_files=local,split='train')
|
| 42 |
+
if a.max_samples>0: ds=ds.select(range(min(a.max_samples,len(ds))))
|
| 43 |
+
columns=list(ds.column_names); plan=vars(a)|{'rows':len(ds),'columns':columns}; out=Path('/cache/eval')/str(int(time.time())); out.mkdir(parents=True,exist_ok=True); (out/'eval_plan.json').write_text(json.dumps(plan,indent=2))
|
| 44 |
+
if a.dry_run: emit(100,'completed',f'EvalJob dry-run validated on {len(ds)} row(s)'); return
|
| 45 |
+
predictions=[]; references=[]
|
| 46 |
+
if a.prediction_column in columns and a.reference_column in columns:
|
| 47 |
+
predictions=[str(x or '') for x in ds[a.prediction_column]]; references=[str(x or '') for x in ds[a.reference_column]]; emit(55,'score','Using prediction and reference columns')
|
| 48 |
+
else:
|
| 49 |
+
from transformers import pipeline
|
| 50 |
+
task='image-to-text' if a.image_column in columns else 'text-generation'; source=str(Path('/cache')/a.source.lstrip('/')) if (Path('/cache')/a.source.lstrip('/')).exists() else a.source
|
| 51 |
+
pipe=pipeline(task,model=source,token=token,trust_remote_code=True,device_map='auto'); emit(30,'inference',f'Loaded {task} pipeline')
|
| 52 |
+
for index,row in enumerate(ds):
|
| 53 |
+
inp=row.get(a.image_column) if task=='image-to-text' else row.get(a.prompt_column) or row.get('text') or ''
|
| 54 |
+
result=pipe(inp,max_new_tokens=256); text=result[0].get('generated_text') or result[0].get('text') or str(result[0]); predictions.append(str(text)); references.append(str(row.get(a.reference_column) or ''))
|
| 55 |
+
if index%max(1,len(ds)//10)==0: emit(30+55*(index+1)/max(1,len(ds)),'inference',f'{index+1}/{len(ds)} samples')
|
| 56 |
+
from jiwer import wer, cer
|
| 57 |
+
exact=sum(p.strip()==r.strip() for p,r in zip(predictions,references))/max(1,len(references)); report={'source':a.source,'dataset':a.dataset_id,'rows':len(references),'exact_match':exact,'wer':wer(references,predictions),'cer':cer(references,predictions),'samples':[{'prediction':p,'reference':r} for p,r in list(zip(predictions,references))[:20]]}; (out/'evaluation.json').write_text(json.dumps(report,indent=2,ensure_ascii=False))
|
| 58 |
+
if a.output_repo:
|
| 59 |
+
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='evaluations',token=token,commit_message='Add EvalJob report')
|
| 60 |
+
emit(100,'completed',f"EvalJob completed: exact {exact:.3f}, CER {report['cer']:.3f}")
|
| 61 |
+
if __name__=='__main__': main()
|