Download source/expanded_evaluate.py from Queimo/rem3di-pcqm-epoch2-cosmo: direct link, hf CLI and curl.
- Browser
- Download file 18.2 kB
-
https://huggingface.co/Queimo/rem3di-pcqm-epoch2-cosmo/resolve/main/source/expanded_evaluate.py
- Command line
-
hf download hf://Queimo/rem3di-pcqm-epoch2-cosmo/source/expanded_evaluate.py
-
curl -L -o expanded_evaluate.py https://huggingface.co/Queimo/rem3di-pcqm-epoch2-cosmo/resolve/main/source/expanded_evaluate.py
18.2 kB
| """Add published REM3DI, Monroe+Kumo, and ECFP4/RDKit2D+Kumo controls.""" | |
| from pathlib import Path | |
| import sys | |
| sys.path.insert(0, str(Path(__file__).resolve().parent)) | |
| import eval_common as common | |
| from eval_common import WORK, DATASETS, SPLITS, arrays, metric, sha, write | |
| import concurrent.futures | |
| import fcntl | |
| import gc | |
| import importlib.metadata | |
| import json | |
| import multiprocessing as mp | |
| import os | |
| import shutil | |
| import subprocess | |
| import time | |
| import traceback | |
| import warnings | |
| import numpy as np | |
| import pandas as pd | |
| import torch | |
| import wandb | |
| from huggingface_hub import HfApi | |
| OUT = WORK / 'expanded_evaluation' | |
| MONROE = WORK / 'external/Monroe' | |
| MONROE_REVISION = 'de075eabe98e4adbbedbc86ca9e877f4bfd9b629' | |
| MONROE_SHA256 = 'df996e8e98b12a3cda5fe5acbef3e1e9a4ea31946d3736461cd07e53a5bf205a' | |
| REPO = 'Queimo/rem3di-pcqm-epoch2-cosmo' | |
| PROTOCOL = { | |
| 'datasets': DATASETS, 'retained_rows': {'esol': 1108, 'freesolv': 625}, | |
| 'folds': 'Exact saved random/scaffold three-fold splits from the completed COSMO comparison', | |
| 'new_fits': {'published_rem3di': 36, 'monroe_kumo': 12, 'ecfp_rdkit2d_kumo': 12}, | |
| 'monroe': {'repository': 'https://github.com/blazejba/Monroe', | |
| 'revision': MONROE_REVISION, 'weights_sha256': MONROE_SHA256, | |
| 'weights': 'checkpoint/weights.pt; ordinary released encoder, not EMA', | |
| 'features': '720-dimensional frozen author encoder embedding', | |
| 'geometry': 'Author SMILES/InChI featurizer and ETKDG/MMFF94s/UFF fallback; cached graphs, native inference preprocessing'}, | |
| 'ecfp_rdkit2d': {'radius': 2, 'bits': 2048, 'include_chirality': False, | |
| 'descriptors': 'RDKit Descriptors._descList excluding 3D descriptors; names saved with features', | |
| 'missing': 'Non-finite descriptors -> NaN; median imputation fitted separately on each outer training fold; all-missing -> 0'}, | |
| 'kumo': {'model': 'Kumo-Tabular large', 'num_estimators': 4, | |
| 'seed': '16000+fold', 'max_columns': 640, | |
| 'selection': 'Existing default recipe, SelectColumns.max_columns=640; preprocessing fitted on context/training rows only', | |
| 'precision': 'float16 autocast; estimator batch size 1'}, | |
| 'published_rem3di': {'repository': 'Felixb7/rem3di-polar', | |
| 'revision': '09e302f4c77f40ddb8a6f8b3fef464e617faaa83', 'path': 'exp138/polar', | |
| 'methods': ['ridge', 'kumo_large', 'finetune'], | |
| 'protocol': 'Identical cached raw MACE features and existing ridge/Kumo/fine-tuning implementation'}, | |
| 'metrics': ['rmse', 'mae', 'r2'], | |
| 'comparison': 'All retained rows and folds preserved. Monroe uses its native conformer pipeline; REM3DI variants use identical saved geometries. No outer-test tuning.', | |
| } | |
| def status(phase, **kw): | |
| row = dict(phase=phase, pid=os.getpid(), updated_unix=time.time(), **kw) | |
| write(OUT / 'status.json', row) | |
| print('EXPANDED_STATUS', json.dumps(row), flush=True) | |
| def setup_monroe(): | |
| status('restoring_monroe_release') | |
| MONROE.parent.mkdir(parents=True, exist_ok=True) | |
| env = {**os.environ, 'GIT_LFS_SKIP_SMUDGE': '1'} | |
| if not (MONROE / '.git').exists(): | |
| subprocess.run(['git', 'clone', '--depth', '1', 'https://github.com/blazejba/Monroe.git', str(MONROE)], check=True, env=env) | |
| revision = subprocess.check_output(['git', '-C', str(MONROE), 'rev-parse', 'HEAD'], text=True).strip() | |
| if revision != MONROE_REVISION: | |
| subprocess.run(['git', '-C', str(MONROE), 'fetch', '--depth', '1', 'origin', MONROE_REVISION], check=True, env=env) | |
| subprocess.run(['git', '-C', str(MONROE), 'checkout', MONROE_REVISION], check=True, env=env) | |
| weights = MONROE / 'checkpoint/weights.pt' | |
| if not weights.exists() or sha(weights) != MONROE_SHA256: | |
| temp = weights.with_suffix('.download') | |
| url = f'https://media.githubusercontent.com/media/blazejba/Monroe/{MONROE_REVISION}/checkpoint/weights.pt' | |
| subprocess.run(['curl', '-fL', '--retry', '4', '--connect-timeout', '20', '-o', str(temp), url], check=True) | |
| assert sha(temp) == MONROE_SHA256, 'Monroe release weight checksum mismatch' | |
| temp.replace(weights) | |
| sys.path.insert(0, str(MONROE)) | |
| write(OUT / 'monroe_release.json', dict(repository=PROTOCOL['monroe']['repository'], | |
| revision=MONROE_REVISION, weights_sha256=sha(weights), config_sha256=sha(MONROE/'checkpoint/config.json'))) | |
| def build_graph_job(item): | |
| index, smiles = item | |
| from rdkit import rdBase | |
| from monroe.eval.embed import _featurize_one | |
| rdBase.SeedRandomNumberGenerator(42026 + index) | |
| return _featurize_one(smiles) | |
| def monroe_features(dataset): | |
| import pyarrow as pa | |
| import pyarrow.parquet as pq | |
| from monroe.eval.embed import to_pyg | |
| from monroe.model.ckpt import load_ckpt, _load_state_dict | |
| from torch_geometric.data import Batch | |
| y, smiles, _ = arrays(dataset) | |
| names = [str(s) for s in smiles] | |
| path = OUT / 'features' / f'{dataset}_monroe.npz' | |
| signature = dict(revision=MONROE_REVISION, weights_sha256=MONROE_SHA256, | |
| smiles_sha256=__import__('hashlib').sha256('\n'.join(names).encode()).hexdigest()) | |
| if path.exists(): | |
| z = np.load(path) | |
| assert json.loads(str(z['signature'])) == signature | |
| assert z['smiles'].tolist() == names | |
| return z['X'] | |
| graph_path = OUT / 'features' / f'{dataset}_monroe_graphs.parquet' | |
| if graph_path.exists(): | |
| records = pq.read_table(graph_path).to_pylist() | |
| assert [r['smiles'] for r in records] == names | |
| built = [(r.pop('smiles'), r) for r in records] | |
| else: | |
| status('featurizing_monroe', dataset=dataset, rows=len(names)) | |
| with concurrent.futures.ProcessPoolExecutor(max_workers=8, mp_context=mp.get_context('fork')) as pool: | |
| built = list(pool.map(build_graph_job, enumerate(names), chunksize=8)) | |
| missing = [names[i] for i, result in enumerate(built) if result is None] | |
| write(OUT / f'{dataset}_monroe_coverage.json', dict(rows=len(names), missing=missing)) | |
| assert not missing, f'Monroe must retain the full matched cohort: {missing[:5]}' | |
| assert [s for s, _ in built] == names | |
| records = [dict(smiles=s, **{k: np.asarray(g[k]).tolist() for k in | |
| ['node_float','node_codes','edge_index','edge_codes','pos_rdkit']}) for s, g in built] | |
| pq.write_table(pa.Table.from_pylist(records), graph_path, compression='zstd') | |
| status('embedding_monroe', dataset=dataset, rows=len(names)) | |
| # The author loader permits task-head extras. Require every encoder tensor explicitly. | |
| encoder = load_ckpt(str(MONROE / 'checkpoint')).eval() | |
| state = _load_state_dict(MONROE / 'checkpoint/weights.pt', device='cpu') | |
| encoder_state = {k[len('encoder.'):]: v for k, v in state.items() if k.startswith('encoder.')} | |
| encoder.load_state_dict(encoder_state, strict=True) | |
| del state, encoder_state | |
| encoder = encoder.cuda() | |
| vectors = [] | |
| with torch.inference_mode(): | |
| for start in range(0, len(built), 8): | |
| graphs = [to_pyg(graph) for _, graph in built[start:start+8]] | |
| batch = Batch.from_data_list(graphs).to('cuda') | |
| emb, _ = encoder(batch) | |
| vectors.append(emb.float().cpu().numpy()) | |
| X = np.concatenate(vectors) | |
| assert X.shape == (len(y), 720) and np.isfinite(X).all() | |
| np.savez_compressed(path, X=X, smiles=smiles, signature=json.dumps(signature)) | |
| write(OUT / f'{dataset}_monroe_features.json', dict(rows=len(X), columns=X.shape[1], | |
| all_z_zero_layouts=sum(bool(np.all(np.asarray(g['pos_rdkit'])[:,2] == 0)) for _,g in built), | |
| features_sha256=sha(path), graphs_sha256=sha(graph_path), encoder_loaded_strictly=True)) | |
| del encoder, built, vectors | |
| gc.collect(); torch.cuda.empty_cache() | |
| return X | |
| def classical_features(dataset): | |
| from rdkit import Chem, DataStructs | |
| from rdkit.Chem import Descriptors, rdFingerprintGenerator | |
| _, smiles, _ = arrays(dataset) | |
| path = OUT / 'features' / f'{dataset}_ecfp_rdkit2d.npz' | |
| if path.exists(): | |
| z = np.load(path) | |
| assert z['smiles'].tolist() == [str(s) for s in smiles] | |
| return z['X'] | |
| status('featurizing_ecfp_rdkit2d', dataset=dataset, rows=len(smiles)) | |
| exclude = {'PMI1','PMI2','PMI3','NPR1','NPR2','RadiusOfGyration', | |
| 'InertialShapeFactor','Eccentricity','Asphericity','SpherocityIndex','PBF'} | |
| descriptors = [(n, f) for n, f in Descriptors._descList if n not in exclude] | |
| names = [f'ECFP4_bit_{i}' for i in range(2048)] + [n for n, _ in descriptors] | |
| generator = rdFingerprintGenerator.GetMorganGenerator(radius=2, fpSize=2048, includeChirality=False) | |
| X = np.full((len(smiles), len(names)), np.nan, dtype=np.float64) | |
| failures = {} | |
| for i, s in enumerate(smiles): | |
| mol = Chem.MolFromSmiles(str(s)); assert mol is not None | |
| bitvec = np.zeros(2048, dtype=np.uint8) | |
| DataStructs.ConvertToNumpyArray(generator.GetFingerprint(mol), bitvec) | |
| X[i,:2048] = bitvec | |
| for j, (name, function) in enumerate(descriptors, 2048): | |
| try: | |
| value = float(function(mol)) | |
| if np.isfinite(value): X[i,j] = value | |
| except Exception: | |
| failures[name] = failures.get(name, 0) + 1 | |
| np.savez_compressed(path, X=X, smiles=smiles, feature_names=np.asarray(names)) | |
| write(OUT / f'{dataset}_ecfp_rdkit2d_features.json', dict(rows=len(X), columns=len(names), | |
| descriptor_names=names[2048:], descriptor_failures=failures, | |
| nonfinite_values=int((~np.isfinite(X)).sum()), features_sha256=sha(path))) | |
| return X | |
| def impute_training_only(X, tr): | |
| values = np.where(np.isfinite(X), X, np.nan) | |
| with warnings.catch_warnings(): | |
| warnings.simplefilter('ignore', RuntimeWarning) | |
| medians = np.nanmedian(values[tr], axis=0) | |
| medians[~np.isfinite(medians)] = 0 | |
| filled = np.where(np.isfinite(values), values, medians) | |
| assert np.isfinite(filled).all() | |
| assert np.max(np.abs(filled)) < np.finfo(np.float32).max | |
| return filled.astype(np.float32), medians | |
| def probe_results(): | |
| p = OUT / 'results.csv' | |
| return pd.read_csv(p).to_dict('records') if p.exists() else [] | |
| def fit_probes(run): | |
| from eval_probes import kumo_probe | |
| import sdm | |
| import sdm.processing as sp | |
| model = sdm.models.KumoTabular(task='regression', size='large', device='cuda') | |
| for representation in ['monroe', 'ecfp_rdkit2d']: | |
| for dataset in DATASETS: | |
| y, _, _ = arrays(dataset) | |
| X = monroe_features(dataset) if representation == 'monroe' else classical_features(dataset) | |
| for scheme in SPLITS: | |
| folds = json.loads((WORK/'evaluation/splits'/f'{dataset}_{scheme}.json').read_text())['folds'] | |
| for fold in folds: | |
| fi = int(fold['fold']) | |
| base = dict(representation=representation, dataset=dataset, split=scheme, | |
| method='kumo_large', fold=fi, seed=16000+fi) | |
| records = probe_results() | |
| if any(all(row[k] == v for k,v in base.items()) for row in records): continue | |
| status('probing', **base, completed=len(records), total=24) | |
| tr, te = np.asarray(fold['train']), np.asarray(fold['test']) | |
| features, medians = impute_training_only(X, tr) | |
| started = time.perf_counter() | |
| pred, extras = kumo_probe(model, features, y, tr, te, fi) | |
| row = dict(**base, **metric(y[te], pred), **extras, raw_columns=X.shape[1], | |
| n_train=len(tr), n_test=len(te), seconds=time.perf_counter()-started) | |
| p = OUT/'predictions'/f'{representation}_{dataset}_{scheme}_fold{fi}.npz' | |
| np.savez_compressed(p, test_indices=te, y_true=y[te], y_pred=pred, | |
| imputation_medians=medians, imputation_train_indices=tr) | |
| records.append(row) | |
| tmp = OUT/'results.partial.csv'; pd.DataFrame(records).to_csv(tmp,index=False) | |
| tmp.replace(OUT/'results.csv') | |
| write(OUT/'progress.json', dict(completed=len(records), total=24, latest=row)) | |
| run.log({'fold/'+k: v for k,v in row.items()}) | |
| artifact = wandb.Artifact('cosmo-expanded-baseline-fold-backups', type='evaluation', metadata=row) | |
| for file in [p, OUT/'results.csv', OUT/'progress.json']: | |
| artifact.add_file(str(file),name=str(file.relative_to(OUT))) | |
| run.log_artifact(artifact,aliases=['latest',f'fold-{len(records):02d}']).wait(timeout=60) | |
| print('EXPANDED_RESULT',json.dumps(row),flush=True) | |
| del model | |
| gc.collect(); torch.cuda.empty_cache() | |
| assert len(probe_results()) == 24 | |
| def wait_for_published(): | |
| out = WORK/'published_evaluation' | |
| while not (out/'complete.json').exists(): | |
| path = out/'status.json' | |
| state = json.loads(path.read_text()) if path.exists() else {} | |
| pid = state.get('pid',0) | |
| cmd = Path(f'/proc/{pid}/cmdline') | |
| active = bool(pid and cmd.exists() and b'published_baseline.py' in cmd.read_bytes()) | |
| if not active: | |
| status('running_published_rem3di') | |
| with (WORK/'published_evaluate.log').open('a') as log: | |
| subprocess.run([sys.executable,'-u',str(Path(__file__).with_name('published_baseline.py'))], | |
| cwd=WORK,stdout=log,stderr=subprocess.STDOUT,check=True) | |
| else: | |
| status('waiting_for_published_rem3di', published_phase=state.get('phase')) | |
| time.sleep(30) | |
| assert json.loads((out/'complete.json').read_text())['results'] == 36 | |
| def publish(run): | |
| artifact = wandb.Artifact('cosmo-expanded-evaluation-results', type='evaluation', | |
| metadata=dict(new_fold_results=60,combined_fold_results=456,protocol=PROTOCOL)) | |
| for p in OUT.rglob('*'): | |
| if p.is_file() and 'wandb' not in p.relative_to(OUT).parts and p.suffix in ['.json','.csv','.npz','.parquet','.png','.svg','.md']: | |
| artifact.add_file(str(p),name='expanded_evaluation/'+str(p.relative_to(OUT))) | |
| for name in ['expanded_evaluate.py','expanded_report.py','published_baseline.py']: | |
| artifact.add_file(str(Path(__file__).with_name(name)),name='source/'+name) | |
| run.log_artifact(artifact,aliases=['latest','complete']).wait(timeout=60) | |
| operations = [] | |
| from huggingface_hub import CommitOperationAdd | |
| for p in OUT.rglob('*'): | |
| if p.is_file() and 'wandb' not in p.relative_to(OUT).parts and p.suffix in ['.json','.csv','.npz','.parquet','.png','.svg','.md']: | |
| operations.append(CommitOperationAdd(path_in_repo='expanded_evaluation/'+str(p.relative_to(OUT)),path_or_fileobj=str(p))) | |
| for name in ['expanded_evaluate.py','expanded_report.py','published_baseline.py']: | |
| operations.append(CommitOperationAdd(path_in_repo='source/'+name,path_or_fileobj=str(Path(__file__).with_name(name)))) | |
| commit = HfApi().create_commit(repo_id=REPO,operations=operations, | |
| commit_message='Add matched published REM3DI, Monroe+Kumo and ECFP4/RDKit2D+Kumo evaluations') | |
| write(OUT/'hub_verified.json',dict(repository=REPO,revision=commit.oid,completed=True)) | |
| return commit.oid | |
| def publish_completion_markers(): | |
| """Persist final markers written after the result-batch commits.""" | |
| from huggingface_hub import CommitOperationAdd | |
| files = [WORK/'published_evaluation/complete.json', WORK/'published_evaluation/status.json', | |
| WORK/'published_rem3di/hub_verified.json', OUT/'status.json', OUT/'hub_verified.json', | |
| Path(__file__)] | |
| operations = [CommitOperationAdd(path_in_repo=str(p.relative_to(WORK)),path_or_fileobj=str(p)) for p in files] | |
| return HfApi().create_commit(repo_id=REPO,operations=operations, | |
| commit_message='Verify completed expanded evaluation and published REM3DI control markers').oid | |
| def main(): | |
| OUT.mkdir(exist_ok=True) | |
| with (OUT/'driver.lock').open('a') as lock: | |
| try: fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB) | |
| except BlockingIOError: | |
| print('EXPANDED_EVALUATION_ALREADY_RUNNING',flush=True); return | |
| for folder in ['features','predictions','analysis']:(OUT/folder).mkdir(exist_ok=True) | |
| PROTOCOL['versions'] = {n:importlib.metadata.version(n) for n in | |
| ['torch','numpy','scikit-learn','rdkit','torch-geometric','datamol','structured-data-models','wandb']} | |
| assert PROTOCOL['versions']['scikit-learn'] == '1.9.0' | |
| write(OUT/'protocol.json', PROTOCOL) | |
| wait_for_published() | |
| setup_monroe() | |
| saved = json.loads((OUT/'wandb.json').read_text()) if (OUT/'wandb.json').exists() else {} | |
| run = wandb.init(entity='queimo',project='rem3di-reproduction',id=saved.get('run_id') or wandb.util.generate_id(), | |
| resume='allow',name='cosmo-expanded-literature-and-classical-baselines-cv3', | |
| group='cosmo-expanded-baselines-cv3',job_type='matched-baseline-comparison', | |
| config=PROTOCOL,dir=str(OUT),settings=wandb.Settings(init_timeout=90)) | |
| write(OUT/'wandb.json',dict(run_id=run.id,url=run.url)) | |
| try: | |
| fit_probes(run) | |
| from expanded_report import build_report | |
| build_report(OUT,run) | |
| write(OUT/'complete.json',dict(completed=True,new_fold_results=60, | |
| published_rem3di_fold_results=36,new_kumo_fold_results=24,combined_fold_results=456,wandb_url=run.url)) | |
| revision = publish(run) | |
| run.summary.update(dict(all_evaluations_complete=True,new_fold_results=60,combined_fold_results=456,hub_revision=revision)) | |
| run.finish() | |
| status('complete',new_fold_results=60,combined_fold_results=456,hub_revision=revision) | |
| publish_completion_markers() | |
| except Exception: | |
| status('failed',error=traceback.format_exc(),completed_probe_folds=len(probe_results())) | |
| run.finish(exit_code=1); raise | |
| if __name__ == '__main__': | |
| try: main() | |
| except Exception: | |
| OUT.mkdir(exist_ok=True);status('failed',error=traceback.format_exc());raise | |