diff --git a/code/snapshot/root/code/ceir_r3_20261110/audit_primitives.py b/code/snapshot/root/code/ceir_r3_20261110/audit_primitives.py new file mode 100644 index 0000000000000000000000000000000000000000..136588bd92215c45f017caa827c7935c6e2d7fa7 --- /dev/null +++ b/code/snapshot/root/code/ceir_r3_20261110/audit_primitives.py @@ -0,0 +1,293 @@ +"""Read-only independent checks for the frozen CEIR-R2 experiment. + +Kept OUTSIDE the frozen training release. No imported training/evaluation +helpers, no GPU access, no edits to checkpoints, candidate pools or predictions. +""" +import argparse +from collections import Counter, defaultdict +import gzip +import hashlib +import json +import math +from pathlib import Path +import random +import sqlite3 +import statistics +import 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) + + + diff --git a/code/snapshot/root/code/ceir_r3_20261110/audit_r3.py b/code/snapshot/root/code/ceir_r3_20261110/audit_r3.py new file mode 100644 index 0000000000000000000000000000000000000000..a5d6548991cb4ac4d444b9ee95ab7f8311cd99b9 --- /dev/null +++ b/code/snapshot/root/code/ceir_r3_20261110/audit_r3.py @@ -0,0 +1,31 @@ +"""Independent full-ledger accounting and source-cursor overlap proof.""" +from collections import Counter +from 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() diff --git a/code/snapshot/root/code/ceir_r3_20261110/compact.supervisor.conf b/code/snapshot/root/code/ceir_r3_20261110/compact.supervisor.conf new file mode 100644 index 0000000000000000000000000000000000000000..ac1d0f3605723bcda47f894f5321d68de930207a --- /dev/null +++ b/code/snapshot/root/code/ceir_r3_20261110/compact.supervisor.conf @@ -0,0 +1,11 @@ +[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.sqlite +directory=/root/xj/SpecPartition-MS/code/ceir_r3_20261110 +autostart=false +autorestart=false +startsecs=2 +stopasgroup=true +killasgroup=true +redirect_stderr=true +stdout_logfile=/root/xj/SpecPartition-MS/runs/ceir_r3_20261110/compact.log +environment=OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1" diff --git a/code/snapshot/root/code/ceir_r3_20261110/compact_r3.py b/code/snapshot/root/code/ceir_r3_20261110/compact_r3.py new file mode 100644 index 0000000000000000000000000000000000000000..5e485eb3081e2c9af4cdbaececc8187c1ec2b98e --- /dev/null +++ b/code/snapshot/root/code/ceir_r3_20261110/compact_r3.py @@ -0,0 +1,75 @@ +"""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 argparse +import hashlib +import json +from pathlib import Path +import sqlite3 +import time +import itertools +import multiprocessing +from concurrent.futures import ProcessPoolExecutor +import numpy as np +import 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) diff --git a/code/snapshot/root/code/ceir_r3_20261110/config.json b/code/snapshot/root/code/ceir_r3_20261110/config.json new file mode 100644 index 0000000000000000000000000000000000000000..1f63c3c51eeccfde46665fb206eac6dc76a967f1 --- /dev/null +++ b/code/snapshot/root/code/ceir_r3_20261110/config.json @@ -0,0 +1,44 @@ +{ + "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" +} diff --git a/code/snapshot/root/code/ceir_r3_20261110/data_r2.py b/code/snapshot/root/code/ceir_r3_20261110/data_r2.py new file mode 100644 index 0000000000000000000000000000000000000000..4bb5ac05b92a1b77e9a762fcf67e6d6626b76379 --- /dev/null +++ b/code/snapshot/root/code/ceir_r3_20261110/data_r2.py @@ -0,0 +1,51 @@ +"""Frozen draw ledger: no PubChem, RDKit parsing, or pool JSON in training.""" +from collections import Counter +from dataclasses import replace +import time +from runtime_r2 import * +import features_r2 as features +from 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) diff --git a/code/snapshot/root/code/ceir_r3_20261110/features_r2.py b/code/snapshot/root/code/ceir_r3_20261110/features_r2.py new file mode 100644 index 0000000000000000000000000000000000000000..a69212363803b1f50c5706b1507899e076951658 --- /dev/null +++ b/code/snapshot/root/code/ceir_r3_20261110/features_r2.py @@ -0,0 +1,183 @@ +"""Versioned label-free static candidate descriptors and connected cut hypotheses.""" +from functools import lru_cache +import hashlib +import itertools +import pickle +import sqlite3 +import struct +import zlib +import numpy as np +from rdkit import Chem,RDLogger +from rdkit.Chem import rdMolDescriptors + +VERSION='connected_cuts_r2_v1';K=32;TRAITS=7;CLASSES=33 +RDLogger.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('>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) diff --git a/code/snapshot/root/code/ceir_r3_20261110/final_audit_r3.py b/code/snapshot/root/code/ceir_r3_20261110/final_audit_r3.py new file mode 100644 index 0000000000000000000000000000000000000000..1ff88cc1f1f095f971a8244093208777b19e572c --- /dev/null +++ b/code/snapshot/root/code/ceir_r3_20261110/final_audit_r3.py @@ -0,0 +1,35 @@ +"""Re-sort every saved score without training or evaluator ranking helpers.""" +import json +from pathlib import Path +import audit_primitives as audit +HERE=Path(__file__).resolve().parent +C=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() diff --git a/code/snapshot/root/code/ceir_r3_20261110/heads_r3.py b/code/snapshot/root/code/ceir_r3_20261110/heads_r3.py new file mode 100644 index 0000000000000000000000000000000000000000..513fba79f63f8551f9f7dbb5f0b2492edf0530fb --- /dev/null +++ b/code/snapshot/root/code/ceir_r3_20261110/heads_r3.py @@ -0,0 +1,102 @@ +"""Label-free residual evidence. No reference identity or score-based pruning.""" +from collections import Counter,OrderedDict +import math +import numpy as np +import torch +from torch import nn +from torch.nn import functional as F +import 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()*correction diff --git a/code/snapshot/root/code/ceir_r3_20261110/mces_r2.py b/code/snapshot/root/code/ceir_r3_20261110/mces_r2.py new file mode 100644 index 0000000000000000000000000000000000000000..8245102363f15c201bdcc99baa938e71843b064b --- /dev/null +++ b/code/snapshot/root/code/ceir_r3_20261110/mces_r2.py @@ -0,0 +1,29 @@ +"""Validation MCES under the same R1 protocol, with a private resumable cache.""" +import argparse +import fcntl +import importlib.util +import json +from pathlib import Path +import sqlite3 +import 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) diff --git a/code/snapshot/root/code/ceir_r3_20261110/model_r2_new.py b/code/snapshot/root/code/ceir_r3_20261110/model_r2_new.py new file mode 100644 index 0000000000000000000000000000000000000000..7be4466af8f001fc616244b5d71bfaa1db470b43 --- /dev/null +++ b/code/snapshot/root/code/ceir_r3_20261110/model_r2_new.py @@ -0,0 +1,205 @@ +"""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 spectrum +heads; scoring never receives the reference identity, its counts, or its formula. +""" +import numpy as np +import torch +from torch import nn +from torch.nn import functional as F +from runtime_r2 import * +import features_r2 as features +from specpartition_ms.model_v122 import BidirectionalRanker +from specpartition_ms.model import Encoded,metadata +from specpartition_ms.fast_formula_r2 import forward_batch as original_formula_forward +from coarse_losses import ProjectionBank +from kernels import install_graph_kernel +from 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_lr diff --git a/code/snapshot/root/code/ceir_r3_20261110/objectives_r2.py b/code/snapshot/root/code/ceir_r3_20261110/objectives_r2.py new file mode 100644 index 0000000000000000000000000000000000000000..4a6bf6497ee2ec53063a20db344c98bef5c980a0 --- /dev/null +++ b/code/snapshot/root/code/ceir_r3_20261110/objectives_r2.py @@ -0,0 +1,138 @@ +"""Exact C03 active objectives, plus qualified chemistry / spectrum supervision.""" +from collections import Counter +import time +import numpy as np +import torch +from torch.nn import functional as F +from torch.utils.checkpoint import checkpoint as recompute +from runtime_r2 import * +from kernels import grouped_contrastive,formula_objective +from 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'].smiles1 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 result diff --git a/code/snapshot/root/code/ceir_r3_20261110/pipeline.supervisor.conf b/code/snapshot/root/code/ceir_r3_20261110/pipeline.supervisor.conf new file mode 100644 index 0000000000000000000000000000000000000000..d2e4fd2cd0fe0221e185a4652f7fb14360ffdafa --- /dev/null +++ b/code/snapshot/root/code/ceir_r3_20261110/pipeline.supervisor.conf @@ -0,0 +1,12 @@ +[program:specpartition-r3-pipeline-20261110] +directory=/root/xj/SpecPartition-MS/code/ceir_r3_20261110 +command=/usr/bin/nice -n 19 /workspace/xj/SpecPartition-MS/.venv/bin/python -u /root/xj/SpecPartition-MS/code/ceir_r3_20261110/pipeline_r3.py +environment=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=false +autorestart=false +startsecs=2 +stopasgroup=true +killasgroup=true +stdout_logfile=/dev/stdout +stdout_logfile_maxbytes=0 +redirect_stderr=true diff --git a/code/snapshot/root/code/ceir_r3_20261110/pipeline_r3.py b/code/snapshot/root/code/ceir_r3_20261110/pipeline_r3.py new file mode 100644 index 0000000000000000000000000000000000000000..25222d4f7f15eeda613ac07141e8e64ec2972664 --- /dev/null +++ b/code/snapshot/root/code/ceir_r3_20261110/pipeline_r3.py @@ -0,0 +1,71 @@ +"""Finite supervised execution: all arms +3000, Validation, fixed Test, MCES.""" +from collections import deque +from 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()));raise diff --git a/code/snapshot/root/code/ceir_r3_20261110/prepare.supervisor.conf b/code/snapshot/root/code/ceir_r3_20261110/prepare.supervisor.conf new file mode 100644 index 0000000000000000000000000000000000000000..5f9d000e735697af6a957d16640cd2d80c91d248 --- /dev/null +++ b/code/snapshot/root/code/ceir_r3_20261110/prepare.supervisor.conf @@ -0,0 +1,12 @@ +[program:specpartition-r3-prepare-20261110] +directory=/root/xj/SpecPartition-MS/code/ceir_r3_20261110 +command=/usr/bin/nice -n 19 /workspace/xj/SpecPartition-MS/.venv/bin/python -u /root/xj/SpecPartition-MS/code/ceir_r3_20261110/prepare_r3.py +environment=PROC_NAME="specpartition-r3-prepare-20261110",OMP_NUM_THREADS="1",MKL_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",PYTHONUNBUFFERED="1" +autostart=false +autorestart=false +startsecs=2 +stopasgroup=true +killasgroup=true +stdout_logfile=/dev/stdout +stdout_logfile_maxbytes=0 +redirect_stderr=true diff --git a/code/snapshot/root/code/ceir_r3_20261110/prepare_r3.py b/code/snapshot/root/code/ceir_r3_20261110/prepare_r3.py new file mode 100644 index 0000000000000000000000000000000000000000..7cf13b3446590f14eb216f03fc0ef12e4c7651a9 --- /dev/null +++ b/code/snapshot/root/code/ceir_r3_20261110/prepare_r3.py @@ -0,0 +1,147 @@ +"""Independent 3000-update ledger and compact read-only-parent feature overlay.""" +from collections import Counter +from concurrent.futures import ProcessPoolExecutor +from functools import lru_cache +import multiprocessing +import random +import sqlite3 +import time +import numpy as np +from rdkit import Chem +from runtime_r2 import * +import features_r2 as ft +from data09 import Reader +from 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['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']) diff --git a/code/snapshot/root/code/ceir_r3_20261110/test_mces_r2.py b/code/snapshot/root/code/ceir_r3_20261110/test_mces_r2.py new file mode 100644 index 0000000000000000000000000000000000000000..ccbb9c16f3eccdef1709cf73937c41dae0505525 --- /dev/null +++ b/code/snapshot/root/code/ceir_r3_20261110/test_mces_r2.py @@ -0,0 +1,26 @@ +"""Post-hoc Test MCES, inherited fixed protocol and a private pair cache.""" +import argparse +import fcntl +import importlib.util +import json +from pathlib import Path +import sys +import 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) diff --git a/code/snapshot/root/code/ceir_r3_20261110/test_r3.py b/code/snapshot/root/code/ceir_r3_20261110/test_r3.py new file mode 100644 index 0000000000000000000000000000000000000000..47ec3bda9fdb3e60d58b15ede148585e8200fc9e --- /dev/null +++ b/code/snapshot/root/code/ceir_r3_20261110/test_r3.py @@ -0,0 +1,60 @@ +"""Full original pools, no Top256 restriction, no injected references.""" +import argparse +from 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) diff --git a/code/snapshot/root/code/ceir_r3_20261110/tests_r3.py b/code/snapshot/root/code/ceir_r3_20261110/tests_r3.py new file mode 100644 index 0000000000000000000000000000000000000000..3fc2022adf501516dc660d8fb59884ae1d0ac77f --- /dev/null +++ b/code/snapshot/root/code/ceir_r3_20261110/tests_r3.py @@ -0,0 +1,53 @@ +"""Small deterministic tests independent of private data / server imports.""" +import unittest +from types import SimpleNamespace +import numpy as np +import torch +from rdkit import Chem +from heads_r3 import Heads +import 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() diff --git a/code/snapshot/root/code/ceir_r3_20261110/train_r2.py b/code/snapshot/root/code/ceir_r3_20261110/train_r2.py new file mode 100644 index 0000000000000000000000000000000000000000..99bda3fa59a1290aef9dac2990165a2818cb43c6 --- /dev/null +++ b/code/snapshot/root/code/ceir_r3_20261110/train_r2.py @@ -0,0 +1,111 @@ +"""Exactly +3000 updates from frozen A3 3k; joint objectives throughout.""" +import argparse +import fcntl +import json +import math +import time +import traceback +import uuid +from 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: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));raise diff --git a/code/snapshot/root/code/ceir_r3_20261110/validate_r2.py b/code/snapshot/root/code/ceir_r3_20261110/validate_r2.py new file mode 100644 index 0000000000000000000000000000000000000000..23b8a089435d194b69c44a9b3eb4bc870bbd57ea --- /dev/null +++ b/code/snapshot/root/code/ceir_r3_20261110/validate_r2.py @@ -0,0 +1,109 @@ +"""Unchanged official Validation, fixed numerical batching, all ranked scores.""" +from dataclasses import replace +import gzip +import fcntl +import hashlib +import json +import time +import torch +from runtime_r2 import * +from validation_ceir import metric,KS,FKS +from 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) diff --git a/code/snapshot/root/code/ceir_r4_9000_20261112/README.md b/code/snapshot/root/code/ceir_r4_9000_20261112/README.md new file mode 100644 index 0000000000000000000000000000000000000000..dde2cc40b2b4f0c3dc6d29ed7e3c23877f08e6e0 --- /dev/null +++ b/code/snapshot/root/code/ceir_r4_9000_20261112/README.md @@ -0,0 +1,68 @@ +# 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. A +disposable 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 residual +uses at most 32 model-selected distinct key14s, compares only rivals of the +same formula, and is initialized to exactly zero. It uses raw spectrum peaks, +their aligned encoder tokens, molecular embeddings and the inherited fragment +hypotheses (not CSI rankings or identities as learned features). Equivalent +aliases may share a residual, but the original official pool entries and ranks +are preserved. B and D use detached **pre-duel** scores to identify up to three +wrong 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 draws +are 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)**; last +consumed 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 Train +spectrum 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 external +same-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 run +four 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 new +state is saved; durable state copies are independently hash-checked. 7k and 8k +are 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 for +each arm, independent ledger-chain/cursor checks pass, the full Validation, +fixed Test and MCES results exist, and `ALL_RESULTS.json` is present. Training +progress 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 and +CASMI full-pool endpoints; paired wins, new failures, confidence intervals and +valid MCES denominators. Report ties/regressions explicitly. + +The follow-up analysis script outside the frozen training release verifies all +four distinct 3,000-step ledgers and the raw endpoint comparisons. Before any +new full validation result was available, the effect audit was set to require +a positive fixed-endpoint Formula Top1 difference over A (key14-cluster bootstrap, +one-sided lower bound adjusted for three prespecified arms), positive difference +over the 6k parent, Mass Top1/5/20 and Formula Top5/20 loss of no more than +0.2 percentage points vs A, and per-view common-prediction MCES worsening of +at most 0.10 vs A. These are single-seed decision rules, not a guarantee +of efficacy or an instruction to continue tuning against the test split. diff --git a/code/snapshot/root/code/ceir_r4_9000_20261112/accept4.py b/code/snapshot/root/code/ceir_r4_9000_20261112/accept4.py new file mode 100644 index 0000000000000000000000000000000000000000..e0b98110263b17faa90b5c64d136c030a2952ad6 --- /dev/null +++ b/code/snapshot/root/code/ceir_r4_9000_20261112/accept4.py @@ -0,0 +1,72 @@ +"""Disposable real GPU steps; only the final *new-ledger* gate authorizes training.""" +import argparse,gc +from dataclasses import replace +import torch +from common4 import * +from model4 import make,setup +from run4 import lease,atomic_torch +from data4 import Batches +from objectives4 import train_step +def 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()));raise diff --git a/code/snapshot/root/code/ceir_r4_9000_20261112/common4.py b/code/snapshot/root/code/ceir_r4_9000_20261112/common4.py new file mode 100644 index 0000000000000000000000000000000000000000..9b0ef27ca390364c8c585781de88b8a285ab9132 --- /dev/null +++ b/code/snapshot/root/code/ceir_r4_9000_20261112/common4.py @@ -0,0 +1,45 @@ +"""R4 owns only its timestamped paths. Imports the immutable R3 implementation.""" +import os,sys,json,time,hashlib,gzip,fcntl,shutil,tempfile,sqlite3 +from pathlib import Path +HERE=Path(__file__).resolve().parent +CFG=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 rt +import features_r2 as ft +sys.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 f +def 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 x +def 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']) diff --git a/code/snapshot/root/code/ceir_r4_9000_20261112/config.json b/code/snapshot/root/code/ceir_r4_9000_20261112/config.json new file mode 100644 index 0000000000000000000000000000000000000000..c58b1357a3e226f14b4c315b4b827206e88c6780 --- /dev/null +++ b/code/snapshot/root/code/ceir_r4_9000_20261112/config.json @@ -0,0 +1,21 @@ +{ + "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 +} diff --git a/code/snapshot/root/code/ceir_r4_9000_20261112/data4.py b/code/snapshot/root/code/ceir_r4_9000_20261112/data4.py new file mode 100644 index 0000000000000000000000000000000000000000..101f6c19fa96e92f8ab9117a5948d25eaed17d2b --- /dev/null +++ b/code/snapshot/root/code/ceir_r4_9000_20261112/data4.py @@ -0,0 +1,61 @@ +from collections import Counter +from dataclasses import replace +from functools import lru_cache +from 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) diff --git a/code/snapshot/root/code/ceir_r4_9000_20261112/duel4.py b/code/snapshot/root/code/ceir_r4_9000_20261112/duel4.py new file mode 100644 index 0000000000000000000000000000000000000000..5f942db668cea5abd2a62f2f2dfbc734198bd133 --- /dev/null +++ b/code/snapshot/root/code/ceir_r4_9000_20261112/duel4.py @@ -0,0 +1,73 @@ +"""Experimental CSI-free evidence reranker. One original pool per call. + +peak_support[i,p] is label-free, adduct-aware candidate fragment support on +observed 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 torch +from torch import nn +from 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} diff --git a/code/snapshot/root/code/ceir_r4_9000_20261112/eval4.py b/code/snapshot/root/code/ceir_r4_9000_20261112/eval4.py new file mode 100644 index 0000000000000000000000000000000000000000..ec6c1674feb785e088619bfcaa5db41ad0df4ae4 --- /dev/null +++ b/code/snapshot/root/code/ceir_r4_9000_20261112/eval4.py @@ -0,0 +1,161 @@ +"""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,math +from dataclasses import replace +import torch +import numpy as np +from common4 import * +from model4 import setup,make +from run4 import lease +from data09 import loads +from validation_ceir import KS,FKS,metric +from specpartition_ms.chemistry import canonical_formula,formula_vector +EVAL_CODE=Path('/root/xj/SpecPartition-MS/code/ceir_r1_test_comparison_20261110') +sys.path.insert(0,str(EVAL_CODE)) +import infer as engine +engine.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,errors +def 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='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) diff --git a/code/snapshot/root/code/ceir_r4_9000_20261112/mces4.py b/code/snapshot/root/code/ceir_r4_9000_20261112/mces4.py new file mode 100644 index 0000000000000000000000000000000000000000..d86566ba2a33ea8b34ce949fc1d9a959bd57c485 --- /dev/null +++ b/code/snapshot/root/code/ceir_r4_9000_20261112/mces4.py @@ -0,0 +1,27 @@ +"""Dedicated CPU environment; inherited validated MCES protocols, private caches only.""" +import argparse,fcntl,importlib.util,json,os,sqlite3,sys +from pathlib import Path +HERE=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 m +def 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) diff --git a/code/snapshot/root/code/ceir_r4_9000_20261112/model4.py b/code/snapshot/root/code/ceir_r4_9000_20261112/model4.py new file mode 100644 index 0000000000000000000000000000000000000000..ddf15fe505a7ae4734c6c9fe40c3b8996c64a746 --- /dev/null +++ b/code/snapshot/root/code/ceir_r4_9000_20261112/model4.py @@ -0,0 +1,117 @@ +"""Base R3D scores for every candidate, with optional bounded pair evidence.""" +import gc +import numpy as np +import torch +from torch.nn import functional as F +from common4 import * +from data4 import Fragments +from model_r2_new import R2Ranker +from 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,progress diff --git a/code/snapshot/root/code/ceir_r4_9000_20261112/objectives4.py b/code/snapshot/root/code/ceir_r4_9000_20261112/objectives4.py new file mode 100644 index 0000000000000000000000000000000000000000..9e011d37626762b9cd35b67f7d1f5df801356624 --- /dev/null +++ b/code/snapshot/root/code/ceir_r4_9000_20261112/objectives4.py @@ -0,0 +1,161 @@ +"""Exact C03 active objectives, plus qualified chemistry / spectrum supervision.""" +from collections import Counter +import time +import numpy as np +import torch +from torch.nn import functional as F +from torch.utils.checkpoint import checkpoint as recompute +from common4 import CFG,rt +from runtime_r2 import * +from kernels import grouped_contrastive,formula_objective +from 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'].smiles1 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 result diff --git a/code/snapshot/root/code/ceir_r4_9000_20261112/pipeline.supervisor.conf b/code/snapshot/root/code/ceir_r4_9000_20261112/pipeline.supervisor.conf new file mode 100644 index 0000000000000000000000000000000000000000..c2a963ea689e778465d229654bc390a55a0dd141 --- /dev/null +++ b/code/snapshot/root/code/ceir_r4_9000_20261112/pipeline.supervisor.conf @@ -0,0 +1,13 @@ +[program:specpartition-r4-9000-pipeline-20261112] +directory=/root/xj/SpecPartition-MS/code/ceir_r4_9000_20261112 +command=/usr/bin/nice -n 12 /workspace/xj/SpecPartition-MS/.venv/bin/python -B -u pipeline4.py +environment=PYTHONUNBUFFERED="1",OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1",CUBLAS_WORKSPACE_CONFIG=":4096:8" +autostart=true +autorestart=unexpected +exitcodes=0,2 +startsecs=2 +stopasgroup=true +killasgroup=true +stdout_logfile=/root/xj/SpecPartition-MS/runs/ceir_r4_9000_20261112/pipeline.log +stdout_logfile_maxbytes=20MB +redirect_stderr=true diff --git a/code/snapshot/root/code/ceir_r4_9000_20261112/pipeline4.py b/code/snapshot/root/code/ceir_r4_9000_20261112/pipeline4.py new file mode 100644 index 0000000000000000000000000000000000000000..e5ae935ead4e7a0aa5dcf0b0324696c957df6551 --- /dev/null +++ b/code/snapshot/root/code/ceir_r4_9000_20261112/pipeline4.py @@ -0,0 +1,69 @@ +"""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,traceback +from 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) diff --git a/code/snapshot/root/code/ceir_r4_9000_20261112/prep.supervisor.conf b/code/snapshot/root/code/ceir_r4_9000_20261112/prep.supervisor.conf new file mode 100644 index 0000000000000000000000000000000000000000..8ccf0d751d3682db66293e287414812fd3a3ba94 --- /dev/null +++ b/code/snapshot/root/code/ceir_r4_9000_20261112/prep.supervisor.conf @@ -0,0 +1,12 @@ +[program:specpartition-r4-9000-prepare-20261112] +directory=/root/xj/SpecPartition-MS/code/ceir_r4_9000_20261112 +command=/usr/bin/nice -n 12 /workspace/xj/SpecPartition-MS/.venv/bin/python -B -u prepare4.py +environment=PYTHONUNBUFFERED="1",OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1",CUDA_VISIBLE_DEVICES="" +autostart=false +autorestart=false +startsecs=1 +stopasgroup=true +killasgroup=true +stdout_logfile=/root/xj/SpecPartition-MS/runs/ceir_r4_9000_20261112/prep.log +stdout_logfile_maxbytes=20MB +redirect_stderr=true diff --git a/code/snapshot/root/code/ceir_r4_9000_20261112/prepare4.py b/code/snapshot/root/code/ceir_r4_9000_20261112/prepare4.py new file mode 100644 index 0000000000000000000000000000000000000000..c5fdf19c710af836a69b9b028252a9cf7c51000f --- /dev/null +++ b/code/snapshot/root/code/ceir_r4_9000_20261112/prepare4.py @@ -0,0 +1,143 @@ +"""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 mp +from functools import lru_cache +from common4 import * +from data09 import Reader,loads +from sampling import epoch_plans,plan_hash +from prepare_ceir import entry_identity +START=6000; N=3000 +def 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 idx +def 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,counts +def 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) R4 continuation. Atomic rolling state, no old run writes.""" +import argparse,gc,math,random,contextlib,subprocess +import numpy as np +import torch +from common4 import * +from model4 import make,setup +from data4 import Batches +from 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']=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: + 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()));raise diff --git a/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/README.md b/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/README.md new file mode 100644 index 0000000000000000000000000000000000000000..cbf8b70b6ce2ea97088dcdd749552e04cee2abaf --- /dev/null +++ b/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/README.md @@ -0,0 +1,39 @@ +# 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 上传权重。 diff --git a/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/accept5.py b/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/accept5.py new file mode 100644 index 0000000000000000000000000000000000000000..3df05e208d9a1cda30cbb69d3f03cd7cf4f5e805 --- /dev/null +++ b/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/accept5.py @@ -0,0 +1,107 @@ +"""Independent checks on full copied states and real batches. No formal updates.""" +import argparse,contextlib,gc,math,os,sys,time,traceback +from dataclasses import replace +from paths5 import * +import numpy as np,torch +from train5 import Batches,binding,lease,make,original,prior,step,teacher +from model5 import H +from teacher5 import annotate +from forward5 import Evidence +def 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,order +def 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 z +def 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 out +def 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()));raise diff --git a/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/addendum.supervisor.conf b/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/addendum.supervisor.conf new file mode 100644 index 0000000000000000000000000000000000000000..17e3596574ee713ae031fab0aa2bc8aec6a4e9d4 --- /dev/null +++ b/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/addendum.supervisor.conf @@ -0,0 +1,13 @@ +[program:specpartition-r5-from-r4d-posthoc-20261112] +directory=/root/xj/SpecPartition-MS/code/ceir_r5_from_r4d_12000_20261112 +command=/usr/bin/nice -n 12 /workspace/xj/SpecPartition-MS/.venv/bin/python -B -u addendum5.py +environment=OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1",CUDA_VISIBLE_DEVICES="" +autostart=false +autorestart=false +startsecs=1 +stopasgroup=true +killasgroup=true +stdout_logfile=/root/xj/SpecPartition-MS/runs/ceir_r5_from_r4d_12000_20261112/posthoc.log +stdout_logfile_maxbytes=1MB +stdout_logfile_backups=1 +redirect_stderr=true diff --git a/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/addendum5.py b/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/addendum5.py new file mode 100644 index 0000000000000000000000000000000000000000..ed11b0e486f7124d9f0dd693038c986c6ddb92b2 --- /dev/null +++ b/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/addendum5.py @@ -0,0 +1,35 @@ +"""One-shot postprocessing: never changes the weights, release or primary metrics.""" +from collections import defaultdict +import sys,time,traceback +from 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()));raise diff --git a/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/assets5.py b/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/assets5.py new file mode 100644 index 0000000000000000000000000000000000000000..0c37ef0cecdc232267752ad09f7abcfdad9f9e06 --- /dev/null +++ b/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/assets5.py @@ -0,0 +1,92 @@ +"""Build verified new static descriptors, sharing R4/R3/R2 read-only. Lossless +packed 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,pickle +import numpy as np +from paths5 import * +sys.path.insert(0,C['r4_code']);import prepare4 as old +def 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 y +def 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,stats +def 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 graph key bindings. +No repair of a label by trusting an unrelated graph. Read only published source. +""" +import json,sys,time +from collections import Counter,defaultdict +from paths5 import * +sys.path.insert(0,C['r4_code']);import prepare4 as old +def 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() diff --git a/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/augment5.py b/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/augment5.py new file mode 100644 index 0000000000000000000000000000000000000000..fb1bfcbe992fd8a8f78a1b37843be349d41c6ef9 --- /dev/null +++ b/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/augment5.py @@ -0,0 +1,92 @@ +"""Training-only offline alternative pools, preserving query IDs and cursor.""" +import concurrent.futures as cf, multiprocessing as mp,random,sys,time,os,traceback,fcntl +from collections import Counter +from functools import lru_cache +from paths5 import * +sys.path.insert(0,C['r4_code']) +import prepare4 as old +from data09 import Reader,loads +H=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=alias +def 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,by +def 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 i +def 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()));raise diff --git a/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/batch5.py b/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/batch5.py new file mode 100644 index 0000000000000000000000000000000000000000..5c6ddc677f6aaa44b1deea605ca862d6741fe388 --- /dev/null +++ b/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/batch5.py @@ -0,0 +1,80 @@ +from dataclasses import replace +from functools import lru_cache +import sys,time +from paths5 import * +sys.path.insert(0,C['r4_code']) +import common4 as old +from data09 import Reader,loads +from data4 import Fragments as Prior +from 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) diff --git a/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/data.supervisor.conf b/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/data.supervisor.conf new file mode 100644 index 0000000000000000000000000000000000000000..6f06384015a96dd800d8eee9ca2848736fbc5444 --- /dev/null +++ b/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/data.supervisor.conf @@ -0,0 +1,13 @@ +[program:specpartition-r5-from-r4d-data-20261112] +directory=/root/xj/SpecPartition-MS/code/ceir_r5_from_r4d_12000_20261112 +command=/usr/bin/nice -n 10 /workspace/xj/SpecPartition-MS/.venv/bin/python -B -u data_pipeline.py +environment=PYTHONUNBUFFERED="1",OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1",CUDA_VISIBLE_DEVICES="" +autostart=false +autorestart=false +startsecs=1 +stopasgroup=true +killasgroup=true +stdout_logfile=/root/xj/SpecPartition-MS/runs/ceir_r5_from_r4d_12000_20261112/data.log +stdout_logfile_maxbytes=2MB +stdout_logfile_backups=1 +redirect_stderr=true diff --git a/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/data_pipeline.py b/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/data_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..129f22945e77c559293399967f3566ec09c47b19 --- /dev/null +++ b/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/data_pipeline.py @@ -0,0 +1,11 @@ +import os,subprocess,sys,time,traceback +from 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()));raise diff --git a/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/eval5.py b/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/eval5.py new file mode 100644 index 0000000000000000000000000000000000000000..38f6a678818e6c0572cf64cd67d1507e08f63ab5 --- /dev/null +++ b/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/eval5.py @@ -0,0 +1,83 @@ +"""R5-only outputs; the frozen R4 official pool adapter is reused verbatim.""" +import argparse,gzip,json,math,os,sqlite3,sys,time,zlib,shutil +from pathlib import Path +import numpy as np,torch +from paths5 import * +sys.path.insert(0,C['r4_code']) +from common4 import lock,get,put,filehash,objhash,digest,ro,rt,R3 +from eval4 import table,dbpath,KS,FKS,metric,engine +from train5 import binding,lease,make,original +OUT=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='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) diff --git a/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/format_report5.py b/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/format_report5.py new file mode 100644 index 0000000000000000000000000000000000000000..4d8a779bbe6534ac5d157ce9f1e10e54398c0e7f --- /dev/null +++ b/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/format_report5.py @@ -0,0 +1,63 @@ +"""Render a finished experiment only; never fill in missing runs.""" +import argparse,json,os +from pathlib import Path +NAMES={'A':'原样续训','B':'困难负例重采样','C':'独占碎片峰残差','D':'大池训练','E':'单侧保序'} +K=[1,3,5,10,20,50,100,200] +def read(p):return json.loads(p.read_bytes()) +def pretty(v):return '—' if v is None else f'{v:.3f}' +def hk(z,k):return f"{100*z[str(k)]['hits']/z[str(k)]['denominator']:.2f}" +def build(base): + j=read(base/'FINAL_VERIFIED.json');extra=read(base/'EXTENDED_STRATA.json') + import hashlib + assert hashlib.sha256((base/'FINAL_VERIFIED.json').read_bytes()).hexdigest()==extra['final_file_sha'] + return render(j,extra) +def render(j,extra): + assert j['complete'] and set(j['new_updates'])==set(NAMES) and set(j['new_updates'].values())=={3000} + lines=['# R5:R4-D 9k 续训至 12k,五个固定终点的对照结果','', + '五组均完成 3,000 个新更新,共 15,000 个。全量 Validation 选模,全部预定终点均报告;不能用 Test 或 CASMI 的最高一行事后选模型。',''] + passed=[a for a,x in j['validation_decisions'].items() if x['primary_meets_single_seed']] + lines.append('**Validation 结论:** '+('、'.join(passed)+' 达到预登记的单种子主指标与保护条件,还不是多种子复现。' if passed else '没有优化分支同时满足预登记的主指标与保护条件;不宣布超过同预算对照。')) + lines+=['','下列 Top-K 是二维连接结构检索命中百分比;Mass 和 Formula 是不同的官方候选视图。MCES 越低越好,报告有效分母。',''] + for ds,label,views in [('validation','MSG Validation',['mass','formula']),('msg_test','MSG Test',['mass','formula']),('casmi2022','CASMI 全候选池',['top10_blind'])]: + ab=j['evaluations'][ds];lines+=['## '+label,''] + for view in views: + lines+=['### '+view,'','| 分支 | '+' | '.join('Top'+str(k) for k in K)+' | MCES@1 | 有效/全部 |','|'+ '|'.join(['---']+['---:']*(len(K)+2))+'|'] + for a,name in NAMES.items(): + d=ab[a];r=d['results'][view];mc=d['MCES']['views'][view] + lines.append('| '+a+' '+name+' | '+' | '.join(hk(r['structure'],k) for k in K)+f" | {pretty(mc['valid_mean'])} | {mc['valid']}/{mc['n']} |") + lines+=['','| 分支 | 对 R4-D 救回 / 改错 | 对 R4-D ΔTop1(百分点) | 对原始 R3D Δ | 对同预算 A Δ(配对 95%) |','|---|---:|---:|---:|---:|'] + for a in NAMES: + comp=ab[a]['paired'];p=comp['R4-D_9000'][view]['1'];o=comp['R3D_6000'][view]['1'];ctrl=comp['matched_A'][view]['1'];ci=ctrl['ci95_pp'] + lines.append(f"| {a} | {p['added']} / {p['lost']} | {p['net_pp']:+.2f} | {o['net_pp']:+.2f} | {ctrl['net_pp']:+.2f} [{ci[0]:+.2f}, {ci[1]:+.2f}] |") + lines+=[''] + if view in ('mass','top10_blind'): + ks=[1,2,3,4,5,6,7,8,9,10] + lines+=['公式指标是**给定池内公式的排序**,不是开放式生成。','', + '| 分支 | '+' | '.join('公式@'+str(k) for k in ks)+' |','|'+'|'.join(['---']+['---:']*len(ks))+'|'] + for a in NAMES: + z=ab[a]['results'][view]['formula'] + lines.append('| '+a+' | '+' | '.join(hk(z,k) if str(k) in z else '未记录' for k in ks)+' |') + lines+=[''] + if ds=='casmi2022': + lines+=['500 条,1,765,420 个原始候选位置;467/500 原池含真值,33 条缺失仍计入分母,不限为 256、不补真值。','', + '| 分支 | 相对同池 CSI Top1 净差(条) | 候选 >5,000:救回 / 改错(对 R4-D) |','|---|---:|---:|'] + for a in NAMES: + x=ab[a]['paired']['CSI_same_full_pool']['top10_blind']['1'];large=extra['strata_vs_R4D'][ds][a]['top10_blind | pool_size:>5000'] + lines.append(f"| {a} | {x['added']-x['lost']:+d} | {large['gained']} / {large['lost']} |") + lines+=[''] + lines+=['## 如何解读','', + '父模型 R4-D:MSG Test Mass / Formula Top1 为 38.50% / 22.66%,CASMI Top1 为 50/500;原始 R3D 相应为 37.48% / 21.81%、51/500。若只在 MSG 获益,不能称为 CASMI 改善。','', + 'FLARE v1 文献参照(非同条件重跑):MSG Test Mass Top1/5/20 43.15/75.59/92.89%,Formula 22.66/50.00/75.15%,MCES 7.84/9.00;其使用已知母体公式。[论文](https://pmc.ncbi.nlm.nih.gov/articles/PMC12873900/)。','', + '配对统计以目标 key14 分组;最终 JSON 同时保留对四个分支调整后的 Validation 主指标下界、MCES 共同有效分母与全部退化。大池训练样本上的工程验收不构成未见结构上的泛化证明。'] + return '\n'.join(lines)+'\n' +def publish(base): + base=Path(base);body=build(base);dest=base/'FINAL_REPORT.md' + if dest.exists(): + if dest.read_text()!=body:raise RuntimeError('different final report exists; refusing to overwrite') + return + tmp=dest.with_name('.r5_report_'+str(os.getpid())+'.pending') + with tmp.open('x') as f:f.write(body);f.flush();os.fsync(f.fileno()) + try:os.link(tmp,dest) + finally:tmp.unlink() +if __name__=='__main__': + ap=argparse.ArgumentParser();ap.add_argument('directory',type=Path);publish(ap.parse_args().directory) diff --git a/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/forward5.py b/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/forward5.py new file mode 100644 index 0000000000000000000000000000000000000000..0bcff95723edc3e41c8bf347912ff346319b2ba2 --- /dev/null +++ b/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/forward5.py @@ -0,0 +1,85 @@ +"""Candidate-only connected internal fragments; no labels or CSI in this module. +R4's existing fragments stay untouched. Relative intensities are predicted +from fragment features and adduct before assignment to the observed peaks. +""" +import numpy as np, torch +from torch import nn +from torch.nn import functional as F +from collections import OrderedDict +MODES=('[M+H]+','[M+Na]+','[M+NH4]+','[M-H]-','[M+Cl]-','[M+FA-H]-') +K=12 +def internal(a): + """For two nested one-boundary components the set difference is connected + and cut off by the two bridges. H/mass are conserved on retained atoms.""" + out=np.zeros((K,9),np.float32) + ok=np.flatnonzero(a['valid']&(np.abs(a['boundary'][:,3]-.25)<1e-6)) + if len(ok)<2:return out + m=(a['members'][ok]>0).astype(np.float32);size=m.sum(1);over=m@m.T + outer,inner=np.nonzero((over==size[None,:])&((size[:,None]-size[None,:])>=3)) + if not len(outer):return out + i,j=ok[outer],ok[inner];n=size[outer]-size[inner];mass=a['masses'][i]-a['masses'][j] + nh=a['hydrogens'][i].astype(np.float32)-a['hydrogens'][j] + fr=(a['boundary'][i][:,[1,2,4,5]]*size[outer,None]-a['boundary'][j][:,[1,2,4,5]]*size[inner,None])/n[:,None] + fixed=np.column_stack((mass,nh,n/a['atoms'],n/40,fr,np.divide(mass,max(.01,a['neutral_mass'])))) + # Stable, order-independent mass tie-break by only candidate descriptors. + order=np.lexsort(tuple(fixed[:,k] for k in reversed(range(fixed.shape[1])))) + fixed=fixed[order];key=np.rint(fixed[:,0]*1000);fixed=fixed[np.r_[True,key[1:]!=key[:-1]]] + if len(fixed)>K:fixed=fixed[np.linspace(0,len(fixed)-1,K).round().astype(int)] + out[:len(fixed)]=fixed + return out +def assign(mz,masses,valid,weight): + mass=masses.contiguous();r=torch.searchsorted(mz,mass).clamp(max=len(mz)-1);l=(r-1).clamp_min(0) + idx=torch.where((mz[l]-mass).abs()<=(mz[r]-mass).abs(),l,r) + ok=valid&((mz[idx]-mass).abs()<=torch.maximum(.00002*mass,mz.new_tensor(.02)))&weight[idx].gt(0) + return torch.where(ok,idx,len(mz)) +class Evidence(nn.Module): + def __init__(self,cap=.3): + super().__init__();self.cap=cap;self.adduct=nn.Embedding(6,6) + self.net=nn.Sequential(nn.Linear(17,32),nn.SiLU(),nn.Linear(32,16),nn.SiLU(),nn.Linear(16,1)) + self.sink=nn.Linear(6,1);self.gain=nn.Parameter(torch.zeros(()));self.cache=OrderedDict() + def bank(self,a): + k=a['smiles'] + if k in self.cache:self.cache.move_to_end(k);return self.cache[k] + x=internal(a);self.cache[k]=x + if len(self.cache)>16384:self.cache.popitem(last=False) + return x + @staticmethod + def grid(mm,hh,oldvalid,off,H): + shifts=mm.new_tensor([-2,-1,0,1,2]);offs=mm.new_tensor(off) + masses=mm[:,:,None,None]+shifts[None,None,:,None]*H+offs[None,None,None,:] + valid=oldvalid[:,:,None,None]&(hh[:,:,None,None]+shifts[None,None,:,None]>=0)&(masses>0) + return masses,valid.expand_as(masses) + def context(self,features,forms,ids,mz,obs,mode,off,H): + n=len(ids);P=len(mz);dev=mz.device + if not n:return mz.new_empty(0),mz.new_empty(0),torch.zeros(0,device=dev,dtype=torch.bool) + if len(ids)!=len(set(ids)) or not all(ids):raise ValueError('expected unique scoreable identities') + if mode not in MODES or not len(mz) or obs.sum().item()<=0: + z=mz.new_zeros(n);return z,z,z.bool() + w=obs/obs.sum().clamp_min(1e-12);context=self.adduct.weight[MODES.index(mode)].float() + old_presence=[];new_dist=[];new_presence=[] + for a in range(0,n,128): + fx=features[a:a+128];vals=torch.from_numpy(np.stack([self.bank(f) for f in fx])).to(dev);B=len(fx) + to=lambda k:torch.as_tensor(np.stack([f[k] for f in fx]),device=dev) + masses,valid=self.grid(to('masses'),to('hydrogens'),to('valid').bool(),off,H) + ix=assign(mz,masses.flatten(1),valid.flatten(1),w) + z=mz.new_zeros((B,P+1)).scatter_add_(1,ix,torch.ones_like(ix,dtype=mz.dtype)) + old_presence.append(z[:,:P]>0) + mm,mask=self.grid(vals[:,:,0],vals[:,:,1],vals[:,:,0]>0,off,H);ch=len(off) + raw=vals.clone();raw[:,:,0]/=600;raw[:,:,1]/=60 + shape=(B,K,5,ch);sh=mz.new_tensor([-1.,-.5,0,.5,1])[None,None,:,None].expand(shape) + channels=torch.arange(ch,device=dev,dtype=mz.dtype)[None,None,None,:].expand(shape) + inp=torch.cat((raw[:,:,None,None,:].expand(*shape,9),sh[...,None],channels[...,None],context.expand(*shape,6)),-1) + logits=self.net(inp).squeeze(-1).flatten(1).masked_fill(~mask.flatten(1),float('-inf')) + prob=torch.cat((logits,self.sink(context).expand(B,1)),-1).softmax(-1) + idx=assign(mz,mm.flatten(1),mask.flatten(1),w) + zn=mz.new_zeros((B,P+1)).scatter_add(1,idx,prob[:,:-1])+F.pad(prob[:,-1:],(P,0)) + new_dist.append(zn);new_presence.append(zn[:,:P].detach()>0) + old=torch.cat(old_presence);nu=torch.cat(new_presence);z=torch.cat(new_dist) + names={f:i for i,f in enumerate(sorted({f for f in forms if f}))} + groups=torch.tensor([names.get(f,len(names)) for f in forms],device=dev) + ct=torch.zeros((len(names)+1,P),dtype=torch.int32,device=dev).index_add_(0,groups,(old|nu).int()) + num=torch.bincount(groups,minlength=len(names)+1) + eligible=(~old)&nu&(ct[groups]==1)&((groups1))[:,None] + evidence=(eligible*w*z[:,:P]/(.02+z[:,:P])).sum(-1) + cosine=F.cosine_similarity(z,F.pad(w,(0,1)).expand_as(z),dim=-1,eps=1.e-8) + return evidence,1.-cosine,nu.any(-1) diff --git a/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/interventions.json b/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/interventions.json new file mode 100644 index 0000000000000000000000000000000000000000..32bf2f66bcf4b6bbab1f97e2d5971f40e992b11e --- /dev/null +++ b/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/interventions.json @@ -0,0 +1,9 @@ +{ + "arms_keep_parent_gap_and_duel":["A","B","C","D","E"], + "B":{"scope":"two deterministic eligible training pools of each kind per update when available; other pools unmodified","pools_per_kind":2,"mining_multiplier":3,"mixture":"non-Mass 40% teacher-confusing different nonempty scaffold / 35% nearest same/near scaffold / remainder random; Mass reserves 25% wrong formula before those strata. Distinct identities, original budget; deterministic backfill shortages. Fixed frozen R4D teacher."}, + "C":{"scope":"every scoreable identity of every training and evaluation pool; bounded, no top32 restriction on new evidence","proposals":"connected internal fragments between two nested single-bridge cut components of the stored candidate graph; only genuinely new observed-peak support absent from all competing identities in the same formula. This production subset of the exploratory expanded cut bank is independently checked on real spectra; no duplicate ring hypotheses.","max_internal":12,"features":"new fragment mass, size, hydrogen count, boundary O/N/aromatic/ring content, H shift and charge channel, adduct. Predicted positive intensity and unmodelled sink. Final increment zero at initialization; bounded to 0.30 inherited raw-logit units. Weak auxiliary cosine supervision on positive examples with nonzero matched intensity, weight 0.03.","raw_logit_cap":0.30,"aux_weight":0.03}, + "D":{"scope":"one deterministically rotated eligible pool per update expanded when possible; all other views retain original denominators","caps":[256,512,2048,5000],"stages":[750,1500,2250,3000],"selection":"hash-uniform distinct training-safe candidates, no chemical or teacher mining. Prefer a real sufficiently large o_data pool when available, else largest presampled eligible training view; never pad or enlarge official pools. Final-score InfoNCE once, including all candidates."}, + "E":{"scope":"same eligible pool scheduling as B, baseline draws unchanged; teacher used in training only","minimum_teacher_margin":0.35,"margin_cap":0.75,"weight":0.10,"eligibility":"frozen R4D correctly ranks a covered truth, clear margin, and neither the truth nor best wrong candidate has new exclusive fragment support. Penalize only a loss of the capped old margin; zero elsewhere."}, + "evaluation":{"official_early":[10000,11000],"fixed":12000,"test_tuning":false,"CASMI_candidates":1765420,"n_casmi":500,"n_msg_test":17556,"n_msg_validation":19429}, + "notes":"Sampling and large-pool interventions are not a full change of every query at once. Counts, realized pool sizes, triggered corrections, sampled strata, actual GPU work and active gradients are logged. Training score distributions are separate from Test/CASMI; these experiments are tests, not automatic model promotion." +} diff --git a/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/ledger.supervisor.conf b/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/ledger.supervisor.conf new file mode 100644 index 0000000000000000000000000000000000000000..355ff450a21feab5656fdff2c66e1fa09efe6e30 --- /dev/null +++ b/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/ledger.supervisor.conf @@ -0,0 +1,13 @@ +[program:specpartition-r5-from-r4d-ledger-20261112] +directory=/root/xj/SpecPartition-MS/code/ceir_r5_from_r4d_12000_20261112 +command=/usr/bin/nice -n 10 /workspace/xj/SpecPartition-MS/.venv/bin/python -B -u ledger5.py +environment=PYTHONUNBUFFERED="1",OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1",CUDA_VISIBLE_DEVICES="" +autostart=false +autorestart=false +startsecs=1 +stopasgroup=true +killasgroup=true +stdout_logfile=/root/xj/SpecPartition-MS/runs/ceir_r5_from_r4d_12000_20261112/ledger.log +stdout_logfile_maxbytes=2MB +stdout_logfile_backups=1 +redirect_stderr=true diff --git a/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/ledger5.py b/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/ledger5.py new file mode 100644 index 0000000000000000000000000000000000000000..00faab5562c116a9dd54c9af8fb2ff8cf75a24a2 --- /dev/null +++ b/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/ledger5.py @@ -0,0 +1,69 @@ +"""Build the *next* random training ledger. No reuse of R4's past updates. +Old modules run in private processes with an output path injected ONLY for +their pure sampler. Old experiments and prepared databases remain read-only. +""" +import concurrent.futures as cf,fcntl,json,multiprocessing as mp,os,shutil,sys,time,traceback +from collections import Counter +from paths5 import * +sys.path.insert(0,C['r4_code']) +import prepare4 as old +import torch + + +def initialize(): + old.prep_root=lambda:BASE + old.init() + + +def task(item):return old.make_batch(item) + + +def run(): + if not str(ROOT).startswith('/dev/shm/') or 'tmpfs' not in os.popen('findmnt -n -o FSTYPE -T /dev/shm').read():raise RuntimeError('Wrong storage') + BASE.mkdir(parents=True,exist_ok=True);(BASE/'batches').mkdir(exist_ok=True);SMALL.mkdir(exist_ok=True,parents=True) + lock=(BASE/'prepare.lock').open('a+');fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB) + start=time.time();parent=Path(C['parent']);receipt=read(parent.with_suffix('.json')) + assert receipt['arm']=='D' and not receipt['inference_only'] and C['parent_sha256']==receipt['sha256']==hashfile(parent) + x=torch.load(parent,map_location='cpu',weights_only=False);pg=x['progress'] + assert x['architecture']=='CEIR_R4' and x['arm']=='D' and pg['update']==9000 and x['optimizer']['state'] + assert x['binding']['original_r3']==old.get(old.R3/'R3D/provenance.json')['binding']['code'] + terms=['torch_rng','cuda_rng','numpy_rng','python_rng'];assert all(k in x for k in terms) + pinfo=dict(update=pg['update'],epoch=pg['epoch'],next_step=pg['next_step'],param_groups=[len(g['params']) for g in x['optimizer']['param_groups']], + weights_sha256=C['parent_sha256'],original_ledger_chain=pg['r4_chain'],optimizer_states=len(x['optimizer']['state']),rng=terms) + save(SMALL/'PARENT_VERIFIED.json',pinfo);del x + epoch,off=pg['epoch'],pg['next_step'];plans=[];epoch_hash=[] + while len(plans)256 for x in queries) + try: + enc,u=super().encode_batch(queries,extras) + for e,info in zip(enc,self._t5,strict=True):e.r5_info=info + return enc,u + finally:self._t5=None;self._r5_large_grad=False + def score_encoded(self,q,peaks,query,mols,atoms,zm,formula_scores,context=None,return_aux=False): + result=super().score_encoded(q,peaks,query,mols,atoms,zm,formula_scores,context,return_aux);info=None + if self.r5_arm=='C' and len(mols)>1: + e,sl,ok=self.evidence_for(self.r5,query,mols) + inc=self.r5.cap*self.r5.gain.clamp(0.,1.)*e + result=(result[0].float()+inc,*result[1:]);info=(e,sl,ok,inc) + if self._t5 is not None:self._t5.append(info) + return result + +def make(arm,path=None,split='train',warm=False,optimizer=True,binding=None): + if arm not in C['arms']:raise ValueError(arm) + parent=path is None;path=Path(C['parent']) if parent else Path(path) + if parent and hashfile(path)!=C['parent_sha256']:raise RuntimeError('parent hash drift') + x=torch.load(path,map_location='cpu',weights_only=False) + if parent: + assert x['architecture']=='CEIR_R4' and x['arm']=='D' and x['progress']['update']==9000 + else: + assert x['architecture']=='CEIR_R5' and x['arm']==arm and x['binding']==binding + torch.manual_seed(C['seed']);net=Model(arm) + keys=net.load_state_dict(x['model'],strict=not parent) + if keys.unexpected_keys or any(not k.startswith('r5.') for k in keys.missing_keys):raise RuntimeError('non-R5 parent weight missing') + net.to('cuda');net.feature_store=Store(split,warm) + pg=dict(x['progress']) + if parent:pg.update(r5_updates=0,r5_chain='',r5_exposures={}) + if not optimizer:net.eval();return net,None,pg + gr=[[],[],[],[],[]] + for name,p in net.named_parameters(): + grp=4 if name.startswith('r5.') else 3 if name.startswith('r4.') else 2 if name.startswith('r3.') else 1 if name.startswith('r2.') else 0;gr[grp].append(p) + prev=x['optimizer']['param_groups'] + if [len(g['params']) for g in prev[:4]]!=[len(g) for g in gr[:4]]:raise RuntimeError('parent optimizer parameter/order mismatch') + opt=torch.optim.AdamW([dict(params=g,lr=prev[j]['lr']) for j,g in enumerate(gr[:4])],weight_decay=rt.LEGACY.C['weight_decay']) + if parent: + opt.load_state_dict(x['optimizer']) + if gr[4]:opt.add_param_group(dict(params=gr[4],lr=.00015)) + else: + if gr[4]:opt.add_param_group(dict(params=gr[4],lr=.00015)) + opt.load_state_dict(x['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(x);return net,opt,pg diff --git a/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/objectives5.py b/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/objectives5.py new file mode 100644 index 0000000000000000000000000000000000000000..f3b05e2dec1c4f39dbc2d6ea7474233e3b376f2c --- /dev/null +++ b/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/objectives5.py @@ -0,0 +1,196 @@ +"""Exact C03 active objectives, plus qualified chemistry / spectrum supervision.""" +from collections import Counter +import time +import numpy as np +import torch +from torch.nn import functional as F +from torch.utils.checkpoint import checkpoint as recompute +from common4 import CFG,rt +from paths5 import HERE,read +from collections import defaultdict +H5=read(HERE/'interventions.json') +from runtime_r2 import * +from kernels import grouped_contrastive,formula_objective +from 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'].smiles1 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'] + blocks=[];pending=[];extra=qc.new_zeros(());extra_live=0;obs_new=0;top_changes=0;inc_total=0.;guard_count=0;penalty_count=0 + eligible_keep=sum('keep_margin' in p for p in pools) + for p in pools: + if len(p['query'].candidates)>256: + if pending:blocks.append(pending);pending=[] + blocks.append([p]) + else: + pending.append(p) + if len(pending)==LEGACY.C['pool_micro_views']:blocks.append(pending);pending=[] + if pending:blocks.append(pending) + for block in blocks: + 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 model.r5_arm=='C' and enc.r5_info is not None: + new_ev,new_loss,new_ok,increment=enc.r5_info + obs_new+=int((new_ev.detach()>0).sum());inc_total+=float(increment.detach().abs().sum()) + top_changes+=int(enc.base.detach().argmax()!=(enc.base.detach()-increment.detach()).argmax()) + if p['quality_eligible'] and new_ok[p['positive_index']]: + term=H5['C']['aux_weight']*new_loss[p['positive_index']]/max(len(pools),1) + extra+=term.detach();loss+=term;extra_live+=1 + if model.r5_arm=='E' and 'keep_margin' in p: + positive=p['positive_index'];sx=enc.base.float() + mask=torch.arange(len(sx),device=sx.device)!=positive + fall=(p['keep_margin']+sx[mask].max()-sx[positive]).relu() + term=H5['E']['weight']*fall/max(1,eligible_keep) + extra+=term.detach();loss+=term;guard_count+=1;penalty_count+=int(fall.detach()>0) + 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+extra + metrics.update(r5_extra_loss=extra,r5_novel_positives=extra_live,r5_candidates_with_novel_peak=obs_new, + r5_bonus_abs_sum=inc_total,r5_inference_top_flips=top_changes,r5_anchor_eligible=guard_count, + r5_anchor_positive_loss=penalty_count,r5_expanded_views=sum(bool(p.get('r5_expanded')) for p in pools), + r5_max_training_pool=max((len(p['ids']) for p in pools),default=0)) + 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. + if model.r5_arm=='C': + extra_grads=[p.grad.detach().float().square().sum() for p in model.r5.parameters() if p.grad is not None] + metrics['r5_gradient_norm']=torch.stack(extra_grads).sum().sqrt() if extra_grads 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() + if model.r5_arm=='C': + with torch.no_grad():model.r5.gain.clamp_(0.,1.) + 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 result diff --git a/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/paths5.py b/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/paths5.py new file mode 100644 index 0000000000000000000000000000000000000000..2cb46c86487d762a18294d7c13428f9564632d10 --- /dev/null +++ b/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/paths5.py @@ -0,0 +1,24 @@ +from pathlib import Path +import hashlib,json,os +HERE=Path(__file__).resolve().parent +C=json.loads((HERE/'protocol.json').read_text()); ROOT=Path(C['root']); SMALL=Path(C['receipts']) +BASE=ROOT/'data'/'random'; LARGE=ROOT/'data'/'larger'; FRESH=ROOT/'data'/'assets' +REV=ROOT/'data'/'identity_revision';NEWASSET=ROOT/'data'/'assets_verified' +def current_batch(box,name): + alt=REV/('base' if box==BASE else 'larger')/name + return alt if (REV/'READY.json').exists() and alt.exists() else box/'batches'/name +def current_hashes(box): + if (REV/'READY.json').exists():return read(REV/('base_hashes.json' if box==BASE else 'larger_hashes.json')) + return read(box/'hashes.json') +def sha(b):return hashlib.sha256(b).hexdigest() +def hashfile(path): + with Path(path).open('rb') as f:return hashlib.file_digest(f,'sha256').hexdigest() if hasattr(hashlib,'file_digest') else _hf(f) +def _hf(f): + h=hashlib.sha256() + for b in iter(lambda:f.read(2**20),b''):h.update(b) + return h.hexdigest() +def save(path,data): + path=Path(path);path.parent.mkdir(parents=True,exist_ok=True);tmp=path.with_name(path.name+'.'+str(os.getpid())+'.tmp') + with tmp.open('w') as f:json.dump(data,f,ensure_ascii=False,sort_keys=True,allow_nan=False);f.flush();os.fsync(f.fileno()) + os.replace(tmp,path) +def read(p):return json.loads(Path(p).read_text()) diff --git a/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/pipeline.supervisor.conf b/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/pipeline.supervisor.conf new file mode 100644 index 0000000000000000000000000000000000000000..d8b8e46aee7184b7550a490839c77c3d4897fe89 --- /dev/null +++ b/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/pipeline.supervisor.conf @@ -0,0 +1,14 @@ +[program:specpartition-r5-from-r4d-train-20261112] +directory=/root/xj/SpecPartition-MS/code/ceir_r5_from_r4d_12000_20261112 +command=/usr/bin/nice -n 10 /workspace/xj/SpecPartition-MS/.venv/bin/python -B -u pipeline5.py +environment=PYTHONUNBUFFERED="1",OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1",CUBLAS_WORKSPACE_CONFIG=":4096:8" +autostart=false +autorestart=unexpected +exitcodes=0,2 +startsecs=2 +stopasgroup=true +killasgroup=true +stdout_logfile=/root/xj/SpecPartition-MS/runs/ceir_r5_from_r4d_12000_20261112/pipeline.log +stdout_logfile_maxbytes=2MB +stdout_logfile_backups=1 +redirect_stderr=true diff --git a/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/pipeline5.py b/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/pipeline5.py new file mode 100644 index 0000000000000000000000000000000000000000..8843c489094cf332d294b831f8c40454f1d6c6e6 --- /dev/null +++ b/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/pipeline5.py @@ -0,0 +1,64 @@ +"""Managed isolated five-arm continuation, at most two GPU processes; bounded +retry, visible failure, and no silent step reset. No other supervisor group is controlled. +""" +from concurrent.futures import ThreadPoolExecutor,as_completed +import fcntl,os,subprocess,sys,time,traceback +from paths5 import * +PY='/workspace/xj/SpecPartition-MS/.venv/bin/python';MCES='/root/xj/SpecPartition-MS/evaluations/mces_all_20261106/.venv/bin/python' +def status(stage,**kw):save(SMALL/'PIPELINE_STATUS.json',dict(stage=stage,ts=time.time(),**kw)) +def log(item): + with (SMALL/'events.jsonl').open('a') as f:f.write(json.dumps(dict(item,timestamp=time.time()))+'\n') +def job(name,script,args=(),cpu=False): + p=ROOT/'logs';p.mkdir(parents=True,exist_ok=True) + for attempt in range(1,C['max_stage_retries']+1): + with (p/(name+'.log')).open('a') as f: + proc=subprocess.Popen([MCES 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'}) + log(dict(event='started',name=name,pid=proc.pid,attempt=attempt));rc=proc.wait() + log(dict(event='exited',name=name,rc=rc)); + if rc==0:return + if attempt=until and (until not in C['checkpoints'] or (ROOT/'arms'/a/f'step_{until:06}.json').exists()) and (until!=12000 or (ROOT/'arms'/a/'TRAIN_COMPLETE.json').exists()):continue + tasks.append((f'train_{a}_{until}','train5.py',(a,until))) + if tasks:status('training',round_end=until,arms=[x[-1][0] for x in tasks]);many(tasks) + if until in C['checkpoints']: + status('official_full_validation',update=until) + many([(f'val_{a}_{until}','eval5.py',(a,until,'validation')) for a in arms if not (folder(a,until,'validation')/'metrics.json').exists()]) + validate(until) + for a in arms: + if not (folder(a,until,'validation')/'MCES.json').exists(): + futures.append(mc.submit(job,f'mces_val_{a}_{until}','mces5.py',(a,until,'validation'),True)) + freeze() + for d in ('msg_test','casmi2022'): + status('fixed_endpoint_evaluation',dataset=d) + many([(a+'_'+d,'eval5.py',(a,12000,d)) for a in arms if not (folder(a,12000,d)/'metrics.json').exists()]) + for a in arms: + if not (folder(a,12000,d)/'MCES.json').exists():futures.append(mc.submit(job,'mces_'+a+'_'+d,'mces5.py',(a,12000,d),True)) + status('posthoc_common_valid_MCES') + for f in futures:f.result() + final();status('completed',each_new_updates=3000,total_new_updates=15000) +if __name__=='__main__': + try:main() + except Exception:save(SMALL/'PIPELINE_ERROR.json',dict(error=traceback.format_exc(),ts=time.time()));status('blocked_see_error');sys.exit(2) diff --git a/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/protocol.json b/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/protocol.json new file mode 100644 index 0000000000000000000000000000000000000000..5aee0292c3afeea01ccd333601a6dedafb9388ee --- /dev/null +++ b/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/protocol.json @@ -0,0 +1,12 @@ +{ + "id":"CEIR_R5_from_R4D_12000_20261112","parent":"/root/xj/SpecPartition-MS/runs/ceir_r4_9000_20261112/D/step_009000.pt", + "parent_sha256":"dd23af7370c35caee1d4f154fd52a2bc5b21c3e53c0f06df1beb368f274ea7b6","source_update":9000,"additional_updates":3000,"endpoint":12000, + "root":"/dev/shm/specpartition_r5_from_r4d_12000_20261112","receipts":"/root/xj/SpecPartition-MS/runs/ceir_r5_from_r4d_12000_20261112", + "r4_code":"/root/xj/SpecPartition-MS/code/ceir_r4_9000_20261112","r5_component":"/root/xj/SpecPartition-MS/code/r5_evidence_pilot_20261112", + "r4_train_fragments":"/dev/shm/specpartition_r4_9000_20261112/prepared/delta.sqlite", + "arms":{"A":"unchanged R4-D training control (keep pair residual and hard gap)","B":"change negative draws only: frozen parent-confusing different scaffolds + chemical neighbors + random; keep wrong-formula competition in Mass","C":"bounded forward exclusive-peak evidence added to full R4-D ranking, no candidate truncated","D":"larger training pool competition; one denominator across all chunks; R4-D inference architecture retained","E":"training-only parent margin retention for correct confident and weakly supported reference; architecture unchanged"}, + "seed":20261103,"checkpoints":[10000,11000,12000],"fixed_endpoint_eval":["validation","msg_test","casmi2022"], + "promotion":"Fixed 12k endpoints reported versus R4-D 9k, original R3D 6k and same-update A; official Validation selects, not MSG Test/CASMI. Retain failures. Promotion requires positive paired MSG Validation Formula Top1 vs A, stable guardrails (Mass Top1 and Formula Top5/20 drop <=0.5pp and common-valid MCES no worse); report paired key14 uncertainty. No claim CASMI improved without a measured gain on 500 fixed full pools.", + "storage":"User-selected tmpfs for large checkpoints, candidate-level evaluation outputs and rebuildable caches; NOT restart-persistent. Compact receipts also on root; no old run mutation or weight upload.", + "min_tmpfs_free_mib":2048,"prep_workers":6,"max_gpu_jobs":2,"max_stage_retries":2 +} diff --git a/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/recover_data5.py b/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/recover_data5.py new file mode 100644 index 0000000000000000000000000000000000000000..6b4d49166eb17d6673b29414564ac05944461aac --- /dev/null +++ b/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/recover_data5.py @@ -0,0 +1,15 @@ +import os,subprocess,sys,time,traceback +from paths5 import * +def main(): + for file in ('repair_keys5.py','resume_assets5.py'): + subprocess.run([sys.executable,'-B','-u',str(HERE/file)],cwd=HERE,check=True) + # Only archive the three superseded failure markers belonging to THIS new + # experiment. Keep the contents for audit and do not touch any model state. + for nm in ('ASSET_ERROR.json','DATA_ERROR.json','PIPELINE_ERROR.json'): + p=SMALL/nm;dest=SMALL/'history'/'initial_candidate_conflict'/nm + if p.is_file() and not dest.exists(): + dest.parent.mkdir(parents=True,exist_ok=True);os.rename(p,dest) + save(SMALL/'DATA_RECOVERED.json',dict(ready=True,when=time.time(),revision=read(REV/'READY.json')['audit'])) +if __name__=='__main__': + try:main() + except Exception:save(SMALL/'REPAIR_SERVICE_ERROR.json',dict(error=traceback.format_exc(),ts=time.time()));raise diff --git a/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/recovery.supervisor.conf b/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/recovery.supervisor.conf new file mode 100644 index 0000000000000000000000000000000000000000..d1ace6a00ab32cd38f0ffa055a51a4cd7508a07d --- /dev/null +++ b/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/recovery.supervisor.conf @@ -0,0 +1,13 @@ +[program:specpartition-r5-from-r4d-recovery-20261112] +directory=/root/xj/SpecPartition-MS/code/ceir_r5_from_r4d_12000_20261112 +command=/usr/bin/nice -n 10 /workspace/xj/SpecPartition-MS/.venv/bin/python -B -u recover_data5.py +environment=PYTHONUNBUFFERED="1",OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1",CUDA_VISIBLE_DEVICES="" +autostart=false +autorestart=false +startsecs=1 +stopasgroup=true +killasgroup=true +stdout_logfile=/root/xj/SpecPartition-MS/runs/ceir_r5_from_r4d_12000_20261112/recovery.log +stdout_logfile_maxbytes=2MB +stdout_logfile_backups=1 +redirect_stderr=true diff --git a/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/repair_keys5.py b/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/repair_keys5.py new file mode 100644 index 0000000000000000000000000000000000000000..b8a3cd92e958841df8cd2a524bbd9e746d93a89b --- /dev/null +++ b/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/repair_keys5.py @@ -0,0 +1,74 @@ +"""Overlay only disputed training NEGATIVES, drawn from the original safe pool. +No changes to old checkpoints, source DBs, official pools or original draw ledgers. +""" +from collections import Counter +import os,sys,time +from paths5 import * +sys.path.insert(0,C['r4_code']) +import prepare4 as old +import augment5 +def main(): + audit=read(SMALL/'IDENTITY_AUDIT_V1.json');assert audit['complete'] + if any(audit['occurrences'].get(k,0) for k in ('label','base_positive','mining_positive','large_positive')):raise RuntimeError('positive identity mismatch: do not substitute or relabel') + forbidden={x['graph'] for x in audit['mismatches']} + if (REV/'READY.json').exists(): + assert read(REV/'READY.json')['audit']==hashfile(SMALL/'IDENTITY_AUDIT_V1.json');return + (REV/'base').mkdir(parents=True,exist_ok=True);(REV/'larger').mkdir(exist_ok=True) + augment5.init();rd=augment5.rd;counts=Counter();receipts=[] + hs=read(BASE/'hashes.json');ha=read(LARGE/'hashes.json') + def compare(r,p,keep=None): + es,by=augment5.universe(r,p) + prefix=list(zip(p['graphs'],p['ids'])) if keep is None else list(zip(keep['graphs'],keep['ids'])) + prev=list(zip(p['graphs'],p['ids']));goal=len(prev);xs=[];seen=set() + def add(g,k): + if g in forbidden or k in seen:return False + # Full trusted graph/key and heldout audit on every changed view. + m=rd.molecule(g) + if m.identity!=k or k in rd.forbidden:return False + xs.append((g,k));seen.add(k);return True + for g,k in prefix+prev: + if len(xs)>=goal:break + add(g,k) + if len(xs)=-.5 for view,k in [('mass','1'),('formula','5'),('formula','20')]) + mc=all(x['mean_difference'] is not None and x['mean_difference']<=0 for x in v['common_valid_MCES']['matched_A'].values()) + parent_gain=cp['formula']['1']['net_pp']>0;original_gain=v['paired']['R3D_6000']['formula']['1']['net_pp']>0 + adjusted_positive=v['adjusted_validation_formula_top1_lower_pp']>0 + decisions[a]=dict(positive_primary_lower_95=fo['ci95_pp'][0]>0,positive_adjusted_lower=adjusted_positive, + net_positive_vs_R4D=parent_gain,net_positive_vs_original_R3D=original_gain, + guardrails=guards,mces=mc,primary_meets_single_seed=bool(a!='A' and guards and mc and adjusted_positive and parent_gain and original_gain), + CASMI_net_top1_vs_R4D=report['casmi2022'][a]['paired']['R4-D_9000']['top10_blind']['1']['net_pp'], + CASMI_net_top1_vs_original=report['casmi2022'][a]['paired']['R3D_6000']['top10_blind']['1']['net_pp']) + obj=dict(complete=True,new_updates=counts,parent=C['parent_sha256'],endpoints=read(ROOT/'FROZEN_TEST.json'),evaluations=report,validation_decisions=decisions, + limits='Single seed. No automatic deployment; external benefit must be tested on the entire frozen pool. Inspect primary endpoint, guards, paired intervals and strata. MCES missing values are never zero.',ts=time.time()) + for dest in (ROOT,SMALL):save(dest/'FINAL_VERIFIED.json',obj) diff --git a/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/resume_assets5.py b/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/resume_assets5.py new file mode 100644 index 0000000000000000000000000000000000000000..77ff2c6782c6bb932c84b982db018d243bdd97f7 --- /dev/null +++ b/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/resume_assets5.py @@ -0,0 +1,77 @@ +"""Verified reuse of successful ORIGINAL asset blocks. Subset changes, omitted +disputed negatives, newly drawn keys and previously unfinished blocks are audited +independently; no modification of the old partial DB or its receipts. +""" +import concurrent.futures as cf,collections,fcntl,multiprocessing as mp,os,shutil,sqlite3,sys,time,traceback +from paths5 import * +import assets5 as base +from assets5 import old +def add(row,g,k): + if row.setdefault(g,k)!=k:raise ValueError('inconsistent identity bindings') +def collect(rectified): + req={};h0=current_hashes(BASE) if rectified else read(BASE/'hashes.json');h1=current_hashes(LARGE) if rectified else read(LARGE/'hashes.json') + for i in range(3000): + name='%04d.z'%i;b=(current_batch(BASE,name) if rectified else BASE/'batches'/name).read_bytes() + z=(current_batch(LARGE,name) if rectified else LARGE/'batches'/name).read_bytes() + assert sha(b)==h0[i] and sha(z)==h1[i];rr=old.ft.loads(b)['rows'];a=old.ft.loads(z);assert a['base_sha']==h0[i] + for r in rr: + add(req,r['ref'],r['identity']) + for p in r['pools']: + for g,k in zip(p['graphs'],p['ids'],strict=True):add(req,g,k) + for p in list(a['teacher'].values())+([a['expanded']] if a['expanded'] else []): + for g,k in zip(p['graphs'],p['ids'],strict=True):add(req,g,k) + return req +def run(): + rev=read(REV/'READY.json') + NEWASSET.mkdir(parents=True,exist_ok=True);guard=(NEWASSET/'prepare.lock').open('a+');fcntl.flock(guard,fcntl.LOCK_EX|fcntl.LOCK_NB) + if (SMALL/'DATA_READY.json').is_file() and (NEWASSET/'READY.json').is_file():return + original=collect(False);correct=collect(True);pairs=sorted(original.items());size=768 + bad={x['graph'] for x in read(SMALL/'IDENTITY_AUDIT_V1.json')['mismatches']};assert not bad.intersection(correct) + prior=old.ro(FRESH/'delta.sqlite');seen={i:(h,json.loads(s)) for i,h,s in prior.execute('select i,hash,stats from blocks')};prior.close() + need=[];counts=collections.Counter();proofs=[];reused=0 + for i in range((len(pairs)+size-1)//size): + pp=pairs[i*size:(i+1)*size];subset=[(g,k) for g,k in pp if correct.get(g)==k] + if i in seen and pp==subset: + h,stats=seen[i];assert h==old.objhash(pp);counts.update(stats);proofs.append(h);reused+=len(pp) + else:need.extend(subset) + need.extend(sorted((g,k) for g,k in correct.items() if g not in original));total=len(correct) + assert reused+len(need)==total + del correct,original,pairs;ts=time.time() + plan=dict(audit=rev['audit'],corrected_base=rev['corrected_base'],corrected_larger=rev['corrected_larger'], + verified_prior_block_proofs=old.objhash(proofs),prior_partial_db=hashfile(FRESH/'delta.sqlite'),reused=reused,pending=len(need),total=total,builder=hashfile(__file__)) + if (NEWASSET/'PLAN.json').exists() and read(NEWASSET/'PLAN.json')!=plan:raise RuntimeError('changed recovery source') + save(NEWASSET/'PLAN.json',plan) + db=sqlite3.connect(NEWASSET/'delta.sqlite',timeout=90);db.execute('pragma page_size=32768');db.execute('pragma journal_mode=WAL') + 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() + blocks={i:h for i,h in db.execute('select i,hash from blocks')};n=(len(need)+size-1)//size + def chunks(): + for i in range(n): + pp=need[i*size:(i+1)*size];h=old.objhash(pp) + if i in blocks:assert blocks[i]==h;continue + yield i,pp,h + it=iter(chunks());jobs={};done=len(blocks) + def status():save(SMALL/'ASSET_RECOVERY_STATUS.json',dict(reused_verified_graphs=reused,total_graphs=total,remaining_blocks=n-done,ts=time.time())) + status() + with cf.ProcessPoolExecutor(8,mp_context=mp.get_context('fork'),initializer=base.init) as ex: + while True: + while len(jobs)<16: + c=next(it,None) + if c is None:break + i,pp,h=c;jobs[ex.submit(base.block,pp)]=(i,h) + if not jobs:break + for f in cf.wait(jobs,return_when=cf.FIRST_COMPLETED).done: + i,h=jobs.pop(f);rs,stats=f.result() + db.executemany('insert or ignore into extra values(?,?,?)',rs);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=H['E']['minimum_teacher_margin']: + ev,_,_=parent.evidence_for(detector,q,mols) + if ev[0].item()==0 and ev[j].item()==0: + p['keep_margin']=min(H['E']['margin_cap'],margin);stats['retention_eligible']+=1 + updates.append((row['record_id'],p['kind'],p['keep_margin'])) + return dict(stats),sha(repr(updates).encode()) diff --git a/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/train5.py b/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/train5.py new file mode 100644 index 0000000000000000000000000000000000000000..a0ffb93452dc1cacf9c36b4f5b72b5e52a9b7328 --- /dev/null +++ b/code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/train5.py @@ -0,0 +1,148 @@ +"""Atomic rolling optimizer/RNG/ledger checkpoints in the authorized tmpfs.""" +import argparse,contextlib,fcntl,gc,gzip,hashlib,json,os,random,shutil,subprocess,sys,time,traceback +from pathlib import Path +import numpy as np,torch +from paths5 import * +sys.path.insert(0,C['r4_code']) +import common4 as prior,model4 as original +from model5 import make,H +from forward5 import Evidence +from batch5 import Batches +from objectives5 import train_step +from teacher5 import annotate + +SCI=('protocol.json','interventions.json','paths5.py','batch5.py','forward5.py','model5.py','teacher5.py','objectives5.py','train5.py','ledger5.py','augment5.py','assets5.py','audit_identity5.py','repair_keys5.py','resume_assets5.py') +def binding(): + d=read(SMALL/'DATA_READY.json') + rev=read(REV/'READY.json');assets=read(NEWASSET/'READY.json') + if rev['corrected_base']!=d['ledger'] or rev['corrected_larger']!=d['augmented'] or assets['sha256']!=d['assets'] or assets['plan']['prior_partial_db']!=d['prior_assets']:raise RuntimeError('incomplete tmpfs; rebuild data instead of resetting checkpoints') + return dict(parent=C['parent_sha256'],data={k:d[k] for k in ('ledger','augmented','assets','prior_assets','repair_audit')}, + release={k:hashfile(HERE/k) for k in SCI},upstream={k:hashfile(Path(C['r4_code'])/k) for k in ('common4.py','model4.py','data4.py','duel4.py','objectives4.py')}) +def atomicstate(path,x): + path.parent.mkdir(exist_ok=True,parents=True);t=path.with_name(path.name+'.writing') + with t.open('wb') as f:torch.save(x,f);f.flush();os.fsync(f.fileno()) + os.replace(t,path) +def trace_file(where,metrics): + start,end=metrics[0]['update'],metrics[-1]['update'] + p=where/'trace'/('%06d_%06d.json.gz'%(start,end));p.parent.mkdir(exist_ok=True,parents=True) + b=gzip.compress(json.dumps(metrics,separators=(',',':'),allow_nan=False).encode(),compresslevel=3,mtime=0) + t=p.with_suffix('.tmp');t.write_bytes(b);os.replace(t,p);return p,sha(b) +def commit(arm,net,opt,pg,bind,metrics): + dest=ROOT/'arms'/arm;resume=dest/'resume';u=pg['update'] + if shutil.disk_usage(ROOT).free=6500: + for f in fds: + try:fcntl.flock(f,fcntl.LOCK_EX|fcntl.LOCK_NB);taken=True;break + except BlockingIOError:pass + if not taken:time.sleep(5) + yield + finally: + for f in fds:f.close() +def teacher(arm,warm=False): + if arm not in ('B','E'):return None,None + m,_,_=make('A',warm=warm,optimizer=False) + # No teacher is attached/registered on the trainable student. Creating a + # detector must never change dropout or otherwise advance the student's RNG. + with torch.random.fork_rng(devices=[torch.cuda.current_device()]): + torch.manual_seed(1794);det=Evidence().to('cuda').eval() if arm=='E' else None + return m,det +def step(arm,model,opt,batch,u,teach,detector): + evidence={};actual='' + if teach is not None:evidence,actual=annotate(batch,arm,teach,detector) + model.train();torch.cuda.reset_peak_memory_stats();mt=train_step(model,opt,batch,u) + mt['intervention']=evidence;mt['training_selection_hash']=actual + if arm=='D': + ex=[(p['record_id'],p['kind'],p['ids']) for r in batch['rows'] for p in r['pools'] if p['r5_expanded']] + mt['training_selection_hash']=sha(repr(ex).encode()) + if arm=='C':mt['bounded_strength']=float(model.r5.gain.detach())*model.r5.cap + return mt +def finish(arm,pg,bind): + dest=ROOT/'arms'/arm;chain='';trt='';n=0;agg={};base_hashes=current_hashes(BASE) + for st,en,filename,d in pg['r5_trace']: + f=dest/'trace'/filename;assert hashfile(f)==d + with gzip.open(f,'rt') as fp:x=json.load(fp) + assert [m['update'] for m in x]==list(range(st,en+1)) and st==9001+n + for m in x: + assert m['random_ledger_sha']==base_hashes[n] + chain=sha((chain+base_hashes[n]).encode());trt=sha((trt+base_hashes[n]+m['training_selection_hash']).encode());n+=1 + for k,v in m['source_counts'].items():agg[k]=agg.get(k,0)+v + assert n==pg['r5_updates']==3000 and pg['update']==12000 and chain==pg['r5_chain'] and trt==pg['r5_treatment_chain'] + assert agg==read(BASE/'READY.json')['sources']==pg['r5_exposures'] + f=dest/'step_012000.pt';record=read(f.with_suffix('.json'));assert hashfile(f)==record['sha256'] + receipt=dict(complete=True,arm=arm,parent=C['parent_sha256'],start=9000,end=12000,actual_new_updates=n,chain=chain,treatment_chain=trt, + endpoint_sha=record['sha256'],source_counts=agg,weights=str(f),storage='volatile tmpfs',ts=time.time()) + for p in (dest/'TRAIN_COMPLETE.json',SMALL/arm/'TRAIN_COMPLETE.json'):save(p,receipt) +def train(arm,until): + if arm not in C['arms'] or not 9000=until: + if pg['update']==12000:finish(arm,pg,bind) + return + start=pg['update']-9000;ds=Batches(arm,start,until-9000);seed=torch.Generator().manual_seed(C['seed']+start) + loader=torch.utils.data.DataLoader(ds,batch_size=None,num_workers=1,prefetch_factor=1,multiprocessing_context='spawn',generator=seed) + lengths={e:n for e,n,_,_ in read(BASE/'PLAN.json')['next_epoch_plans']};trace=[];clock=time.monotonic() + for b in loader: + u=pg['update'];assert b['manifest_index']==u-9000 and (b['epoch'],b['step'])==(pg['epoch'],pg['next_step']) + mt=step(arm,net,opt,b,u,pt,det);u+=1;e=b['epoch'];k=b['step']+1 + if k==lengths[e]:e,k=e+1,0 + pg.update(update=u,new_updates=u-9000,r5_updates=u-9000,epoch=e,next_step=k, + r5_chain=sha((pg['r5_chain']+b['ledger_sha256']).encode()), + r5_treatment_chain=sha((pg['r5_treatment_chain']+b['ledger_sha256']+mt['training_selection_hash']).encode())) + for k,v in mt['source_counts'].items():pg['r5_exposures'][k]=pg['r5_exposures'].get(k,0)+v + mt.update(update=u,arm=arm,random_ledger_sha=b['ledger_sha256'],epoch=b['epoch'],data_step=b['step'],seconds=time.monotonic()-clock,timestamp=time.time()) + trace.append(mt);clock=time.monotonic() + if u%100==0 or u==until or u in C['checkpoints']: + commit(arm,net,opt,pg,bind,trace);trace=[] + if u%10==0 or u<=9004 or u==until: + save(SMALL/arm/'status.json',dict(phase='training' if u<12000 else 'endpoint',arm=arm,update=u,new_updates=u-9000,target=12000, + loss=mt['loss'],runtime_s=mt['seconds'],peak_gpu_mib=mt['peak_allocated_mib'],intervention=mt['intervention'], + max_pool=mt['r5_max_training_pool'],ts=time.time())) + assert pg['update']==until and not trace + if until==12000:finish(arm,pg,bind) +if __name__=='__main__': + ap=argparse.ArgumentParser();ap.add_argument('arm',choices=list(C['arms']));ap.add_argument('until',type=int);a=ap.parse_args() + try:train(a.arm,a.until) + except Exception:save(SMALL/a.arm/'last_error.json',dict(error=traceback.format_exc(),ts=time.time()));raise