| |
| |
| |
| |
| from __future__ import annotations |
| import argparse, atexit, json, os, threading, time |
| from pathlib import Path |
| import psutil |
| from datasets import load_dataset |
| from huggingface_hub import HfApi, hf_hub_download |
|
|
| def emit(p,s,m): print(json.dumps({'event':'progress','percent':p,'stage':s,'message':m}),flush=True) |
| def gpu_sample(): |
| try: |
| import pynvml; pynvml.nvmlInit(); count=pynvml.nvmlDeviceGetCount(); names=[]; utils=[]; used=total=0; temps=[] |
| for i in range(count): |
| 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 |
| try: temps.append(float(pynvml.nvmlDeviceGetTemperature(h,pynvml.NVML_TEMPERATURE_GPU))) |
| except Exception: pass |
| 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} |
| 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} |
|
|
| class Telemetry: |
| def __init__(self): self.stop=threading.Event(); self.t=threading.Thread(target=self.run,daemon=True) |
| def start(self): psutil.cpu_percent(None); self.t.start(); atexit.register(self.stop.set) |
| def run(self): |
| while not self.stop.wait(1): |
| 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) |
| def main(): |
| 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() |
| emit(5,'dataset',f'Loading {a.dataset_id}:{a.split}') |
| try: |
| ds=load_dataset(a.dataset_id,split=a.split,token=token) |
| except Exception: |
| files=HfApi(token=token).list_repo_files(a.dataset_id,repo_type='dataset',token=token) |
| wanted=[f for f in files if f.lower().endswith(('.jsonl','.json')) and a.split.lower() in f.lower()] |
| if not wanted: wanted=[f for f in files if f.lower().endswith(('.jsonl','.json')) and 'validation' in f.lower()] |
| if not wanted: wanted=[f for f in files if f.lower().endswith(('.jsonl','.json')) and 'train' in f.lower()] |
| if not wanted: raise |
| local=hf_hub_download(a.dataset_id,wanted[0],repo_type='dataset',token=token) |
| ds=load_dataset('json',data_files=local,split='train') |
| if a.max_samples>0: ds=ds.select(range(min(a.max_samples,len(ds)))) |
| 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)) |
| if a.dry_run: emit(100,'completed',f'EvalJob dry-run validated on {len(ds)} row(s)'); return |
| predictions=[]; references=[] |
| if a.prediction_column in columns and a.reference_column in columns: |
| 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') |
| else: |
| from transformers import pipeline |
| 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 |
| pipe=pipeline(task,model=source,token=token,trust_remote_code=True,device_map='auto'); emit(30,'inference',f'Loaded {task} pipeline') |
| for index,row in enumerate(ds): |
| inp=row.get(a.image_column) if task=='image-to-text' else row.get(a.prompt_column) or row.get('text') or '' |
| 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 '')) |
| if index%max(1,len(ds)//10)==0: emit(30+55*(index+1)/max(1,len(ds)),'inference',f'{index+1}/{len(ds)} samples') |
| from jiwer import wer, cer |
| 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)) |
| if a.output_repo: |
| 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') |
| emit(100,'completed',f"EvalJob completed: exact {exact:.3f}, CER {report['cer']:.3f}") |
| if __name__=='__main__': main() |
|
|