Add exact model code and documentation (3/7)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- code/snapshot/root/code/ceir_r3_20261110/audit_primitives.pyAdded+293
- code/snapshot/root/code/ceir_r3_20261110/audit_r3.pyAdded+31
- code/snapshot/root/code/ceir_r3_20261110/compact.supervisor.confAdded+11
- code/snapshot/root/code/ceir_r3_20261110/compact_r3.pyAdded+75
- code/snapshot/root/code/ceir_r3_20261110/config.jsonAdded+44
- code/snapshot/root/code/ceir_r3_20261110/data_r2.pyAdded+51
- code/snapshot/root/code/ceir_r3_20261110/features_r2.pyAdded+183
- code/snapshot/root/code/ceir_r3_20261110/final_audit_r3.pyAdded+35
- code/snapshot/root/code/ceir_r3_20261110/heads_r3.pyAdded+102
- code/snapshot/root/code/ceir_r3_20261110/mces_r2.pyAdded+29
- code/snapshot/root/code/ceir_r3_20261110/model_r2_new.pyAdded+205
- code/snapshot/root/code/ceir_r3_20261110/objectives_r2.pyAdded+138
- code/snapshot/root/code/ceir_r3_20261110/pipeline.supervisor.confAdded+12
- code/snapshot/root/code/ceir_r3_20261110/pipeline_r3.pyAdded+71
- code/snapshot/root/code/ceir_r3_20261110/prepare.supervisor.confAdded+12
- code/snapshot/root/code/ceir_r3_20261110/prepare_r3.pyAdded+147
- code/snapshot/root/code/ceir_r3_20261110/probe_r3.pyAdded+30
- code/snapshot/root/code/ceir_r3_20261110/runtime_r2.pyAdded+128
- code/snapshot/root/code/ceir_r3_20261110/test_mces_r2.pyAdded+26
- code/snapshot/root/code/ceir_r3_20261110/test_r3.pyAdded+60
- code/snapshot/root/code/ceir_r3_20261110/tests_r3.pyAdded+53
- code/snapshot/root/code/ceir_r3_20261110/train_r2.pyAdded+111
- code/snapshot/root/code/ceir_r3_20261110/validate_r2.pyAdded+109
- code/snapshot/root/code/ceir_r4_9000_20261112/README.mdAdded+68
- code/snapshot/root/code/ceir_r4_9000_20261112/accept4.pyAdded+72
- code/snapshot/root/code/ceir_r4_9000_20261112/common4.pyAdded+45
- code/snapshot/root/code/ceir_r4_9000_20261112/config.jsonAdded+21
- code/snapshot/root/code/ceir_r4_9000_20261112/data4.pyAdded+61
- code/snapshot/root/code/ceir_r4_9000_20261112/duel4.pyAdded+73
- code/snapshot/root/code/ceir_r4_9000_20261112/eval4.pyAdded+161
- code/snapshot/root/code/ceir_r4_9000_20261112/mces4.pyAdded+27
- code/snapshot/root/code/ceir_r4_9000_20261112/model4.pyAdded+117
- code/snapshot/root/code/ceir_r4_9000_20261112/objectives4.pyAdded+161
- code/snapshot/root/code/ceir_r4_9000_20261112/pipeline.supervisor.confAdded+13
- code/snapshot/root/code/ceir_r4_9000_20261112/pipeline4.pyAdded+69
- code/snapshot/root/code/ceir_r4_9000_20261112/prep.supervisor.confAdded+12
- code/snapshot/root/code/ceir_r4_9000_20261112/prepare4.pyAdded+143
- code/snapshot/root/code/ceir_r4_9000_20261112/report4.pyAdded+59
- code/snapshot/root/code/ceir_r4_9000_20261112/run4.pyAdded+140
- code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/README.mdAdded+39
- code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/accept5.pyAdded+107
- code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/addendum.supervisor.confAdded+13
- code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/addendum5.pyAdded+35
- code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/assets5.pyAdded+92
- code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/audit_identity5.pyAdded+45
- code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/augment5.pyAdded+92
- code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/batch5.pyAdded+80
- code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/data.supervisor.confAdded+13
- code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/data_pipeline.pyAdded+11
- code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/eval5.pyAdded+83
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293"""Read-only independent checks for the frozen CEIR-R2 experiment.
Kept OUTSIDE the frozen training release. No imported training/evaluationhelpers, no GPU access, no edits to checkpoints, candidate pools or predictions."""import argparsefrom collections import Counter, defaultdictimport gzipimport hashlibimport jsonimport mathfrom pathlib import Pathimport randomimport sqlite3import statisticsimport time
ROOT = Path('/root/xj/SpecPartition-MS/runs/ceir_r2_20261110')SOURCE = Path('/workspace/xj/SpecPartition-MS/data/derived/post_training_evaluation_20261103')KS = (1, 3, 5, 10, 20, 50, 100, 200)FKS = (*range(1, 11), 20, 50, 100, 200)MODELS = ('C03_002000', 'A0_003000', 'A1_003000', 'A2_003000', 'A3_003000')
def load(path): path = Path(path) if path.suffix == '.gz': with gzip.open(path, 'rt') as stream: return json.load(stream) return json.loads(path.read_text())
def save(path, value): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_suffix(path.suffix + '.tmp') temporary.write_text(json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False) + '\n') temporary.replace(path)
def sha(path): result = hashlib.sha256() with Path(path).open('rb') as stream: for block in iter(lambda: stream.read(1024 * 1024), b''): result.update(block) return result.hexdigest()
def close(actual, expected, context): if not math.isclose(actual, expected, rel_tol=0., abs_tol=1e-12): raise AssertionError((context, actual, expected))
def independent_metrics(rows, field, ks): if not rows: return {} answer = {} for k in ks: targets = defaultdict(list) identities = defaultdict(list) hits = 0 for row in rows: rank = row[field] if rank is not None and (not isinstance(rank, int) or isinstance(rank, bool) or rank < 1): raise AssertionError(('invalid rank', row['identifier'], field, rank)) hit = rank is not None and rank <= k hits += hit targets[row['target']].append(hit) identities[row['reference_identity']].append(hit) answer[str(k)] = dict(hits=hits, denominator=len(rows), micro=hits / len(rows), target_macro=statistics.mean(statistics.mean(v) for v in targets.values()), key14_macro=statistics.mean(statistics.mean(v) for v in identities.values())) return answer
def compare_metric(actual, original, context): for k, values in actual.items(): for key, value in values.items(): close(value, original[k][key], (context, k, key))
def aggregate(directory, dataset): original = load(directory / 'metrics.json') rows = load(directory / 'per_spectrum_summary.json.gz') denominator = {'validation': 19429, 'msg_test': 17556, 'casmi2022': 500}[dataset] answer = {} expected_views = {'mass', 'formula'} if dataset != 'casmi2022' else {r['view'] for r in rows} if {r['view'] for r in rows} != expected_views or (dataset == 'casmi2022' and len(expected_views) != 1): raise AssertionError('Incorrect views') for view in sorted(expected_views): selected = [r for r in rows if r['view'] == view] if len(selected) != denominator or len({r['identifier'] for r in selected}) != denominator: raise AssertionError(('Incorrect population', directory, view)) fields = [('rank', 'structure', KS), ('formula_rank', 'formula', FKS)] if dataset != 'validation': fields += [('canonical_rank', 'canonical_smiles', KS), ('inchikey_rank', 'full_inchikey', KS)] source = original[view] if dataset == 'validation' else original['views'][view] computed = {} for field, name, ks in fields: computed[name] = independent_metrics(selected, field, ks) compare_metric(computed[name], source[name], (str(directory), view, name)) in_pool = 'reference_present_in_original_pool' if dataset == 'validation' else 'reference_in_pool' scorable = 'reference_scoreable' if dataset == 'validation' else 'reference_scoreable_in_pool' computed['original_pool_coverage'] = sum(r[in_pool] for r in selected) computed['scoreable_coverage'] = sum(r[scorable] for r in selected) for row in selected: if row['rank'] is not None and not row[scorable]: raise AssertionError('Unscoreable truth was assigned a hit') if row['rank'] is not None and row['rank'] > row['candidate_count']: raise AssertionError('Rank exceeds original candidate count') for field, name, ks in fields: flags = 'recall_at_k' if field == 'rank' else ('formula_recall_at_k' if field == 'formula_rank' else None) if flags and flags in row: for k in ks: if row[flags][str(k)] != (row[field] is not None and row[field] <= k): raise AssertionError('Per-spectrum boolean disagrees with rank') if dataset == 'casmi2022': if sum(r['candidate_count'] for r in selected) != 1765420 or computed['original_pool_coverage'] != 467: raise AssertionError('Frozen CASMI full-pool protocol changed') computed['by_adduct'] = {adduct: independent_metrics([r for r in selected if r['adduct'] == adduct], 'rank', KS) for adduct in sorted({r['adduct'] for r in selected})} computed['by_polarity'] = {polarity: independent_metrics([r for r in selected if ('negative' if r['adduct'].endswith('-') else 'positive') == polarity], 'rank', KS) for polarity in sorted({'negative' if r['adduct'].endswith('-') else 'positive' for r in selected})} computed['reference_not_in_pool'] = denominator - computed['original_pool_coverage'] computed['conditional_given_original_coverage'] = independent_metrics([r for r in selected if r[in_pool]], 'rank', KS) answer[view] = computed mces = load(directory / 'MCES.json') details = load(directory / 'MCES_per_spectrum.json.gz') expected_ids = {(r['identifier'], r['view']) for r in rows} if {(r['identifier'], r['view']) for r in details} != expected_ids or len(details) != len(rows): raise AssertionError('MCES population differs') for view in expected_views: data = [r for r in details if r['view'] == view] values = [r['distance'] for r in data if r['distance'] is not None] if any(not math.isfinite(x) or x < 0 for x in values): raise AssertionError('Invalid MCES') source = mces['views'][view] if source['n'] != len(data) or source['valid'] != len(values) or source['missing'] != len(data) - len(values): raise AssertionError('MCES denominators disagree') if values: close(statistics.mean(values), source['valid_mean'], ('MCES', directory, view)) if len(values) != len(data) and source['full_mean'] is not None: raise AssertionError('Missing MCES was converted into a full-population mean') answer[view]['MCES'] = source lookup = {(r['identifier'], r['view']): r for r in rows} for name in ('adduct', 'polarity'): groups = defaultdict(list) for item in data: row = lookup[item['identifier'], item['view']] key = row['adduct'] if name == 'adduct' else ('negative' if row['adduct'].endswith('-') else 'positive') groups[key].append(item['distance']) answer[view]['MCES_by_' + name] = {key: dict(n=len(group), valid=sum(v is not None for v in group), missing=sum(v is None for v in group), valid_mean=statistics.mean(v for v in group if v is not None) if any(v is not None for v in group) else None, full_mean=statistics.mean(group) if all(v is not None for v in group) else None) for key, group in groups.items()} return answer, rows
def paired(base_rows, arm_rows, repetitions=2000): import numpy as np if {(r['identifier'], r['view']) for r in base_rows} != {(r['identifier'], r['view']) for r in arm_rows}: raise AssertionError('Paired comparison populations differ') lookup = {(r['identifier'], r['view']): r for r in base_rows} answer = {} for view in sorted({r['view'] for r in arm_rows}): groups = defaultdict(lambda: [0, 0]) gained = lost = 0 for row in arm_rows: if row['view'] != view: continue baseline = lookup[row['identifier'], view] if (row['reference_identity'], row['candidate_count'], row['target']) != ( baseline['reference_identity'], baseline['candidate_count'], baseline['target']): raise AssertionError('Paired query/candidate metadata changed') hit = row['rank'] is not None and row['rank'] <= 1 before = baseline['rank'] is not None and baseline['rank'] <= 1 gained += hit and not before lost += before and not hit groups[row['reference_identity']][0] += int(hit) - int(before) groups[row['reference_identity']][1] += 1 values = np.asarray([groups[k] for k in sorted(groups)], dtype=np.int64) generator = np.random.default_rng(20261110) draws = [] for start in range(0, repetitions, 100): index = generator.integers(len(values), size=(min(100, repetitions - start), len(values))) sampled = values[index].sum(axis=1) draws.extend((sampled[:, 0] / sampled[:, 1] * 100).tolist()) answer[view] = dict(top1_gained=gained, top1_lost=lost, top1_delta_pp=100 * (gained - lost) / int(values[:, 1].sum()), key14_macro_top1_delta_pp=float(np.mean(values[:, 0] / values[:, 1]) * 100), key14_groups_net_improved=int((values[:, 0] > 0).sum()), key14_groups_net_worsened=int((values[:, 0] < 0).sum()), key14_groups_net_tied=int((values[:, 0] == 0).sum()), key14_cluster_bootstrap_95_percent_interval_pp=np.quantile(draws, [.025, .975]).tolist(), bootstrap_repetitions=repetitions, inferential_unit='reference_key14', limitation='one training seed; not protection from adaptive experiment design') return answer
def pool_and_prediction_audit(name, dataset, comparison_hashes): """All pool identities and scores, independently re-sorted without rank helper.""" directory = ROOT / 'test/inference' / name / dataset db = sqlite3.connect('file:' + str(SOURCE / (dataset + '.sqlite')) + '?mode=ro', uri=True) db.execute('PRAGMA query_only=ON') actual_targets = set() predictions_checked = aliases_checked = 0 summary = {(r['identifier'], r['view']): r for r in load(directory / 'per_spectrum_summary.json.gz')} for path in sorted((directory / 'per_target').glob('*.json.gz')): result = load(path) target = result['target'] if target in actual_targets: raise AssertionError('Duplicate target output') actual_targets.add(target) pool_path = ROOT / 'test/shared_pools' / dataset / path.name shared = load(pool_path) original = {v: json.loads(b) for v, b in db.execute('SELECT view,body FROM pools WHERE target=?', (target,))} all_smiles = sorted({c['smiles'] for entries in shared['pools'].values() for c in entries}) source_aliases = {} for start in range(0, len(all_smiles), 500): block = all_smiles[start:start + 500] command = 'SELECT smiles,graph_key,identity,formula,canonical,fullkey,error FROM aliases WHERE smiles IN (' + ','.join('?' for _ in block) + ')' source_aliases.update({r[0]: r[1:] for r in db.execute(command, block)}) for view, entries in shared['pools'].items(): if [c['smiles'] for c in entries] != original[view]: raise AssertionError('Candidate order or membership changed from frozen source') for candidate in entries: stored = tuple(candidate[k] for k in ('graph_key', 'key14', 'formula', 'canonical_smiles', 'full_inchikey', 'error')) if stored != source_aliases[candidate['smiles']]: raise AssertionError('Shared candidate identity differs from immutable source') reported = result['candidate_order_sha256'][view] if reported != shared['candidate_order_sha256'][view]: raise AssertionError('Shared candidate binding disagrees') key = dataset, target, view if key in comparison_hashes and comparison_hashes[key] != reported: raise AssertionError('Candidate identities changed across models') comparison_hashes[key] = reported aliases_checked += len(entries) file_rows = {(r['identifier'], r['view']): r for r in result['rows']} for prediction in result['predictions']: key = prediction['identifier'], prediction['view'] row = summary[key] if file_rows[key] != row: raise AssertionError('Target and aggregate row disagree') entries = shared['pools'][key[1]] scores = prediction['scores_in_raw_pool_order'] if len(scores) != len(entries) or any(x is not None and not math.isfinite(x) for x in scores): raise AssertionError('Incorrect score population or nonfinite score') order = sorted(range(len(entries)), key=lambda j: (scores[j] is None, -scores[j] if scores[j] is not None else 0., entries[j]['key14'] or '', entries[j]['smiles'])) if prediction['ranked_raw_pool_indices'] != order: raise AssertionError('Saved sorted order disagrees with final scores') for field, name in [('key14', 'rank'), ('canonical_smiles', 'canonical_rank'), ('full_inchikey', 'inchikey_rank')]: if field == 'key14': truth = row['reference_identity'] else: truth_fields = db.execute('SELECT canonical,fullkey FROM aliases WHERE smiles=?', (row['reference_smiles'],)).fetchone() truth = truth_fields[0 if field == 'canonical_smiles' else 1] rank = next((i + 1 for i, j in enumerate(order) if scores[j] is not None and truth is not None and entries[j][field] == truth), None) if rank != row[name]: raise AssertionError(('Rank mismatch', name, key)) top1 = entries[order[0]]['smiles'] if order and scores[order[0]] is not None else None if top1 != row['top1_smiles']: raise AssertionError('Top1 molecule differs') formula_scores = prediction['formula_scores'] formulas = prediction['formulas'] if row['query_error'] is None: if len(formula_scores) != len(formulas) or any(not math.isfinite(x) for x in formula_scores): raise AssertionError('Invalid formula scores') expected_order = sorted(range(len(formulas)), key=lambda j: (-formula_scores[j], formulas[j])) if expected_order != prediction['ranked_formula_indices']: raise AssertionError('Formula sorting differs') truth = row['reference_formula'] # Formula string normalization is already frozen in source aliases; # verify rank against stored supported truth without new RDKit parsing. truth_alias = db.execute('SELECT formula FROM aliases WHERE smiles=?', (row['reference_smiles'],)).fetchone() if truth_alias and truth_alias[0]: truth = truth_alias[0] computed = next((i + 1 for i, j in enumerate(expected_order) if formulas[j] == truth), None) if computed != row['formula_rank']: raise AssertionError(('Formula rank differs', key, truth, row['reference_formula'], computed, row['formula_rank'])) predictions_checked += 1 expected = {target for target, in db.execute('SELECT DISTINCT target FROM spectra')} db.close() if actual_targets != expected: raise AssertionError('Missing/extra targets') return dict(targets=len(actual_targets), spectral_view_predictions=predictions_checked, raw_alias_memberships_checked=aliases_checked, all_ranked_scores_recomputed=True, original_pools_identical=True, injected_reference_count=0)
12345678910111213141516171819202122232425262728293031"""Independent full-ledger accounting and source-cursor overlap proof."""from collections import Counterfrom runtime_r2 import *import features_r2 as ft
def run(): db=readonly(PREP/'assets.sqlite');prior=readonly(Path(C['r2_output'])/'prepared/assets.sqlite') hashes=json.loads((PREP/'ledger_hashes.json').read_text())['unique'];counts=Counter();views=Counter();checks=0 for i,b in db.execute('SELECT idx,body FROM batches WHERE mode="unique" ORDER BY idx'): if hashlib.sha256(b).hexdigest()!=hashes[i]:raise RuntimeError('Ledger hash mismatch') plan=ft.loads(b) if i<1000: expected=prior.execute('SELECT body FROM batches WHERE mode="unique" AND idx=?',(i+1000,)).fetchone() if expected is None or ft.loads(expected[0])!=plan:raise RuntimeError('Original future cursor/sampling drift') checks+=1 for r in plan['rows']: counts['query_presentations']+=1;counts['candidate_views']+=len(r['pools']) for p in r['pools']: views[p['kind']]+=1;counts['negative_draws']+=p['negative_draws'] if p['reference_injected']:raise RuntimeError('Injected reference') if len(hashes)!=3000 or checks!=1000:raise RuntimeError('Incomplete continuation audit') missing=db.execute('SELECT count(*) FROM r3_features WHERE distance IS NULL').fetchone()[0] if missing:raise RuntimeError('Offline structures missing') result=dict(complete=True,steps=3000,source_update=3000,target_update=6000,original_future_batches_exactly_matched=checks, counts=dict(counts),candidate_view_counts=dict(views),offline_structures=db.execute('SELECT count(*) FROM r3_features').fetchone()[0], parent_sha256=C['parent_sha256'],ledger_sha256=sha(PREP/'ledger_hashes.json'),all_arms_same_ledger=True,original_data_modified=False) save(PREP/'INDEPENDENT_LEDGER_AUDIT.json',result);print(json.dumps(result),flush=True)
if __name__=='__main__':run()1234567891011[program:specpartition-r3-compact-20261110]command=/workspace/xj/SpecPartition-MS/.venv/bin/python -u /root/xj/SpecPartition-MS/code/ceir_r3_20261110/compact_r3.py --source /root/xj/SpecPartition-MS/runs/ceir_r3_20261110/prepared/assets.sqlite --target /dev/shm/ceir-r3-compact-bvygxam_/packed.sqlitedirectory=/root/xj/SpecPartition-MS/code/ceir_r3_20261110autostart=falseautorestart=falsestartsecs=2stopasgroup=truekillasgroup=trueredirect_stderr=truestdout_logfile=/root/xj/SpecPartition-MS/runs/ceir_r3_20261110/compact.logenvironment=OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475"""One-time lossless compaction of this release's NEW private feature overlay.
Never removes or overwrites the source. Publication is a separate audited step."""import argparseimport hashlibimport jsonfrom pathlib import Pathimport sqlite3import timeimport itertoolsimport multiprocessingfrom concurrent.futures import ProcessPoolExecutorimport numpy as npimport features_r2 as ft
def logical_update(h,row): k,s,b,bh,d,dh=row if b is not None and not ft.digest_matches(b,bh):raise RuntimeError('Fragment checksum mismatch') if d is not None and not ft.digest_matches(d,dh):raise RuntimeError('Distance checksum mismatch') values=[k.encode(),s.encode(),b,b'' if d is None else ft.distance_loads(d).tobytes()] for value in values: h.update(b'N' if value is None else b'V'+len(value).to_bytes(8,'little')+value)
def record_digest(row): h=hashlib.sha256();logical_update(h,row);return h.digest()
def convert(row): digest=record_digest(row);k,s,blob,bh,d,dh=row if d is not None: before=ft.distance_loads(d);d=ft.distance_dumps(before) if not np.array_equal(before,ft.distance_loads(d)):raise RuntimeError('Lossy topology conversion') return (k,s,blob,hashlib.sha256(blob).digest() if blob is not None else None,d,hashlib.sha256(d).digest() if d is not None else None),digest
def run(source,target): if target.exists():raise RuntimeError('Refuse to overwrite compaction target') a=sqlite3.connect('file:'+str(source)+'?mode=ro',uri=True);b=sqlite3.connect(target) b.execute('PRAGMA page_size=16384') b.execute('PRAGMA journal_mode=OFF');b.execute('PRAGMA synchronous=OFF') b.execute('CREATE TABLE batches(mode TEXT,idx INTEGER,body BLOB,PRIMARY KEY(mode,idx)) WITHOUT ROWID') b.execute('CREATE TABLE r3_features(feature_key TEXT PRIMARY KEY,smiles TEXT,feature BLOB,feature_sha BLOB,distance BLOB,distance_sha BLOB) WITHOUT ROWID') for row in a.execute('SELECT mode,idx,body FROM batches ORDER BY mode,idx'):b.execute('INSERT INTO batches VALUES (?,?,?)',row) old=hashlib.sha256();count=0;start=time.time() with ProcessPoolExecutor(max_workers=12,mp_context=multiprocessing.get_context('spawn')) as workers: cursor=a.execute('SELECT feature_key,smiles,feature,feature_sha,distance,distance_sha FROM r3_features ORDER BY feature_key') while rows:=list(itertools.islice(cursor,8192)): for row,digest in workers.map(convert,rows,chunksize=128): old.update(digest);b.execute('INSERT INTO r3_features VALUES (?,?,?,?,?,?)',row);count+=1 b.commit() if count%98304==0:print(json.dumps(dict(phase='compact',records=count,seconds=time.time()-start,bytes=target.stat().st_size)),flush=True) b.execute('CREATE INDEX pending_r3 ON r3_features(feature_key) WHERE distance IS NULL');b.commit() check=hashlib.sha256() with ProcessPoolExecutor(max_workers=12,mp_context=multiprocessing.get_context('spawn')) as workers: cursor=b.execute('SELECT feature_key,smiles,feature,feature_sha,distance,distance_sha FROM r3_features ORDER BY feature_key') while rows:=list(itertools.islice(cursor,8192)): for digest in workers.map(record_digest,rows,chunksize=128):check.update(digest) if old.digest()!=check.digest():raise RuntimeError('Independent logical checksum mismatch') old_batches=list(a.execute('SELECT mode,idx,body FROM batches ORDER BY mode,idx')) new_batches=list(b.execute('SELECT mode,idx,body FROM batches ORDER BY mode,idx')) if old_batches!=new_batches:raise RuntimeError('Sampler ledger changed') integrity=b.execute('PRAGMA integrity_check').fetchone()[0] if integrity!='ok':raise RuntimeError(integrity) b.execute('PRAGMA journal_mode=DELETE');b.close();a.close() result=dict(complete=True,source=str(source),target=str(target),source_bytes=source.stat().st_size,target_bytes=target.stat().st_size, structures=count,batches=len(old_batches),source_logical_sha256=old.hexdigest(),target_logical_sha256=check.hexdigest(), all_distance_arrays_exact=True,all_fragment_blobs_unchanged=True,integrity=integrity,seconds=time.time()-start) target.with_suffix('.audit.json').write_text(json.dumps(result,indent=2)+'\n');print(json.dumps(result),flush=True)
if __name__=='__main__': p=argparse.ArgumentParser();p.add_argument('--source',type=Path,required=True);p.add_argument('--target',type=Path,required=True);a=p.parse_args();run(a.source,a.target)1234567891011121314151617181920212223242526272829303132333435363738394041424344{ "release": "CEIR_R3_20261110", "root": "/workspace/xj/SpecPartition-MS", "source_r1": "/root/xj/SpecPartition-MS/code/ceir_r1_20261109", "source_r2": "/root/xj/SpecPartition-MS/code/ceir_r2_20261110", "r2_output": "/root/xj/SpecPartition-MS/runs/ceir_r2_20261110", "output": "/root/xj/SpecPartition-MS/runs/ceir_r3_20261110", "evaluation_output": "/workspace/xj/SpecPartition-MS/runs/ceir_r3_evaluations_20261110", "parent_checkpoint": "/root/xj/SpecPartition-MS/runs/ceir_r2_20261110/A3/step_003000.pt", "parent_sha256": "78841458441e38b260c076e75ccd06e0729e83887450eb8b64667edeab87aa46", "arms": ["R3C", "R3M", "R3H", "R3D", "R3F"], "source_update": 3000, "pilot_target_update": 6000, "manifest_updates": 3000, "seed": 20261103, "feature_version": "r3_spatial_distance_v1", "chem_weight": 0.05, "spectrum_weight": 0.05, "prepare_workers": 12, "spectrum_chunk": 16, "graph_chunk": 256, "local_chunk": 128, "pool_micro_views": 8, "max_atoms_per_microbatch": 12000, "gpu_memory_fraction": 0.42, "minimum_free_gpu_mib": 5500, "gpu_slots": 2, "minimum_output_disk_gib": 1.5, "backbone_lr_multiplier": 1.0, "new_head_lr": 0.0001, "lr_ramp_updates": 100, "save_interval": 100, "validation_updates": [4000, 5000, 6000], "validation_spectrum_batch": 16, "validation_graph_chunk": 32, "validation_local_chunk": 32, "validation_degradation_tolerance_pp": 0.2, "test_used_for_model_selection": false, "test_development_exposure": "Prior Test/CASMI badcases informed design; not pristine holdouts", "original_assets_read_only": true, "negative_sampling": "same A3 unique-key14 random training draws in all arms; no mining change in this architecture ablation", "formula_normalization": "bounded learned per-formula logmeanexp correction; no pruning; sample/full-pool discrepancy audited", "test_checkpoint_policy": "all five fixed 6000-update endpoints, after Validation-only recommendation"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051"""Frozen draw ledger: no PubChem, RDKit parsing, or pool JSON in training."""from collections import Counterfrom dataclasses import replaceimport timefrom runtime_r2 import *import features_r2 as featuresfrom data09 import Reader
class Dataset: def __init__(self,arm,start=0,stop=None,feature_path=None): self.arm=arm;self.start=start;self.stop=C['manifest_updates'] if stop is None else stop self.reader=None;self.db=None;self.features=None;self.feature_path=feature_path self.ledger_hashes=None
def __len__(self):return self.stop-self.start
def __getitem__(self,index): started=time.monotonic() if self.reader is None: self.reader=Reader();self.db=readonly(PREP/'assets.sqlite') self.features=features.FeatureStore(self.feature_path or PREP/'assets.sqlite') if self.feature_path is None:self.ledger_hashes=json.loads((PREP/'ledger_hashes.json').read_text()) mode='unique' offset=self.start+index ledger=self.db.execute('SELECT body FROM batches WHERE mode=? AND idx=?',(mode,offset)).fetchone() if ledger is None:raise RuntimeError('Missing immutable R2 sampler batch') digest=hashlib.sha256(ledger[0]).hexdigest() if self.ledger_hashes is not None and digest!=self.ledger_hashes[mode][offset]:raise RuntimeError('Sampler ledger changed after acceptance') plan=features.loads(ledger[0]);rows=[] for selected in plan['rows']: original=self.reader.db.execute('SELECT body FROM samples WHERE record_id=?',(selected['rid'],)).fetchone() row=loads(original[0]);ref=self.reader.molecule(selected['ref']) if ref.identity!=row['identity'] or ref.identity in self.reader.forbidden:raise RuntimeError('Unsafe reference') row['ref']=ref;row['formulas']=tuple(selected['formulas']);row['pools']=[] row['query']=replace(row['query'],formula_candidates=row['formulas']) feature=self.features.get(ref.smiles) if feature['layout']!=features.layout(ref.mol):raise RuntimeError('Reference atom layout changed') row['chemical_counts']=feature['counts'] for p in selected['pools']: mols=tuple(self.reader.molecule(g) for g in p['graphs']) if mols[0].identity!=ref.identity or any(m.identity==ref.identity for m in mols[1:]):raise RuntimeError('Missing positive or false negative') if any(m.identity in self.reader.forbidden for m in mols):raise RuntimeError('Heldout negative') kind=p['kind'];q=replace(row['query'],candidates=mols,formula_candidates=tuple(p['formulas']), candidate_view='odata_oracle' if kind=='odata' else 'msg_'+kind) eligible=bool(row['mass_ok'] and features.supported_positive(q,self.features.get(mols[0].smiles))) row['pools'].append(dict(**p,query=q,positive_index=0,truth_identity=ref.identity, truth_formula=row['formula'],record_id=row['record_id'],quality_eligible=bool(row['mass_ok']),spectrum_eligible=eligible)) rows.append(row) return dict(epoch=plan['epoch'],step=plan['step'],rows=rows,mode=mode,manifest_index=offset, ledger_sha256=digest,data_seconds=time.monotonic()-started)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183"""Versioned label-free static candidate descriptors and connected cut hypotheses."""from functools import lru_cacheimport hashlibimport itertoolsimport pickleimport sqlite3import structimport zlibimport numpy as npfrom rdkit import Chem,RDLoggerfrom rdkit.Chem import rdMolDescriptors
VERSION='connected_cuts_r2_v1';K=32;TRAITS=7;CLASSES=33RDLogger.DisableLog('rdApp.*')PATTERNS=[Chem.MolFromSmarts(s) for s in ('[OX2H]','[CX3]=[OX1]','[#6][OX2][#6]')]PT=Chem.GetPeriodicTable();H=PT.GetMostCommonIsotopeMass(1)
def dumps(value):return zlib.compress(pickle.dumps(value,protocol=5),1)def loads(value):return pickle.loads(zlib.decompress(value))def key(smiles):return hashlib.sha256(smiles.encode()).hexdigest()
def digest_matches(blob,digest): actual=hashlib.sha256(blob) return actual.digest()==digest if isinstance(digest,bytes) else actual.hexdigest()==digest
def distance_dumps(value): """Lossless symmetric, capped uint8 distances; two distances per byte.""" value=np.asarray(value,dtype=np.uint8);n=value.shape[0] if value.shape!=(n,n) or np.any(value>15) or np.any(np.diag(value)) or not np.array_equal(value,value.T): raise ValueError('Invalid symmetric capped distance matrix') upper=value[np.triu_indices(n,1)] if len(upper)%2:upper=np.pad(upper,(0,1)) packed=(upper[::2]<<4)|upper[1::2] return b'R3D1'+struct.pack('<I',n)+zlib.compress(packed.tobytes(),9)
def distance_loads(blob): if not blob.startswith(b'R3D1'):return loads(blob) n=struct.unpack('<I',blob[4:8])[0];packed=np.frombuffer(zlib.decompress(blob[8:]),dtype=np.uint8) upper=np.empty(len(packed)*2,dtype=np.uint8);upper[::2]=packed>>4;upper[1::2]=packed&15 upper=upper[:n*(n-1)//2];result=np.zeros((n,n),dtype=np.uint8);idx=np.triu_indices(n,1) result[idx]=upper;result[(idx[1],idx[0])]=upper return result
def layout(mol): atoms=[a.GetAtomicNum() for a in mol.GetAtoms()] edges=sorted((min(b.GetBeginAtomIdx(),b.GetEndAtomIdx()),max(b.GetBeginAtomIdx(),b.GetEndAtomIdx()),str(b.GetBondType())) for b in mol.GetBonds()) return hashlib.sha256(repr((atoms,edges)).encode()).hexdigest()
def components(n,adj,removed): seen=set();result=[] for first in range(n): if first in seen:continue todo=[first];seen.add(first);part=[] while todo: i=todo.pop();part.append(i) for j,bid in adj[i]: if bid not in removed and j not in seen:seen.add(j);todo.append(j) result.append(tuple(sorted(part))) return result
def build(smiles): mol=Chem.MolFromSmiles(smiles) if mol is None:raise ValueError('Invalid candidate SMILES') n=mol.GetNumAtoms();counts=[len(mol.GetSubstructMatches(p)) for p in PATTERNS] counts += [rdMolDescriptors.CalcNumAromaticRings(mol),rdMolDescriptors.CalcNumAliphaticRings(mol),rdMolDescriptors.CalcNumHeterocycles(mol),len(Chem.GetMolFrags(mol))] out=dict(version=VERSION,smiles=smiles,layout=layout(mol),atoms=n, counts=np.asarray([min(32,v) for v in counts],dtype=np.int64),members=np.zeros((K,n),dtype=np.float32), boundary=np.zeros((K,8),dtype=np.float32), masses=np.zeros(K,dtype=np.float32),hydrogens=np.zeros(K,dtype=np.int16),valid=np.zeros(K,dtype=bool), neutral_mass=rdMolDescriptors.CalcExactMolWt(mol),reason=None) if len(Chem.GetMolFrags(mol))!=1 or Chem.GetFormalCharge(mol)!=0 or any(a.GetIsotope() for a in mol.GetAtoms()): out['reason']='unsupported_fragment_hypothesis_structure';return out adj=[[] for _ in range(n)] for b in mol.GetBonds(): i,j=b.GetBeginAtomIdx(),b.GetEndAtomIdx();adj[i].append((j,b.GetIdx()));adj[j].append((i,b.GetIdx())) bridges=[b for b in mol.GetBonds() if not b.IsInRing() and b.GetBondType()==Chem.BondType.SINGLE] bridges.sort(key=lambda b:(-int(b.GetBeginAtom().GetAtomicNum() in (7,8,15,16))-int(b.GetEndAtom().GetAtomicNum() in (7,8,15,16)),b.GetIdx())) ring=[b.GetIdx() for b in mol.GetBonds() if b.IsInRing()] pairs=list(itertools.combinations(ring,2)) pairs.sort(key=lambda p:hashlib.sha256(repr(p).encode()).digest()) cuts=[(b.GetIdx(),) for b in bridges[:20]]+pairs[:12] parts=set() for cut in cuts: for part in components(n,adj,set(cut)): if 3<=len(part)<=n-2:parts.add(part) choices=sorted(parts,key=lambda p:(len(p),p)) if len(choices)>K:choices=[choices[int(i)] for i in np.linspace(0,len(choices)-1,K).round()] masses=[];nh=[] for a in mol.GetAtoms(): hydrogen=a.GetTotalNumHs();nh.append(hydrogen) masses.append(PT.GetMostCommonIsotopeMass(a.GetAtomicNum())+hydrogen*H) for j,part in enumerate(choices): out['members'][j,list(part)]=1/len(part) out['masses'][j]=sum(masses[i] for i in part);out['hydrogens'][j]=sum(nh[i] for i in part);out['valid'][j]=True chosen=set(part);aa=[mol.GetAtomWithIdx(i) for i in part] out['boundary'][j]=[len(part)/n,sum(a.GetAtomicNum()==8 for a in aa)/len(part), sum(a.GetAtomicNum()==7 for a in aa)/len(part),sum(v not in chosen for i in part for v,_ in adj[i])/4, sum(a.IsInRing() for a in aa)/len(part),sum(a.GetIsAromatic() for a in aa)/len(part), sum(nh[i] for i in part)/len(part),out['masses'][j]/max(out['neutral_mass'],1)] out['reason']='ok' if choices else 'no_supported_connected_cut' return out
class FeatureStore: def __init__(self,path): from runtime_r2 import C,PREP self.db=sqlite3.connect('file:'+str(path)+'?mode=ro',uri=True) self.overlay=self.db.execute("SELECT 1 FROM sqlite_master WHERE name='r3_features'").fetchone() is not None self.parents=[] if self.overlay: paths=[C['r2_output']+'/prepared/assets.sqlite'] if str(path)!=str(PREP/'assets.sqlite'):paths.append(C['r2_output']+'/test/prepared/assets.sqlite') for p in paths: db=sqlite3.connect('file:'+p+'?mode=ro',uri=True) table='canonical_features' if db.execute("SELECT 1 FROM sqlite_master WHERE name='canonical_features'").fetchone() else 'molecules' self.parents.append((db,table)) self.table='canonical_features' if self.db.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='canonical_features'").fetchone() else 'molecules' self.get=lru_cache(maxsize=12000)(self._get)
def _get(self,smiles): if self.overlay: item=self.db.execute('SELECT feature,feature_sha,distance,distance_sha FROM r3_features WHERE feature_key=?',(key(smiles),)).fetchone() if item is None:raise RuntimeError('Missing offline R3 structure '+smiles[:100]) blob,digest,distance,dh=item if blob is None: for db,table in self.parents: old=db.execute('SELECT feature,feature_sha FROM '+table+' WHERE feature_key=?',(key(smiles),)).fetchone() if old is not None and old[0] is not None:blob,digest=old;break if blob is None or not digest_matches(blob,digest):raise RuntimeError('Missing/changed R2 descriptor') if distance is None or not digest_matches(distance,dh):raise RuntimeError('Missing/changed R3 topology') value=loads(blob) if value['smiles']!=smiles:raise RuntimeError('R3 feature identity mismatch') value['distance']=distance_loads(distance) return value row=self.db.execute('SELECT feature,feature_sha FROM '+self.table+' WHERE feature_key=?',(key(smiles),)).fetchone() if row is None or row[0] is None:raise RuntimeError('Missing preprocessed R2 candidate feature: '+smiles[:120]) if hashlib.sha256(row[0]).hexdigest()!=row[1]:raise RuntimeError('R2 feature hash mismatch') value=loads(row[0]) if value['version']!=VERSION or value['smiles']!=smiles:raise RuntimeError('R2 feature identity mismatch') return value
def ion_offsets(adduct): proton=1.007276452090935 if adduct=='[M+H]+':return (proton,None) if adduct=='[M-H]-':return (-proton,None) if adduct=='[M+Na]+':return (22.989220702090936,proton) if adduct=='[M+NH4]+':return (proton,18.033825548090935) if adduct=='[M+Cl]-':return (-proton,34.96940125990906) if adduct=='[M+FA-H]-':return (-proton,44.99820285190906) return (None,None)
def spectrum(query): peaks=sorted(query.peaks,key=lambda p:(-p[1],p[0]))[:256];peaks.sort() mz=np.asarray([p[0] for p in peaks],dtype=np.float32) y=np.sqrt(np.asarray([p[1] for p in peaks],dtype=np.float32)/max(p[1] for p in peaks)) y[np.abs(mz-query.precursor_mz)<=max(.05,query.precursor_mz*20e-6)]=0 return mz,y
def supported_positive(query,feature): offsets=ion_offsets(query.adduct) if offsets[0] is None:return False mz,y=spectrum(query) if not y.sum():return False masses=[] for j in range(K): if not feature['valid'][j]:continue for shift in (-2,-1,0,1,2): if feature['hydrogens'][j]+shift<0:continue masses.extend(feature['masses'][j]+shift*H+v for v in offsets if v is not None) if not masses:return False mass=np.asarray(masses,dtype=np.float32) valid=(np.abs(mz[:,None]-mass[None,:])<=np.maximum(.02,mass[None,:]*20e-6)).any(1) return bool((y[valid].sum()/y.sum())>=.05)1234567891011121314151617181920212223242526272829303132333435"""Re-sort every saved score without training or evaluator ranking helpers."""import jsonfrom pathlib import Pathimport audit_primitives as auditHERE=Path(__file__).resolve().parentC=json.loads((HERE/'config.json').read_text());OUT=Path(C['output'])
def run(): frozen=audit.load(OUT/'test/FROZEN.json');result=dict(complete=False,arms={},paired_vs_A3={},paired_vs_control={}) for name,h in frozen['r3_binding']['code'].items(): if audit.sha(HERE/name)!=h:raise RuntimeError('Frozen R3 source changed') for name,h in frozen['r3_binding']['external_evaluation_code'].items(): if audit.sha(name)!=h:raise RuntimeError('Dependency source changed') for d in ('msg_test','casmi2022'): if audit.sha(audit.SOURCE/(d+'_ready.json'))!=frozen['inputs'][d]['ready_sha256']:raise RuntimeError('Frozen candidate input changed') parent=Path(C['r2_output']);hashes={};rows={};audit.ROOT=OUT for a in C['arms']: name=a+'_006000';checkpoint=frozen['models'][name] if audit.sha(checkpoint['checkpoint'])!=checkpoint['sha256']:raise RuntimeError('Checkpoint changed') value,_=audit.aggregate(OUT/a/'validation_006000','validation');result['arms'][a]=dict(Validation=value) for d in ('msg_test','casmi2022'): value,rr=audit.aggregate(OUT/'test/inference'/name/d,d) value['all_scores_verified']=audit.pool_and_prediction_audit(name,d,hashes) result['arms'][a][d]=value;rows[a,d]=rr for d in ('msg_test','casmi2022'): _,base=audit.aggregate(parent/'test/inference/A3_003000'/d,d) result['paired_vs_A3'][d]={a:audit.paired(base,rows[a,d]) for a in C['arms']} result['paired_vs_control'][d]={a:audit.paired(rows['R3C',d],rows[a,d]) for a in C['arms'] if a!='R3C'} result.update(complete=True,all_scores_and_denominators_verified=True,candidate_identity_comparisons=len(hashes)*len(C['arms']), original_data_or_weights_modified=False,one_training_seed=True,Test_development_exposed=True) audit.save(OUT/'INDEPENDENT_ALL_RESULTS.json',result)
if __name__=='__main__':run()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102"""Label-free residual evidence. No reference identity or score-based pruning."""from collections import Counter,OrderedDictimport mathimport numpy as npimport torchfrom torch import nnfrom torch.nn import functional as Fimport features_r2 as ft
class Heads(nn.Module): def __init__(self): super().__init__() self.mass=nn.Sequential(nn.Linear(19,64),nn.GELU(),nn.Linear(64,64)) self.query=nn.Linear(320,128) self.atom=nn.Linear(256,128) self.qkv=nn.Linear(128,384) self.spatial=nn.Embedding(16,4) self.norm=nn.LayerNorm(128) self.topology=nn.Sequential(nn.Linear(256,128),nn.GELU(),nn.Linear(128,128)) self.difference=nn.Sequential(nn.Linear(4,32),nn.GELU(),nn.Linear(32,1)) self.formula_alpha=nn.Parameter(torch.zeros(())) nn.init.zeros_(self.topology[-1].weight);nn.init.zeros_(self.topology[-1].bias) nn.init.zeros_(self.difference[-1].weight);nn.init.zeros_(self.difference[-1].bias) self._rarity_cache=OrderedDict()
def precision_query(self,q,query): mz,w=ft.spectrum(query) # Explicit FP32 trigonometry/MLP; precursor delta is NOT labelled as a # neutral loss. Correct ion templates remain in the fragment branch. with torch.autocast(q.device.type,enabled=False): mz=torch.as_tensor(mz,device=q.device,dtype=torch.float32);w=torch.as_tensor(w,device=q.device) angles=2*math.pi*mz[:,None]*mz.new_tensor([1,2,4,8,16,32,64,128])[None,:] x=torch.cat((mz[:,None]/1000,(mz-mz.floor())[:,None],w[:,None],angles.sin(),angles.cos()),-1) z=self.mass(x);pooled=(z*w[:,None]).sum(0)/w.sum().clamp_min(1e-8) return F.normalize(self.query(torch.cat((q.float(),pooled))),dim=-1)
def topology_scores(self,q,query,atoms,assets): zq=self.precision_query(q,query);parts=[] for start in range(0,len(atoms),32): aa=atoms[start:start+32];ff=assets[start:start+32];n=max(len(a) for a in aa);b=len(aa);device=q.device # Differentiable padding keeps the current GNN's gradients. x=torch.stack([F.pad(a,(0,0,0,n-len(a))) for a in aa]);mask=torch.arange(n,device=device)[None,:]>=torch.tensor([len(a) for a in aa],device=device)[:,None] ds=np.full((b,n,n),15,dtype=np.int64) for j,f in enumerate(ff):ds[j,:f['atoms'],:f['atoms']]=f['distance'] h=self.atom(x);qkv=self.qkv(h).reshape(b,n,3,4,32).permute(2,0,3,1,4);qq,kk,vv=qkv.unbind(0) bias=self.spatial(torch.as_tensor(ds,device=device)).permute(0,3,1,2) weights=(qq@kk.transpose(-1,-2)/math.sqrt(32)+bias).float().masked_fill(mask[:,None,None,:],-1e9).softmax(-1) mixed=(weights.to(vv.dtype)@vv).transpose(1,2).reshape(b,n,128);h=self.norm(h+mixed) valid=(~mask).float();mean=(h.float()*valid[:,:,None]).sum(1)/valid.sum(1)[:,None] maximum=h.float().masked_fill(mask[:,:,None],-1e9).max(1).values z=self.topology(torch.cat((mean,maximum),-1)).float() parts.append((z*zq).sum(-1)/math.sqrt(128)) return torch.cat(parts)
def rarity(self,mols,assets): # Bounded CPU cache, no learned embeddings and no truth-derived keys. key=tuple(m.smiles for m in mols) if key in self._rarity_cache: result=self._rarity_cache.pop(key);self._rarity_cache[key]=result;return result bins=[np.rint(a['masses']/.02).astype(np.int64) for a in assets] counts=Counter(v for bb,a in zip(bins,assets) for v in set(bb[a['valid']].tolist())) n=len(mols);result=np.asarray([[math.log1p(n/max(1,counts.get(int(v),1)))/math.log1p(max(1,n)) if valid else 0. for v,valid in zip(bb,a['valid'])] for bb,a in zip(bins,assets)],dtype=np.float32) self._rarity_cache[key]=result while len(self._rarity_cache)>2:self._rarity_cache.popitem(last=False) return result
def difference_scores(self,q,query,mols,assets): off=ft.ion_offsets(query.adduct) if off[0] is None:return q.float().sum().expand(len(mols))*0. rarity=self.rarity(mols,assets);mz,y=ft.spectrum(query);device=q.device mz=torch.as_tensor(mz,device=device);y=torch.as_tensor(y,device=device);out=[] for start in range(0,len(mols),128): ff=assets[start:start+128];m=torch.as_tensor(np.stack([a['masses'] for a in ff]),device=device) valid=torch.as_tensor(np.stack([a['valid'] for a in ff]),device=device) hh=torch.as_tensor(np.stack([a['hydrogens'] for a in ff]),device=device);rr=torch.as_tensor(rarity[start:start+128],device=device) shifts=m.new_tensor([-2,-1,0,1,2]);offsets=m.new_tensor([v for v in off if v is not None]) hypothesis=m[:,:,None,None]+shifts[None,None,:,None]*ft.H+offsets[None,None,None,:] supported=valid[:,:,None,None]&(hh[:,:,None,None]+shifts[None,None,:,None]>=0)&hypothesis.gt(0) right=torch.searchsorted(mz,hypothesis.contiguous()).clamp(max=len(mz)-1);left=(right-1).clamp(min=0) ix=torch.where((mz[right]-hypothesis).abs()<(mz[left]-hypothesis).abs(),right,left) matched=((mz[ix]-hypothesis).abs()<=torch.maximum(hypothesis*20e-6,m.new_tensor(.02)))&supported best=(y[ix]*matched).flatten(2).max(-1).values;hit=matched.flatten(2).any(-1).float() denominator=rr.sum(-1).clamp_min(1e-8);number=valid.sum(-1).clamp_min(1) evidence=torch.stack(((rr*best).sum(-1)/denominator,(rr*hit).sum(-1)/denominator, (best*valid).sum(-1)/number,(rr*(1-hit)).sum(-1)/denominator),-1) out.append(self.difference(evidence).float().squeeze(-1)*valid.any(-1)) return torch.cat(out)
def calibrate(self,base,direct,formulas): groups={} for j,f in enumerate(formulas):groups.setdefault(f,[]).append(j) if len(groups)<=1:return base correction=torch.zeros_like(base) for indices in groups.values(): index=torch.tensor(indices,device=base.device);b=direct[index].float() value=b.logsumexp(0)-math.log(len(indices)) correction=correction.index_copy(0,index,value.expand(len(indices))) # Zero starts as exact A3; bounded signed correction is learnable. # logmeanexp avoids a deterministic advantage merely from group size. return base-.5*self.formula_alpha.tanh()*correction1234567891011121314151617181920212223242526272829"""Validation MCES under the same R1 protocol, with a private resumable cache."""import argparseimport fcntlimport importlib.utilimport jsonfrom pathlib import Pathimport sqlite3import sys
HERE=Path(__file__).resolve().parent;C=json.loads((HERE/'config.json').read_text());OUT=Path(C['output'])
def run(directory): path=Path(C['source_r1'])/'mces_ceir.py';name='r2_validation_mces_engine' spec=importlib.util.spec_from_file_location(name,path);module=importlib.util.module_from_spec(spec);sys.modules[name]=module;spec.loader.exec_module(module) own=OUT/'mces_validation';own.mkdir(parents=True,exist_ok=True) lock=(own/'compute.lock').open('a+');fcntl.flock(lock,fcntl.LOCK_EX) if (Path(directory)/'MCES.json').exists():return target=own/'Validation_mces_pairs.sqlite' if not target.exists(): source=Path(C['r2_output'])/'mces_validation/Validation_mces_pairs.sqlite' if source.exists(): a=sqlite3.connect('file:'+str(source)+'?mode=ro',uri=True);b=sqlite3.connect(target);a.backup(b);a.close();b.close() module.OUT=OUT;module.CACHE=own module.evaluate(Path(directory))
if __name__=='__main__': p=argparse.ArgumentParser();p.add_argument('--directory',required=True);a=p.parse_args();run(a.directory)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205"""C03-preserving discriminative chemistry and candidate-to-spectrum evidence.
Static connected cuts are hypotheses, NOT ground-truth fragment annotations.Only training reference labels supervise the count and reconstructed spectrumheads; scoring never receives the reference identity, its counts, or its formula."""import numpy as npimport torchfrom torch import nnfrom torch.nn import functional as Ffrom runtime_r2 import *import features_r2 as featuresfrom specpartition_ms.model_v122 import BidirectionalRankerfrom specpartition_ms.model import Encoded,metadatafrom specpartition_ms.fast_formula_r2 import forward_batch as original_formula_forwardfrom coarse_losses import ProjectionBankfrom kernels import install_graph_kernelfrom heads_r3 import Heads
class EvidenceHeads(nn.Module): def __init__(self): super().__init__() self.counts=nn.Sequential(nn.Linear(256,256),nn.GELU(),nn.Linear(256,features.TRAITS*features.CLASSES)) self.fragment=nn.Sequential(nn.Linear(264,128),nn.GELU(),nn.LayerNorm(128)) self.meta=nn.Sequential(nn.Linear(17,128),nn.GELU(),nn.Linear(128,128)) self.intensity=nn.Linear(128,10) self.fragment_key=nn.Linear(128,64);self.peak_key=nn.Linear(256,64) self.fragment_score=nn.Sequential(nn.Linear(4,32),nn.GELU(),nn.Linear(32,1)) self.chemical_scale=nn.Parameter(torch.ones(()));self.fragment_scale=nn.Parameter(torch.ones(())) nn.init.zeros_(self.counts[-1].weight);nn.init.zeros_(self.counts[-1].bias) nn.init.zeros_(self.fragment_score[-1].weight);nn.init.zeros_(self.fragment_score[-1].bias)
def count_log_prob(self,q): shape=(*q.shape[:-1],features.TRAITS,features.CLASSES) return self.counts(q).float().reshape(shape).log_softmax(-1)
class R2Ranker(BidirectionalRanker): def __init__(self,c,arm): super().__init__(c);self.hierarchy=ProjectionBank();self.r2=EvidenceHeads();self.r3=Heads() self.arm=arm;self.feature_store=None;self.layout_checked=set();install_graph_kernel(self)
def install_features(self,path=None): self.feature_store=features.FeatureStore(path or PREP/'assets.sqlite')
def feature(self,mol): if self.feature_store is None:raise RuntimeError('R2 offline features missing') result=self.feature_store.get(mol.smiles) if mol.smiles not in self.layout_checked: if result['layout']!=features.layout(mol.mol) or result['atoms']!=len(mol.atom_features): raise RuntimeError('Static fragment / trainable graph atom layout mismatch') self.layout_checked.add(mol.smiles) return result
def formula_batch(self,qs,queries,tokens,return_context=False): values=original_formula_forward(self.formula_v07,qs,queries,tokens) return (values,[None]*len(queries)) if return_context else values
def chemical_scores(self,q,assets): counts=torch.as_tensor(np.stack([a['counts'] for a in assets]),device=q.device,dtype=torch.long) logp=self.r2.count_log_prob(q.float()) selected=logp[torch.arange(features.TRAITS,device=q.device)[None,:],counts].mean(-1) # The same log-softmax operation makes zero-initialization exactly zero. uniform=torch.zeros_like(logp).log_softmax(-1)[0,0] return self.r2.chemical_scale*(selected-uniform)
def fragment_scores(self,peaks,query,mols,atoms,assets): device=peaks.device;n=len(mols);zero=peaks.float().sum()*0. # No candidate-wise softmax across the pool: safe exact tiling for # CASMI's >30k pools, not a 256-candidate truncation. if n>128: pieces=[self.fragment_scores(peaks,query,mols[j:j+128],atoms[j:j+128],assets[j:j+128]) for j in range(0,n,128)] return tuple(torch.cat([p[k] for p in pieces]) for k in range(3)) offsets=features.ion_offsets(query.adduct) if offsets[0] is None: return zero.expand(n),zero.expand(n),torch.zeros(n,device=device,dtype=torch.bool) mz_np,y_np=features.spectrum(query);mz=torch.as_tensor(mz_np,device=device);y=torch.as_tensor(y_np,device=device) if len(mz)!=len(peaks):raise RuntimeError('R2 peak token alignment mismatch') representations=[] for atom,a in zip(atoms,assets): members=torch.as_tensor(a['members'],device=device,dtype=torch.float32) boundary=torch.as_tensor(a['boundary'],device=device,dtype=torch.float32) representations.append(torch.cat((members@atom.float(),boundary),-1)) h=self.r2.fragment(torch.stack(representations)) meta=torch.as_tensor(metadata(query),device=device,dtype=torch.float32) logits=self.r2.intensity(h+self.r2.meta(meta)[None,None,:]).float().reshape(n,features.K,5,2) masses=torch.as_tensor(np.stack([a['masses'] for a in assets]),device=device) hydrogens=torch.as_tensor(np.stack([a['hydrogens'] for a in assets]),device=device) valid=torch.as_tensor(np.stack([a['valid'] for a in assets]),device=device,dtype=torch.bool) shifts=masses.new_tensor([-2,-1,0,1,2]);adduct=masses.new_tensor([v if v is not None else 0. for v in offsets]) hypotheses=masses[:,:,None,None]+shifts[None,None,:,None]*features.H+adduct[None,None,None,:] mask=valid[:,:,None,None]&(hydrogens[:,:,None,None]+shifts[None,None,:,None]>=0) mask=mask.expand(-1,-1,-1,2)&hypotheses.gt(0) if offsets[1] is None: template=torch.tensor([True,False],device=device);mask=mask&template[None,None,None,:] usable=mask.flatten(1).any(-1) # Avoid all -inf softmax rows without inventing a supported fragment. masked=logits.masked_fill(~mask,-1e9) probability=masked.flatten(1).softmax(-1).reshape_as(masked)*mask flat=hypotheses.flatten(1).contiguous();pp=probability.flatten(1) right=torch.searchsorted(mz,flat).clamp(max=len(mz)-1);left=(right-1).clamp(min=0) index=torch.where((mz[right]-flat).abs()<(mz[left]-flat).abs(),right,left) delta=(mz[index]-flat).abs();tolerance=torch.maximum(flat*20e-6,flat.new_full((),.02)) matched=(delta<=tolerance)&mask.flatten(1) explained=pp*matched;predicted=pp.new_zeros((n,len(mz))).scatter_add(1,index,explained) outside=(pp*(~matched)).sum(-1) norm=(predicted.square().sum(-1)+outside.square()).clamp_min(1e-12).sqrt() cosine=(predicted*y[None,:]).sum(-1)/(norm*y.norm().clamp_min(1e-12)) present=pp.new_zeros((n,len(mz))).scatter_add(1,index,matched.float()).gt(0) coverage=(present*y[None,:]).sum(-1)/y.sum().clamp_min(1e-12) key=F.normalize(self.r2.fragment_key(h).float(),dim=-1) peak=F.normalize(self.r2.peak_key(peaks).float(),dim=-1) alignment=(key[:,:,None,:].expand(-1,-1,10,-1).reshape(n,-1,64)*peak[index]).sum(-1) matched_alignment=(alignment*explained).sum(-1) diagnostics=torch.stack((cosine,coverage,matched_alignment,1.-outside),-1) correction=self.r2.fragment_scale*self.r2.fragment_score(diagnostics).float().squeeze(-1)*usable spec_loss=(1.-cosine)*usable return correction,spec_loss,usable
def score_encoded(self,q,peaks,query,mols,atoms,zm,formula_scores,context=None,return_aux=False): conditional,joint,relation=self.conditioned(q,query,[m.formula for m in mols],zm,formula_scores) local=self.local_weight*self.local_scores(peaks,atoms) if self.cfg.model.local_match else torch.zeros_like(joint) base=joint+local;direct=conditional+local diagnostic={} collecting=self.training and getattr(self,'collect_score_diagnostics',False) if collecting: diagnostic['formula_prior_abs']=(joint-conditional).detach().float().abs().mean() diagnostic['parent_structural_std']=direct.detach().float().std(unbiased=False) aux=None if self.arm in C['arms']: assets=[self.feature(m) for m in mols] chemistry=self.chemical_scores(q,assets) base=base+chemistry;direct=direct+chemistry if self.arm in C['arms']: correction,spec_loss,usable=self.fragment_scores(peaks,query,mols,atoms,assets) base=base+correction;direct=direct+correction aux=(spec_loss,usable) if self.arm in ('R3H','R3M'): topology=self.r3.topology_scores(q,query,atoms,assets) base=base+topology;direct=direct+topology if collecting:diagnostic['topology_abs']=topology.detach().float().abs().mean() if self.arm in ('R3D','R3M'): difference=self.r3.difference_scores(q,query,mols,assets) base=base+difference;direct=direct+difference if collecting:diagnostic['difference_abs']=difference.detach().float().abs().mean() if self.arm in ('R3F','R3M'): calibrated=self.r3.calibrate(base,direct,[m.formula for m in mols]) if collecting:diagnostic['formula_calibration_abs']=(calibrated-base).detach().float().abs().mean() base=calibrated if collecting: diagnostic['final_score_std']=base.detach().float().std(unbiased=False) self.score_diagnostics.append(diagnostic) result=(base,direct,relation) return (*result,aux) if return_aux else result
def encode_batch(self,queries,extras=()): tokens,qs,metas=self.spectrum.forward_batch(queries) key=lambda m:(m.identity,m.smiles) lookup={key(m):m for q in queries for m in q.candidates};lookup.update({key(m):m for m in extras}) keys=sorted(lookup);positions={k:i for i,k in enumerate(keys)} u,atoms,zm=self.encode_molecules([lookup[k] for k in keys]) zq=F.normalize(self.query_projection(qs).float(),dim=-1) fs=self.formula_batch(qs,queries,tokens);encs=[] for i,q in enumerate(queries): ii=[positions[key(m)] for m in q.candidates];index=torch.tensor(ii,device=self.device,dtype=torch.long);aa=[atoms[j] for j in ii] base,direct,context,aux=self.score_encoded(qs[i],tokens[i],q,q.candidates,aa,zm[index],fs[i],return_aux=True) whole=torch.as_tensor(np.stack([m.whole for m in q.candidates]),device=self.device) anchors=torch.as_tensor(np.stack([m.anchors for m in q.candidates]),device=self.device) enc=Encoded(q,tokens[i].float(),qs[i].float(),metas[i].float(),u[index].float(),zq[i],zm[index], [a.float() for a in aa],whole,anchors,fs[i],base,direct) enc.conditional_context_q=context;enc.r2_spectrum=aux;encs.append(enc) extra_index=torch.tensor([positions[key(m)] for m in extras],device=self.device,dtype=torch.long) return encs,zm[extra_index]
def make_model_optimizer(arm,checkpoint_path=None): state=parent_state() if checkpoint_path is None else torch.load(checkpoint_path,map_location='cpu',weights_only=False) torch.manual_seed(C['seed']);model=R2Ranker(LEGACY.C,arm) if checkpoint_path is not None and state.get('architecture')!='CEIR_R3':raise RuntimeError('Wrong resume architecture') result=model.load_state_dict(state['model'],strict=checkpoint_path is not None) if result.unexpected_keys or any(not k.startswith('r3.') for k in result.missing_keys):raise RuntimeError('Parent state keys differ '+str(result)) if checkpoint_path is None: for k,v in state['model'].items(): if not torch.equal(model.state_dict()[k],v):raise RuntimeError('Old parameter changed '+k) old=[p for n,p in model.named_parameters() if not n.startswith(('r2.','r3.'))] evidence=[p for n,p in model.named_parameters() if n.startswith('r2.')] new=[p for n,p in model.named_parameters() if n.startswith('r3.')] source=parent_state() if checkpoint_path is not None else state if [len(old),len(evidence)]!=[len(g['params']) for g in source['optimizer']['param_groups']]:raise RuntimeError('Old optimizer parameter ordering/count mismatch') original_lr=float(source['optimizer']['param_groups'][0]['lr']);model.to(LEGACY.C['device']) opt=torch.optim.AdamW(old,lr=original_lr,weight_decay=LEGACY.C['weight_decay']) opt.add_param_group(dict(params=evidence,lr=float(source['optimizer']['param_groups'][1]['lr']))) if checkpoint_path is None: opt.load_state_dict(state['optimizer']);opt.add_param_group(dict(params=new,lr=C['new_head_lr'])) else: opt.add_param_group(dict(params=new,lr=C['new_head_lr']));opt.load_state_dict(state['optimizer']) for p,s in opt.state.items(): for k,v in s.items(): if torch.is_tensor(v) and k!='step':s[k]=v.to(p.device) progress=dict(state['progress']);progress.setdefault('new_updates',progress['update']-C['source_update']) if checkpoint_path is None: progress.update(new_updates=0,r2_validated=[],r2_exposures={}) model.install_features();restore_rng(state) return model,opt,progress,original_lr123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138"""Exact C03 active objectives, plus qualified chemistry / spectrum supervision."""from collections import Counterimport timeimport numpy as npimport torchfrom torch.nn import functional as Ffrom torch.utils.checkpoint import checkpoint as recomputefrom runtime_r2 import *from kernels import grouped_contrastive,formula_objectivefrom losses import ms_ms_supcon,molecule_molecule_two_view
def molecular_views(model,mols,probability): # Reinstate the dropout hook during activation recomputation. The original # implementation removed it before backward; fix identically in all arms. def one(dummy): threshold=model.activation_checkpoint_atom_threshold model.activation_checkpoint_atom_threshold=10**12 handle=model.graph.atom.register_forward_hook(lambda module,inputs,output:F.dropout(output,p=probability,training=True)) try: with amp():return model.encode_molecules(mols)[0].float() finally:handle.remove();model.activation_checkpoint_atom_threshold=threshold return (recompute(one,model.graph.atom.weight,use_reentrant=False,preserve_rng_state=True), recompute(one,model.graph.atom.weight,use_reentrant=False,preserve_rng_state=True))
def auxiliary_loss(model,q,mols,rows,spec,step): weights=spec['loss']['auxiliary'] if any(v for k,v in weights.items() if k not in ('ms_fine','mol_fine')): raise RuntimeError('This release matches C03 fine-only auxiliaries; other arms require a separate release') ids=[r['identity'] for r in rows];rids=[r['record_id'] for r in rows];head=model.hierarchy v1,v2=molecular_views(model,mols,spec['views']['molecule']['dropout']) temperature=spec['loss']['temperature']['identity'];ramp=min(1.,(step+1)/spec['loss']['auxiliary_ramp_steps']) ms=ms_ms_supcon(head('ms_identity',q),ids,rids,temperature) mol=molecule_molecule_two_view(head('mol_identity',v1),head('mol_identity',v2),[m.identity for m in mols],temperature) total=ramp*(weights['ms_fine']*ms.loss+weights['mol_fine']*mol.loss) # The original zero-weight coarse graphs produced zero (not None) grads. # Preserve AdamW decay/moment semantics for those registered unused heads. for name in ('ms_formula','mol_formula','ms_mass','mol_mass'): total=total+sum(p.sum()*0. for p in head.heads[name].parameters()) out=dict(ms_fine_raw=ms.loss.detach(),mol_fine_raw=mol.loss.detach(),auxiliary_total=total.detach(),auxiliary_ramp=ramp, molecule_view_mean_abs_difference=(v1.detach()-v2.detach()).abs().mean()) for name,item in [('ms_fine',ms),('mol_fine',mol)]: for k,v in item.diagnostics.items():out[name+'_'+k]=v.detach() if torch.is_tensor(v) else v return total,out
def chemical_loss(model,q,rows): if model.arm not in C['arms']:return q.sum()*0. counts=torch.as_tensor(np.stack([r['chemical_counts'] for r in rows]),device=q.device,dtype=torch.long) logp=model.r2.count_log_prob(q) losses=-logp.gather(-1,counts[:,:,None]).squeeze(-1).mean(-1) ids=[r['identity'] for r in rows];occurrences=Counter(ids) w=q.new_tensor([1/occurrences[k]/len(occurrences) for k in ids]) return (losses*w).sum()
def train_step(model,opt,batch,update,apply_update=True): model.collect_score_diagnostics=True;model.score_diagnostics=[] started=time.monotonic();rows=batch['rows'];queries=[r['query'] for r in rows];ids=[r['identity'] for r in rows] reps={} for r in rows: if r['identity'] not in reps or r['ref'].smiles<reps[r['identity']].smiles:reps[r['identity']]=r['ref'] columns=sorted(reps);mols=[reps[k] for k in columns];w=LEGACY.C['loss_weights'];opt.zero_grad(set_to_none=True) sc=LEGACY.C['spectrum_chunk'];gc=LEGACY.C['graph_chunk'] with torch.no_grad(),amp(): qc=torch.cat([model.spectrum.forward_batch(queries[a:a+sc])[1] for a in range(0,len(rows),sc)]) mc=torch.cat([model.encode_molecules(mols[a:a+gc])[0] for a in range(0,len(mols),gc)]) qc=qc.float().detach().requires_grad_();mc=mc.float().detach().requires_grad_() with amp(): zq=F.normalize(model.query_projection(qc).float(),dim=-1);zm=F.normalize(model.mol_projection(mc).float(),dim=-1) f,b=grouped_contrastive(zq@zm.T/LEGACY.C['contrastive_temperature'],ids,columns) base=w['inbatch_ms_to_mol']*f+w['inbatch_mol_to_ms']*b # Match the parent's FP32 auxiliary invocation, not R1's outer autocast. auxiliary,details=auxiliary_loss(model,qc,mols,rows,SPEC,update) chem=chemical_loss(model,qc,rows) ramp=min(1.,(update-C['source_update']+1)/C['lr_ramp_updates']) # A3 auxiliaries are already trained: retain their full weights, not a # second accidental warm-up. New heads use final pool CE, not duplicate CE. cw=C['chem_weight'];sw=C['spectrum_weight'] (base+auxiliary+cw*chem).backward();dq=qc.grad.detach();dm=mc.grad.detach() metrics=dict(inbatch_ms_to_mol=f.detach(),inbatch_mol_to_ms=b.detach(),formula_loss=0.,formula_ce=0.,formula_gap=0.,element_ce=0.,formula_correct=0., chemical_loss=chem.detach(),chemical_weight=cw,spectrum_weight=sw) valid=sum(r['mass_ok'] and len(r['formulas'])>1 and r['formula'] in r['formulas'] for r in rows) for a in range(0,len(rows),sc): block=rows[a:a+sc] with amp(): tokens,q,_=model.spectrum.forward_batch([r['query'] for r in block]) lf,d=formula_objective(model,q,tokens,block,valid,len(rows)) loss=(q*dq[a:a+len(block)]).sum()+w['formula']*lf loss.backward();metrics['formula_loss']+=lf.detach() for k in ('formula_ce','formula_gap','element_ce','formula_correct'):metrics[k]+=d[k] for a in range(0,len(mols),gc): with amp():u=model.encode_molecules(mols[a:a+gc])[0];surrogate=(u*dm[a:a+len(u)]).sum() surrogate.backward() pools=[p for r in rows for p in r['pools']];counts=Counter(p['kind'] for p in pools) pm={k:qc.new_zeros(()) for k in ('odata','mass','formula')};spec_total=qc.new_zeros(()) supervised={p['record_id'] for p in pools if p['spectrum_eligible']};seen=set();used=0 for a in range(0,len(pools),LEGACY.C['pool_micro_views']): block=pools[a:a+LEGACY.C['pool_micro_views']] with amp(): encs,_=model.encode_batch([p['query'] for p in block]);loss=encs[0].q.sum()*0. for p,enc in zip(block,encs): ce=enc.base.float().logsumexp(0)-enc.base[p['positive_index']].float();kind=p['kind'] pm[kind]+=ce.detach()/counts[kind] loss+=w[{'odata':'odata_pool','mass':'msg_mass_pool','formula':'msg_formula_pool'}[kind]]*ce/counts[kind] if p['spectrum_eligible'] and p['record_id'] not in seen: if enc.r2_spectrum is None:raise RuntimeError('Qualified spectrum has no fragment predictions') spec,usable=enc.r2_spectrum if not bool(usable[p['positive_index']]):raise RuntimeError('CPU / GPU fragment eligibility disagrees') sl=spec[p['positive_index']]/max(1,len(supervised));loss+=sw*sl;spec_total+=sl.detach() seen.add(p['record_id']);used+=1 loss.backward() total=base.detach()+auxiliary.detach()+cw*chem.detach()+sw*spec_total+w['formula']*metrics['formula_loss'] for k,v in pm.items():metrics[k+'_pool']=v;total+=w[{'odata':'odata_pool','mass':'msg_mass_pool','formula':'msg_formula_pool'}[k]]*v metrics.update(details);metrics.update(spectrum_loss=spec_total,loss=total) if not torch.isfinite(total):raise RuntimeError('Nonfinite R2 objective') for name,parameters in [('backbone',[p for n,p in model.named_parameters() if not n.startswith(('r2.','r3.'))]), ('chemical',model.r2.counts.parameters()),('fragment',[p for n,p in model.r2.named_parameters() if not n.startswith('counts.') and n!='chemical_scale']), ('r3',model.r3.parameters())]: gs=[p.grad.detach().float().square().sum() for p in parameters if p.grad is not None] metrics[name+'_gradient_norm']=torch.stack(gs).sum().sqrt() if gs else total*0. norm=torch.nn.utils.clip_grad_norm_(model.parameters(),LEGACY.C['gradient_clip'],error_if_nonfinite=True) metrics['gradient_norm']=norm.detach() for name in ('formula_prior_abs','parent_structural_std','topology_abs','difference_abs','formula_calibration_abs','final_score_std'): values=[r[name] for r in model.score_diagnostics if name in r] metrics['score_'+name]=torch.stack(values).mean() if values else total*0. metrics['formula_calibration_alpha']=.5*model.r3.formula_alpha.detach().tanh() model.collect_score_diagnostics=False;model.score_diagnostics=[] if apply_update:opt.step() packed=torch.stack([v.detach().float().to(model.device) if torch.is_tensor(v) else torch.tensor(v,device=model.device).float() for v in metrics.values()]).cpu().tolist() result=dict(zip(metrics,packed));result.update(queries=len(rows),unique_connectivity=len(columns),formula_valid=valid, pool_valid=dict(counts),spectrum_valid=used,chemical_valid=len(rows) if cw else 0, source_counts=dict(Counter(r['source'] for r in rows)),negative_draws=sum(p['negative_draws'] for p in pools), negative_unique_key14=sum(p['unique_negative_key14'] for p in pools),duplicate_physical_MS=len(rows)-len({r['record_id'] for r in rows}), molecular_encoder_views=2,zero_weight_coarse_auxiliaries='not_computed',data_seconds=batch['data_seconds'], step_compute_seconds=time.monotonic()-started,peak_allocated_mib=torch.cuda.max_memory_allocated()/2**20) return result123456789101112[program:specpartition-r3-pipeline-20261110]directory=/root/xj/SpecPartition-MS/code/ceir_r3_20261110command=/usr/bin/nice -n 19 /workspace/xj/SpecPartition-MS/.venv/bin/python -u /root/xj/SpecPartition-MS/code/ceir_r3_20261110/pipeline_r3.pyenvironment=PROC_NAME="specpartition-r3-pipeline-20261110",OMP_NUM_THREADS="1",MKL_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",CUBLAS_WORKSPACE_CONFIG=":4096:8",PYTHONUNBUFFERED="1"autostart=falseautorestart=falsestartsecs=2stopasgroup=truekillasgroup=truestdout_logfile=/dev/stdoutstdout_logfile_maxbytes=0redirect_stderr=true1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071"""Finite supervised execution: all arms +3000, Validation, fixed Test, MCES."""from collections import dequefrom runtime_r2 import *PYTHON='/workspace/xj/SpecPartition-MS/.venv/bin/python'MCES='/root/xj/SpecPartition-MS/evaluations/mces_all_20261106/.venv/bin/python'
def launch(label,args,python=PYTHON): folder=OUT/'service_logs';folder.mkdir(parents=True,exist_ok=True) with (folder/(label+'.log')).open('a') as f: process=subprocess.Popen([python,'-u',*map(str,args)],cwd=HERE,stdout=f,stderr=subprocess.STDOUT, env=dict(os.environ,PROC_NAME='specpartition-r3-'+label+'-20261110',OMP_NUM_THREADS='1',OPENBLAS_NUM_THREADS='1',MKL_NUM_THREADS='1')) log(OUT/'PIPELINE_EVENTS.jsonl',dict(event='child_started',label=label,pid=process.pid,args=list(map(str,args)),unix_time=time.time())) return process
def checked(label,args,python=PYTHON): p=launch(label,args,python) while p.poll() is None:time.sleep(3) if p.returncode:raise RuntimeError(label+' failed; see service_logs; full checkpoints retained')
def parallel(jobs): queue=deque(jobs);active=[] while queue or active: while queue and len(active)<2: label,args=queue.popleft();active.append((label,args,launch(label,args),0)) rest=[] for label,args,p,retries in active: if p.poll() is None:rest.append((label,args,p,retries)) elif p.returncode: if retries>=2:raise RuntimeError('Repeated failure '+label) time.sleep(5);rest.append((label,args,launch(label,args),retries+1)) active=rest save(OUT/'PIPELINE_STATUS.json',dict(active=[dict(label=l,pid=p.pid,retries=r) for l,_,p,r in active],queued=[x[0] for x in queue],unix_time=time.time())) if active:time.sleep(5)
def run(): OUT.mkdir(parents=True,exist_ok=True);lock=(OUT/'pipeline.lock').open('a+');fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB) test_path=Path(C['evaluation_output'])/'test';test_path.mkdir(parents=True,exist_ok=True) if not (OUT/'test').exists():(OUT/'test').symlink_to(test_path,target_is_directory=True) if (OUT/'test').resolve()!=test_path.resolve():raise RuntimeError('Unexpected Test output location') if (OUT/'ALL_RESULTS.json').exists():return while not (PREP/'DATA_ACCEPTANCE.json').exists(): if (PREP/'failure.json').exists():raise RuntimeError('Preparation failed') save(OUT/'PIPELINE_STATUS.json',dict(phase='waiting_for_preparation',unix_time=time.time()));time.sleep(5) if not (PREP/'INDEPENDENT_LEDGER_AUDIT.json').exists():checked('independent-data-audit',[HERE/'audit_r3.py']) if not (OUT/'TRAIN_READY.json').exists():checked('GPU-acceptance',[HERE/'acceptance_r3.py']) if json.loads((OUT/'TRAIN_READY.json').read_text())['binding']!=binding():raise RuntimeError('Acceptance binding changed') parallel([(a+'-train',[HERE/'train_r2.py','--arm',a]) for a in C['arms']]) for a in C['arms']: directory=run_dir(a)/'validation_006000' if not (directory/'MCES.json').exists():checked(a+'-Validation-MCES',[HERE/'mces_r2.py','--directory',directory],MCES) checked('Validation-selection',[HERE/'analyze_r3.py']) checked('Test-features',[HERE/'test_r3.py','--prepare']) parallel([(a+'-'+d,[HERE/'test_r3.py','--name',a+'_006000','--dataset',d]) for a in C['arms'] for d in ('msg_test','casmi2022')]) for a in C['arms']: for d in ('msg_test','casmi2022'): directory=OUT/'test/inference'/(a+'_006000')/d if not (directory/'MCES.json').exists():checked(a+'-'+d+'-MCES',[HERE/'test_mces_r2.py','--directory',directory],MCES) checked('complete-comparison',[HERE/'analyze_r3.py','--test']) checked('independent-all-scores-audit',[HERE/'final_audit_r3.py']) save(OUT/'PIPELINE_STATUS.json',dict(phase='all_3000_step_experiments_and_evaluations_complete',unix_time=time.time()))
if __name__=='__main__': try:run() except Exception: import traceback save(OUT/'PIPELINE_FAILURE.json',dict(traceback=traceback.format_exc(),unix_time=time.time()));raise123456789101112[program:specpartition-r3-prepare-20261110]directory=/root/xj/SpecPartition-MS/code/ceir_r3_20261110command=/usr/bin/nice -n 19 /workspace/xj/SpecPartition-MS/.venv/bin/python -u /root/xj/SpecPartition-MS/code/ceir_r3_20261110/prepare_r3.pyenvironment=PROC_NAME="specpartition-r3-prepare-20261110",OMP_NUM_THREADS="1",MKL_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",PYTHONUNBUFFERED="1"autostart=falseautorestart=falsestartsecs=2stopasgroup=truekillasgroup=truestdout_logfile=/dev/stdoutstdout_logfile_maxbytes=0redirect_stderr=true123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147"""Independent 3000-update ledger and compact read-only-parent feature overlay."""from collections import Counterfrom concurrent.futures import ProcessPoolExecutorfrom functools import lru_cacheimport multiprocessingimport randomimport sqlite3import timeimport numpy as npfrom rdkit import Chemfrom runtime_r2 import *import features_r2 as ftfrom data09 import Readerfrom prepare_ceir import entry_identity
def db_open(path=None): path=Path(path or PREP/'assets.sqlite');path.parent.mkdir(parents=True,exist_ok=True) db=sqlite3.connect(path);db.execute('PRAGMA page_size=16384');db.execute('PRAGMA journal_mode=WAL') db.execute('CREATE TABLE IF NOT EXISTS batches(mode TEXT,idx INTEGER,body BLOB,PRIMARY KEY(mode,idx))') db.execute('CREATE TABLE IF NOT EXISTS r3_features(feature_key TEXT PRIMARY KEY,smiles TEXT,feature BLOB,feature_sha BLOB,distance BLOB,distance_sha BLOB) WITHOUT ROWID') db.execute('CREATE INDEX IF NOT EXISTS pending_r3 ON r3_features(feature_key) WHERE distance IS NULL') return db
def plans(): from sampling import epoch_plans,plan_hash state=parent_state();progress=state['progress'];epoch=progress['epoch'];offset=progress['next_step'];out=[];audit=[] while len(out)<C['manifest_updates']: pp=epoch_plans(epoch,C['seed']);audit.append(dict(epoch=epoch,sha256=plan_hash(pp),start=offset)) out.extend(pp[offset:offset+C['manifest_updates']-len(out)]);epoch+=1;offset=0 return out,audit
def planning(): if (PREP/'SAMPLING_READY.json').exists():return db=db_open();reader=Reader();pp,epoch_audit=plans();stats=Counter() @lru_cache(maxsize=160000) def register(gh): m=reader.molecule(gh) if m.identity in reader.forbidden:raise RuntimeError('Heldout structure in training ledger') db.execute('INSERT OR IGNORE INTO r3_features(feature_key,smiles) VALUES (?,?)',(ft.key(m.smiles),m.smiles)) return m.identity @lru_cache(maxsize=160000) def alias(s): value=reader.assets.execute('SELECT graph_hash FROM smiles WHERE smiles=?',(s,)).fetchone() if not value:raise RuntimeError('Missing offline graph') return value[0] def graph(e): gh=e.get('graph_hash') or alias(e.get('canonical_smiles') or e.get('smiles')) if register(gh)!=entry_identity(e):raise RuntimeError('Graph identity mismatch') return gh for index,(epoch,step,groups) in enumerate(pp): if db.execute('SELECT 1 FROM batches WHERE idx=?',(index,)).fetchone():continue rows=[] for source,ids in groups.items(): for j,rid in enumerate(ids): row=loads(reader.db.execute('SELECT body FROM samples WHERE record_id=?',(rid,)).fetchone()[0]);register(row['graph_hash']) if row['identity'] in reader.forbidden:raise RuntimeError('Heldout training label') seed=C['seed']+epoch*100000000+step*10000+j+(1000000 if source=='msg' else 0);rng=random.Random(seed) kinds=('mass','formula') if row['source']=='MSG_Train' else (('odata',) if source=='odata' and j<16 else ()) forms=tuple(reader.official(row['target'],'mass')['formula_classes']) if row['source']=='MSG_Train' else tuple(row['view']['formulas']) pools=[] for kind in kinds: if kind=='odata': view=row['view'];pool=reader.pool(view['pool_path'],view['pool_sha256']);entries=pool['records'] allowed=pool['safe_mass_order'][view['mass_order_start']:view['mass_order_stop']] else: pool=reader.official(row['target'],kind);entries=pool['entries'];allowed=[i for i,e in enumerate(entries) if e['eligible_for_training']] positives=[i for i in allowed if entry_identity(entries[i])==row['identity']];by_id={} for i in allowed: identity=entry_identity(entries[i]) if identity!=row['identity']:by_id.setdefault(identity,[]).append(i) if not positives or not by_id:continue rr=random.Random(seed) if kind=='odata' else rng;positive=rr.choice(positives) budget=LEGACY.C['odata_negative_draws'] if kind=='odata' else LEGACY.C['msg_negative_draws'] identities=rr.sample(sorted(by_id),min(budget,len(by_id)));chosen=[rr.choice(by_id[k]) for k in identities] selected=[positive,*chosen];gh=[graph(entries[i]) for i in selected] fs=tuple(pool['formula_classes']) if kind!='odata' else tuple(sorted({entries[i]['formula'] for i in selected})) pools.append(dict(kind=kind,graphs=gh,formulas=fs,negative_draws=len(chosen),unique_negative_key14=len(chosen),reference_injected=False)) rows.append(dict(rid=rid,ref=row['graph_hash'],formulas=forms,pools=pools));stats[row['source']]+=1 blob=ft.dumps(dict(epoch=epoch,step=step,rows=rows));db.execute('INSERT INTO batches VALUES (?,?,?)',('unique',index,blob));db.commit() if index%10==0: save(PREP/'status.json',dict(phase='training_ledger',completed=index+1,total=len(pp),unix_time=time.time()));disk_check() hashes=[hashlib.sha256(b).hexdigest() for b, in db.execute('SELECT body FROM batches ORDER BY idx')] if len(hashes)!=3000:raise RuntimeError('Incomplete 3000-step ledger') save(PREP/'ledger_hashes.json',dict(unique=hashes)) save(PREP/'SAMPLING_READY.json',dict(complete=True,updates=3000,source_update=3000,target_update=6000,epochs=epoch_audit, ledger_sha256=sha(PREP/'ledger_hashes.json'),candidate_pools_changed=False,source_counts_this_attempt=dict(stats))) db.close()
def add_validation(): marker=PREP/'VALIDATION_STRUCTURES_READY.json' if marker.exists():return db=db_open();source=readonly(LEGACY.PREP/'validation.sqlite');n=0 for b, in source.execute('SELECT body FROM graphs'): m=loads(b);db.execute('INSERT OR IGNORE INTO r3_features(feature_key,smiles) VALUES (?,?)',(ft.key(m.smiles),m.smiles));n+=1 if n%10000==0:db.commit() db.commit();db.close();save(marker,dict(complete=True,rows=n,labels_used_for_training=False))
def distance_task(task): key,smiles,need=task;mol=Chem.MolFromSmiles(smiles) if mol is None:raise RuntimeError('Invalid pre-accepted graph') dist=ft.distance_dumps(np.minimum(Chem.GetDistanceMatrix(mol),15).astype(np.uint8)) body=ft.dumps(ft.build(smiles)) if need else None return key,body,hashlib.sha256(body).digest() if body else None,dist,hashlib.sha256(dist).digest()
def build_features(path=None,test=False): db=db_open(path);parents=[readonly(Path(C['r2_output'])/'prepared/assets.sqlite')] if test:parents.append(readonly(Path(C['r2_output'])/'test/prepared/assets.sqlite')) tables=['canonical_features' if d.execute("SELECT 1 FROM sqlite_master WHERE name='canonical_features'").fetchone() else 'molecules' for d in parents] ctx=multiprocessing.get_context('spawn');count=0 with ProcessPoolExecutor(max_workers=C['prepare_workers'],mp_context=ctx) as executor: while True: pending=db.execute('SELECT feature_key,smiles FROM r3_features WHERE distance IS NULL ORDER BY feature_key LIMIT 1024').fetchall() if not pending:break tasks=[] for k,s in pending: exists=any(d.execute('SELECT 1 FROM '+t+' WHERE feature_key=? AND feature IS NOT NULL',(k,)).fetchone() for d,t in zip(parents,tables)) tasks.append((k,s,not exists)) for k,b,h,d,dh in executor.map(distance_task,tasks,chunksize=16): db.execute('UPDATE r3_features SET feature=?,feature_sha=?,distance=?,distance_sha=? WHERE feature_key=?',(b,h,d,dh,k));count+=1 db.commit() if count%8192==0: save(Path(path).parent/'status.json' if path else PREP/'status.json',dict(phase='offline_incremental_topology',processed_this_attempt=count,unix_time=time.time()));disk_check() total=db.execute('SELECT count(*) FROM r3_features').fetchone()[0];new=db.execute('SELECT count(*) FROM r3_features WHERE feature IS NOT NULL').fetchone()[0] db.execute('PRAGMA wal_checkpoint(TRUNCATE)');db.close() return dict(complete=True,features=total,new_fragment_descriptors=new,parent_caches_read_only=True)
def run(): OUT.mkdir(parents=True,exist_ok=True);disk_check();planning();add_validation();result=build_features() save(PREP/'READY.json',dict(**result,sampling=json.loads((PREP/'SAMPLING_READY.json').read_text()),feature_version=C['feature_version'])) # Dataset re-verifies every sampled label/negative identity against the # immutable heldout registry when it is read. Planning also checked all. save(PREP/'DATA_ACCEPTANCE.json',dict(complete=True,all_training_graphs_checked_against_heldout_registry=True, shared_ledger_all_five_arms=True,original_candidates_modified=False,ledger_hashes_sha256=sha(PREP/'ledger_hashes.json')))
if __name__=='__main__': try:run() except Exception: import traceback save(PREP/'failure.json',dict(traceback=traceback.format_exc(),unix_time=time.time()));raise123456789101112131415161718192021222324252627282930"""Early real mixed-batch engineering probe; never grants training readiness."""import sqlite3from runtime_r2 import *from prepare_r3 import db_open,build_featuresfrom data09 import Readerimport features_r2 as ft
def prepare(): source=readonly(PREP/'assets.sqlite');index=None;plan=None for i,b in source.execute('SELECT idx,body FROM batches ORDER BY idx'): candidate=ft.loads(b) if len(candidate['rows'])==288:index=i;plan=candidate;break if index is None:raise RuntimeError('No real mixed batch materialized yet') path=PREP/'probe.sqlite';db=db_open(path);reader=Reader();graphs=set() for row in plan['rows']: graphs.add(row['ref']) for p in row['pools']:graphs.update(p['graphs']) for gh in graphs: m=reader.molecule(gh) if m.identity in reader.forbidden:raise RuntimeError('Heldout graph') db.execute('INSERT OR IGNORE INTO r3_features(feature_key,smiles) VALUES (?,?)',(ft.key(m.smiles),m.smiles)) db.commit();db.close();build_features(path) save(PREP/'PROBE_READY.json',dict(complete=True,index=index,graphs=len(graphs),formal_training_ready=False))
if __name__=='__main__': prepare() from acceptance_r3 import run run(provisional=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128"""Independent release and full-state continuation; old experiments are read-only."""import contextlibimport fcntlimport hashlibimport jsonimport osfrom pathlib import Pathimport randomimport shutilimport subprocessimport sysimport time
os.environ.setdefault('CUBLAS_WORKSPACE_CONFIG',':4096:8')
HERE=Path(__file__).resolve().parentC=json.loads((HERE/'config.json').read_text())OUT=Path(C['output']);PREP=OUT/'prepared';ROOT=Path(C['root'])sys.path.insert(0,C['source_r1'])import runtime_ceir as OLDLEGACY=OLD.LEGACY;SPEC=OLD.SPECLEGACY.C.update(spectrum_chunk=C['spectrum_chunk'],graph_chunk=C['graph_chunk'],local_chunk=C['local_chunk'], pool_micro_views=C['pool_micro_views'],threads=1,workers=1,max_atoms_per_microbatch=C['max_atoms_per_microbatch'])from runtime09 import readonly,save,shafrom data09 import loads
def run_dir(arm): if arm not in C['arms']:raise ValueError('Unknown R2 arm') p=OUT/arm;p.mkdir(parents=True,exist_ok=True);return p
def code_manifest(): return {p.name:sha(p) for p in sorted([*HERE.glob('*.py'),HERE/'config.json']) if not p.name.startswith('.')}
def parent_state(): import torch if sha(C['parent_checkpoint'])!=C['parent_sha256']:raise RuntimeError('Parent checkpoint hash changed') state=torch.load(C['parent_checkpoint'],map_location='cpu',weights_only=False) if state['progress']['update']!=C['source_update']:raise RuntimeError('Incorrect parent update') if state['binding']['original_data']!=LEGACY.bind():raise RuntimeError('Original training data binding changed') return state
def binding(): ready=json.loads((PREP/'READY.json').read_text()) evaluation_code=Path('/root/xj/SpecPartition-MS/code/ceir_r1_test_comparison_20261110') external={str(p):sha(p) for p in sorted(evaluation_code.glob('*.py'))} external[str(Path(C['source_r1'])/'mces_ceir.py')]=sha(Path(C['source_r1'])/'mces_ceir.py') external.update({str(p):sha(p) for p in Path(C['source_r2']).glob('*.py')}) return dict(code=code_manifest(),parent_sha256=C['parent_sha256'],prepared=ready, original_data=LEGACY.bind(),feature_version=C['feature_version'], dependency_sources=OLD.bind()['dependency_sources'],parent_formula_loss=LEGACY.C['r2'], parent_loss_weights=LEGACY.C['loss_weights'],auxiliary=SPEC['loss']['auxiliary'], data_acceptance=json.loads((PREP/'DATA_ACCEPTANCE.json').read_text()),external_evaluation_code=external)
def disk_check(): OUT.mkdir(parents=True,exist_ok=True) if shutil.disk_usage(OUT).free<C['minimum_output_disk_gib']*2**30: raise RuntimeError('R3 disk reserve insufficient; original files were not deleted') evaluation=Path(C['evaluation_output']);evaluation.mkdir(parents=True,exist_ok=True) if shutil.disk_usage(evaluation).free<.7*2**30: raise RuntimeError('R3 evaluation filesystem reserve <0.7 GiB; all results retained')
def evaluation_directory(arm,label): destination=Path(C['evaluation_output'])/arm/label;destination.mkdir(parents=True,exist_ok=True) link=run_dir(arm)/label if not link.exists():link.symlink_to(destination,target_is_directory=True) if link.resolve()!=destination.resolve():raise RuntimeError('Unexpected evaluation destination') return link
def log(path,row): path=Path(path);path.parent.mkdir(parents=True,exist_ok=True) with path.open('a') as f:f.write(json.dumps(row,ensure_ascii=False,allow_nan=False)+'\n')
def setup_gpu(): import torch torch.set_num_threads(1);torch.set_float32_matmul_precision('high');torch.use_deterministic_algorithms(True) torch.cuda.set_per_process_memory_fraction(C['gpu_memory_fraction']);LEGACY.seed_all(C['seed'])
@contextlib.contextmanagerdef gpu_work(directory,phase): disk_check();locks=OUT/'gpu_slots';locks.mkdir(parents=True,exist_ok=True) files=[(locks/f'{i}.lock').open('a+') for i in range(C['gpu_slots'])];held=None try: while held is None: raw=subprocess.check_output(['nvidia-smi','--query-gpu=memory.free','--format=csv,noheader,nounits'],text=True) if int(raw.strip().splitlines()[0])>=C['minimum_free_gpu_mib']: for f in files: try:fcntl.flock(f,fcntl.LOCK_EX|fcntl.LOCK_NB);held=f;break except BlockingIOError:pass if held is None: save(Path(directory)/'resource_status.json',dict(phase=phase,state='waiting_for_R2_GPU_slot',unix_time=time.time())) time.sleep(3) yield finally: import torch if torch.cuda.is_initialized():torch.cuda.empty_cache() if held is not None:fcntl.flock(held,fcntl.LOCK_UN) for f in files:f.close()
def restore_rng(state): import numpy as np import torch torch.set_rng_state(state['torch_rng']);torch.cuda.set_rng_state_all(state['cuda_rng']) np.random.set_state(state['numpy_rng']);random.setstate(state['python_rng'])
def checkpoint(path,model,opt,progress,bind): import numpy as np import torch path=Path(path);temporary=path.with_suffix('.tmp') torch.save(dict(architecture='CEIR_R3',model=model.state_dict(),optimizer=opt.state_dict(),progress=progress, binding=bind,torch_rng=torch.get_rng_state(),cuda_rng=torch.cuda.get_rng_state_all(), numpy_rng=np.random.get_state(),python_rng=random.getstate()),temporary) temporary.replace(path)
def amp(): import torch return torch.autocast('cuda',dtype=torch.bfloat16,enabled=LEGACY.C['bf16'])1234567891011121314151617181920212223242526"""Post-hoc Test MCES, inherited fixed protocol and a private pair cache."""import argparseimport fcntlimport importlib.utilimport jsonfrom pathlib import Pathimport sysimport sqlite3
HERE=Path(__file__).resolve().parent;C=json.loads((HERE/'config.json').read_text());OUT=Path(C['output'])/'test'
def run(directory): own=OUT/'mces';own.mkdir(parents=True,exist_ok=True) lock=(own/'compute.lock').open('a+');fcntl.flock(lock,fcntl.LOCK_EX) path=Path('/root/xj/SpecPartition-MS/code/ceir_r1_test_comparison_20261110/mces.py') spec=importlib.util.spec_from_file_location('r2_fixed_Test_MCES',path);module=importlib.util.module_from_spec(spec);sys.modules[spec.name]=module;spec.loader.exec_module(module) module.OUT=OUT;module.old.OUT=OUT/'mces' # workers may record solver state: never write the old run previous=Path(C['r2_output'])/'test/mces/pairs.sqlite' if not (own/'pairs.sqlite').exists() and previous.exists(): a=sqlite3.connect('file:'+str(previous)+'?mode=ro',uri=True);b=sqlite3.connect(own/'pairs.sqlite');a.backup(b);a.close();b.close() db=module.initialize();module.compute(Path(directory),db);db.close()
if __name__=='__main__': p=argparse.ArgumentParser();p.add_argument('--directory',required=True);a=p.parse_args();run(a.directory)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960"""Full original pools, no Top256 restriction, no injected references."""import argparsefrom runtime_r2 import *EVAL=OUT/'test'EVAL_CODE=Path('/root/xj/SpecPartition-MS/code/ceir_r1_test_comparison_20261110')
def prepare(): from prepare_r3 import db_open,build_features if (EVAL/'prepared/READY.json').exists():return import evaluation_runtime as original path=EVAL/'prepared/assets.sqlite';db=db_open(path) import features_r2 as ft for dataset in ('msg_test','casmi2022'): source=readonly(original.PREP/(dataset+'.sqlite'));n=0 for blob, in source.execute('SELECT body FROM graphs'): m=loads(blob);db.execute('INSERT OR IGNORE INTO r3_features(feature_key,smiles) VALUES (?,?)',(ft.key(m.smiles),m.smiles));n+=1 if n%10000==0:db.commit() db.commit();source.close() db.close();result=build_features(path,test=True) save(EVAL/'prepared/READY.json',dict(**result,labels_used_for_training=False,inputs={d:original.inputs(d) for d in ('msg_test','casmi2022')}))
def freeze(): import evaluation_runtime as original selected=json.loads((OUT/'SELECTION.json').read_text()) if not selected['complete'] or selected['test_used_for_selection']:raise RuntimeError('Unfrozen Validation decision') models={} for arm in C['arms']: path=run_dir(arm)/'step_006000.pt';done=json.loads((run_dir(arm)/'COMPLETE.json').read_text()) if not done['complete'] or done['new_updates']!=3000:raise RuntimeError('Not all 3000 updates complete') models[arm+'_006000']=dict(arm=arm,update=6000,checkpoint=str(path),sha256=sha(path),role='fixed_3000_new_update_endpoint') frozen=dict(models=models,r3_binding=binding(),selection_sha256=sha(OUT/'SELECTION.json'),inputs={d:original.inputs(d) for d in ('msg_test','casmi2022')}, candidate_limit=None,truth_injection=False,Test_used_for_selection=False) path=EVAL/'FROZEN.json' if path.exists() and json.loads(path.read_text())!=frozen:raise RuntimeError('Frozen Test release changed') save(path,frozen)
def make_model(name): import torch from model_r2_new import make_model_optimizer frozen=json.loads((EVAL/'FROZEN.json').read_text());item=frozen['models'][name] if sha(item['checkpoint'])!=item['sha256']:raise RuntimeError('Changed frozen checkpoint') setup_gpu();model,opt,progress,_=make_model_optimizer(item['arm'],item['checkpoint']);del opt if progress['update']!=6000:raise RuntimeError('Wrong endpoint') model.graph_chunk=C['validation_graph_chunk'];model.local_chunk=C['validation_local_chunk'] model.install_features(EVAL/'prepared/assets.sqlite');model.eval();return model,item
def run(name,dataset): freeze();module=OLD.load_module('r3_fixed_Test_adapter',EVAL_CODE/'infer.py') module.OUT=EVAL;module.make_model=make_model;module.gpu_slot=lambda d:gpu_work(d,'fixed_Test') module.check_disk=disk_check;module.C=dict(module.C,spectrum_batch=C['validation_spectrum_batch'],graph_chunk=C['validation_graph_chunk'],local_chunk=C['validation_local_chunk']) module.evaluate(name,dataset)
if __name__=='__main__': sys.path.insert(0,str(EVAL_CODE));p=argparse.ArgumentParser();p.add_argument('--prepare',action='store_true');p.add_argument('--name');p.add_argument('--dataset');a=p.parse_args() prepare() if a.prepare else run(a.name,a.dataset)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253"""Small deterministic tests independent of private data / server imports."""import unittestfrom types import SimpleNamespaceimport numpy as npimport torchfrom rdkit import Chemfrom heads_r3 import Headsimport features_r2 as ft
class Tests(unittest.TestCase): def setUp(self): torch.manual_seed(3);self.head=Heads();self.q=torch.randn(256) self.query=SimpleNamespace(peaks=((50.1,20.),(76.2,80.),(120.3,100.)),precursor_mz=180.,adduct='[M+H]+') self.assets=[];self.atoms=[];self.mols=[] for s in ('CCOC(=O)c1ccccc1','CC(=O)Oc1ccccc1','CCN(CC)CC'): f=ft.build(s);f['distance']=np.minimum(Chem.GetDistanceMatrix(Chem.MolFromSmiles(s)),15).astype(np.uint8) self.assets.append(f);self.atoms.append(torch.randn(f['atoms'],256,requires_grad=True));self.mols.append(SimpleNamespace(smiles=s)) def test_initial_zero(self): self.assertEqual(float(self.head.topology_scores(self.q,self.query,self.atoms,self.assets).abs().max()),0.) self.assertEqual(float(self.head.difference_scores(self.q,self.query,self.mols,self.assets).abs().max()),0.) base=torch.randn(3);self.assertTrue(torch.equal(self.head.calibrate(base,base,['A','A','B']),base)) def test_order(self): with torch.no_grad(): self.head.topology[-1].weight.normal_(std=.1);self.head.difference[-1].weight.normal_(std=.1);self.head.formula_alpha.fill_(.5) p=[2,0,1] for name,items in [('topology_scores',self.atoms),('difference_scores',self.mols)]: f=getattr(self.head,name);a=f(self.q,self.query,items,self.assets);b=f(self.q,self.query,[items[i] for i in p],[self.assets[i] for i in p]) self.assertTrue(torch.allclose(b,a[p],atol=1e-5)) b=torch.tensor([1.,3.,2.]);a=self.head.calibrate(b,b,['A','A','B']);c=self.head.calibrate(b[p],b[p],['B','A','A']);self.assertTrue(torch.allclose(c,a[p])) def test_single_formula_unchanged(self): self.head.formula_alpha.data.fill_(1.);b=torch.randn(8) self.assertTrue(torch.equal(self.head.calibrate(b,b,['A']*8),b)) def test_current_graph_gradients(self): self.head.topology[-1].weight.data.normal_(std=.1) self.head.topology_scores(self.q,self.query,self.atoms,self.assets).sum().backward() self.assertTrue(all(a.grad.norm()>0 for a in self.atoms)) self.assertGreater(float(self.head.mass[0].weight.grad.norm()),0.) def test_unsupported_adduct_keeps_parent(self): self.query.adduct='[M+2H]2+' self.assertEqual(float(self.head.difference_scores(self.q,self.query,self.mols,self.assets).abs().max()),0.) def test_lossless_distance_storage(self): for n in (1,2,3,18,49): a=np.minimum(np.abs(np.arange(n)[:,None]-np.arange(n)[None,:]),15).astype(np.uint8) self.assertTrue(np.array_equal(a,ft.distance_loads(ft.distance_dumps(a)))) self.assertTrue(np.array_equal(a,ft.distance_loads(ft.dumps(a)))) import hashlib b=b'unchanged' self.assertTrue(ft.digest_matches(b,hashlib.sha256(b).digest())) self.assertTrue(ft.digest_matches(b,hashlib.sha256(b).hexdigest()))
if __name__=='__main__':unittest.main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111"""Exactly +3000 updates from frozen A3 3k; joint objectives throughout."""import argparseimport fcntlimport jsonimport mathimport timeimport tracebackimport uuidfrom runtime_r2 import *
def train(arm): import torch from torch.utils.data import DataLoader from data_r2 import Dataset from model_r2_new import make_model_optimizer from objectives_r2 import train_step from validate_r2 import evaluate directory=run_dir(arm);lock=(directory/'training.lock').open('a+');fcntl.flock(lock,fcntl.LOCK_EX) ready=json.loads((OUT/'TRAIN_READY.json').read_text());bind=binding() if ready['binding']!=bind or not ready['complete']:raise RuntimeError('Code/data/GPU acceptance binding changed') if (directory/'COMPLETE.json').exists():return target=C['pilot_target_update'];setup_gpu();last=directory/'last.pt' source=parent_state();parent_lrs=[g['lr'] for g in source['optimizer']['param_groups']];del source with gpu_work(directory,'restore'): model,opt,progress,original_lr=make_model_optimizer(arm,last if last.exists() else None) if last.exists(): state=torch.load(last,map_location='cpu',weights_only=False) if state['binding']!=bind:raise RuntimeError('Resume binding differs') del state else:checkpoint(last,model,opt,progress,bind) save(directory/'provenance.json',dict(arm=arm,source_update=C['source_update'],target_update=target,parent_checkpoint=C['parent_checkpoint'], parent_sha256=C['parent_sha256'],parameters=sum(p.numel() for p in model.parameters()),binding=bind, old_parameters_loaded_exactly=True,optimizer_moments_continued=True,source_data_cursor_preserved=True, original_pools_modified=False,training_uses_Test_or_CASMI=False, zero_weight_coarse_tasks_skipped=True,all_arms_receive_same_stochastic_view_checkpoint_fix=True)) attempt=uuid.uuid4().hex;resumed=progress['update'] prior_failure=directory/'failure.json' if prior_failure.exists():prior_failure.rename(directory/('failure_recovered_'+attempt+'.json')) log(directory/'events.jsonl',dict(event='resumed',attempt=attempt,update=resumed,unix_time=time.time())) pending=[u for u in C['validation_updates'] if u<=progress['update'] and u not in progress.get('r2_validated',[])] for u in pending: if u!=progress['update']:raise RuntimeError('Pending historical Validation checkpoint must be evaluated explicitly') snapshot=directory/('step_%06d.pt'%u) if not snapshot.exists():shutil.copy2(last,snapshot) evaluate(model,arm,u,128 if u<target else None,directory/('step_%06d.pt'%u)) progress.setdefault('r2_validated',[]).append(u) with gpu_work(directory,'save_validated_progress'):checkpoint(last,model,opt,progress,bind) offset=progress['update']-C['source_update'] dataset=Dataset(arm,offset,target-C['source_update']) generator=torch.Generator().manual_seed(C['seed']+offset) loader=DataLoader(dataset,batch_size=None,num_workers=1,prefetch_factor=2,multiprocessing_context='spawn',generator=generator) previous=time.monotonic() for batch in loader: started=time.monotonic();waiting=started-previous;u=progress['update'];n=u-C['source_update'] if batch['manifest_index']!=n:raise RuntimeError('Data cursor changed') # Predeclared +3000 schedule, identical in every arm. Test never selects # an intermediate checkpoint or changes the number of updates. ramp=min(1.,(n+1)/C['lr_ramp_updates']);decay=.2+.8*.5*(1+math.cos(math.pi*min(1.,n/C['manifest_updates']))) opt.param_groups[0]['lr']=original_lr*C['backbone_lr_multiplier']*ramp*decay opt.param_groups[1]['lr']=float(parent_lrs[1])*ramp*decay opt.param_groups[2]['lr']=C['new_head_lr']*ramp*decay with gpu_work(directory,'training'): admission=time.monotonic()-started;model.train();torch.cuda.reset_peak_memory_stats() metrics=train_step(model,opt,batch,u) progress.update(update=u+1,new_updates=n+1,epoch=batch['epoch'],next_step=batch['step']+1) for source,count in metrics['source_counts'].items(): exposures=progress.setdefault('r2_exposures',{});exposures[source]=exposures.get(source,0)+count if progress['update']%C['save_interval']==0 or n==0:checkpoint(last,model,opt,progress,bind) if progress['update'] in C['validation_updates']: snapshot=directory/('step_%06d.pt'%progress['update']) if progress['update']==target: checkpoint(snapshot,model,opt,progress,bind) else: # Intermediate evaluation weights do not claim optimizer # resume support. last.pt always retains complete state. torch.save(dict(architecture='CEIR_R3_inference_only',model=model.state_dict(),progress=progress,binding=bind),snapshot) metrics.update(update=progress['update'],new_updates=progress['new_updates'],arm=arm,attempt=attempt, data_wait_seconds=waiting,gpu_admission_seconds=admission,wall_seconds=time.monotonic()-started, backbone_lr=opt.param_groups[0]['lr'],A3_head_lr=opt.param_groups[1]['lr'],new_lr=opt.param_groups[2]['lr'],manifest_index=n,ledger_sha256=batch['ledger_sha256'],unix_time=time.time()) log(directory/'loss.jsonl',metrics) if n<3 or (n+1)%10==0: save(directory/'status.json',dict(phase='training',update=progress['update'],target_update=target,latest=metrics,unix_time=time.time())) print(json.dumps(dict(arm=arm,update=progress['update'],loss=metrics['loss'],seconds=metrics['wall_seconds'])),flush=True) if progress['update'] in C['validation_updates']: save(directory/'status.json',dict(phase='Validation',update=progress['update'],unix_time=time.time())) evaluate(model,arm,progress['update'],128 if progress['update']<target else None,directory/('step_%06d.pt'%progress['update'])) progress.setdefault('r2_validated',[]).append(progress['update']) with gpu_work(directory,'save_after_Validation'): if progress['update']==target: # Preserve the exact endpoint SHA used by Validation. # Validation completion is recorded in COMPLETE.json; a # recovery reuses its idempotent metrics, without updates. endpoint=directory/('step_%06d.pt'%target) alias=directory/'last.link.tmp' if alias.exists():alias.unlink() os.link(endpoint,alias);os.replace(alias,last) else:checkpoint(last,model,opt,progress,bind) if progress['update']>=target:break previous=time.monotonic() if progress['update']!=target:raise RuntimeError('Training exhausted before target') save(directory/'COMPLETE.json',dict(complete=True,source_update=C['source_update'],update=target,new_updates=target-C['source_update'], checkpoint=str(directory/('step_%06d.pt'%target)),validated=progress['r2_validated'],exposures=progress['r2_exposures'],unix_time=time.time())) save(directory/'status.json',dict(phase='completed',update=target,new_updates=target-C['source_update'],unix_time=time.time()))
if __name__=='__main__': p=argparse.ArgumentParser();p.add_argument('--arm',choices=C['arms'],required=True);a=p.parse_args() try:train(a.arm) except Exception: save(run_dir(a.arm)/'failure.json',dict(traceback=traceback.format_exc(),unix_time=time.time(),resume_checkpoint_preserved=True));raise123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109"""Unchanged official Validation, fixed numerical batching, all ranked scores."""from dataclasses import replaceimport gzipimport fcntlimport hashlibimport jsonimport timeimport torchfrom runtime_r2 import *from validation_ceir import metric,KS,FKSfrom specpartition_ms.chemistry import canonical_formula,formula_vector
def evaluate(model,arm,update,maximum_targets=None,checkpoint_path=None): label='validation_%06d'%update if maximum_targets is None else 'probe_%06d_%04d'%(update,maximum_targets) dest=evaluation_directory(arm,label) lock=(dest/'evaluation.lock').open('a+');fcntl.flock(lock,fcntl.LOCK_EX) protocol=dict(binding=binding(),arm=arm,update=update,maximum_targets=maximum_targets, checkpoint_sha256=sha(checkpoint_path) if checkpoint_path else C['parent_sha256'], spectrum_batch=C['validation_spectrum_batch'],graph_chunk=C['validation_graph_chunk'], local_chunk=C['validation_local_chunk'],candidate_policy='original_official_raw_entries_no_injection', structure_identity='key14',probe_selection='sha256(target)_ascending') path=dest/'protocol.json' if path.exists() and json.loads(path.read_text())!=protocol:raise RuntimeError('Validation binding changed') save(path,protocol) if (dest/'metrics.json').exists():return json.loads((dest/'metrics.json').read_text()) model.eval();old_gc,old_lc=model.graph_chunk,model.local_chunk model.graph_chunk=C['validation_graph_chunk'];model.local_chunk=C['validation_local_chunk'] db=readonly(LEGACY.PREP/'validation.sqlite');summary=[];started=time.monotonic() targets=[r[0] for r in db.execute('SELECT DISTINCT target FROM spectra ORDER BY target')] if maximum_targets is not None:targets=sorted(targets,key=lambda s:hashlib.sha256(s.encode()).digest())[:maximum_targets] for ti,target in enumerate(targets): output=dest/(hashlib.sha256(target.encode()).hexdigest()+'.json.gz') if output.exists(): with gzip.open(output,'rt') as f:summary.extend(json.load(f)['rows']) continue pools={v:json.loads(db.execute('SELECT body FROM pools WHERE target=? AND view=?',(target,v)).fetchone()[0]) for v in ('mass','formula')} aliases={s:db.execute('SELECT graph_key,identity,formula,error FROM aliases WHERE smiles=?',(s,)).fetchone() for s in set(sum(pools.values(),[]))} graphs={} for g,identity,formula,error in aliases.values(): if g is not None and g not in graphs:graphs[g]=loads(db.execute('SELECT body FROM graphs WHERE graph_key=?',(g,)).fetchone()[0]) keys=sorted(graphs);positions={g:i for i,g in enumerate(keys)};mols=[graphs[g] for g in keys] data=[loads(r[0]) for r in db.execute('SELECT body FROM spectra WHERE target=? ORDER BY identifier',(target,))] forms={} for v in ('mass','formula'): fs=set() for s in pools[v]: if aliases[s][2]: try:formula_vector(aliases[s][2]);fs.add(canonical_formula(aliases[s][2])) except ValueError:pass forms[v]=tuple(sorted(fs)) rows=[];ranked={} with gpu_work(dest,'Validation'),torch.inference_mode(),amp(): if mols:_,atoms,zm=model.encode_molecules(mols) for start in range(0,len(data),C['validation_spectrum_batch']): block=data[start:start+C['validation_spectrum_batch']] tokens,qs,_=model.spectrum.forward_batch([r['query'] for r in block]) views=[(i,v,replace(r['query'],formula_candidates=forms[v])) for i,r in enumerate(block) for v in ('mass','formula')] fs=model.formula_batch(torch.stack([qs[i] for i,_,_ in views]),[q for _,_,q in views],[tokens[i] for i,_,_ in views]) for vi,(i,v,q) in enumerate(views): r=block[i];selected=sorted({aliases[s][0] for s in pools[v] if aliases[s][0] is not None}) index=[positions[g] for g in selected];scores={} if index: values,_,_=model.score_encoded(qs[i],tokens[i],q,[graphs[g] for g in selected],[atoms[j] for j in index],zm[index],fs[vi]) if not torch.isfinite(values).all():raise RuntimeError('Nonfinite Validation score') scores=dict(zip(selected,values.float().cpu().tolist())) candidates=[dict(smiles=s,identity=aliases[s][1],formula=aliases[s][2],score=scores.get(aliases[s][0]), scoreable=aliases[s][0] in scores) for s in pools[v]] candidates.sort(key=lambda c:(not c['scoreable'],-c['score'] if c['scoreable'] else 0,c['identity'] or '',c['smiles'])) rank=next((j+1 for j,c in enumerate(candidates) if c['scoreable'] and c['identity']==r['identity']),None) fv=fs[vi].float().cpu().tolist();order=sorted(range(len(fv)),key=lambda j:(-fv[j],q.formula_candidates[j])) try:truth=canonical_formula(r['formula']);formula_vector(truth) except ValueError:truth=None frank=next((j+1 for j,k in enumerate(order) if q.formula_candidates[k]==truth),None) rows.append(dict(identifier=r['identifier'],target=target,view=v,reference_identity=r['identity'],reference_formula=truth, rank=rank,formula_rank=frank,candidate_count=len(candidates),formula_count=len(fv), unscoreable=sum(not c['scoreable'] for c in candidates),adduct=q.adduct,peak_count=len(q.peaks), collision_energy=q.collision_energy,instrument=q.instrument, reference_present_in_original_pool=any(c['identity']==r['identity'] for c in candidates), reference_scoreable=any(c['scoreable'] and c['identity']==r['identity'] for c in candidates), top1_smiles=candidates[0]['smiles'] if candidates and candidates[0]['scoreable'] else None)) ranked[r['identifier']+'/'+v]=dict(candidates=candidates,formulas=[dict(formula=q.formula_candidates[j],score=fv[j],rank=k+1) for k,j in enumerate(order)]) temporary=Path(str(output)+'.tmp') with gzip.open(temporary,'wt',compresslevel=3) as f:json.dump(dict(rows=rows,ranked=ranked),f,separators=(',',':')) temporary.replace(output);summary.extend(rows) save(dest/'status.json',dict(targets=ti+1,total=len(targets),spectral_views=len(summary),seconds=time.monotonic()-started,unix_time=time.time())) disk_check() metrics={} for view in ('mass','formula'): rr=[r for r in summary if r['view']==view] if maximum_targets is None and (len(rr)!=19429 or len({r['identifier'] for r in rr})!=19429):raise RuntimeError('Incomplete official Validation denominator') metrics[view]=dict(spectra=len(rr),structure=metric(rr,'rank',KS),formula=metric(rr,'formula_rank',FKS), original_pool_coverage=sum(r['reference_present_in_original_pool'] for r in rr),scoreable_coverage=sum(r['reference_scoreable'] for r in rr)) with gzip.open(dest/'per_spectrum_summary.json.gz','wt',compresslevel=3) as f:json.dump(summary,f,separators=(',',':')) x=metrics['mass']['structure']['1']['micro'];y=metrics['formula']['structure']['1']['micro'] metrics.update(complete=True,update=update,full_Validation=maximum_targets is None,selection_harmonic_Top1=2*x*y/max(1e-12,x+y), protocol=protocol,MCES='not_yet_computed_not_zero_filled',seconds=time.monotonic()-started) save(dest/'metrics.json',metrics);db.close();model.graph_chunk=old_gc;model.local_chunk=old_lc;model.train() return metrics
if __name__=='__main__': import argparse from model_r2_new import make_model_optimizer p=argparse.ArgumentParser();p.add_argument('--arm',choices=C['arms'],required=True);p.add_argument('--checkpoint');p.add_argument('--targets',type=int) a=p.parse_args();setup_gpu() with gpu_work(run_dir(a.arm),'restore_for_evaluation'):model,opt,progress,_=make_model_optimizer(a.arm,a.checkpoint) del opt evaluate(model,a.arm,progress['update'],a.targets,a.checkpoint)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768# R4: R3D 6k → 9k, four-arm matched continuation
Every arm starts from the same full R3D optimizer/model/RNG checkpoint`e14cfa3819ba33141f92202686e5b02c5b8d6668b55d5c56e01806ae85d6ef4e`.6,000 is the starting cumulative update, **not** the number of new steps:each arm must make exactly 3,000 successful updates and finish at 9,000. Adisposable warm GPU probe and official GPU acceptance steps are not counted.
| Arm | Candidate score | Objective added on top of R3D || --- | --- | --- || A | inherited R3D | none; optimizer and parent group LRs carried forward || B | inherited R3D | same-formula hard gap || C | R3D + bounded differential-peak pair residual | none || D | R3D + bounded differential-peak pair residual | same-formula hard gap |
The complete-parent score still exists for every candidate. The pair residualuses at most 32 model-selected distinct key14s, compares only rivals of thesame formula, and is initialized to exactly zero. It uses raw spectrum peaks,their aligned encoder tokens, molecular embeddings and the inherited fragmenthypotheses (not CSI rankings or identities as learned features). Equivalentaliases may share a residual, but the original official pool entries and ranksare preserved. B and D use detached **pre-duel** scores to identify up to threewrong key14s in each eligible same-formula competition; weight 0.1, margin 0.2.The inherited whole-pool CE is counted once. Other tasks and candidate drawsare identical. There is no test-set mining or test-based checkpoint selection.
## Execution and validation
- Remote code: `/root/xj/SpecPartition-MS/code/ceir_r4_9000_20261112`.- Logs, acceptance receipts, durable states, results: `/root/xj/SpecPartition-MS/runs/ceir_r4_9000_20261112`.- Rebuildable offline features, hot checkpoints: `/dev/shm/specpartition_r4_9000_20261112`.- Compact per-candidate float32 outputs: `/workspace/xj/SpecPartition-MS/runs/ceir_r4_compact_evaluations_20261112`. The hash-bound original pool defines the candidate index. The null mask, formula ordering, row metadata and exact raw-score hash are saved. No extra copy of the canonical candidate strings is needed.
The starting data cursor is **epoch 1, step 907 (zero-based)**; lastconsumed batch is epoch 1, step 3906. The shared immutable batch hash is`48c489b3cd16902afb2669ae0d65181206345fff1713771929f4ff9894db6edf`.The data preparation verified 4,626,599 distinct graph IDs, 96,000 MSG Trainspectrum exposures, 149,599 MS2-SAN exposures and 133,537 MSP exposures per arm.No evaluation labels or test candidate pools were introduced into the ledger.Of the group views, 96,000 are MSG Mass, 95,852 MSG Formula and 16,901 externalsame-formula pools. Counts are exposures, not counts of new unique spectra.
The supervisor queues paired GPU work on one 24-GiB RTX 4090; it does not runfour unconstrained CUDA contexts. All four arms first do a short *real* block,then rotate in blocks of at most 250 updates. Checkpoints include AdamW moments,RNG, ledger cursor and chain. Hot rolled states are replaced only after a newstate is saved; durable state copies are independently hash-checked. 7k and 8kare separately retained inference snapshots; 9k is a fully resumable endpoint.This is not a GitHub weight publication.
Release the result as **completed** only after `TRAIN_COMPLETE.json` exists foreach arm, independent ledger-chain/cursor checks pass, the full Validation,fixed Test and MCES results exist, and `ALL_RESULTS.json` is present. Trainingprogress or lower training loss alone is not evidence of better retrieval.Compare each arm against both A at the same update and the frozen 6k parent:all original MSG Validation views at 7k/8k/9k; predeclared 9k MSG Test andCASMI full-pool endpoints; paired wins, new failures, confidence intervals andvalid MCES denominators. Report ties/regressions explicitly.
The follow-up analysis script outside the frozen training release verifies allfour distinct 3,000-step ledgers and the raw endpoint comparisons. Before anynew full validation result was available, the effect audit was set to requirea positive fixed-endpoint Formula Top1 difference over A (key14-cluster bootstrap,one-sided lower bound adjusted for three prespecified arms), positive differenceover the 6k parent, Mass Top1/5/20 and Formula Top5/20 loss of no more than0.2 percentage points vs A, and per-view common-prediction MCES worsening ofat most 0.10 vs A. These are single-seed decision rules, not a guaranteeof efficacy or an instruction to continue tuning against the test split.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172"""Disposable real GPU steps; only the final *new-ledger* gate authorizes training."""import argparse,gcfrom dataclasses import replaceimport torchfrom common4 import *from model4 import make,setupfrom run4 import lease,atomic_torchfrom data4 import Batchesfrom objectives4 import train_stepdef acceptance(warm): if not warm and (OUT/'TRAIN_READY.json').exists() and get(OUT/'TRAIN_READY.json')['binding']==state_binding():return setup() if warm: from data_r2 import Dataset data=Dataset('R3D',0,30);bind={'probe':'historical real batch; no formal update'} else:data=Batches(0,30);bind=state_binding() for i in range(len(data)): batch=data[i] if len(batch['rows'])>=256 and all(any(p['kind']==kind for r in batch['rows'] for p in r['pools']) for kind in ['mass','formula','odata']):break else:raise RuntimeError('No full multi-source GPU acceptance batch') query=next(p['query'] for r in batch['rows'] for p in r['pools'] if p['kind']=='formula' and len(p['graphs'])>=3) with lease('acceptance'): from model_r2_new import make_model_optimizer parent_model,oldopt,_,_=make_model_optimizer('R3D',PARENT) del oldopt if not warm:parent_model.feature_store=data.store parent_model.eval() with torch.inference_mode(),rt.amp():expected=parent_model.encode_batch([query])[0][0].base.float().cpu() del parent_model;gc.collect();torch.cuda.empty_cache() arms={};bases={} for a in ('A','C','B','D'): model,opt,p=make(a,provisional=warm);model.eval() with torch.inference_mode(),rt.amp(): actual=model.encode_batch([query])[0][0].base.float().cpu() order=list(range(len(query.candidates)-1,-1,-1)) changed=replace(query,candidates=tuple(query.candidates[j] for j in order)) flipped=model.encode_batch([changed])[0][0].base.float().cpu() parity=float((actual-expected).abs().max());permutation=float((flipped-actual[order]).abs().max()) if parity>1e-5 or permutation>3e-4:raise RuntimeError(f'{a}: parent/permutation parity {parity} {permutation}') rt.restore_rng(parent());model.train();torch.cuda.reset_peak_memory_stats() m=train_step(model,opt,batch,6000) if not(m['backbone_gradient_norm']>0 and m['r3_gradient_norm']>0 and m['r4_gap_eligible']>0):raise RuntimeError('Inherited gradient or competing pool missing') if CFG['arms'][a]['gap']!=(m['r4_gap_loss']>0) or CFG['arms'][a]['duel']!=(m['r4_gradient_norm']>0):raise RuntimeError('Factorial gradient/mask mismatch: '+a) bases[a]=m['loss'];resume_error=None if a=='D' and not warm: import random,numpy as np snap=HOT/'acceptance'/'D_full_resume.pt' atomic_torch(snap,dict(architecture='CEIR_R4',arm=a,model=model.state_dict(),optimizer=opt.state_dict(),progress=dict(p,update=6001),binding=bind, torch_rng=torch.get_rng_state(),cuda_rng=torch.cuda.get_rng_state_all(),numpy_rng=np.random.get_state(),python_rng=random.getstate())) before=train_step(model,opt,batch,6001,False)['loss'] del model,opt;gc.collect();torch.cuda.empty_cache() model,opt,p=make(a,snap,expected_binding=bind);model.train() after=train_step(model,opt,batch,6001,False)['loss'];resume_error=abs(after-before) if resume_error>3e-4:raise RuntimeError('R4 continuation parity failed') arms[a]=dict(parent_score_error=parity,permutation_error=permutation,full_state_resume_loss_error=resume_error, metrics=m,parameter_count=sum(v.numel() for v in model.parameters()),groups=[len(g['params']) for g in opt.param_groups]) put(OUT/(('warm_' if warm else 'formal_')+'acceptance_'+a+'.json'),arms[a]) print(a,parity,permutation,m['loss'],m['r4_gradient_norm'],flush=True) del model,opt;gc.collect();torch.cuda.empty_cache() if abs(bases['A']-bases['C'])>3e-4 or abs(bases['B']-bases['D'])>3e-4:raise RuntimeError('Unequal initial factorial objectives') if not warm: from eval4 import acceptance_validation val=acceptance_validation(bind) else:val=None put(OUT/('EARLY_GPU_PROBE.json' if warm else 'TRAIN_READY.json'),dict(passed=True,formal_steps=0,binding=bind, batch_index=i,batch_sha=batch['ledger_sha256'],real_queries=len(batch['rows']),arms=arms,validation_adapter_probe=val,ts=time.time()))if __name__=='__main__': ap=argparse.ArgumentParser();ap.add_argument('--warm',action='store_true');a=ap.parse_args() try:acceptance(a.warm) except Exception: import traceback put(OUT/('EARLY_GPU_ERROR.json' if a.warm else 'GPU_ERROR.json'),dict(error=traceback.format_exc(),ts=time.time()));raise123456789101112131415161718192021222324252627282930313233343536373839404142434445"""R4 owns only its timestamped paths. Imports the immutable R3 implementation."""import os,sys,json,time,hashlib,gzip,fcntl,shutil,tempfile,sqlite3from pathlib import PathHERE=Path(__file__).resolve().parentCFG=json.loads((HERE/'config.json').read_text());OUT=Path(CFG['output']);HOT=Path(CFG['scratch'])R3=Path(CFG['r3_root']);R2=Path(CFG['r2_root']);PARENT=R3/CFG['parent']sys.path.insert(0,CFG['r3_code'])import runtime_r2 as rtimport features_r2 as ftsys.path.insert(0,str(HERE))def digest(b):return hashlib.sha256(b).hexdigest()def filehash(p): h=hashlib.sha256() with Path(p).open('rb') as f: for b in iter(lambda:f.read(2**20),b''):h.update(b) return h.hexdigest()def objhash(o):return digest(json.dumps(o,sort_keys=True,separators=(',',':')).encode())def put(p,o): p=Path(p);p.parent.mkdir(parents=True,exist_ok=True) t=p.with_name(p.name+'.'+str(os.getpid())+'.tmp');t.write_text(json.dumps(o,ensure_ascii=False,allow_nan=False,indent=1)+'\n');os.replace(t,p)def get(p):return json.loads(Path(p).read_text())def event(p,o): p=Path(p);p.parent.mkdir(parents=True,exist_ok=True) with p.open('a') as f:f.write(json.dumps(dict(o,timestamp=time.time()),separators=(',',':'),allow_nan=False)+'\n')def ro(path): return sqlite3.connect('file:'+str(path)+'?mode=ro',uri=True,timeout=60)def lock(p): p=Path(p);p.parent.mkdir(parents=True,exist_ok=True);f=p.open('a+');fcntl.flock(f,fcntl.LOCK_EX|fcntl.LOCK_NB);return fdef parent(): import torch if filehash(PARENT)!=CFG['parent_sha256']:raise RuntimeError('R3D parent hash mismatch') x=torch.load(PARENT,map_location='cpu',weights_only=False) if x['architecture']!='CEIR_R3' or x['progress']['update']!=6000 or x['binding']['original_data']!=rt.LEGACY.bind(): raise RuntimeError('Wrong parent state or data binding') return xdef prep_root():return HOT/'prepared'def scratch_check(): HOT.mkdir(exist_ok=True,parents=True) if shutil.disk_usage(HOT).free<2*2**30:raise RuntimeError('R4 scratch reserve <2GiB; preserving all outputs')def state_binding(): gate=get(OUT/'DATA_READY.json') if not (prep_root()/'READY.json').is_file() or get(prep_root()/'READY.json')!=gate:raise RuntimeError('Cold or incomplete R4 cache') return dict(config=filehash(HERE/'config.json'),parent=CFG['parent_sha256'],ledger=gate['ledger_hash'], code={p.name:filehash(p) for p in sorted(HERE.glob('*.py')) if not p.name.startswith('.')}, original_r3=get(R3/'R3D/provenance.json')['binding']['code'])123456789101112131415161718192021{ "experiment": "CEIR_R4_9000_20261112", "r3_code": "/root/xj/SpecPartition-MS/code/ceir_r3_20261110", "r3_root": "/root/xj/SpecPartition-MS/runs/ceir_r3_20261110", "r2_root": "/root/xj/SpecPartition-MS/runs/ceir_r2_20261110", "output": "/root/xj/SpecPartition-MS/runs/ceir_r4_9000_20261112", "scratch": "/dev/shm/specpartition_r4_9000_20261112", "parent_sha256": "e14cfa3819ba33141f92202686e5b02c5b8d6668b55d5c56e01806ae85d6ef4e", "parent": "R3D/step_006000.pt", "source_update": 6000, "additional_updates": 3000, "target_update": 9000, "checkpoints": [7000,8000,9000], "seed": 20261103, "hot_interval": 50, "durable_interval": 200, "arms": {"A":{"gap":false,"duel":false},"B":{"gap":true,"duel":false},"C":{"gap":false,"duel":true},"D":{"gap":true,"duel":true}}, "gap":{"weight":0.10,"margin":0.2,"hard_k":3}, "duel":{"n":32,"hidden":64,"cap":1.0}, "learning_rate":{"existing":"constant inherited R3D e6 endpoint group LRs, all arms identical","new_head":0.0001,"new_warmup":100}, "validation":"Full official MSG Validation, separate untouched Mass and Formula views at 7000, 8000, 9000. Baseline full 6000 reused.", "selection":"At fixed 9000 compare to matched A; primary full Validation Formula Hit@1. Report wins, harms, target-key14 paired intervals, Mass, Formula, Top-K, MCES and formula guardrails; no Test selection.", "heldout_evaluation":"All four fixed endpoints, original MSG Test Mass and Formula and uncapped CASMI blind full pool, post-hoc MCES; no truth injection.", "max_training_processes":2, "gpu_fraction":0.42, "free_before_job_mib":5800, "locals_on_tmpfs":true, "upload_new_weights":false}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061from collections import Counterfrom dataclasses import replacefrom functools import lru_cachefrom common4 import *from data09 import Reader,loads
class Fragments: """No test features opened during training. D arm never uses R3H distances.""" def __init__(self,split='train',extra=None): self.sources=[] if extra is not None:self.sources.append((ro(extra),'SELECT b,h FROM extra WHERE k=?')) for parent,table,where in [(R2,'canonical_features','prepared'),(R3,'r3_features','prepared')]: self.sources.append((ro(parent/where/'assets.sqlite'),f'SELECT feature,feature_sha FROM {table} WHERE feature_key=?')) if split=='test': for parent in (R2,R3): db=ro(parent/'test/prepared/assets.sqlite') ts={v[0] for v in db.execute("SELECT name FROM sqlite_master WHERE type='table'")} t=next(t for t in ('canonical_features','r3_features','molecules') if t in ts) self.sources.append((db,'SELECT feature,feature_sha FROM '+t+' WHERE feature_key=?')) self.get=lru_cache(maxsize=4096)(self.fetch) def fetch(self,smiles): k=ft.key(smiles) for db,sql in self.sources: row=db.execute(sql,(k,)).fetchone() if row is None or row[0] is None:continue b,h=row if not ft.digest_matches(b,h):raise RuntimeError('Static fragment digest mismatch') obj=ft.loads(b) if obj['smiles']!=smiles or obj['version']!=ft.VERSION:raise RuntimeError('Static feature identity/version changed') return obj raise RuntimeError('Missing precomputed fragment data: '+k)
class Batches: def __init__(self,start=0,stop=3000,provisional=False): self.start=start;self.stop=stop;self.reader=None;self.provisional=provisional def __len__(self):return self.stop-self.start def __getitem__(self,j): start=time.monotonic();n=self.start+j if not self.reader: self.reader=Reader();self.store=Fragments('train',prep_root()/'delta.sqlite' if not self.provisional else None) self.hashes=None if self.provisional else get(prep_root()/'hashes.json') blob=(prep_root()/'batches'/('%04d.z'%n)).read_bytes();h=digest(blob) if self.hashes and h!=self.hashes[n]:raise RuntimeError('Changed ledger block') plan=ft.loads(blob);rows=[];rdr=self.reader for sel in plan['rows']: row=loads(rdr.db.execute('SELECT body FROM samples WHERE record_id=?',(sel['rid'],)).fetchone()[0]);ref=rdr.molecule(sel['ref']) if ref.identity!=row['identity'] or ref.identity!=sel['identity'] or ref.identity in rdr.forbidden:raise ValueError('Training identity/holdout check failed') row.update(ref=ref,formulas=sel['formulas'],pools=[]);row['query']=replace(row['query'],formula_candidates=row['formulas']) feature=self.store.get(ref.smiles) if ft.layout(ref.mol)!=feature['layout']:raise ValueError('Atom order mismatch') row['chemical_counts']=feature['counts'] for p in sel['pools']: ms=tuple(rdr.molecule(g) for g in p['graphs']) if [m.identity for m in ms]!=p['ids'] or ms[0].identity!=ref.identity or len(set(p['ids']))!=len(ms):raise ValueError('False negative/alias') kind=p['kind'];q=replace(row['query'],candidates=ms,formula_candidates=tuple(p['formulas']), candidate_view='odata_oracle' if kind=='odata' else 'msg_'+kind) eligible=bool(row['mass_ok'] and ft.supported_positive(q,self.store.get(ms[0].smiles))) row['pools'].append(dict(**p,query=q,positive_index=0,truth_identity=ref.identity,truth_formula=row['formula'], record_id=row['record_id'],quality_eligible=bool(row['mass_ok']),spectrum_eligible=eligible)) rows.append(row) return dict(rows=rows,manifest_index=n,ledger_sha256=h,epoch=plan['epoch'],step=plan['step'],data_seconds=time.monotonic()-start)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273"""Experimental CSI-free evidence reranker. One original pool per call.
peak_support[i,p] is label-free, adduct-aware candidate fragment support onobserved peak p (in [0,1]); it must come from the spectrum forward path.No reference, CID, CSI score, or stored row position is a model input."""import torchfrom torch import nnfrom torch.nn import functional as F
class CandidateDuels(nn.Module): def __init__(self, query_dim=256, molecule_dim=256, hidden=64, max_competitors=32, residual_cap=1.0): super().__init__();self.max_competitors=max_competitors;self.cap=residual_cap self.q=nn.Linear(query_dim,hidden);self.m=nn.Linear(molecule_dim,hidden) self.peak_reliability=nn.Sequential(nn.Linear(query_dim+2,hidden),nn.SiLU(),nn.Linear(hidden,1)) nn.init.zeros_(self.peak_reliability[-1].weight);nn.init.zeros_(self.peak_reliability[-1].bias) self.duel=nn.Sequential(nn.Linear(2*hidden+4,hidden),nn.SiLU(),nn.Linear(hidden,1)) nn.init.zeros_(self.duel[-1].weight);nn.init.zeros_(self.duel[-1].bias)
def forward(self,base,query,molecules,formula_ids,stable_ids,peak_support,intensity,peak_context=None): # Supply only finite/scorable candidates. Unscoreables remain in the external evaluator. n=len(base) if base.ndim!=1 or molecules.shape[0]!=n or peak_support.shape!=(n,len(intensity)) or formula_ids.shape!=(n,) or stable_ids.shape!=(n,):raise ValueError('mismatched pool') if not (torch.isfinite(base).all() and torch.isfinite(peak_support).all() and torch.isfinite(intensity).all()):raise ValueError('nonfinite input') if stable_ids.unique().numel()!=n:raise ValueError('deduplicate connectivity before pair competition; keep alias mapping') if n<2 or not len(intensity):return base # Content-derived deterministic ID for exact ties only; never embed it. t=stable_ids.argsort(stable=True) idx=t[base[t].detach().argsort(descending=True,stable=True)[:self.max_competitors]] h=self.m(molecules[idx]);q=self.q(query).view(1,1,-1).expand(len(idx),len(idx),-1) support=peak_support[idx].clamp(0,1) w=intensity.clamp_min(0).sqrt();w=w/w.sum().clamp_min(1e-8) if peak_context is not None: if peak_context.shape!=(len(w),query.numel()) or not torch.isfinite(peak_context).all(): raise ValueError('expected one aligned encoder token per observed peak') # Common matches are less diagnostic; learn reliability from aligned # spectrum tokens, measured intensity, and the support prevalence. # No truth, winner ID, CSI rank, or supervised peak annotation. a=torch.cat((peak_context,w[:,None],support.mean(0)[:,None]),dim=-1) rel=self.peak_reliability(a).squeeze(-1).sigmoid() w=w*rel exclusive=(support[:,None,:]-support[None,:,:]).clamp_min(0) own=(exclusive*w).sum(-1);other=own.T evidence=torch.stack((own,other,own-other,own+other),dim=-1) f=self.duel(torch.cat((q,h[:,None,:]-h[None,:,:],evidence),dim=-1)).squeeze(-1) vote=(f-f.T).tanh() # d_ij = -d_ji same=formula_ids[idx,None]==formula_ids[idx][None,:] eligible=same & ~torch.eye(len(idx),dtype=torch.bool,device=base.device) & (formula_ids[idx,None]>=0) gated=(own+other).clamp(0,1)*vote*eligible # exactly neutral if no discriminating peak residual=self.cap*gated.sum(1)/eligible.sum(1).clamp_min(1) return base.index_add(0,idx,residual.to(base.dtype))
def pool_objective(final,base,formula_ids,identities,truth_identity,margin=.2,hard_k=3,temperature=1.): """Reference is used here only. Aliases share probability mass; no false-negative stereoisomers.""" y=identities==truth_identity zero=final.sum()*0 if not y.any() or not (~y).any():return zero,zero,{'pool_ce':0,'same_formula_gap':0} if formula_ids[y].unique().numel()!=1:raise ValueError('conflicting positive formula') if temperature<=0:raise ValueError('temperature must be positive') logits=final/temperature pos=logits[y].logsumexp(0) ce=logits.logsumexp(0)-pos negatives=(~y)&(formula_ids==formula_ids[y][0])&(formula_ids>=0) if not negatives.any():return ce,zero,{'pool_ce':1,'same_formula_gap':0} indices=negatives.nonzero().flatten() # At most one representative per rival identity. Selection detached and training-only. reprs=[] for k in identities[indices].unique(): g=indices[identities[indices]==k];reprs.append(g[base[g].detach().argmax()]) ix=torch.stack(reprs);ix=ix[base[ix].detach().topk(min(hard_k,len(ix))).indices] best_positive=final[y].max() gap=F.softplus(margin+final[ix]-best_positive).mean() return ce,gap,{'pool_ce':1,'same_formula_gap':1}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161"""Exact raw official pools; compact float32 scores, stable raw order, null mask.All rankings, reference labels and MCES inputs are computed AFTER model.forward."""import argparse,sqlite3,zlib,struct,mathfrom dataclasses import replaceimport torchimport numpy as npfrom common4 import *from model4 import setup,makefrom run4 import leasefrom data09 import loadsfrom validation_ceir import KS,FKS,metricfrom specpartition_ms.chemistry import canonical_formula,formula_vectorEVAL_CODE=Path('/root/xj/SpecPartition-MS/code/ceir_r1_test_comparison_20261110')sys.path.insert(0,str(EVAL_CODE))import infer as engineengine.C=dict(engine.C,spectrum_batch=16,graph_chunk=32,local_chunk=32)EVAL=Path(rt.C['root'])/'runs'/'ceir_r4_compact_evaluations_20261112'def target_val(model,db,target): pools={v:json.loads(db.execute('SELECT body FROM pools WHERE target=? AND view=?',(target,v)).fetchone()[0]) for v in ('mass','formula')} aliases={s:tuple(db.execute('SELECT graph_key,identity,formula,error FROM aliases WHERE smiles=?',(s,)).fetchone()) for s in set(sum(pools.values(),[]))} graphs={g:loads(db.execute('SELECT body FROM graphs WHERE graph_key=?',(g,)).fetchone()[0]) for g in sorted({a[0] for a in aliases.values() if a[0] is not None})} keys=sorted(graphs);positions={g:i for i,g in enumerate(keys)} data=[loads(r[0]) for r in db.execute('SELECT body FROM spectra WHERE target=? ORDER BY identifier',(target,))] forms={} for v in pools: ff=set() for s in pools[v]: f=aliases[s][2] if f: try:formula_vector(f);ff.add(canonical_formula(f)) except ValueError:pass forms[v]=tuple(sorted(ff)) values=[{} for r in data];fvals=[{} for r in data] with torch.inference_mode(),rt.amp(): if keys:_,atoms,zm=model.encode_molecules([graphs[k] for k in keys]) for start in range(0,len(data),16): block=data[start:start+16];tokens,qs,_=model.spectrum.forward_batch([r['query'] for r in block]) views=[(i,v,replace(r['query'],formula_candidates=forms[v])) for i,r in enumerate(block) for v in ('mass','formula')] fs=model.formula_batch(torch.stack([qs[i] for i,_,_ in views]),[q for _,_,q in views],[tokens[i] for i,_,_ in views]) for vi,(i,v,q) in enumerate(views): selected=sorted({aliases[s][0] for s in pools[v] if aliases[s][0] is not None});ii=[positions[g] for g in selected];scores={} if selected: vls,_,_=model.score_encoded(qs[i],tokens[i],q,[graphs[g] for g in selected],[atoms[j] for j in ii],zm[ii],fs[vi]) scores=dict(zip(selected,vls.float().cpu().tolist())) values[start+i][v]=scores;fvals[start+i][v]=fs[vi].float().cpu().tolist() aliases={s:(a[0],a[1],a[2],None,None,a[3]) for s,a in aliases.items()} return pools,aliases,forms,data,values,fvals,[None]*len(data)def target_test(model,db,target,dataset): pools,aliases,forms,sources=engine.universe(db,target,dataset) data=[loads(r[0]) for r in db.execute('SELECT body FROM spectra WHERE target=? ORDER BY identifier',(target,))] values,fvals,errors=engine.score_group(model,db,data,pools,aliases,forms) return pools,aliases,forms,data,values,fvals,errorsdef table(model,db,target,dataset): val=dataset=='validation' pools,aliases,forms,data,values,fvals,errors=target_val(model,db,target) if val else target_test(model,db,target,dataset) rows=[];buffers=[];nfloat=0;static={v:objhash(list(pool)) for v,pool in pools.items()} for i,r in enumerate(data): for v,pool in pools.items(): vv=[values[i][v].get(aliases[s][0]) for s in pool] if any(x is not None and not math.isfinite(x) for x in vv):raise RuntimeError('Nonfinite compact score') arr=np.asarray(vv,dtype='<f4');order=sorted(range(len(pool)),key=lambda j:(vv[j] is None,-vv[j] if vv[j] is not None else 0.,aliases[pool[j]][1] or '',pool[j])) def rank(k,ref):return next((z+1 for z,j in enumerate(order) if vv[j] is not None and ref is not None and aliases[pool[j]][k]==ref),None) truth=engine.supported_formula(r['formula']);fs=fvals[i][v];fs=list(fs) if any(not math.isfinite(x) for x in fs):raise RuntimeError('Nonfinite formula score') fo=sorted(range(len(fs)),key=lambda j:(-fs[j],forms[v][j])) row=dict(identifier=r['identifier'],target=target,view=v,reference_identity=r['identity'], reference_smiles=r.get('reference_smiles') or target,reference_formula=truth, rank=rank(1,r['identity']),formula_rank=next((j+1 for j,k in enumerate(fo) if forms[v][k]==truth),None), candidate_count=len(vv),formula_count=len(forms[v]),scored_formulas=len(fs), reference_in_pool=any(aliases[s][1]==r['identity'] for s in pool), reference_scoreable_in_pool=any(vv[j] is not None and aliases[s][1]==r['identity'] for j,s in enumerate(pool)), top1_smiles=pool[order[0]] if order and vv[order[0]] is not None else None, unscoreable=sum(x is None for x in vv),adduct=r['query'].adduct, polarity='negative' if r['query'].adduct.endswith('-') else 'positive', peak_count=len(r['query'].peaks),collision_energy=r['query'].collision_energy,instrument=r['query'].instrument, query_error=errors[i],float_offset=nfloat) if not val: ref=db.execute('SELECT canonical,fullkey FROM aliases WHERE smiles=?',(r['reference_smiles'],)).fetchone() if ref is None:raise RuntimeError('Missing evaluation reference alias') row.update(canonical_rank=rank(3,ref[0]),inchikey_rank=rank(4,ref[1])) if (row['rank'] is not None)!=row['reference_scoreable_in_pool']:raise RuntimeError('Invalid rank/mask') buffers.append(arr.tobytes());buffers.append(np.array(fs,dtype='<f4').tobytes());nfloat+=len(arr)+len(fs);rows.append(row) raw=b''.join(buffers);assert len(raw)==4*nfloat meta=dict(target=target,pool_order_hash=static,formula_names=forms,rows=rows,score_sha256=digest(raw)) return meta,rawdef dbpath(dataset):return rt.LEGACY.PREP/'validation.sqlite' if dataset=='validation' else engine.PREP/(dataset+'.sqlite')def acceptance_validation(bind): with lease('validation_preflight'): model,_,_=make('D',split='validation',optimizer=False);model.graph_chunk=32;model.local_chunk=32;model.eval() db=ro(dbpath('validation'));target=db.execute('SELECT DISTINCT target FROM spectra ORDER BY target LIMIT 1').fetchone()[0] meta,raw=table(model,db,target,'validation') source=R3/'R3D/validation_006000'/(digest(target.encode())+'.json.gz') with gzip.open(source,'rt') as f:prior=json.load(f) vals=np.frombuffer(raw,dtype='<f4');n=0;mx=0. for row,old in zip(meta['rows'],prior['rows'],strict=True): for k in ['identifier','view','rank','formula_rank','candidate_count','top1_smiles']: if row[k]!=old[k]:raise RuntimeError('Frozen Validation parity mismatch: '+k) v=row['view'];pool=json.loads(db.execute('SELECT body FROM pools WHERE target=? AND view=?',(target,v)).fetchone()[0]) expected={c['smiles']:c['score'] for c in prior['ranked'][row['identifier']+'/'+v]['candidates']} actual=vals[row['float_offset']:row['float_offset']+len(pool)] for s,x in zip(pool,actual): if (expected[s] is None)!=bool(np.isnan(x)):raise RuntimeError('Scorability drift') if expected[s] is not None:mx=max(mx,abs(expected[s]-float(x)));n+=1 if mx>1e-5 or not n:raise RuntimeError('Numerical validation parity mismatch: '+str(mx)) db.close();return dict(passed=True,targets=1,rows=len(meta['rows']),scored_comparisons=n,max_error=mx,checkpoint_sha=CFG['parent_sha256'])def eval_dir(arm,update,dataset):return OUT/arm/('%s_%06d'%(dataset,update))def run(arm,update,dataset): dest=eval_dir(arm,update,dataset);hold=lock(dest/'eval.lock');bind=state_binding() if dataset!='validation' and (update!=9000 or not (OUT/'FROZEN_TEST.json').exists()):raise RuntimeError('Test is not frozen') ck=OUT/arm/('step_%06d.pt'%update);check=get(ck.with_suffix('.json')) if check['sha256']!=filehash(ck):raise RuntimeError('Invalid evaluation checkpoint') protocol=dict(dataset=dataset,arm=arm,update=update,checkpoint_sha=check['sha256'],binding_sha=objhash(bind), encoding='Per target: float32 little-endian in source order; NaN means no score; formulas follow each structure block. No pruning or substitution.', input_path=str(dbpath(dataset)),official_order_hash_per_target=True, fixed_input=engine.inputs(dataset) if dataset!='validation' else rt.LEGACY.bind(),truth_injection=False,limit=None) if (dest/'protocol.json').exists() and protocol!=get(dest/'protocol.json'):raise RuntimeError('Mixed evaluation binding') put(dest/'protocol.json',protocol) if (dest/'metrics.json').exists():return EVAL.mkdir(parents=True,exist_ok=True) compact=EVAL/arm/('%s_%06d.sqlite'%(dataset,update));compact.parent.mkdir(parents=True,exist_ok=True) out=sqlite3.connect(compact);out.execute('PRAGMA journal_mode=WAL');out.execute('CREATE TABLE IF NOT EXISTS predictions(target TEXT PRIMARY KEY,meta BLOB, scores BLOB) WITHOUT ROWID') out.execute('CREATE TABLE IF NOT EXISTS binding(hash TEXT PRIMARY KEY)') oid=objhash(protocol);old=out.execute('SELECT hash FROM binding').fetchall() if old and old!=[(oid,)]:raise ValueError('Stale compact predictions') out.execute('INSERT OR IGNORE INTO binding VALUES(?)',(oid,));out.commit() db=ro(dbpath(dataset));targets=[x[0] for x in db.execute('SELECT DISTINCT target FROM spectra ORDER BY target')] done={k[0] for k in out.execute('SELECT target FROM predictions')};assert done<=set(targets) with lease('eval_'+arm): setup();model,_,_=make(arm,ck,split='validation' if dataset=='validation' else 'test',optimizer=False,expected_binding=bind);model.eval() model.graph_chunk=32;model.local_chunk=32 for j,target in enumerate(targets): if target in done:continue if j%40==0 and shutil.disk_usage(compact.parent).free<75*2**20:raise RuntimeError('Compact output filesystem reserve; source unchanged') meta,raw=table(model,db,target,dataset) out.execute('INSERT INTO predictions VALUES(?,?,?)',(target,zlib.compress(json.dumps(meta,separators=(',',':'),allow_nan=False).encode(),3),zlib.compress(raw,3))) if j%16==0:out.commit();put(dest/'status.json',dict(targets=j+1,total=len(targets),ts=time.time())) out.commit() rows=[] for m,s in out.execute('SELECT meta,scores FROM predictions ORDER BY target'): v=json.loads(zlib.decompress(m));raw=zlib.decompress(s) if digest(raw)!=v['score_sha256'] or len(raw)!=4*sum(r['candidate_count']+r['scored_formulas'] for r in v['rows']):raise RuntimeError('Compact output integrity error') rows.extend(v['rows']) out.execute('PRAGMA wal_checkpoint(TRUNCATE)');out.close();db.close() expected={'msg_test':17556,'validation':19429,'casmi2022':500}[dataset];views=sorted({r['view'] for r in rows}) assert len(rows)==expected*len(views) and set(views)==({'top10_blind'} if dataset=='casmi2022' else {'mass','formula'}) if dataset=='casmi2022':assert sum(r['candidate_count'] for r in rows)==1765420 and sum(r['reference_in_pool'] for r in rows)==467 results={} for v in views: rr=[r for r in rows if r['view']==v];assert len(rr)==len({r['identifier'] for r in rr})==expected results[v]=dict(n=expected,structure=metric(rr,'rank',KS),formula=metric(rr,'formula_rank',FKS), coverage=sum(r['reference_in_pool'] for r in rr),scoreable=sum(r['reference_scoreable_in_pool'] for r in rr)) if dataset!='validation': results[v].update(canonical=metric(rr,'canonical_rank',KS),full_inchikey=metric(rr,'inchikey_rank',KS)) tmp=dest/'rows.tmp.gz' with gzip.open(tmp,'wt',compresslevel=4) as f:json.dump(rows,f,separators=(',',':'),allow_nan=False) os.replace(tmp,dest/'per_spectrum_summary.json.gz') put(dest/'metrics.json',dict(complete=True,results=results,checkpoint=check,compact=str(compact),compact_sha256=filehash(compact),ts=time.time()))if __name__=='__main__': ap=argparse.ArgumentParser();ap.add_argument('arm',choices=list(CFG['arms']));ap.add_argument('update',type=int);ap.add_argument('dataset',choices=['validation','msg_test','casmi2022']) a=ap.parse_args();run(a.arm,a.update,a.dataset)123456789101112131415161718192021222324252627"""Dedicated CPU environment; inherited validated MCES protocols, private caches only."""import argparse,fcntl,importlib.util,json,os,sqlite3,sysfrom pathlib import PathHERE=Path(__file__).resolve().parent;C=json.loads((HERE/'config.json').read_text())OUT=Path(C['output']);R3=Path(C['r3_root'])def load(name,p): s=importlib.util.spec_from_file_location(name,p);m=importlib.util.module_from_spec(s);sys.modules[name]=m;s.loader.exec_module(m);return mdef copydb(src,dst): if dst.exists():return tmp=dst.with_suffix('.pending') a=sqlite3.connect('file:'+str(src)+'?mode=ro',uri=True);b=sqlite3.connect(tmp);a.backup(b);a.close();b.close();os.replace(tmp,dst)def run(arm,u,dataset): dest=OUT/arm/('%s_%06d'%(dataset,u)) cache=OUT/'mces_private';cache.mkdir(exist_ok=True);fd=(cache/'serial.lock').open('a+');fcntl.flock(fd,fcntl.LOCK_EX) if (dest/'MCES.json').exists():return if not (dest/'metrics.json').exists():raise RuntimeError('Missing full ranking result') if dataset=='validation': m=load('frozen_R4_val_mces',Path('/root/xj/SpecPartition-MS/code/ceir_r1_20261109/mces_ceir.py')) m.OUT=OUT;m.CACHE=cache;copydb(R3/'mces_validation/Validation_mces_pairs.sqlite',cache/'Validation_mces_pairs.sqlite');m.evaluate(dest) else: m=load('frozen_R4_test_mces',Path('/root/xj/SpecPartition-MS/code/ceir_r1_test_comparison_20261110/mces.py')) m.OUT=cache;m.old.OUT=cache/'mces';m.old.OUT.mkdir(exist_ok=True) copydb(R3/'test/mces/pairs.sqlite',m.old.OUT/'pairs.sqlite') db=m.initialize();m.compute(dest,db);db.close()if __name__=='__main__': p=argparse.ArgumentParser();p.add_argument('arm',choices=list(C['arms']));p.add_argument('update',type=int);p.add_argument('dataset',choices=['validation','msg_test','casmi2022']) a=p.parse_args();run(a.arm,a.update,a.dataset)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117"""Base R3D scores for every candidate, with optional bounded pair evidence."""import gcimport numpy as npimport torchfrom torch.nn import functional as Ffrom common4 import *from data4 import Fragmentsfrom model_r2_new import R2Rankerfrom duel4 import CandidateDuels
def setup(): torch.set_num_threads(1);torch.set_float32_matmul_precision('high');torch.use_deterministic_algorithms(True) torch.cuda.set_per_process_memory_fraction(CFG['gpu_fraction']);rt.LEGACY.seed_all(CFG['seed'])
def true_peak_support(assets,query,peak_tokens,max_peaks): raw=sorted(sorted(query.peaks,key=lambda p:(-p[1],p[0]))[:max_peaks]) if len(raw)!=len(peak_tokens) or max_peaks!=256:raise ValueError('R4 token to original peak alignment mismatch') dev=peak_tokens.device p=torch.as_tensor(raw,dtype=torch.float32,device=dev) mz=p[:,0].contiguous();y=p[:,1].clamp_min(0) y=y.masked_fill((mz-query.precursor_mz).abs()<=max(.05,query.precursor_mz*20e-6),0) offsets=[v for v in ft.ion_offsets(query.adduct) if v is not None] if not offsets:return mz.new_zeros((len(assets),len(mz))),y to=lambda k:torch.as_tensor(np.stack([a[k] for a in assets]),device=dev) m=to('masses').float();h=to('hydrogens');valid=to('valid').bool();shift=m.new_tensor([-2,-1,0,1,2]) f=m[:,:,None,None]+shift[None,None,:,None]*ft.H+m.new_tensor(offsets)[None,None,None,:] mask=valid[:,:,None,None]&(h[:,:,None,None]+shift[None,None,:,None]>=0)&f.gt(0) ordered=f.masked_fill(~mask,float('inf')).flatten(1).sort(1).values.contiguous() grid=mz[None,:].expand(len(assets),-1).contiguous() j=torch.searchsorted(ordered,grid);ix=j.clamp(max=ordered.shape[1]-1);ix2=(j-1).clamp(min=0,max=ordered.shape[1]-1) def matched(idx): x=ordered.gather(1,idx) return x.isfinite() & ((grid-x).abs()<=torch.maximum(.00002*x,mz.new_tensor(.02))) return ((matched(ix)|matched(ix2))&(y>0)).float(),y
class Model(R2Ranker): def __init__(self,arm): super().__init__(rt.LEGACY.C,'R3D') # always execute all inherited R3D branches and losses self.r4_arm=arm;self.has_duel=CFG['arms'][arm]['duel'];self._trace=None if self.has_duel: self.r4=CandidateDuels(256,256,CFG['duel']['hidden'],CFG['duel']['n'],CFG['duel']['cap']) def install_store(self,split,provisional=False): self.feature_store=Fragments(split,prep_root()/'delta.sqlite' if split=='train' and not provisional else None) def encode_batch(self,queries,extras=()): self._trace=[] try: encs,u=super().encode_batch(queries,extras) for enc,(base,info) in zip(encs,self._trace,strict=True): enc.r4_base=base;enc.r4_info=info return encs,u finally:self._trace=None def score_encoded(self,q,peaks,query,mols,atoms,zm,formula_scores,context=None,return_aux=False): orig=super().score_encoded(q,peaks,query,mols,atoms,zm,formula_scores,context,return_aux) base=orig[0];final=base;info=None if self.has_duel and len(mols)>1: # Choose the best base-scored representative per identity. Exact ties # use stable structure/SMILES content. All original aliases retain # their scores and receive the same identity-level residual. ids=[m.identity for m in mols];forms=[m.formula for m in mols] if not all(ids):raise ValueError('Scoreable graph without structure identity') base_np=base.detach().float().cpu().numpy() reps={} for j,k in enumerate(ids): old=reps.get(k) if old is None or (-base_np[j],mols[j].smiles)<(-base_np[old],mols[old].smiles):reps[k]=j if old is not None and forms[old]!=forms[j]:raise ValueError('Aliased identity with conflicting formula') chosen=sorted(reps.values(),key=lambda i:(-base_np[i],ids[i]))[:CFG['duel']['n']] selected=[mols[i] for i in chosen];fs=sorted({m.formula for m in selected}) fi=torch.tensor([fs.index(m.formula) for m in selected],device=q.device) ii=torch.tensor(chosen,device=q.device) si={v:i for i,v in enumerate(sorted(m.identity for m in selected))} stable=torch.tensor([si[m.identity] for m in selected],device=q.device) assets=[self.feature(m) for m in selected] with torch.no_grad():support,y=true_peak_support(assets,query,peaks,self.spectrum.max_peaks) with torch.autocast(q.device.type,enabled=False): loc=self.r4(base[ii].float(),q.float(),zm[ii].float(),fi,stable,support,y,peaks.float()) delta=loc-base[ii].float() if len(reps)==len(mols): final=base.float().index_add(0,ii,delta) else: positions={m.identity:i for i,m in enumerate(selected)};n=len(chosen) mapping=torch.tensor([positions.get(x,n) for x in ids],device=q.device);final=base.float()+F.pad(delta,(0,1))[mapping] if self._trace is not None:info=(delta.abs().mean().detach(),len(chosen)) if self._trace is not None:self._trace.append((base.detach(),info)) return (final,*orig[1:])
def make(arm,path=None,split='train',provisional=False,optimizer=True,expected_binding=None): if arm not in CFG['arms']:raise ValueError(arm) state=parent() if path is None else torch.load(path,map_location='cpu',weights_only=False) if path is not None and (state.get('architecture')!='CEIR_R4' or state['arm']!=arm or (expected_binding is not None and state['binding']!=expected_binding)):raise RuntimeError('Wrong R4 resume binding') torch.manual_seed(CFG['seed']);model=Model(arm) keys=model.load_state_dict(state['model'],strict=path is not None) if keys.unexpected_keys or any(not k.startswith('r4.') for k in keys.missing_keys):raise RuntimeError('Unmatched parent parameters') model.to('cuda');model.install_store(split,provisional) progress=dict(state['progress']) if path is None:progress.update(new_updates=0,r4_exposures={},r4_chain='',r4_validated=[]) if not optimizer: model.eval();return model,None,progress groups=[[],[],[],[]] for name,p in model.named_parameters(): g=3 if name.startswith('r4.') else 2 if name.startswith('r3.') else 1 if name.startswith('r2.') else 0 groups[g].append(p) old=state['optimizer']['param_groups'] if [len(g['params']) for g in old[:3]]!=[len(g) for g in groups[:3]]:raise RuntimeError('Optimizer ordering mismatch') opt=torch.optim.AdamW([dict(params=g,lr=old[i]['lr']) for i,g in enumerate(groups[:3])],weight_decay=rt.LEGACY.C['weight_decay']) if path is None: opt.load_state_dict(state['optimizer']) if groups[3]:opt.add_param_group(dict(params=groups[3],lr=CFG['learning_rate']['new_head'])) else: if groups[3]:opt.add_param_group(dict(params=groups[3],lr=CFG['learning_rate']['new_head'])) opt.load_state_dict(state['optimizer']) for p,st in opt.state.items(): for k,v in st.items(): if torch.is_tensor(v) and k!='step':st[k]=v.to(p.device) rt.restore_rng(state) return model,opt,progress123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161"""Exact C03 active objectives, plus qualified chemistry / spectrum supervision."""from collections import Counterimport timeimport numpy as npimport torchfrom torch.nn import functional as Ffrom torch.utils.checkpoint import checkpoint as recomputefrom common4 import CFG,rtfrom runtime_r2 import *from kernels import grouped_contrastive,formula_objectivefrom losses import ms_ms_supcon,molecule_molecule_two_view
def molecular_views(model,mols,probability): # Reinstate the dropout hook during activation recomputation. The original # implementation removed it before backward; fix identically in all arms. def one(dummy): threshold=model.activation_checkpoint_atom_threshold model.activation_checkpoint_atom_threshold=10**12 handle=model.graph.atom.register_forward_hook(lambda module,inputs,output:F.dropout(output,p=probability,training=True)) try: with amp():return model.encode_molecules(mols)[0].float() finally:handle.remove();model.activation_checkpoint_atom_threshold=threshold return (recompute(one,model.graph.atom.weight,use_reentrant=False,preserve_rng_state=True), recompute(one,model.graph.atom.weight,use_reentrant=False,preserve_rng_state=True))
def auxiliary_loss(model,q,mols,rows,spec,step): weights=spec['loss']['auxiliary'] if any(v for k,v in weights.items() if k not in ('ms_fine','mol_fine')): raise RuntimeError('This release matches C03 fine-only auxiliaries; other arms require a separate release') ids=[r['identity'] for r in rows];rids=[r['record_id'] for r in rows];head=model.hierarchy v1,v2=molecular_views(model,mols,spec['views']['molecule']['dropout']) temperature=spec['loss']['temperature']['identity'];ramp=min(1.,(step+1)/spec['loss']['auxiliary_ramp_steps']) ms=ms_ms_supcon(head('ms_identity',q),ids,rids,temperature) mol=molecule_molecule_two_view(head('mol_identity',v1),head('mol_identity',v2),[m.identity for m in mols],temperature) total=ramp*(weights['ms_fine']*ms.loss+weights['mol_fine']*mol.loss) # The original zero-weight coarse graphs produced zero (not None) grads. # Preserve AdamW decay/moment semantics for those registered unused heads. for name in ('ms_formula','mol_formula','ms_mass','mol_mass'): total=total+sum(p.sum()*0. for p in head.heads[name].parameters()) out=dict(ms_fine_raw=ms.loss.detach(),mol_fine_raw=mol.loss.detach(),auxiliary_total=total.detach(),auxiliary_ramp=ramp, molecule_view_mean_abs_difference=(v1.detach()-v2.detach()).abs().mean()) for name,item in [('ms_fine',ms),('mol_fine',mol)]: for k,v in item.diagnostics.items():out[name+'_'+k]=v.detach() if torch.is_tensor(v) else v return total,out
def chemical_loss(model,q,rows): if model.arm not in C['arms']:return q.sum()*0. counts=torch.as_tensor(np.stack([r['chemical_counts'] for r in rows]),device=q.device,dtype=torch.long) logp=model.r2.count_log_prob(q) losses=-logp.gather(-1,counts[:,:,None]).squeeze(-1).mean(-1) ids=[r['identity'] for r in rows];occurrences=Counter(ids) w=q.new_tensor([1/occurrences[k]/len(occurrences) for k in ids]) return (losses*w).sum()
def train_step(model,opt,batch,update,apply_update=True): model.collect_score_diagnostics=True;model.score_diagnostics=[] started=time.monotonic();rows=batch['rows'];queries=[r['query'] for r in rows];ids=[r['identity'] for r in rows] reps={} for r in rows: if r['identity'] not in reps or r['ref'].smiles<reps[r['identity']].smiles:reps[r['identity']]=r['ref'] columns=sorted(reps);mols=[reps[k] for k in columns];w=LEGACY.C['loss_weights'];opt.zero_grad(set_to_none=True) sc=LEGACY.C['spectrum_chunk'];gc=LEGACY.C['graph_chunk'] with torch.no_grad(),amp(): qc=torch.cat([model.spectrum.forward_batch(queries[a:a+sc])[1] for a in range(0,len(rows),sc)]) mc=torch.cat([model.encode_molecules(mols[a:a+gc])[0] for a in range(0,len(mols),gc)]) qc=qc.float().detach().requires_grad_();mc=mc.float().detach().requires_grad_() with amp(): zq=F.normalize(model.query_projection(qc).float(),dim=-1);zm=F.normalize(model.mol_projection(mc).float(),dim=-1) f,b=grouped_contrastive(zq@zm.T/LEGACY.C['contrastive_temperature'],ids,columns) base=w['inbatch_ms_to_mol']*f+w['inbatch_mol_to_ms']*b # Match the parent's FP32 auxiliary invocation, not R1's outer autocast. auxiliary,details=auxiliary_loss(model,qc,mols,rows,SPEC,update) chem=chemical_loss(model,qc,rows) ramp=min(1.,(update-C['source_update']+1)/C['lr_ramp_updates']) # A3 auxiliaries are already trained: retain their full weights, not a # second accidental warm-up. New heads use final pool CE, not duplicate CE. cw=C['chem_weight'];sw=C['spectrum_weight'] (base+auxiliary+cw*chem).backward();dq=qc.grad.detach();dm=mc.grad.detach() metrics=dict(inbatch_ms_to_mol=f.detach(),inbatch_mol_to_ms=b.detach(),formula_loss=0.,formula_ce=0.,formula_gap=0.,element_ce=0.,formula_correct=0., chemical_loss=chem.detach(),chemical_weight=cw,spectrum_weight=sw) valid=sum(r['mass_ok'] and len(r['formulas'])>1 and r['formula'] in r['formulas'] for r in rows) for a in range(0,len(rows),sc): block=rows[a:a+sc] with amp(): tokens,q,_=model.spectrum.forward_batch([r['query'] for r in block]) lf,d=formula_objective(model,q,tokens,block,valid,len(rows)) loss=(q*dq[a:a+len(block)]).sum()+w['formula']*lf loss.backward();metrics['formula_loss']+=lf.detach() for k in ('formula_ce','formula_gap','element_ce','formula_correct'):metrics[k]+=d[k] for a in range(0,len(mols),gc): with amp():u=model.encode_molecules(mols[a:a+gc])[0];surrogate=(u*dm[a:a+len(u)]).sum() surrogate.backward() pools=[p for r in rows for p in r['pools']];counts=Counter(p['kind'] for p in pools) pm={k:qc.new_zeros(()) for k in ('odata','mass','formula')};spec_total=qc.new_zeros(()) supervised={p['record_id'] for p in pools if p['spectrum_eligible']};seen=set();used=0 gap_total=qc.new_zeros(());delta_total=qc.new_zeros(());delta_n=0 def same_negatives(p): if not p['quality_eligible']:return [] truth=p['truth_identity'];f=p['query'].candidates[p['positive_index']].formula return [i for i,m in enumerate(p['query'].candidates) if m.identity!=truth and m.formula==f] gap_eligible=sum(bool(same_negatives(p)) for p in pools);gap_on=CFG['arms'][model.r4_arm]['gap'] for a in range(0,len(pools),LEGACY.C['pool_micro_views']): block=pools[a:a+LEGACY.C['pool_micro_views']] with amp(): encs,_=model.encode_batch([p['query'] for p in block]);loss=encs[0].q.sum()*0. for p,enc in zip(block,encs): ce=enc.base.float().logsumexp(0)-enc.base[p['positive_index']].float();kind=p['kind'] pm[kind]+=ce.detach()/counts[kind] loss+=w[{'odata':'odata_pool','mass':'msg_mass_pool','formula':'msg_formula_pool'}[kind]]*ce/counts[kind] if gap_on: jj=same_negatives(p) if jj: ix=torch.tensor(jj,device=enc.base.device);mining_scores=enc.r4_base.float() # The draw ledger already has unique key14; choose top # errors by detached, pre-duel scores. Stable chemical # tie-breaks, never use stored candidate position. ss=sorted(range(len(jj)),key=lambda i:p['query'].candidates[jj[i]].identity) ix=ix[torch.tensor(ss,device=ix.device)] hard=ix[mining_scores[ix].argsort(descending=True,stable=True)[:CFG['gap']['hard_k']]] gap=F.softplus(CFG['gap']['margin']+enc.base[hard].float()-enc.base[p['positive_index']].float()).mean()/gap_eligible loss+=CFG['gap']['weight']*gap;gap_total+=gap.detach() if enc.r4_info is not None: delta_total+=enc.r4_info[0];delta_n+=1 if p['spectrum_eligible'] and p['record_id'] not in seen: if enc.r2_spectrum is None:raise RuntimeError('Qualified spectrum has no fragment predictions') spec,usable=enc.r2_spectrum if not bool(usable[p['positive_index']]):raise RuntimeError('CPU / GPU fragment eligibility disagrees') sl=spec[p['positive_index']]/max(1,len(supervised));loss+=sw*sl;spec_total+=sl.detach() seen.add(p['record_id']);used+=1 loss.backward() total=base.detach()+auxiliary.detach()+cw*chem.detach()+sw*spec_total+w['formula']*metrics['formula_loss'] for k,v in pm.items():metrics[k+'_pool']=v;total+=w[{'odata':'odata_pool','mass':'msg_mass_pool','formula':'msg_formula_pool'}[k]]*v total=total+CFG['gap']['weight']*gap_total metrics.update(details);metrics.update(spectrum_loss=spec_total,loss=total,r4_gap_loss=gap_total, r4_gap_eligible=gap_eligible,r4_duel_residual=delta_total/max(1,delta_n),r4_duel_pools=delta_n) if not torch.isfinite(total):raise RuntimeError('Nonfinite R2 objective') for name,parameters in [('backbone',[p for n,p in model.named_parameters() if not n.startswith(('r2.','r3.'))]), ('chemical',model.r2.counts.parameters()),('fragment',[p for n,p in model.r2.named_parameters() if not n.startswith('counts.') and n!='chemical_scale']), ('r3',model.r3.parameters()),('r4',[p for n,p in model.named_parameters() if n.startswith('r4.')])]: gs=[p.grad.detach().float().square().sum() for p in parameters if p.grad is not None] metrics[name+'_gradient_norm']=torch.stack(gs).sum().sqrt() if gs else total*0. norm=torch.nn.utils.clip_grad_norm_(model.parameters(),LEGACY.C['gradient_clip'],error_if_nonfinite=True) metrics['gradient_norm']=norm.detach() for name in ('formula_prior_abs','parent_structural_std','topology_abs','difference_abs','formula_calibration_abs','final_score_std'): values=[r[name] for r in model.score_diagnostics if name in r] metrics['score_'+name]=torch.stack(values).mean() if values else total*0. metrics['formula_calibration_alpha']=.5*model.r3.formula_alpha.detach().tanh() model.collect_score_diagnostics=False;model.score_diagnostics=[] if apply_update:opt.step() packed=torch.stack([v.detach().float().to(model.device) if torch.is_tensor(v) else torch.tensor(v,device=model.device).float() for v in metrics.values()]).cpu().tolist() result=dict(zip(metrics,packed));result.update(queries=len(rows),unique_connectivity=len(columns),formula_valid=valid, pool_valid=dict(counts),spectrum_valid=used,chemical_valid=len(rows) if cw else 0, source_counts=dict(Counter(r['source'] for r in rows)),negative_draws=sum(p['negative_draws'] for p in pools), negative_unique_key14=sum(p['unique_negative_key14'] for p in pools),duplicate_physical_MS=len(rows)-len({r['record_id'] for r in rows}), molecular_encoder_views=2,zero_weight_coarse_auxiliaries='not_computed',data_seconds=batch['data_seconds'], step_compute_seconds=time.monotonic()-started,peak_allocated_mib=torch.cuda.max_memory_allocated()/2**20) return result12345678910111213[program:specpartition-r4-9000-pipeline-20261112]directory=/root/xj/SpecPartition-MS/code/ceir_r4_9000_20261112command=/usr/bin/nice -n 12 /workspace/xj/SpecPartition-MS/.venv/bin/python -B -u pipeline4.pyenvironment=PYTHONUNBUFFERED="1",OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1",CUBLAS_WORKSPACE_CONFIG=":4096:8"autostart=trueautorestart=unexpectedexitcodes=0,2startsecs=2stopasgroup=truekillasgroup=truestdout_logfile=/root/xj/SpecPartition-MS/runs/ceir_r4_9000_20261112/pipeline.logstdout_logfile_maxbytes=20MBredirect_stderr=true123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869"""Managed queue. All four get a real starting block, then alternate two GPU slots.Statistical failures/flat metrics are results, not an excuse to train on Test."""import concurrent.futures as cf,subprocess,tracebackfrom common4 import *PY='/workspace/xj/SpecPartition-MS/.venv/bin/python'MP='/root/xj/SpecPartition-MS/evaluations/mces_all_20261106/.venv/bin/python'ORDER=('A','C','B','D')def launch(name,script,*args,cpu=False): logs=OUT/'logs';logs.mkdir(exist_ok=True) for i in range(3): with (logs/(name+'.log')).open('a') as f: p=subprocess.Popen([MP if cpu else PY,'-B','-u',str(HERE/script),*map(str,args)],cwd=HERE,stdout=f,stderr=subprocess.STDOUT, env={**os.environ,'OMP_NUM_THREADS':'1','OPENBLAS_NUM_THREADS':'1','MKL_NUM_THREADS':'1','CUBLAS_WORKSPACE_CONFIG':':4096:8'}) event(OUT/'pipeline_events.jsonl',dict(event='start',job=name,pid=p.pid,attempt=i+1));rc=p.wait() event(OUT/'pipeline_events.jsonl',dict(event='exit',job=name,returncode=rc)) if rc==0:return if i<2:time.sleep(8*(i+1)) raise RuntimeError('R4 job failed after bounded retries: '+name)def jobs(items,limit=2): with cf.ThreadPoolExecutor(max_workers=limit) as ex: fs=[ex.submit(launch,*s) for s in items] for f in cf.as_completed(fs):f.result()def status(phase,**kw):put(OUT/'PIPELINE_STATUS.json',dict(phase=phase,ts=time.time(),**kw))def main(): held=lock(OUT/'pipeline.lock') if (OUT/'ALL_RESULTS.json').exists():status('completed');return while not (prep_root()/'READY.json').is_file(): status('waiting_for_offline_preparation') if (OUT/'PREP_FAILURE.json').is_file():raise RuntimeError('Preparation failed; no formal updates') # On a cold restart tmpfs needs rebuilding. Do not duplicate a live coordinator. state=subprocess.run(['supervisorctl','status','specpartition-r4-9000-prepare-20261112'],capture_output=True,text=True).stdout if 'RUNNING' not in state and 'STARTING' not in state: subprocess.run(['supervisorctl','start','specpartition-r4-9000-prepare-20261112'],check=True) time.sleep(8) if not (OUT/'TRAIN_READY.json').exists():status('real_GPU_acceptance');launch('formal_gpu_acceptance','accept4.py') if get(OUT/'TRAIN_READY.json')['binding']!=state_binding():raise RuntimeError('Accepted code/data drift') from report4 import val,freeze,final # CPU MCES overlaps later training without taking a GPU slot. with cf.ThreadPoolExecutor(max_workers=1) as cpu: cpu_jobs=[] for u in [6004,6250,6500,6750,7000,7250,7500,7750,8000,8250,8500,8750,9000]: work=[] for a in ORDER: pointer=OUT/a/'resume/LAST.json' if pointer.exists() and get(pointer)['update']>=u and (u not in CFG['checkpoints'] or (OUT/a/('step_%06d.json'%u)).exists()) and (u!=9000 or (OUT/a/'TRAIN_COMPLETE.json').exists()):continue work.append((a+'_train_'+str(u),'run4.py',a,u)) if work:status('training',round_end=u,queue=[w[0] for w in work]);jobs(work) if u not in CFG['checkpoints']:continue work=[(a+'_validation_'+str(u),'eval4.py',a,u,'validation') for a in ORDER if not (OUT/a/('validation_%06d/metrics.json'%u)).exists()] if work:status('full_validation',update=u,queue=[w[0] for w in work]);jobs(work) val(u) for a in ORDER: if not (OUT/a/('validation_%06d/MCES.json'%u)).exists(): cpu_jobs.append(cpu.submit(launch,a+'_MCES_validation_'+str(u),'mces4.py',a,u,'validation',cpu=True)) freeze() for d in ('msg_test','casmi2022'): status('fixed_endpoint_test',dataset=d) work=[(a+'_'+d,'eval4.py',a,9000,d) for a in ORDER if not (OUT/a/(d+'_009000/metrics.json')).exists()] jobs(work) for a in ORDER: if not (OUT/a/(d+'_009000/MCES.json')).exists():cpu_jobs.append(cpu.submit(launch,a+'_MCES_'+d,'mces4.py',a,9000,d,cpu=True)) status('posthoc_cpu_MCES') for f in cpu_jobs:f.result() final();status('completed',actual_updates={a:3000 for a in ORDER})if __name__=='__main__': try:main() except Exception: put(OUT/'PIPELINE_ERROR.json',dict(error=traceback.format_exc(),ts=time.time()));status('blocked_check_logs');sys.exit(2)123456789101112[program:specpartition-r4-9000-prepare-20261112]directory=/root/xj/SpecPartition-MS/code/ceir_r4_9000_20261112command=/usr/bin/nice -n 12 /workspace/xj/SpecPartition-MS/.venv/bin/python -B -u prepare4.pyenvironment=PYTHONUNBUFFERED="1",OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1",CUDA_VISIBLE_DEVICES=""autostart=falseautorestart=falsestartsecs=1stopasgroup=truekillasgroup=truestdout_logfile=/root/xj/SpecPartition-MS/runs/ceir_r4_9000_20261112/prep.logstdout_logfile_maxbytes=20MBredirect_stderr=true123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143"""Rebuildable offline ledger for *next* 3000 updates, plus missing train-only fragments.Physical batches/pools are not replaced by the previous R3 3000-step ledger."""import collections,random,concurrent.futures as futures,multiprocessing as mpfrom functools import lru_cachefrom common4 import *from data09 import Reader,loadsfrom sampling import epoch_plans,plan_hashfrom prepare_ceir import entry_identitySTART=6000; N=3000def init(): global reader,lookup,fragments reader=Reader() @lru_cache(65536) def alias(s): row=reader.assets.execute('SELECT graph_hash FROM smiles WHERE smiles=?',(s,)).fetchone() if not row:raise RuntimeError('Unmapped training alias') return row[0] lookup=alias fragments=[ro(R2/'prepared/assets.sqlite'),ro(R3/'prepared/assets.sqlite')]def batchfile(i):return prep_root()/'batches'/('%04d.z'%i)def make_batch(task): idx,(epoch,step,groups)=task;path=batchfile(idx) if path.is_file():return idx rows=[] for source,rids in groups.items(): for j,rid in enumerate(rids): r=loads(reader.db.execute('SELECT body FROM samples WHERE record_id=?',(rid,)).fetchone()[0]) if r['identity'] in reader.forbidden:raise RuntimeError('Heldout label') seed=CFG['seed']+epoch*100000000+step*10000+j+(1000000 if source=='msg' else 0);rng=random.Random(seed) msg=r['source']=='MSG_Train'; kinds=('mass','formula') if msg else (('odata',) if source=='odata' and j<16 else ()) forms=tuple(reader.official(r['target'],'mass')['formula_classes']) if msg else tuple(r['view']['formulas']) pools=[] for kind in kinds: if kind=='odata': v=r['view'];pool=reader.pool(v['pool_path'],v['pool_sha256']);entries=pool['records'] allowed=pool['safe_mass_order'][v['mass_order_start']:v['mass_order_stop']] else: pool=reader.official(r['target'],kind);entries=pool['entries'];allowed=[i for i,e in enumerate(entries) if e['eligible_for_training']] pos=[];neg={} for i in allowed: key=entry_identity(entries[i]) if key==r['identity']:pos.append(i) else:neg.setdefault(key,[]).append(i) if not pos or not neg:continue rr=random.Random(seed) if kind=='odata' else rng positive=rr.choice(pos);budget=rt.LEGACY.C['odata_negative_draws' if kind=='odata' else 'msg_negative_draws'] keys=rr.sample(sorted(neg),min(budget,len(neg))) selected=[positive]+[rr.choice(neg[k]) for k in keys] ids=[entry_identity(entries[i]) for i in selected] if len(set(ids))!=len(ids) or set(ids)&reader.forbidden:raise RuntimeError('Forbidden/duplicate sampled candidate') graphs=[e.get('graph_hash') or lookup(e.get('canonical_smiles') or e['smiles']) for e in (entries[i] for i in selected)] fs=tuple(pool['formula_classes']) if kind!='odata' else tuple(sorted({entries[i]['formula'] for i in selected})) pools.append(dict(kind=kind,graphs=graphs,ids=ids,formulas=fs,negative_draws=len(keys),unique_negative_key14=len(keys),reference_injected=False)) rows.append(dict(rid=rid,ref=r['graph_hash'],identity=r['identity'],source=r['source'],formulas=forms,pools=pools)) tmp=path.with_suffix('.tmp');tmp.write_bytes(ft.dumps(dict(epoch=epoch,step=step,rows=rows)));os.replace(tmp,path);return idxdef asset_block(items): # Actual checkpoint-compatible Molecule.smiles, not an assumed raw SMILES literal. results=[];counts=collections.Counter() for gh,expected in items: m=reader.molecule(gh) if m.identity!=expected:raise RuntimeError('Graph/key14 binding mismatch') fk=ft.key(m.smiles) if fragments[0].execute('SELECT 1 FROM canonical_features WHERE feature_key=? AND feature_sha IS NOT NULL',(fk,)).fetchone():counts['r2']+=1;continue if fragments[1].execute('SELECT 1 FROM r3_features WHERE feature_key=? AND feature_sha IS NOT NULL',(fk,)).fetchone():counts['r3']+=1;continue value=ft.build(m.smiles) if value['layout']!=ft.layout(m.mol):raise RuntimeError('Offline fragment layout inconsistent') b=ft.dumps(value);results.append((fk,b,digest(b)));counts['new']+=1 return results,countsdef run(): live=lock(OUT/'prep.lock');scratch_check();pr=prep_root();pr.mkdir(exist_ok=True) if (pr/'READY.json').exists() and (OUT/'DATA_READY.json').exists() and get(pr/'READY.json')==get(OUT/'DATA_READY.json'):return x=parent();prog=x['progress'];del x epoch=prog['epoch'];first=prog['next_step'];plans=[];aud=[] while len(plans)<N: ep=epoch_plans(epoch,CFG['seed']);aud.append([epoch,first,plan_hash(ep)]) plans.extend(ep[first:first+N-len(plans)]);epoch+=1;first=0 assert len(plans)==N and plans[0][:2]==(prog['epoch'],prog['next_step']) tag=dict(parent=CFG['parent_sha256'],plans=aud,script=filehash(__file__),next_updates=N) if (pr/'PLAN.json').exists() and get(pr/'PLAN.json')!=tag:raise RuntimeError('Stale private ledger') put(pr/'PLAN.json',tag);(pr/'batches').mkdir(exist_ok=True) ctx=mp.get_context('fork') def status(phase,done,total):put(OUT/'prep_status.json',dict(phase=phase,done=done,total=total,ts=time.time())) status('next_cursor_sampling',0,N) with futures.ProcessPoolExecutor(8,mp_context=ctx,initializer=init) as ex: for j,_ in enumerate(ex.map(make_batch,enumerate(plans),chunksize=3),1): if j%30==0:status('next_cursor_sampling',j,N);scratch_check() # One global identity audit; batches are identical in all four arms. required={};hashes=[];sources=collections.Counter();pool_counts=collections.Counter() def verify(gh,key): if required.setdefault(gh,key)!=key:raise RuntimeError('Conflicting graph identity') for i,(e,s,groups) in enumerate(plans): b=batchfile(i).read_bytes();hashes.append(digest(b));v=ft.loads(b) if (v['epoch'],v['step'])!=(e,s) or [r['rid'] for r in v['rows']] != [rid for group in groups.values() for rid in group]:raise RuntimeError('Wrong epoch cursor/order') for r in v['rows']: verify(r['ref'],r['identity']);sources[r['source']]+=1 for p in r['pools']: if len(set(p['ids']))!=len(p['ids']) or p['ids'][0]!=r['identity']:raise RuntimeError('Invalid negatives') pool_counts[p['kind']]+=1 for gh,key in zip(p['graphs'],p['ids']):verify(gh,key) put(pr/'hashes.json',hashes);req=sorted(required.items());del required db=sqlite3.connect(pr/'delta.sqlite');db.execute('PRAGMA journal_mode=WAL') db.execute('CREATE TABLE IF NOT EXISTS extra(k TEXT PRIMARY KEY,b BLOB NOT NULL,h TEXT NOT NULL) WITHOUT ROWID') db.execute('CREATE TABLE IF NOT EXISTS blocks(i INTEGER PRIMARY KEY,hash TEXT,counts TEXT)') blocksize=1024;count=(len(req)+blocksize-1)//blocksize processed={i:h for i,h in db.execute('SELECT i,hash FROM blocks')} pending=[];blockhash={} for i in range(count): h=objhash(req[i*blocksize:(i+1)*blocksize]);blockhash[i]=h if i in processed: if processed[i]!=h:raise RuntimeError('Stale feature resume block') else:pending.append(i) status('offline_feature_identity_check',len(processed)*blocksize,len(req)) # Bound in-flight results; completed chunks survive process restarts. it=iter(pending);jobs={} with futures.ProcessPoolExecutor(8,mp_context=ctx,initializer=init) as ex: while True: while len(jobs)<16: i=next(it,None) if i is None:break jobs[ex.submit(asset_block,req[i*blocksize:(i+1)*blocksize])]=i if not jobs:break for done in futures.wait(jobs,return_when=futures.FIRST_COMPLETED).done: i=jobs.pop(done);extra,stats=done.result() db.executemany('INSERT OR IGNORE INTO extra VALUES(?,?,?)',extra);db.execute('INSERT INTO blocks VALUES(?,?,?)',(i,blockhash[i],json.dumps(stats)));db.commit();processed[i]=blockhash[i] if len(processed)%32==0:status('offline_feature_identity_check',min(len(req),len(processed)*blocksize),len(req));scratch_check() counts=collections.Counter() for s, in db.execute('SELECT counts FROM blocks'):counts.update(json.loads(s)) assert sum(counts.values())==len(req) and len(processed)==count db.execute('PRAGMA wal_checkpoint(TRUNCATE)');db.close() ready=dict(complete=True,parent_sha256=CFG['parent_sha256'],new_updates=N,first_cursor=plans[0][:2],last_cursor=plans[-1][:2], epoch_binding=aud,ledger_hash=objhash(hashes),unique_graphs=len(req),source_counts=dict(sources),pool_counts=dict(pool_counts), descriptor_sources=dict(counts),delta_sha256=filehash(pr/'delta.sqlite'),heldout_labels_and_negatives_checked=True) if (OUT/'DATA_READY.json').exists(): old=get(OUT/'DATA_READY.json') for key in ('ledger_hash','unique_graphs','descriptor_sources','epoch_binding','source_counts','pool_counts'): if old[key]!=ready[key]:raise RuntimeError('Reconstructed ledger differs: '+key) put(pr/'READY.json',ready);put(OUT/'DATA_READY.json',ready);status('ready',N,N)if __name__=='__main__': try:run() except Exception: import traceback put(OUT/'PREP_FAILURE.json',dict(traceback=traceback.format_exc(),time=time.time()));raise1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859"""Paired target-key14 cluster bootstrap, wins AND regressions; no Test selection."""from collections import defaultdictimport numpy as npfrom common4 import *def rows(p): with gzip.open(p/'per_spectrum_summary.json.gz','rt') as f:rr=json.load(f) out={(r['identifier'],r['view']):r for r in rr} if len(rr)!=len(out):raise RuntimeError('Duplicate spectrum/view row') return outdef compare(left,right): if left.keys()!=right.keys():raise RuntimeError('Unmatched evaluation splits') out={} for view in sorted({v for i,v in left}): report={} for k in (1,5,20): grouped=defaultdict(lambda:[0,0]);wins=losses=0 for i,r in left.items(): if i[1]!=view:continue o=right[i] if (o['target'],o['candidate_count'],o['reference_identity'])!=(r['target'],r['candidate_count'],r['reference_identity']):raise RuntimeError('Changed paired candidate population') d=int(r['rank'] is not None and r['rank']<=k)-int(o['rank'] is not None and o['rank']<=k) wins+=int(d==1);losses+=int(d==-1);g=grouped[r['reference_identity']];g[0]+=d;g[1]+=1 a=np.array(list(grouped.values()));rng=np.random.default_rng(47011);est=[] for _ in range(20): ix=rng.integers(0,len(a),(100,len(a)));d,n=a[ix].sum(1).T;est.extend(100*d/n) report[str(k)]=dict(added=wins,lost=losses,denominator=int(a[:,1].sum()),net_pp=100*(wins-losses)/a[:,1].sum(), ci95_pp=np.quantile(est,[.025,.975]).tolist(),unit='paired target key14; single training seed') out[view]=report return outdef directory(arm,u,dataset):return OUT/arm/(dataset+'_%06d'%u)def val(u): parentdir=R3/'R3D/validation_006000';original=rows(parentdir);control=rows(directory('A',u,'validation')) arms={};comp={} for arm in CFG['arms']: d=directory(arm,u,'validation');row=rows(d);metric=get(d/'metrics.json')['results'] arms[arm]=metric;comp[arm]=dict(vs_control=compare(row,control),vs_parent=compare(row,original)) recommended=max(arms,key=lambda a:arms[a]['formula']['structure']['1']['hits']) report=dict(complete=True,update=u,arms=arms,paired=comp,validation_formula_top1_leader=recommended, exploratory='Report alongside Mass, MCES, effect uncertainty and harm; a point estimate alone is not verified superiority', test_used_for_selection=False) put(OUT/('VALIDATION_%06d.json'%u),report) return reportdef freeze(): val9=get(OUT/'VALIDATION_009000.json') eps={a:get(OUT/a/'TRAIN_COMPLETE.json') for a in CFG['arms']} assert len({v['ledger_chain'] for v in eps.values()})==1 and all(v['actual_new_updates']==3000 for v in eps.values()) put(OUT/'FROZEN_TEST.json',dict(arms={a:e['endpoint_sha'] for a,e in eps.items()},weights_policy='all four predetermined 9000-step endpoints', validation_sha=filehash(OUT/'VALIDATION_009000.json'),test_used_for_selection=False,validation_point_leader=val9['validation_formula_top1_leader']))def final(): result={} for d in ('msg_test','casmi2022','validation'): parentdir=R3/'test/inference/R3D_006000'/d if d!='validation' else R3/'R3D/validation_006000' control=rows(directory('A',9000,d));old=rows(parentdir);summary={} for a in CFG['arms']: p=directory(a,9000,d);rr=rows(p);metrics=get(p/'metrics.json');mces=get(p/'MCES.json') summary[a]=dict(results=metrics['results'],MCES=mces,vs_matched_A=compare(rr,control),vs_R3D_6000=compare(rr,old)) result[d]=summary put(OUT/'ALL_RESULTS.json',dict(complete=True,actual_updates={a:3000 for a in CFG['arms']},test_choice=get(OUT/'FROZEN_TEST.json'), results=result,validation_checkpoints=CFG['checkpoints'],public_baselines='literature, not rerun',ts=time.time()))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140"""Finite R3D -> R4 continuation. Atomic rolling state, no old run writes."""import argparse,gc,math,random,contextlib,subprocessimport numpy as npimport torchfrom common4 import *from model4 import make,setupfrom data4 import Batchesfrom objectives4 import train_step
def synced_file(src,dest): dest.parent.mkdir(parents=True,exist_ok=True) tmp=dest.with_name(dest.name+'.copy.tmp') with open(src,'rb') as a,open(tmp,'wb') as b:shutil.copyfileobj(a,b,4*2**20);b.flush();os.fsync(b.fileno()) if filehash(tmp)!=filehash(src):raise RuntimeError('Checkpoint copy did not verify') os.replace(tmp,dest);fd=os.open(dest.parent,os.O_RDONLY);os.fsync(fd);os.close(fd)
def atomic_torch(dest,value): dest.parent.mkdir(parents=True,exist_ok=True);tmp=dest.with_name(dest.name+'.write.tmp') with tmp.open('wb') as f:torch.save(value,f);f.flush();os.fsync(f.fileno()) os.replace(tmp,dest)
def save_state(model,opt,pg,bind,arm,durable): up=pg['update']; hot=HOT/'runs'/arm/'resume'; cold=OUT/arm/'resume' p=hot/('state_%06d.pt'%up) value=dict(architecture='CEIR_R4',arm=arm,model=model.state_dict(),optimizer=opt.state_dict(),progress=dict(pg), binding=bind,torch_rng=torch.get_rng_state(),cuda_rng=torch.cuda.get_rng_state_all(), numpy_rng=np.random.get_state(),python_rng=random.getstate()) atomic_torch(p,value);meta=dict(update=up,name=p.name,sha256=filehash(p),bytes=p.stat().st_size,binding_sha=objhash(bind)) def publish(folder): old=get(folder/'LAST.json') if (folder/'LAST.json').is_file() else None put(folder/'LAST.json',meta) # Rotate ONLY this arm's superseded private rolling cache. Permanent # milestone snapshots and the parent checkpoint never enter this folder. if old and old['update']!=up and old['name']=='state_%06d.pt'%old['update'] and old['update']<up: older=folder/old['name'] if older.is_file():older.unlink() publish(hot) if durable: if shutil.disk_usage(OUT).free<max(320*2**20,meta['bytes']+96*2**20):raise RuntimeError('Durable capacity guard: hot state preserved') synced_file(p,cold/p.name);publish(cold) return p,meta
def resume(arm,bind): candidates=[] for box in [OUT/arm/'resume',HOT/'runs'/arm/'resume']: if (box/'LAST.json').exists(): m=get(box/'LAST.json');p=box/m['name'] if m['name']!='state_%06d.pt'%m['update'] or m['binding_sha']!=objhash(bind):raise RuntimeError('Wrong rolling state binding') candidates.append((m['update'],box==OUT/arm/'resume',m,p)) for u,_,m,p in sorted(candidates,reverse=True): if p.exists() and filehash(p)==m['sha256']:return p if candidates:raise RuntimeError('No verified recoverable checkpoint') return None
def milestone(model,pg,bind,arm,meta): u=pg['update'];dest=OUT/arm/('step_%06d.pt'%u) if not dest.exists(): if u==CFG['target_update']:os.link(OUT/arm/'resume'/meta['name'],dest) else:atomic_torch(dest,dict(architecture='CEIR_R4',arm=arm,model=model.state_dict(),progress=dict(pg),binding=bind)) h=filehash(dest) if u==CFG['target_update'] and h!=meta['sha256']:raise RuntimeError('Endpoint hardlink not identical to durable full state') put(dest.with_suffix('.json'),dict(update=u,sha256=h,size=dest.stat().st_size,inference_only=u!=CFG['target_update'],arm=arm))
@contextlib.contextmanagerdef lease(label): status=OUT/'admission'/label;status.parent.mkdir(parents=True,exist_ok=True) folder=OUT/'gpu_leases';folder.mkdir(exist_ok=True) handles=[(folder/(str(i)+'.lock')).open('a+') for i in range(CFG['max_training_processes'])];mine=None try: while mine is None: free=int(subprocess.check_output(['nvidia-smi','--query-gpu=memory.free','--format=csv,noheader,nounits'],text=True).strip().splitlines()[0]) if free>=CFG['free_before_job_mib']: for f in handles: try:fcntl.flock(f,fcntl.LOCK_EX|fcntl.LOCK_NB);mine=f;break except BlockingIOError:pass if mine is None:put(status,dict(state='waiting_for_free_resources',free_mib=free,ts=time.time()));time.sleep(6) put(status,dict(state='admitted',ts=time.time()));yield finally: for f in handles:f.close() put(status,dict(state='released',ts=time.time()))
def accepted(): bind=state_binding();r=get(OUT/'TRAIN_READY.json') if not r['passed'] or r['binding']!=bind:raise RuntimeError('Formal real-GPU acceptance missing or changed') return bind
def train(arm,until): if arm not in CFG['arms'] or not 6000<until<=9000:raise ValueError('Invalid R4 request') dest=OUT/arm;held=lock(dest/'training.lock');bind=accepted() with lease('train_'+arm): setup();path=resume(arm,bind);model,opt,pg=make(arm,path,expected_binding=bind) if path is None and (pg['epoch'],pg['next_step'])!=(1,907):raise RuntimeError('Wrong cold data cursor') if pg['update'] in CFG['checkpoints'] and not (dest/('step_%06d.json'%pg['update'])).exists(): _,m=save_state(model,opt,pg,bind,arm,True);milestone(model,pg,bind,arm,m) if pg['update']>=until: if pg['update']==9000:finish(dest,pg,bind) return begin=pg['update']-6000;dataset=Batches(begin,until-6000) loader=torch.utils.data.DataLoader(dataset,batch_size=None,num_workers=1,prefetch_factor=2, multiprocessing_context='spawn',generator=torch.Generator().manual_seed(CFG['seed']+begin)) event(dest/'events.jsonl',dict(event='train_continue',from_update=pg['update'],until=until,source='verified_state' if path else 'R3D_006000')) put(dest/'status.json',dict(phase='training',update=pg['update'],target=9000,ts=time.time())) last_clock=time.monotonic() for batch in loader: u=pg['update'];n=u-6000;ts=time.monotonic();wait=ts-last_clock if (n!=batch['manifest_index'] or (batch['epoch'],batch['step'])!=(pg['epoch'],pg['next_step'])):raise RuntimeError('Training cursor mismatch') if model.has_duel:opt.param_groups[3]['lr']=CFG['learning_rate']['new_head']*min(1.,(n+1)/CFG['learning_rate']['new_warmup']) model.train();torch.cuda.reset_peak_memory_stats();m=train_step(model,opt,batch,u) pg.update(update=u+1,new_updates=n+1,epoch=batch['epoch'],next_step=batch['step']+1, r4_chain=digest((pg['r4_chain']+batch['ledger_sha256']).encode())) for k,v in m['source_counts'].items():pg['r4_exposures'][k]=pg['r4_exposures'].get(k,0)+v u=pg['update'];durable=(u%CFG['durable_interval']==0 or u in CFG['checkpoints'] or u==until) if durable or u%CFG['hot_interval']==0: _,receipt=save_state(model,opt,pg,bind,arm,durable) if u in CFG['checkpoints']:milestone(model,pg,bind,arm,receipt) m.update(update=u,new_updates=u-6000,arm=arm,epoch=pg['epoch'],data_step=batch['step'], ledger_sha256=batch['ledger_sha256'],batch_chain=pg['r4_chain'],lr=[g['lr'] for g in opt.param_groups], data_wait_seconds=wait,wall_seconds=time.monotonic()-ts+wait,timestamp=time.time()) event(dest/'loss.jsonl',m) if u%10==0 or u<=6003 or u==until: put(dest/'status.json',dict(phase='training' if u<9000 else 'endpoint_saved',update=u,target=9000, new_updates=u-6000,loss=m['loss'],gap=m['r4_gap_loss'],residual=m['r4_duel_residual'], seconds=m['wall_seconds'],peak_mib=m['peak_allocated_mib'],ts=time.time())) last_clock=time.monotonic() if pg['update']!=until:raise RuntimeError('Incomplete training block') if until==9000:finish(dest,pg,bind)def finish(dest,pg,bind): ledger=get(prep_root()/'hashes.json');h='' for d in ledger:h=digest((h+d).encode()) assert len(ledger)==3000 and pg['update']==9000 and pg['new_updates']==3000 and pg['r4_chain']==h ep=dest/'step_009000.pt';rc=get(ep.with_suffix('.json'));assert rc['sha256']==filehash(ep) assert pg['r4_exposures']==get(OUT/'DATA_READY.json')['source_counts'] put(dest/'TRAIN_COMPLETE.json',dict(complete=True,source=6000,endpoint=9000,actual_new_updates=3000, ledger_chain=h,sources=pg['r4_exposures'],endpoint_sha=rc['sha256'],binding_sha=objhash(bind)))if __name__=='__main__': p=argparse.ArgumentParser();p.add_argument('arm',choices=list(CFG['arms']));p.add_argument('until',type=int);a=p.parse_args() try:train(a.arm,a.until) except Exception: import traceback put(OUT/a.arm/'last_error.json',dict(error=traceback.format_exc(),time=time.time()));raise123456789101112131415161718192021222324252627282930313233343536373839# R5: R4-D 9k → 12k,五组独立续训
这不是从 R3D 再开五个分支。共同父文件是服务器`/root/xj/SpecPartition-MS/runs/ceir_r4_9000_20261112/D/step_009000.pt`,SHA-256 `dd23af7370c35caee1d4f154fd52a2bc5b21c3e53c0f06df1beb368f274ea7b6`。复制的是权重、四个参数组(301/24/22/12 个参数张量)、304 份非空 AdamW 状态、训练数据游标、Python/NumPy/PyTorch/CUDA RNG。C 仅把新参数加入第五组,不重置已有优化器。
每组固定 **9,001~12,000 共 3,000 次新更新**。一次性验收不计步,五组总数 15,000。原 R4-D 的全候选直接分数、Top32 差异峰精排及同公式困难负例 Loss 所有组都保留。R3D 6k 是效果历史参照,不是任何一组的训练起点。
| 分支 | 相对 R4-D 的唯一主要改动 ||---|---|| A | 原样续训。匹配同一起点、数据游标、步数、优化器;比较新设计不能只比 9k 父权重。 || B | 每步对每种存在的训练视图轮换至多两个真实谱池,从同池扩大 reservoir 后按冻结 R4-D 高分的同公式异骨架、同/近骨架化学邻居和随机候选重采样;Mass 预留跨公式配额。每个池仍用原训练抽样预算,其他池不变。教师不参与推理。 || C | 在 R4-D 最终分数上增加全池、同公式、候选专属峰强度的有界加分。生产提案是已有两个单边界连通片段之间的新的双桥内部碎片;区别于小试中更广的双切/开环枚举。预测离子强度包含未匹配通道;相同 key14 在支持计数中只投一票,无支持就不改分。使用融合后的最终分数计算一次候选池 CE,增加弱正例谱强度监督,初始分数等于父模型。 || D | 每步扩大一个真实训练池,其余保留原样。连续四个 750 步阶段的**训练**上限为 256、512、2048、5000;只用真实合格候选,没有那么多就不补。激活按块重算,所有候选只用一个最终分数 softmax 分母;不按块各算一份 CE。 || E | 对轮换的真实训练池,用冻结 R4-D 判定“原本排对、分差足够、正确候选及最强对手均无新增独占峰”时,单侧保护父模型分差。允许纠正父模型原本的错误;没有分差缩小时该新损失可以为零。教师和标签都不进入评测模型。 |
训练侧随机池、扩展抽样、静态分子图、参考结构 key14 与 heldout 注册表分别检查;不合格真值不人工补入。正式进程在 `GPU_READY.json` 存在且训练代码/数据哈希匹配时才可运行。验收包括从正式游标取真实 batch,旧模型分数/置换一致性、新机制活动、C 的优化器恢复、四档真实池梯度及统一分母、官方 Validation 输入回放。大池验收是工程和数值检查;**不等于已在独立大池提高召回**。启动五个验证性实验不代表通过科学晋级。
### 本次训练数据修正
新抽样的 6,729,969 个图映射中发现 1 个声明 key14 与图结构不一致。数据服务主动停止,总审计确认只涉及一次 D 扩展池负例(批次索引 2731),不涉及任何正例、其他四组基础抽样或官方评测。独立修订层保存原始与修正批次双哈希。尝试在原池内等额补取;因为该池合法候选已经用尽,**实际少一个负例**,没有复制候选或换标签凑数。尚未发现的错例不能因为修正这一个而宣称不存在;正式运行继续校验图和样本绑定。
### 保存位置与检查
- 热权重、优化器、分批训练日志、验证数据、逐候选分数: `/dev/shm/specpartition_r5_from_r4d_12000_20261112/`。各组里程碑在 `arms/{A,B,C,D,E}/step_010000.pt`、`step_011000.pt`、`step_012000.pt`。前两个是推理权重,12k 是包括优化器/RNG 的完整断点。大文件只放用户指定的内存盘,**重启实例会丢失**;此处不承诺跨重启恢复。- 服务器代码:`/root/xj/SpecPartition-MS/code/ceir_r5_from_r4d_12000_20261112/`。- 小型持续记录、数据/验收哈希、状态和最终指标: `/root/xj/SpecPartition-MS/runs/ceir_r5_from_r4d_12000_20261112/`。这些不含完整训练权重。- 运行状态只读命令(服务器项目代码目录内): `/workspace/xj/SpecPartition-MS/.venv/bin/python -B status5.py`。区分 observed、committed 和已完成评测;`supervisorctl status specpartition-r5-from-r4d-train-20261112` 只描述调度进程,不代表五组都完成。- 监督器同卡最多两组轮转,不启动五个无保护 GPU 进程。每组每 100 步和轮转边界原子保存新断点及可核验的连续训练日志;只轮换该组自己已被替代的临时文件。任何哈希/游标/数据身份问题都停在错误记录处,不静默从头重跑。
### 效果判定
10k、11k、12k 运行完整 MSG Validation;五组**预先指定的 12k 终点**全部运行 MSG Test 两个秩序不变的官方视图,以及 CASMI2022 无截断的 500 条盲预测公式并集全池(1,765,420 个候选,467/500 原池含真值)。结果包括结构与池内公式各 Top-K,以及按可计算分母的 MCES。对照为同预算 A、R4-D 9k、原始 R3D 6k;CASMI 另列同池 CSI,不用 CSI 特征或分数训练。
最终对齐候选顺序哈希,核验每组连续 3,000 个更新、父模型哈希、抽样链和源数据曝光。主比较为 Validation Formula 结构 Top1,基于 target key14 配对重采样,并对四个对照比较报告调整的区间下界;同时检验 Mass、Formula 其他 K 和共同有效样本的 MCES。Test 和 CASMI 不选超参/权重,不把单种子结果当成反复训练均有效。训练 Loss 下降或任务运行成功均**不是效果提升证据**。若各组未达到标准,保留负结果和原 R4-D;本次不向 GitHub 上传权重。123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107"""Independent checks on full copied states and real batches. No formal updates."""import argparse,contextlib,gc,math,os,sys,time,tracebackfrom dataclasses import replacefrom paths5 import *import numpy as np,torchfrom train5 import Batches,binding,lease,make,original,prior,step,teacherfrom model5 import Hfrom teacher5 import annotatefrom forward5 import Evidencedef free(): gc.collect();torch.cuda.empty_cache()def parity(q,model,original_values): model.eval() with torch.inference_mode(),prior.rt.amp(): a=model.encode_batch([q])[0][0].base.float().cpu() rev=list(range(len(a)-1,-1,-1));b=model.encode_batch([replace(q,candidates=tuple(q.candidates[j] for j in rev))])[0][0].base.float().cpu() p=float((a-original_values).abs().max());order=float((a[rev]-b).abs().max()) if p>1e-5 or order>4e-4:raise RuntimeError(f'parent/permutation {p=} {order=}') return p,orderdef one(arm,warm,idx,q,s,bind): pt,det=teacher(arm,warm);model,opt,pg=make(arm,warm=warm) assert pg['update']==9000 and pg['next_step']==3907 and len(opt.state)==304 a,b=parity(q,model,s) batch=Batches(arm,idx,idx+1,warm)[0] if arm=='C': # Independently verify the newly registered head both preserves the # parent at zero and receives real gradients without affecting labels. assert model.r5.gain.item()==0 mt=step(arm,model,opt,batch,9000,pt,det) if not math.isfinite(mt['loss']) or min(mt['backbone_gradient_norm'],mt['r4_gradient_norm'],mt['r4_gap_loss'])<=0:raise RuntimeError('inactive inherited R4D path') if arm=='B' and mt['intervention'].get('actually_changed_identities',0)==0:raise RuntimeError('no actual negative changed') if arm=='C' and not (mt['r5_gradient_norm']>0 and mt['r5_candidates_with_novel_peak']>0):raise RuntimeError('forward mechanism has no training evidence or gradient') if arm=='D' and mt['r5_expanded_views']==0:raise RuntimeError('no expanded denominator') if arm=='E' and not mt['intervention'].get('teacher_views'):raise RuntimeError('no teacher observations') z=dict(parent_score_max_error=a,permutation_max_error=b,raw_parent_update=9000,optimizer_groups=len(opt.param_groups),metrics=mt,n_parameters=sum(p.numel() for p in model.parameters())) if arm=='E': x=torch.tensor([1.,.9],requires_grad=True);pen=(.75+x[1]-x[0]).relu();pen.backward() assert x.grad.tolist()==[-1.,1.];z['synthetic_anchor_derivative']=x.grad.tolist() if arm=='C' and not warm: # Check optimizer moments and RNG on a real training update, not just saved logits. import random from train5 import atomicstate path=ROOT/'acceptance/C_full_state.pt' state=dict(architecture='CEIR_R5',arm=arm,binding=bind,progress=dict(pg,update=9001),model=model.state_dict(),optimizer=opt.state_dict(), numpy_rng=np.random.get_state(),python_rng=random.getstate(),torch_rng=torch.get_rng_state(),cuda_rng=torch.cuda.get_rng_state_all()) atomicstate(path,state);del state from objectives5 import train_step model.train();before=train_step(model,opt,batch,9001,False)['loss'];del model,opt;free() model,opt,rr=make(arm,path,optimizer=True,binding=bind);model.train();after=train_step(model,opt,batch,9001,False)['loss'] if rr['update']!=9001 or abs(before-after)>5e-4:raise RuntimeError(f'resume parity {before} vs {after}') z['resume_loss_max_error']=abs(before-after) return zdef large_checks(warm): # Real, train-only, parent-score and full-denominator checks across target # sizes. Use no Test/CASMI queries. These are engineering/stability checks, # not generalization measurements on parent-unseen structures. out=[] for start,cap in ((0,256),(750,512),(1500,2048),(2250,5000)): best=None for i in range(start,start+750): row=prior.ft.loads(current_batch(LARGE,'%04d.z'%i).read_bytes())['expanded'] if row and len(row['ids'])==cap:best=(i,row['rid'],row['kind']);break if not best:raise RuntimeError('No real eligible large-pool batch of size '+str(cap)) i,rid,kind=best;bb=Batches('D',i,i+1,warm)[0] p=next(p for r in bb['rows'] if r['record_id']==rid for p in r['pools'] if p['kind']==kind) q=p['query'];assert len(q.candidates)==cap and len(set(p['ids']))==cap net,op,_=make('D',warm=warm);net.train();op.zero_grad(set_to_none=True);torch.cuda.reset_peak_memory_stats() # A single softmax across the entire real query; streamed graph tiles # are only activation checkpoints. Every candidate remains in the denominator. with prior.rt.amp(): enc=net.encode_batch([q])[0][0];sc=enc.base.float();loss=sc.logsumexp(0)-sc[0] tiled=torch.stack([s.logsumexp(0) for s in sc.split(37)]).logsumexp(0)-sc[0] err=abs(float(loss.detach()-tiled.detach()));loss.backward() norm=torch.nn.utils.clip_grad_norm_(net.parameters(),100.,error_if_nonfinite=True).item() if err>2e-5 or not math.isfinite(norm) or norm<=0:raise RuntimeError('invalid global denominator/gradient') out.append(dict(n=cap,batch=i,source='train',raw_view=kind,softmax_parity_error=err,gradient_norm=norm,ce=float(loss.detach()),gpu_peak_mib=torch.cuda.max_memory_allocated()/2**20)) del net,op,enc,sc,loss,tiled,bb,q,p;free() save(SMALL/'LARGE_GPU_PROBE.json',dict(complete=len(out)==4,rows=out,formal_updates=0)) return outdef run(warm=False): bind=None if warm else binding();dest=SMALL/('WARM_GPU.json' if warm else 'GPU_READY.json') if not warm and dest.exists() and read(dest)['binding']==bind and read(dest)['passed']:return with lease('accept'): original.setup();idx=None for i in range(20): p=prior.ft.loads(current_batch(BASE,'%04d.z'%i).read_bytes()) if len(p['rows'])>=256 and any(x['kind']=='odata' for r in p['rows'] for x in r['pools']): alt=prior.ft.loads(current_batch(LARGE,'%04d.z'%i).read_bytes()) if alt['expanded'] and len(alt['expanded']['ids'])>alt['expanded']['base_n']:idx=i;break if idx is None:raise RuntimeError('no complete real mixed batch for acceptance') b=Batches('A',idx,idx+1,warm)[0];q=next(p['query'] for r in b['rows'] for p in r['pools'] if p['kind']=='formula' and len(p['ids'])>=6) old,_,_=original.make('D',C['parent'],split='train',optimizer=False);old.feature_store=__import__('batch5').Store('train',warm);old.eval() with torch.inference_mode(),prior.rt.amp():s=old.encode_batch([q])[0][0].base.float().cpu() del old;free();arms={} for arm in C['arms']: arms[arm]=one(arm,warm,idx,q,s,bind);free() save(SMALL/('warm_'+arm+'.json' if warm else 'accept_'+arm+'.json'),arms[arm]) if not warm: lg=large_checks(False) import eval5 v=eval5.parent_validation_parity() else:lg=[];v=None save(dest,dict(passed=True,binding=bind,batch=idx,n_queries=len(b['rows']),arms=arms,large=lg,official_validation_parity=v,formal_updates=0,ts=time.time()))if __name__=='__main__': ap=argparse.ArgumentParser();ap.add_argument('--warm',action='store_true');args=ap.parse_args() try:run(args.warm) except Exception:save(SMALL/('WARM_ERROR.json' if args.warm else 'GPU_ERROR.json'),dict(error=traceback.format_exc(),ts=time.time()));raise12345678910111213[program:specpartition-r5-from-r4d-posthoc-20261112]directory=/root/xj/SpecPartition-MS/code/ceir_r5_from_r4d_12000_20261112command=/usr/bin/nice -n 12 /workspace/xj/SpecPartition-MS/.venv/bin/python -B -u addendum5.pyenvironment=OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1",CUDA_VISIBLE_DEVICES=""autostart=falseautorestart=falsestartsecs=1stopasgroup=truekillasgroup=truestdout_logfile=/root/xj/SpecPartition-MS/runs/ceir_r5_from_r4d_12000_20261112/posthoc.logstdout_logfile_maxbytes=1MBstdout_logfile_backups=1redirect_stderr=true1234567891011121314151617181920212223242526272829303132333435"""One-shot postprocessing: never changes the weights, release or primary metrics."""from collections import defaultdictimport sys,time,tracebackfrom paths5 import *def strata(rows,parent): buckets=defaultdict(lambda:dict(n=0,covered=0,gained=0,lost=0,parent_top1=0,model_top1=0,parent_top32=0,model_top32=0)) for key,r in rows.items(): oldrow=parent[key];size=r['candidate_count'];tag='<=256' if size<=256 else '257-1000' if size<=1000 else '1001-5000' if size<=5000 else '>5000' def hit(z,k):return z['rank'] is not None and z['rank']<=k for name in ('pool_size:'+tag,'adduct:'+str(r.get('adduct')),'polarity:'+str(r.get('polarity'))): b=buckets[r['view']+' | '+name];b['n']+=1;b['covered']+=int(r['reference_in_pool']);p=hit(oldrow,1);c=hit(r,1) b['gained']+=int(c and not p);b['lost']+=int(p and not c);b['parent_top1']+=int(p);b['model_top1']+=int(c) b['parent_top32']+=int(hit(oldrow,32));b['model_top32']+=int(hit(r,32)) return dict(buckets)def follow(): while not (SMALL/'FINAL_VERIFIED.json').exists(): if (SMALL/'PIPELINE_STATUS.json').exists() and read(SMALL/'PIPELINE_STATUS.json')['stage']=='blocked_see_error':raise RuntimeError('formal pipeline not complete') time.sleep(50) import report5 as rep source=read(SMALL/'FINAL_VERIFIED.json');assert source['complete'] and set(source['new_updates'].values())=={3000} splits={} for split in ('validation','msg_test','casmi2022'): p=rep.old.rows(rep.reference('R4-D_9000',split)) splits[split]={a:strata(rep.old.rows(rep.folder(a,12000,split)),p) for a in C['arms']} out=dict(final_file_sha=hashfile(SMALL/'FINAL_VERIFIED.json'),strata_vs_R4D=splits,promotion_deferred=True, independent_large_pool_development='Training-pool engineering checks do not measure generalization to parent-unseen spectra. Official full CASMI is report only, not a tuning set.', literature_only={'FLARE_v1_MSG_Test':{'mass_structure_hit_pct_1_5_20':[43.15,75.59,92.89],'formula_structure_hit_pct_1_5_20':[22.66,50,75.15], 'mces_mass_formula':[7.84,9.00],'uses_known_precursor_formula':True,'not_rerun':True,'source':'https://pmc.ncbi.nlm.nih.gov/articles/PMC12873900/'}}, ts=time.time()) save(SMALL/'EXTENDED_STRATA.json',out) from format_report5 import publish publish(SMALL)if __name__=='__main__': try:follow() except Exception:save(SMALL/'ADDENDUM_ERROR.json',dict(error=traceback.format_exc(),ts=time.time()));raise1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192"""Build verified new static descriptors, sharing R4/R3/R2 read-only. Losslesspacked representation avoids megabytes of float-zero padding in small fragments."""import collections,concurrent.futures as cf,fcntl,multiprocessing as mp,os,shutil,sqlite3,sys,time,traceback,zlib,pickleimport numpy as npfrom paths5 import *sys.path.insert(0,C['r4_code']);import prepare4 as olddef pack(x): y=dict(x);m=y.pop('members');used=m>0 # Each non-zero entry is identical within a row. Keep that float32 bit # pattern explicitly instead of recomputing 1/n in a different dtype. y['_bits']=np.packbits(used,axis=1);y['_weight']=m.max(1) if m.shape[1] else np.zeros(len(m),np.float32) return zlib.compress(pickle.dumps(y,protocol=5),3)def unpack(b): y=pickle.loads(zlib.decompress(b));bits=y.pop('_bits');w=y.pop('_weight') y['members']=np.unpackbits(bits,axis=1,count=y['atoms']).astype('float32')*w[:,None];return ydef init(): global rd,parents rd=old.Reader();parents=[(old.ro(C['r4_train_fragments']),'SELECT 1 FROM extra WHERE k=?'), (old.ro(old.R2/'prepared/assets.sqlite'),'SELECT 1 FROM canonical_features WHERE feature_key=? AND feature_sha IS NOT NULL'), (old.ro(old.R3/'prepared/assets.sqlite'),'SELECT 1 FROM r3_features WHERE feature_key=? AND feature_sha IS NOT NULL')]def block(pairs): rows=[];stats=collections.Counter() for gh,k in pairs: m=rd.molecule(gh) if m.identity!=k:raise ValueError('training structure key drift') fk=old.ft.key(m.smiles) for j,(db,q) in enumerate(parents): if db.execute(q,(fk,)).fetchone():stats[['r4','r2','r3'][j]]+=1;break else: v=old.ft.build(m.smiles) if old.ft.layout(m.mol)!=v['layout']:raise ValueError('unsafe feature atom layout') b=pack(v) if len(rows)==0 and not np.array_equal(unpack(b)['members'],v['members']):raise RuntimeError('packing changed features') rows.append((fk,b,bytes.fromhex(sha(b))));stats['new']+=1 return rows,statsdef run(): while not (LARGE/'READY.json').exists(): if (SMALL/'AUGMENT_ERROR.json').exists():raise RuntimeError('alternative pools not ready') time.sleep(4) FRESH.mkdir(parents=True,exist_ok=True);fd=(FRESH/'prepare.lock').open('a+');fcntl.flock(fd,fcntl.LOCK_EX|fcntl.LOCK_NB) bind=dict(random=read(BASE/'READY.json')['ledger_hash'],augmented=read(LARGE/'READY.json')['hash'],builder=hashfile(__file__)) if (FRESH/'PLAN.json').exists() and read(FRESH/'PLAN.json')!=bind:raise RuntimeError('stale feature cache') if (FRESH/'READY.json').exists() and read(FRESH/'READY.json')['binding']==bind:return save(FRESH/'PLAN.json',bind);store={};h0=read(BASE/'hashes.json');h1=read(LARGE/'hashes.json') def add(a,b): if store.setdefault(a,b)!=b:raise RuntimeError('conflicting graph key') for i in range(3000): name='%04d.z'%i;b=(BASE/'batches'/name).read_bytes();z=(LARGE/'batches'/name).read_bytes() if sha(b)!=h0[i] or sha(z)!=h1[i]:raise ValueError('changed data ledger') rr=old.ft.loads(b)['rows'];special=old.ft.loads(z) for r in rr: add(r['ref'],r['identity']) for p in r['pools']: for g,k in zip(p['graphs'],p['ids'],strict=True):add(g,k) for p in list(special['teacher'].values())+([special['expanded']] if special['expanded'] else []): for g,k in zip(p['graphs'],p['ids'],strict=True):add(g,k) if i%150==0:save(SMALL/'ASSET_STATUS.json',dict(phase='unique_candidate_index',batches=i,graphs=len(store),ts=time.time())) pairs=sorted(store.items());del store;bsize=768;n=(len(pairs)+bsize-1)//bsize db=sqlite3.connect(FRESH/'delta.sqlite',timeout=90);db.execute('PRAGMA page_size=32768');db.execute('PRAGMA journal_mode=WAL') db.execute('PRAGMA wal_autocheckpoint=180');db.execute('CREATE TABLE IF NOT EXISTS extra(k TEXT PRIMARY KEY,b BLOB NOT NULL,h BLOB NOT NULL) WITHOUT ROWID') db.execute('CREATE TABLE IF NOT EXISTS blocks(i INTEGER PRIMARY KEY, hash TEXT, stats TEXT)');db.commit() before=dict(db.execute('select i,hash from blocks'));starts=[] for i in range(n): if i in before: if before[i]!=old.objhash(pairs[i*bsize:(i+1)*bsize]):raise RuntimeError('block receipt changed') else:starts.append(i) it=iter(starts);jobs={};done=len(before);beg=time.monotonic() def status():save(SMALL/'ASSET_STATUS.json',dict(phase='offline_graph_and_fragment_audit',blocks=done,blocks_total=n,unique_graphs=len(pairs),ts=time.time(),seconds=time.monotonic()-beg)) status() with cf.ProcessPoolExecutor(8,mp_context=mp.get_context('fork'),initializer=init) as ex: while True: while len(jobs)<16: i=next(it,None) if i is None:break pp=pairs[i*bsize:(i+1)*bsize];jobs[ex.submit(block,pp)]=(i,old.objhash(pp)) if not jobs:break for f in cf.wait(jobs,return_when=cf.FIRST_COMPLETED).done: i,h=jobs.pop(f);rows,stats=f.result() db.executemany('insert or ignore into extra values(?,?,?)',rows);db.execute('insert into blocks values(?,?,?)',(i,h,json.dumps(stats)));db.commit();done+=1 if done%30==0: status() if shutil.disk_usage(ROOT).free<C['min_tmpfs_free_mib']*2**20:raise RuntimeError('tmpfs reserve; no old data removed') counts=collections.Counter() for s, in db.execute('select stats from blocks'):counts.update(json.loads(s)) assert done==n and sum(counts.values())==len(pairs) db.execute('PRAGMA wal_checkpoint(TRUNCATE)');db.close() ready=dict(binding=bind,complete=True,graphs=len(pairs),counts=dict(counts),sha256=hashfile(FRESH/'delta.sqlite')) save(FRESH/'READY.json',ready);save(SMALL/'ASSETS_READY.json',ready);status()if __name__=='__main__': try:run() except Exception:save(SMALL/'ASSET_ERROR.json',dict(error=traceback.format_exc(),ts=time.time()));raise123456789101112131415161718192021222324252627282930313233343536373839404142434445"""Identify *all* mismatched accepted-candidate record -> graph key bindings.No repair of a label by trusting an unrelated graph. Read only published source."""import json,sys,timefrom collections import Counter,defaultdictfrom paths5 import *sys.path.insert(0,C['r4_code']);import prepare4 as olddef main(): expected={};bad={};r=old.Reader();st=time.time() def index(g,k): if g in expected and expected[g]!=k:raise ValueError('graph used with two distinct recorded identities') expected[g]=k for j in range(3000): nm='%04d.z'%j;aa=old.ft.loads((BASE/'batches'/nm).read_bytes());bb=old.ft.loads((LARGE/'batches'/nm).read_bytes()) for row in aa['rows']: index(row['ref'],row['identity']) for p in row['pools']: for g,k in zip(p['graphs'],p['ids'],strict=True):index(g,k) for p in list(bb['teacher'].values())+([bb['expanded']] if bb['expanded'] else []): for g,k in zip(p['graphs'],p['ids'],strict=True):index(g,k) keys=sorted(expected) for i in range(0,len(keys),512): kk=keys[i:i+512];q='select graph_hash,identity,safety from graphs where graph_hash in ('+','.join(['?']*len(kk))+')' rows=list(r.assets.execute(q,kk));assert len(rows)==len(kk) for g,k,safety in rows: if expected[g]!=k or safety!='safe' or k in r.forbidden:bad[g]={'graph':g,'declared':expected[g],'actual':k,'safe':safety=='safe','heldout':k in r.forbidden} occurrences=Counter();detail=[];files=set() for j in range(3000): nm='%04d.z'%j;aa=old.ft.loads((BASE/'batches'/nm).read_bytes());bb=old.ft.loads((LARGE/'batches'/nm).read_bytes()) def test(g,k,role,typ,rid): if g in bad: assert k==bad[g]['declared'];occurrences[role]+=1;files.add(j) detail.append(dict(batch=j,rid=rid,role=role,kind=typ,graph=g)) for row in aa['rows']: test(row['ref'],row['identity'],'label','label',row['rid']) for p in row['pools']: for z,(g,k) in enumerate(zip(p['graphs'],p['ids'])):test(g,k,'base_positive' if not z else 'base_negative',p['kind'],row['rid']) for typ,ps in [('mining',bb['teacher'].values()),('large',[bb['expanded']] if bb['expanded'] else [])]: for p in ps: for z,(g,k) in enumerate(zip(p['graphs'],p['ids'])):test(g,k,typ+('_positive' if not z else '_negative'),p['kind'],p['rid']) out=dict(complete=True,total_graphs=len(keys),mismatches=list(bad.values()),occurrences=dict(occurrences),affected_batches=sorted(files), detail=detail,original_draw_ledger=read(BASE/'READY.json')['ledger_hash'],original_alternatives=read(LARGE/'READY.json')['hash'],seconds=time.time()-st) save(SMALL/'IDENTITY_AUDIT_V1.json',out) print(json.dumps({k:v for k,v in out.items() if k not in ('detail','affected_batches')})[:2500],flush=True)if __name__=='__main__':main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192"""Training-only offline alternative pools, preserving query IDs and cursor."""import concurrent.futures as cf, multiprocessing as mp,random,sys,time,os,traceback,fcntlfrom collections import Counterfrom functools import lru_cachefrom paths5 import *sys.path.insert(0,C['r4_code'])import prepare4 as oldfrom data09 import Reader,loadsH=read(HERE/'interventions.json')def u64(t):return int(sha(t.encode())[:16],16)def order_key(r,p):return (u64('R5/view/'+r['rid']+p['kind']),r['rid'])def init(): global rd,lookup rd=Reader() @lru_cache(maxsize=32768) def alias(s): v=rd.assets.execute('SELECT graph_hash FROM smiles WHERE smiles=?',(s,)).fetchone() if not v:raise RuntimeError('Missing accepted alias') return v[0] lookup=aliasdef universe(r,p): v=loads(rd.db.execute('SELECT body FROM samples WHERE record_id=?',(r['rid'],)).fetchone()[0]) if p['kind']=='odata': vv=v['view'];o=rd.pool(vv['pool_path'],vv['pool_sha256']);es=o['records'];allowed=o['safe_mass_order'][vv['mass_order_start']:vv['mass_order_stop']] else: o=rd.official(v['target'],p['kind']);es=o['entries'];allowed=[j for j,e in enumerate(es) if e['eligible_for_training']] by={} for j in allowed: ident=old.entry_identity(es[j]) if ident in rd.forbidden:raise ValueError('heldout candidate in accepted training view') if ident!=r['identity']:by.setdefault(ident,j) return es,bydef select(r,p,maxn,scope): es,by=universe(r,p);base=list(p['ids']);orig=set(base) if not set(base[1:])<=set(by):raise ValueError('base draw not in unmodified pool') extra=sorted(set(by)-orig) rng=random.Random(u64(f'R5/draw/{scope}/{r["rid"]}/{p["kind"]}')) if len(extra)>max(0,maxn-len(base)):extra=rng.sample(extra,max(0,maxn-len(base))) graphs=list(p['graphs']) for k in extra: e=es[by[k]];graphs.append(e.get('graph_hash') or lookup(e.get('canonical_smiles') or e['smiles'])) ids=base+extra assert len(ids)==len(set(ids))==len(graphs) and not(set(ids)&rd.forbidden) return dict(ids=ids,graphs=graphs,base_n=len(base),available=len(by)+1,kind=p['kind'],rid=r['rid'],truth=r['identity'], formulas=p['formulas'],negative_draws=len(ids)-1,unique_negative_key14=len(ids)-1,reference_injected=False)def make(i): dest=LARGE/'batches'/('%04d.z'%i);base=BASE/'batches'/dest.name if dest.exists():return i plan=old.ft.loads(base.read_bytes());by={k:[] for k in ('odata','mass','formula')} for r in plan['rows']: for p in r['pools']:by[p['kind']].append((r,p)) cands={} for k,rr in by.items(): for r,p in sorted(rr,key=lambda tup:order_key(*tup))[:H['B']['pools_per_kind']]: cands[(r['rid'],k)]=select(r,p,1+H['B']['mining_multiplier']*(len(p['ids'])-1),'mining') cap=H['D']['caps'][min(i//750,3)];large=None # Inspect real available sizes; choose without any model score. Base positives # were originally in pool. At most one expanded view per step. options=[] for k in ('odata','mass','formula'): for r,p in sorted(by[k],key=lambda tup:order_key(*tup))[:4]: item=cands.get((r['rid'],k));avail=item['available'] if item is not None else len(universe(r,p)[1])+1 if avail>len(p['ids']):options.append((min(avail,cap),k=='odata',-order_key(r,p)[0],r,p)) if options: _,_,_,r,p=max(options,key=lambda z:z[:3]);large=select(r,p,cap,'larger') b=old.ft.dumps(dict(index=i,base_sha=hashfile(base),teacher=cands,expanded=large,cap=cap)) t=dest.with_suffix('.tmp');t.write_bytes(b);os.replace(t,dest);return idef main(): while not (BASE/'READY.json').exists(): if (SMALL/'LEDGER_ERROR.json').exists():raise RuntimeError('base preparation error') time.sleep(4) LARGE.mkdir(exist_ok=True,parents=True);(LARGE/'batches').mkdir(exist_ok=True) fd=(LARGE/'prep.lock').open('a+');fcntl.flock(fd,fcntl.LOCK_EX|fcntl.LOCK_NB) binding=dict(ledger=read(BASE/'READY.json')['ledger_hash'],source=hashfile(__file__),settings=hashfile(HERE/'interventions.json')) if (LARGE/'PLAN.json').exists() and read(LARGE/'PLAN.json')!=binding:raise RuntimeError('changed prepared input binding') save(LARGE/'PLAN.json',binding) if (LARGE/'READY.json').exists() and read(LARGE/'READY.json')['binding']==binding:return with cf.ProcessPoolExecutor(6,mp_context=mp.get_context('fork'),initializer=init) as ex: for j,_ in enumerate(ex.map(make,range(3000),chunksize=4),1): if j%60==0:save(SMALL/'AUGMENT_STATUS.json',dict(done=j,total=3000,phase='training_only_alternative_draws',ts=time.time())) hs=[];views=Counter();stats={c:[] for c in H['D']['caps']};oldhash=read(BASE/'hashes.json') for i in range(3000): b=(LARGE/'batches'/('%04d.z'%i)).read_bytes();item=old.ft.loads(b);hs.append(sha(b));assert item['base_sha']==oldhash[i] and item['index']==i for _,p in item['teacher'].items():views[p['kind']]+=1 p=item['expanded'];stats[item['cap']].append(len(p['ids']) if p else 0) import numpy as np diag={str(c):dict(steps=len(z),nonzero=sum(x>0 for x in z),at_cap=sum(x==c for x in z),min=min(z),median=float(np.median(z)),maximum=max(z)) for c,z in stats.items()} out=dict(binding=binding,hash=old.objhash(hs),teacher_views=dict(views),larger_windows=diag) save(LARGE/'hashes.json',hs);save(LARGE/'READY.json',out);save(SMALL/'ALTERNATIVES_READY.json',out)if __name__=='__main__': try:main() except Exception:save(SMALL/'AUGMENT_ERROR.json',dict(error=traceback.format_exc(),ts=time.time()));raise1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980from dataclasses import replacefrom functools import lru_cacheimport sys,timefrom paths5 import *sys.path.insert(0,C['r4_code'])import common4 as oldfrom data09 import Reader,loadsfrom data4 import Fragments as Priorfrom assets5 import unpack
class Store(Prior): def __init__(self,split='train',warm=False): super().__init__(split,Path(C['r4_train_fragments']) if split=='train' else None) self.extras=[] if split=='train' and (NEWASSET/'READY.json').exists(): self.extras=[old.ro(s/'delta.sqlite') for s in (NEWASSET,FRESH)] elif split=='train' and (FRESH/'READY.json').exists():self.extras=[old.ro(FRESH/'delta.sqlite')] self.warm=warm if split=='train' and not warm and not self.extras:raise RuntimeError('unverified training cache') self.get=lru_cache(8192)(self.fetch) def fetch(self,smi): for ex in self.extras: rows=ex.execute('select b,h from extra where k=?',(old.ft.key(smi),)).fetchone() if rows: if not old.ft.digest_matches(rows[0],rows[1]):raise RuntimeError('altered static features') a=unpack(rows[0]) if a['smiles']!=smi or a['version']!=old.ft.VERSION:raise RuntimeError('feature identity mismatch') return a try:return super().fetch(smi) except RuntimeError as e: if self.warm and str(e).startswith('Missing precomputed fragment data'):return old.ft.build(smi) raise
class Batches: def __init__(self,arm,start,end,warm=False): self.arm=arm;self.start=start;self.end=end;self.rd=None;self.warm=warm def __len__(self):return self.end-self.start def __getitem__(self,j): if j>=len(self):raise IndexError(j) beg=time.monotonic();i=self.start+j;name='%04d.z'%i if self.rd is None: self.rd=Reader();self.store=Store('train',self.warm);self.hs=current_hashes(BASE) self.alt=current_hashes(LARGE) if self.arm in 'BDE' and (LARGE/'READY.json').exists() else None b=current_batch(BASE,name).read_bytes() if sha(b)!=self.hs[i]:raise RuntimeError('random batch hash drift') sel=old.ft.loads(b);alt={} if self.arm in 'BDE': z=current_batch(LARGE,name).read_bytes() if self.alt and self.alt[i]!=sha(z):raise RuntimeError('alternative batch hash drift') if not self.alt and not self.warm:raise RuntimeError('unverified alternative batch') alt=old.ft.loads(z) assert alt['base_sha']==self.hs[i] and alt['index']==i rows=[];rd=self.rd for s in sel['rows']: row=loads(rd.db.execute('select body from samples where record_id=?',(s['rid'],)).fetchone()[0]) ref=rd.molecule(s['ref']);assert ref.identity==row['identity']==s['identity'] and ref.identity not in rd.forbidden row.update(ref=ref,formulas=s['formulas'],pools=[]);row['query']=replace(row['query'],formula_candidates=row['formulas']) feat=self.store.get(ref.smiles) if old.ft.layout(ref.mol)!=feat['layout']:raise RuntimeError('wrong atom layout') row['chemical_counts']=feat['counts'] for p0 in s['pools']: p=p0;key=(s['rid'],p0['kind']);expanded=False if self.arm=='D' and alt.get('expanded') and key==(alt['expanded']['rid'],alt['expanded']['kind']): p=alt['expanded'];expanded=len(p['ids'])>len(p0['ids']) ms=tuple(rd.molecule(g) for g in p['graphs']);ids=[m.identity for m in ms] if ids!=p['ids'] or ids[0]!=ref.identity or len(set(ids))!=len(ids):raise RuntimeError('false negative') view='odata_oracle' if p['kind']=='odata' else 'msg_'+p['kind'] q=replace(row['query'],candidates=ms,formula_candidates=tuple(p['formulas']),candidate_view=view) item=dict(**p,query=q,positive_index=0,truth_identity=ref.identity,truth_formula=row['formula'],record_id=s['rid'], quality_eligible=bool(row['mass_ok']),spectrum_eligible=bool(row['mass_ok'] and old.ft.supported_positive(q,feat)), r5_expanded=expanded,r5_retention=False,r5_teacher_bank=None) if self.arm=='B' and key in alt['teacher']: t=alt['teacher'][key];tm=tuple(rd.molecule(g) for g in t['graphs']) if [m.identity for m in tm]!=t['ids'] or t['ids'][:len(ids)]!=ids:raise RuntimeError('changed teacher source') item['r5_teacher_bank']=(replace(q,candidates=tm),t['graphs']) if self.arm=='E' and key in alt['teacher']:item['r5_retention']=True row['pools'].append(item) rows.append(row) return dict(rows=rows,manifest_index=i,ledger_sha256=self.hs[i],epoch=sel['epoch'],step=sel['step'], data_seconds=time.monotonic()-beg)12345678910111213[program:specpartition-r5-from-r4d-data-20261112]directory=/root/xj/SpecPartition-MS/code/ceir_r5_from_r4d_12000_20261112command=/usr/bin/nice -n 10 /workspace/xj/SpecPartition-MS/.venv/bin/python -B -u data_pipeline.pyenvironment=PYTHONUNBUFFERED="1",OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1",CUDA_VISIBLE_DEVICES=""autostart=falseautorestart=falsestartsecs=1stopasgroup=truekillasgroup=truestdout_logfile=/root/xj/SpecPartition-MS/runs/ceir_r5_from_r4d_12000_20261112/data.logstdout_logfile_maxbytes=2MBstdout_logfile_backups=1redirect_stderr=true1234567891011import os,subprocess,sys,time,tracebackfrom paths5 import *def main(): for script in ['augment5.py','assets5.py']: job=subprocess.run([sys.executable,'-B','-u',str(HERE/script)],cwd=HERE) if job.returncode:raise RuntimeError(f'{script} failed: {job.returncode}') save(SMALL/'DATA_READY.json',dict(complete=True,storage='tmpfs',ledger=read(BASE/'READY.json')['ledger_hash'], augmented=read(LARGE/'READY.json')['hash'],assets=read(FRESH/'READY.json')['sha256'],ts=time.time()))if __name__=='__main__': try:main() except Exception:save(SMALL/'DATA_ERROR.json',dict(error=traceback.format_exc(),ts=time.time()));raise1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283"""R5-only outputs; the frozen R4 official pool adapter is reused verbatim."""import argparse,gzip,json,math,os,sqlite3,sys,time,zlib,shutilfrom pathlib import Pathimport numpy as np,torchfrom paths5 import *sys.path.insert(0,C['r4_code'])from common4 import lock,get,put,filehash,objhash,digest,ro,rt,R3from eval4 import table,dbpath,KS,FKS,metric,enginefrom train5 import binding,lease,make,originalOUT=ROOT/'arms';EVAL=ROOT/'evaluation_scores'def eval_dir(arm,u,dataset):return OUT/arm/('%s_%06d'%(dataset,u))def parent_validation_parity(): root=Path(C['parent']).parent/'validation_009000' d=get(root/'metrics.json');db=ro(dbpath('validation')) target=db.execute('select distinct target from spectra order by target limit 1').fetchone()[0] cache=sqlite3.connect('file:'+d['compact']+'?mode=ro&immutable=1',uri=True) z,b=cache.execute('select meta,scores from predictions where target=?',(target,)).fetchone();meta=json.loads(zlib.decompress(z));exp=np.frombuffer(zlib.decompress(b),dtype='<f4') errors={};counts={} for a in C['arms']: m,_,_=make(a,split='validation',optimizer=False);m.graph_chunk=32;m.local_chunk=32;m.eval() out,raw=table(m,db,target,'validation');act=np.frombuffer(raw,dtype='<f4') assert out['pool_order_hash']==meta['pool_order_hash'] and np.array_equal(np.isnan(exp),np.isnan(act)) for r,t in zip(out['rows'],meta['rows'],strict=True): assert all(r[k]==t[k] for k in ('identifier','view','rank','formula_rank','candidate_count','top1_smiles')) errors[a]=float(np.nanmax(abs(act-exp)));counts[a]=int(np.isfinite(act).sum()) if errors[a]>1e-5:raise RuntimeError('official unchanged parent path mismatch '+str((a,errors[a]))) del m;torch.cuda.empty_cache() cache.close();db.close();return dict(n_targets=1,real_validation_rows=len(meta['rows']),finite_scores=counts,max_error=errors)def run(arm,update,dataset): dest=eval_dir(arm,update,dataset);hold=lock(dest/'eval.lock');bind=binding() if dataset!='validation' and (update!=12000 or not (ROOT/'FROZEN_TEST.json').exists()):raise RuntimeError('Test is not frozen') ck=OUT/arm/('step_%06d.pt'%update);check=get(ck.with_suffix('.json')) if check['sha256']!=filehash(ck):raise RuntimeError('Invalid evaluation checkpoint') protocol=dict(dataset=dataset,arm=arm,update=update,checkpoint_sha=check['sha256'],binding_sha=objhash(bind), encoding='Per target: float32 little-endian in source order; NaN means no score; formulas follow each structure block. No pruning or substitution.', input_path=str(dbpath(dataset)),official_order_hash_per_target=True, fixed_input=engine.inputs(dataset) if dataset!='validation' else rt.LEGACY.bind(),truth_injection=False,limit=None) if (dest/'protocol.json').exists() and protocol!=get(dest/'protocol.json'):raise RuntimeError('Mixed evaluation binding') put(dest/'protocol.json',protocol) if (dest/'metrics.json').exists():return EVAL.mkdir(parents=True,exist_ok=True) compact=EVAL/arm/('%s_%06d.sqlite'%(dataset,update));compact.parent.mkdir(parents=True,exist_ok=True) out=sqlite3.connect(compact);out.execute('PRAGMA journal_mode=WAL');out.execute('CREATE TABLE IF NOT EXISTS predictions(target TEXT PRIMARY KEY,meta BLOB, scores BLOB) WITHOUT ROWID') out.execute('CREATE TABLE IF NOT EXISTS binding(hash TEXT PRIMARY KEY)') oid=objhash(protocol);old=out.execute('SELECT hash FROM binding').fetchall() if old and old!=[(oid,)]:raise ValueError('Stale compact predictions') out.execute('INSERT OR IGNORE INTO binding VALUES(?)',(oid,));out.commit() db=ro(dbpath(dataset));targets=[x[0] for x in db.execute('SELECT DISTINCT target FROM spectra ORDER BY target')] done={k[0] for k in out.execute('SELECT target FROM predictions')};assert done<=set(targets) with lease('eval_'+arm): original.setup();model,_,_=make(arm,ck,split='validation' if dataset=='validation' else 'test',optimizer=False,binding=bind);model.eval() model.graph_chunk=32;model.local_chunk=32 for j,target in enumerate(targets): if target in done:continue if j%40==0 and shutil.disk_usage(compact.parent).free<75*2**20:raise RuntimeError('Compact output filesystem reserve; source unchanged') meta,raw=table(model,db,target,dataset) out.execute('INSERT INTO predictions VALUES(?,?,?)',(target,zlib.compress(json.dumps(meta,separators=(',',':'),allow_nan=False).encode(),3),zlib.compress(raw,3))) if j%16==0:out.commit();put(dest/'status.json',dict(targets=j+1,total=len(targets),ts=time.time())) out.commit() rows=[] for m,s in out.execute('SELECT meta,scores FROM predictions ORDER BY target'): v=json.loads(zlib.decompress(m));raw=zlib.decompress(s) if digest(raw)!=v['score_sha256'] or len(raw)!=4*sum(r['candidate_count']+r['scored_formulas'] for r in v['rows']):raise RuntimeError('Compact output integrity error') rows.extend(v['rows']) out.execute('PRAGMA wal_checkpoint(TRUNCATE)');out.close();db.close() expected={'msg_test':17556,'validation':19429,'casmi2022':500}[dataset];views=sorted({r['view'] for r in rows}) assert len(rows)==expected*len(views) and set(views)==({'top10_blind'} if dataset=='casmi2022' else {'mass','formula'}) if dataset=='casmi2022':assert sum(r['candidate_count'] for r in rows)==1765420 and sum(r['reference_in_pool'] for r in rows)==467 results={} for v in views: rr=[r for r in rows if r['view']==v];assert len(rr)==len({r['identifier'] for r in rr})==expected results[v]=dict(n=expected,structure=metric(rr,'rank',KS),formula=metric(rr,'formula_rank',FKS), coverage=sum(r['reference_in_pool'] for r in rr),scoreable=sum(r['reference_scoreable_in_pool'] for r in rr)) if dataset!='validation': results[v].update(canonical=metric(rr,'canonical_rank',KS),full_inchikey=metric(rr,'inchikey_rank',KS)) tmp=dest/'rows.tmp.gz' with gzip.open(tmp,'wt',compresslevel=4) as f:json.dump(rows,f,separators=(',',':'),allow_nan=False) os.replace(tmp,dest/'per_spectrum_summary.json.gz') put(dest/'metrics.json',dict(complete=True,results=results,checkpoint=check,compact=str(compact),compact_sha256=filehash(compact),ts=time.time()))
if __name__=='__main__': p=argparse.ArgumentParser();p.add_argument('arm',choices=list(C['arms']));p.add_argument('update',type=int);p.add_argument('dataset',choices=['validation','msg_test','casmi2022']) a=p.parse_args();run(a.arm,a.update,a.dataset)code/snapshot/root/code/ceir_r3_20261110/audit_primitives.pyAdded+293
code/snapshot/root/code/ceir_r3_20261110/audit_r3.pyAdded+31
code/snapshot/root/code/ceir_r3_20261110/compact.supervisor.confAdded+11
code/snapshot/root/code/ceir_r3_20261110/compact_r3.pyAdded+75
code/snapshot/root/code/ceir_r3_20261110/config.jsonAdded+44
code/snapshot/root/code/ceir_r3_20261110/data_r2.pyAdded+51
code/snapshot/root/code/ceir_r3_20261110/features_r2.pyAdded+183
code/snapshot/root/code/ceir_r3_20261110/final_audit_r3.pyAdded+35
code/snapshot/root/code/ceir_r3_20261110/heads_r3.pyAdded+102
code/snapshot/root/code/ceir_r3_20261110/mces_r2.pyAdded+29
code/snapshot/root/code/ceir_r3_20261110/model_r2_new.pyAdded+205
code/snapshot/root/code/ceir_r3_20261110/objectives_r2.pyAdded+138
code/snapshot/root/code/ceir_r3_20261110/pipeline.supervisor.confAdded+12
code/snapshot/root/code/ceir_r3_20261110/pipeline_r3.pyAdded+71
code/snapshot/root/code/ceir_r3_20261110/prepare.supervisor.confAdded+12
code/snapshot/root/code/ceir_r3_20261110/prepare_r3.pyAdded+147
code/snapshot/root/code/ceir_r3_20261110/probe_r3.pyAdded+30
code/snapshot/root/code/ceir_r3_20261110/runtime_r2.pyAdded+128
code/snapshot/root/code/ceir_r3_20261110/test_mces_r2.pyAdded+26
code/snapshot/root/code/ceir_r3_20261110/test_r3.pyAdded+60
code/snapshot/root/code/ceir_r3_20261110/tests_r3.pyAdded+53
code/snapshot/root/code/ceir_r3_20261110/train_r2.pyAdded+111
code/snapshot/root/code/ceir_r3_20261110/validate_r2.pyAdded+109
code/snapshot/root/code/ceir_r4_9000_20261112/README.mdAdded+68
code/snapshot/root/code/ceir_r4_9000_20261112/accept4.pyAdded+72
code/snapshot/root/code/ceir_r4_9000_20261112/common4.pyAdded+45
code/snapshot/root/code/ceir_r4_9000_20261112/config.jsonAdded+21
code/snapshot/root/code/ceir_r4_9000_20261112/data4.pyAdded+61
code/snapshot/root/code/ceir_r4_9000_20261112/duel4.pyAdded+73
code/snapshot/root/code/ceir_r4_9000_20261112/eval4.pyAdded+161
code/snapshot/root/code/ceir_r4_9000_20261112/mces4.pyAdded+27
code/snapshot/root/code/ceir_r4_9000_20261112/model4.pyAdded+117
code/snapshot/root/code/ceir_r4_9000_20261112/objectives4.pyAdded+161
code/snapshot/root/code/ceir_r4_9000_20261112/pipeline.supervisor.confAdded+13
code/snapshot/root/code/ceir_r4_9000_20261112/pipeline4.pyAdded+69
code/snapshot/root/code/ceir_r4_9000_20261112/prep.supervisor.confAdded+12
code/snapshot/root/code/ceir_r4_9000_20261112/prepare4.pyAdded+143
code/snapshot/root/code/ceir_r4_9000_20261112/report4.pyAdded+59
code/snapshot/root/code/ceir_r4_9000_20261112/run4.pyAdded+140
code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/README.mdAdded+39
code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/accept5.pyAdded+107
code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/addendum.supervisor.confAdded+13
code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/addendum5.pyAdded+35
code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/assets5.pyAdded+92
code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/audit_identity5.pyAdded+45
code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/augment5.pyAdded+92
code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/batch5.pyAdded+80
code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/data.supervisor.confAdded+13
code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/data_pipeline.pyAdded+11
code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/eval5.pyAdded+83