File size: 18,203 Bytes
57eaa2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1cc3428
 
 
 
 
 
 
 
 
 
 
57eaa2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f7ab65f
57eaa2f
 
1cc3428
57eaa2f
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
"""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