Download source/evaluate.py from Queimo/rem3di-pcqm-epoch2-cosmo: direct link, hf CLI and curl.
- Browser
- Download file 11.1 kB
-
https://huggingface.co/Queimo/rem3di-pcqm-epoch2-cosmo/resolve/main/source/evaluate.py
- Command line
-
hf download hf://Queimo/rem3di-pcqm-epoch2-cosmo/source/evaluate.py
-
curl -L -o evaluate.py https://huggingface.co/Queimo/rem3di-pcqm-epoch2-cosmo/resolve/main/source/evaluate.py
11.1 kB
| """Run all frozen probes first, followed by all supervised fine-tuning folds.""" | |
| from pathlib import Path | |
| import sys | |
| # molab enables Python's safe-path mode, which omits the script directory. | |
| sys.path.insert(0,str(Path(__file__).resolve().parent)) | |
| from eval_common import * | |
| import argparse,fcntl,gc,traceback | |
| import pandas as pd | |
| import wandb | |
| from eval_probes import raw_cache,descriptors,ridge_probe,kumo_probe | |
| RUN_LABEL=globals().get('EVAL_RUN_LABEL','cosmo-rem3di') | |
| HUB_PREFIX=globals().get('EVAL_HUB_PREFIX','evaluation') | |
| PROBE_FITS=len(CHECKPOINTS)*len(DATASETS)*len(SPLITS)*3*2 | |
| FINE_FITS=len(CHECKPOINTS)*len(DATASETS)*len(SPLITS)*3 | |
| TOTAL_FITS=PROBE_FITS+FINE_FITS | |
| RESULTS=OUT/'results.csv' | |
| def rows():return pd.read_csv(RESULTS).to_dict('records') if RESULTS.exists() else [] | |
| def key(row):return tuple(row[k] for k in ['dataset','split','checkpoint_epoch','method','fold']) | |
| def persist(row): | |
| records=rows() | |
| if key(row) not in {key(r) for r in records}:records.append(row) | |
| tmp=RESULTS.with_suffix('.csv.partial');pd.DataFrame(records).to_csv(tmp,index=False);tmp.replace(RESULTS) | |
| return records | |
| def save_summary(run): | |
| records=rows() | |
| if not records:return | |
| frame=pd.DataFrame(records) | |
| summary=frame.groupby(['dataset','split','checkpoint_epoch','method']).agg( | |
| rmse_mean=('rmse','mean'),rmse_std=('rmse','std'),mae_mean=('mae','mean'),r2_mean=('r2','mean'),folds=('fold','count')).reset_index() | |
| summary.to_csv(OUT/'summary.csv',index=False) | |
| run.log({'fold_results':wandb.Table(dataframe=frame),'checkpoint_summary':wandb.Table(dataframe=summary)}) | |
| # Mean +/- sample SD describes fold variation; folds are not independent repeats. | |
| for _,r in summary[summary.folds==3].iterrows(): | |
| prefix=f"{r['dataset']}/{r['split']}/{r['method']}/checkpoint_{int(r['checkpoint_epoch']):02d}" | |
| run.summary[prefix+'/rmse_mean']=float(r.rmse_mean) | |
| run.summary[prefix+'/rmse_std']=float(r.rmse_std) | |
| def archive(run,stage): | |
| artifact=wandb.Artifact(f'{RUN_LABEL}-checkpoint-cv3-results',type='evaluation',metadata={'stage':stage,'protocol':PROTOCOL}) | |
| for p in [OUT/'protocol.json',OUT/'results.csv',OUT/'summary.csv',OUT/'source_manifest.json']: | |
| if p.exists():artifact.add_file(str(p)) | |
| for folder in ['splits','predictions']: | |
| if (OUT/folder).exists():artifact.add_dir(str(OUT/folder),name=folder) | |
| for p in (OUT/'finetuning').glob('**/predictions.npz'): | |
| artifact.add_file(str(p),name=str(p.relative_to(OUT))) | |
| run.log_artifact(artifact,aliases=['latest',stage]) | |
| def hub_paused(): | |
| path=WORK/'evaluation/hub_backoff.json' | |
| return path.exists() and json.loads(path.read_text()).get('resume_unix',0)>time.time() | |
| def backup_evaluation(): | |
| if hub_paused():return False | |
| from huggingface_hub import HfApi | |
| cfg=json.loads((WORK/'config.json').read_text()) | |
| commit=HfApi().upload_folder(repo_id=cfg['model_repository'],folder_path=OUT,path_in_repo=HUB_PREFIX, | |
| allow_patterns=['*.json','*.csv','splits/*','predictions/*','finetuning/**/result.json','finetuning/**/history.json','finetuning/**/predictions.npz'], | |
| commit_message='Save COSMO epoch checkpoint CV results and held-out predictions') | |
| write(OUT/'hub_backup.json',dict(revision=commit.oid,time=time.time())) | |
| return True | |
| def backup_fold(row,run): | |
| records=rows() | |
| progress=dict(completed=len(records),total=TOTAL_FITS,probes=sum(r['method']!='finetune' for r in records), | |
| finetuning=sum(r['method']=='finetune' for r in records),latest=row,time=time.time()) | |
| write(OUT/'progress.json',progress) | |
| files=[OUT/'results.csv',OUT/'progress.json'] | |
| if row['method']=='finetune': | |
| directory=OUT/'finetuning'/row['dataset']/row['split']/f"checkpoint_{int(row['checkpoint_epoch']):02d}"/f"fold_{int(row['fold'])}" | |
| files += [directory/name for name in ['result.json','history.json','predictions.npz','wandb.json']] | |
| else: | |
| files.append(OUT/'predictions'/f"{row['dataset']}_{row['split']}_checkpoint{int(row['checkpoint_epoch']):02d}_{row['method']}_fold{int(row['fold'])}.npz") | |
| artifact=wandb.Artifact(f'{RUN_LABEL}-cv-fold-backups',type='evaluation',metadata={'completed':len(records),'latest_fold':row}) | |
| for path in files: | |
| if path.exists():artifact.add_file(str(path),name=str(path.relative_to(OUT))) | |
| run.log_artifact(artifact,aliases=['latest',f'fold-{len(records):03d}']).wait(timeout=60) | |
| def main(): | |
| parser=argparse.ArgumentParser();parser.add_argument('--validate-only',action='store_true');args=parser.parse_args() | |
| OUT.mkdir(exist_ok=True) | |
| lock=(OUT/'driver.lock').open('a') | |
| try:fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB) | |
| except BlockingIOError: | |
| print('EVALUATION_ALREADY_RUNNING',flush=True);return | |
| status('validating_protocol') | |
| prepare_splits() | |
| for epoch in CHECKPOINTS: | |
| assert (checkpoint(epoch)/'hub_verified.json').exists(), 'Checkpoint must be backed up before evaluation' | |
| for name in ['encoder.pth','atomic_preprocessor.pth','geometric_preprocessor.pth']:assert (checkpoint(epoch)/name).exists() | |
| import importlib.metadata | |
| PROTOCOL['installed_versions']={n:importlib.metadata.version(n) for n in ['torch','scikit-learn','rdkit','wandb']} | |
| PROTOCOL['checkpoint_sha256']={str(e):{n:sha(checkpoint(e)/n) for n in ['encoder.pth','atomic_preprocessor.pth','geometric_preprocessor.pth']} for e in CHECKPOINTS} | |
| import sdm | |
| PROTOCOL['installed_versions']['sdm']=importlib.metadata.version('structured-data-models') | |
| write(OUT/'protocol.json',PROTOCOL) | |
| write(OUT/'source_manifest.json',{p.name:sha(p) for p in Path(__file__).parent.glob('*.py')}) | |
| backup_evaluation() | |
| if args.validate_only: | |
| status('protocol_validated',expected_probes=PROBE_FITS,expected_finetuning=FINE_FITS);return | |
| saved=json.loads((OUT/'wandb.json').read_text()) if (OUT/'wandb.json').exists() else {} | |
| run_id=saved.get('run_id') or wandb.util.generate_id() | |
| write(OUT/'wandb.json',{'run_id':run_id}) | |
| run=wandb.init(entity='queimo',project='rem3di-reproduction',id=run_id,resume='allow',mode='online', | |
| name=f'{RUN_LABEL}-all-checkpoints-cv3-random-scaffold',group=f'{RUN_LABEL}-checkpoint-cv3',job_type='checkpoint-comparison', | |
| config={**PROTOCOL,'cosmo_training':json.loads((WORK/'config.json').read_text()),'dataset_reference':json.loads((WORK/'dataset_reference.json').read_text())},dir=str(OUT),settings=wandb.Settings(init_timeout=90)) | |
| write(OUT/'wandb.json',dict(run_id=run.id,url=run.url)) | |
| try: | |
| data={name:raw_cache(name) for name in DATASETS} | |
| from eval_finetuning import smoke | |
| status('checking_finetuning_gradients') | |
| smoke(data['esol']) | |
| known={key(r) for r in rows()} | |
| import sdm | |
| kumo=sdm.models.KumoTabular(task='regression',size='large',device='cuda') | |
| for epoch in CHECKPOINTS: | |
| for dataset in DATASETS: | |
| y,_,groups=arrays(dataset);X=descriptors(epoch,dataset,data[dataset]) | |
| for scheme in SPLITS: | |
| for fold in get_splits(dataset,scheme): | |
| tr=np.array(fold['train']);te=np.array(fold['test']);fi=int(fold['fold']) | |
| for method in ['ridge','kumo_large']: | |
| base=dict(checkpoint_epoch=epoch,dataset=dataset,split=scheme,fold=fi,method=method,seed=16000+fi) | |
| if key(base) in known:continue | |
| status('probing',**base,completed_probe_fits=len([r for r in rows() if r['method']!='finetune']),total_probe_fits=PROBE_FITS) | |
| started=time.perf_counter() | |
| pred,extras=ridge_probe(X,y,tr,te,groups,scheme,fi) if method=='ridge' else kumo_probe(kumo,X,y,tr,te,fi) | |
| result=dict(**base,**metric(y[te],pred),**extras,n_train=len(tr),n_test=len(te),seconds=time.perf_counter()-started) | |
| p=OUT/'predictions'/f'{dataset}_{scheme}_checkpoint{epoch:02d}_{method}_fold{fi}.npz' | |
| p.parent.mkdir(exist_ok=True) | |
| np.savez_compressed(p,test_indices=te,y_true=y[te],y_pred=pred) | |
| persist(result);known.add(key(result));run.log({'probe_fold/'+k:v for k,v in result.items()});backup_fold(result,run) | |
| print('RESULT',json.dumps(result),flush=True) | |
| save_summary(run) | |
| archive(run,f'probes-epoch-{epoch}');backup_evaluation() | |
| del kumo;gc.collect();torch.cuda.empty_cache() | |
| assert len([r for r in rows() if r['method']!='finetune'])==PROBE_FITS | |
| write(OUT/'probes_complete.json',dict(completed=True,results=PROBE_FITS,time=time.time())) | |
| archive(run,'probes-complete') | |
| from eval_finetuning import fit_one | |
| for epoch in CHECKPOINTS: | |
| for dataset in DATASETS: | |
| X=descriptors(epoch,dataset,data[dataset]) | |
| for scheme in SPLITS: | |
| for fold in get_splits(dataset,scheme): | |
| fi=int(fold['fold']);base=dict(checkpoint_epoch=epoch,dataset=dataset,split=scheme,fold=fi,method='finetune') | |
| if key(base) in known:continue | |
| dest=OUT/'finetuning'/dataset/scheme/f'checkpoint_{epoch:02d}'/f'fold_{fi}' | |
| # A completed fold can survive a disconnect before aggregate CSV logging. | |
| if (dest/'result.json').exists(): | |
| result=json.loads((dest/'result.json').read_text());persist(result);known.add(key(result));backup_fold(result,run);continue | |
| dest.mkdir(parents=True,exist_ok=True) | |
| state=json.loads((dest/'wandb.json').read_text()) if (dest/'wandb.json').exists() else {} | |
| fine_id=state.get('run_id') or wandb.util.generate_id();write(dest/'wandb.json',{'run_id':fine_id}) | |
| ft=wandb.init(entity='queimo',project='rem3di-reproduction',id=fine_id,resume='allow',mode='online',reinit='create_new', | |
| name=f'finetune-{dataset}-{scheme}-checkpoint{epoch:02d}-fold{fi}',group=f'{RUN_LABEL}-checkpoint-cv3',job_type='supervised-finetuning', | |
| config={**base,**PROTOCOL['finetuning'],'seed':16000+fi,'parent_comparison_url':run.url},dir=str(dest), | |
| settings=wandb.Settings(init_timeout=90)) | |
| write(dest/'wandb.json',dict(run_id=ft.id,url=ft.url)) | |
| try: | |
| result,model_dir=fit_one(epoch,dataset,scheme,fold,data[dataset],X,ft) | |
| artifact=wandb.Artifact(f'predictions-{dataset}-{scheme}-checkpoint{epoch:02d}-fold{fi}',type='evaluation') | |
| for filename in ['predictions.npz','result.json','history.json']:artifact.add_file(str(model_dir/filename)) | |
| ft.log_artifact(artifact);ft.finish() | |
| except Exception: | |
| ft.finish(exit_code=1);raise | |
| persist(result);known.add(key(result));run.log({'finetune_fold/'+k:v for k,v in result.items()});backup_fold(result,run) | |
| save_summary(run) | |
| print('RESULT',json.dumps(result),flush=True) | |
| archive(run,f'finetuning-epoch-{epoch}-{dataset}');backup_evaluation() | |
| assert len(rows())==TOTAL_FITS | |
| save_summary(run);archive(run,'complete');backup_evaluation() | |
| write(OUT/'complete.json',dict(completed=True,results=TOTAL_FITS,probes=PROBE_FITS,finetuning=FINE_FITS,wandb_url=run.url,time=time.time())) | |
| status('complete',results=TOTAL_FITS,wandb_url=run.url) | |
| run.summary['all_evaluations_complete']=True;run.finish() | |
| except Exception: | |
| status('failed',error=traceback.format_exc(),completed_fold_results=len(rows())) | |
| run.finish(exit_code=1);raise | |
| if __name__=='__main__': | |
| try:main() | |
| except Exception: | |
| status('failed',error=traceback.format_exc(),completed_fold_results=len(rows())) | |
| try:backup_evaluation() | |
| except Exception:print('EVALUATION_FAILURE_BACKUP_ERROR',traceback.format_exc(),flush=True) | |
| raise | |