patdev commited on
Commit
3e09c82
verified
1 Parent(s): 7c55e49

Add GPU telemetry to eval_job.py

Browse files
Files changed (1) hide show
  1. 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, statistics, tempfile, time
7
  from pathlib import Path
 
8
  from datasets import load_dataset
9
- from huggingface_hub import HfApi
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 main():
15
- ap=argparse.ArgumentParser(description='Evaluate dataset compatibility and available quality signals')
16
- 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('--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()
17
- token=os.environ['HF_TOKEN'];api=HfApi(token=token);emit(5,'inspect',f'Checking source {a.source}')
18
- source_status='cache'
19
- if not (Path(a.source).exists() or (Path('/cache')/a.source.lstrip('/')).exists()):
20
- try: api.model_info(a.source,token=token); source_status='Hub'
21
- except Exception: source_status='planned output' if a.dry_run else (_ for _ in ()).throw(RuntimeError(f'Source not found: {a.source}'))
22
- emit(20,'dataset',f'Loading {a.dataset_id}:{a.split} source={source_status}')
23
- try: data=load_dataset(a.dataset_id,split=a.split,token=token)
24
- except Exception:
25
- data=load_dataset(a.dataset_id,split='train',token=token)
26
- if a.max_samples>0:data=data.select(range(min(a.max_samples,len(data))))
27
- columns=list(data.column_names);emit(40,'analyze',f'{len(data)} rows 路 {len(columns)} columns')
28
- if a.dry_run:
29
- emit(100,'completed',f'EvalJob dry-run valid columns={columns}');return
30
- references=[];prompts=[];images=0
31
- for row in data:
32
- ref=row.get(a.reference_column);prompt=row.get(a.prompt_column);image=row.get(a.image_column)
33
- if ref not in (None,''):references.append(str(ref))
34
- if prompt not in (None,''):prompts.append(str(prompt))
35
- if image is not None:images+=1
36
- report={'source':a.source,'dataset_id':a.dataset_id,'split':a.split,'metric':a.metric,'rows':len(data),'columns':columns,'reference_coverage':len(references)/max(1,len(data)),'prompt_coverage':len(prompts)/max(1,len(data)),'image_coverage':images/max(1,len(data)),'reference_length_mean':statistics.mean(map(len,references)) if references else 0,'prompt_length_mean':statistics.mean(map(len,prompts)) if prompts else 0,'note':'Generic quality readiness report. Model-specific inference metrics can be added as custom properties or a custom Job.','generated_at':time.time()}
37
- emit(75,'report','Writing evaluation report')
38
- with tempfile.TemporaryDirectory() as tmp:
39
- root=Path(tmp);(root/'evaluation.json').write_text(json.dumps(report,indent=2),encoding='utf-8')
40
- if a.output_repo:
41
- api.create_repo(a.output_repo,repo_type='model',private=a.private,exist_ok=True,token=token);api.upload_folder(folder_path=root,repo_id=a.output_repo,repo_type='model',token=token,commit_message='Add evaluation report')
42
- emit(100,'completed',f'Evaluated {len(data)} rows')
43
- if __name__=='__main__':main()
 
 
 
 
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()