Add exact model code and documentation (3/7)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- code/snapshot/root/code/ceir_r3_20261110/audit_primitives.py +293 -0
- code/snapshot/root/code/ceir_r3_20261110/audit_r3.py +31 -0
- code/snapshot/root/code/ceir_r3_20261110/compact.supervisor.conf +11 -0
- code/snapshot/root/code/ceir_r3_20261110/compact_r3.py +75 -0
- code/snapshot/root/code/ceir_r3_20261110/config.json +44 -0
- code/snapshot/root/code/ceir_r3_20261110/data_r2.py +51 -0
- code/snapshot/root/code/ceir_r3_20261110/features_r2.py +183 -0
- code/snapshot/root/code/ceir_r3_20261110/final_audit_r3.py +35 -0
- code/snapshot/root/code/ceir_r3_20261110/heads_r3.py +102 -0
- code/snapshot/root/code/ceir_r3_20261110/mces_r2.py +29 -0
- code/snapshot/root/code/ceir_r3_20261110/model_r2_new.py +205 -0
- code/snapshot/root/code/ceir_r3_20261110/objectives_r2.py +138 -0
- code/snapshot/root/code/ceir_r3_20261110/pipeline.supervisor.conf +12 -0
- code/snapshot/root/code/ceir_r3_20261110/pipeline_r3.py +71 -0
- code/snapshot/root/code/ceir_r3_20261110/prepare.supervisor.conf +12 -0
- code/snapshot/root/code/ceir_r3_20261110/prepare_r3.py +147 -0
- code/snapshot/root/code/ceir_r3_20261110/probe_r3.py +30 -0
- code/snapshot/root/code/ceir_r3_20261110/runtime_r2.py +128 -0
- code/snapshot/root/code/ceir_r3_20261110/test_mces_r2.py +26 -0
- code/snapshot/root/code/ceir_r3_20261110/test_r3.py +60 -0
- code/snapshot/root/code/ceir_r3_20261110/tests_r3.py +53 -0
- code/snapshot/root/code/ceir_r3_20261110/train_r2.py +111 -0
- code/snapshot/root/code/ceir_r3_20261110/validate_r2.py +109 -0
- code/snapshot/root/code/ceir_r4_9000_20261112/README.md +68 -0
- code/snapshot/root/code/ceir_r4_9000_20261112/accept4.py +72 -0
- code/snapshot/root/code/ceir_r4_9000_20261112/common4.py +45 -0
- code/snapshot/root/code/ceir_r4_9000_20261112/config.json +21 -0
- code/snapshot/root/code/ceir_r4_9000_20261112/data4.py +61 -0
- code/snapshot/root/code/ceir_r4_9000_20261112/duel4.py +73 -0
- code/snapshot/root/code/ceir_r4_9000_20261112/eval4.py +161 -0
- code/snapshot/root/code/ceir_r4_9000_20261112/mces4.py +27 -0
- code/snapshot/root/code/ceir_r4_9000_20261112/model4.py +117 -0
- code/snapshot/root/code/ceir_r4_9000_20261112/objectives4.py +161 -0
- code/snapshot/root/code/ceir_r4_9000_20261112/pipeline.supervisor.conf +13 -0
- code/snapshot/root/code/ceir_r4_9000_20261112/pipeline4.py +69 -0
- code/snapshot/root/code/ceir_r4_9000_20261112/prep.supervisor.conf +12 -0
- code/snapshot/root/code/ceir_r4_9000_20261112/prepare4.py +143 -0
- code/snapshot/root/code/ceir_r4_9000_20261112/report4.py +59 -0
- code/snapshot/root/code/ceir_r4_9000_20261112/run4.py +140 -0
- code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/README.md +39 -0
- code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/accept5.py +107 -0
- code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/addendum.supervisor.conf +13 -0
- code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/addendum5.py +35 -0
- code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/assets5.py +92 -0
- code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/audit_identity5.py +45 -0
- code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/augment5.py +92 -0
- code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/batch5.py +80 -0
- code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/data.supervisor.conf +13 -0
- code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/data_pipeline.py +11 -0
- code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/eval5.py +83 -0
code/snapshot/root/code/ceir_r3_20261110/audit_primitives.py
ADDED
|
@@ -0,0 +1,293 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Read-only independent checks for the frozen CEIR-R2 experiment.
|
| 2 |
+
|
| 3 |
+
Kept OUTSIDE the frozen training release. No imported training/evaluation
|
| 4 |
+
helpers, no GPU access, no edits to checkpoints, candidate pools or predictions.
|
| 5 |
+
"""
|
| 6 |
+
import argparse
|
| 7 |
+
from collections import Counter, defaultdict
|
| 8 |
+
import gzip
|
| 9 |
+
import hashlib
|
| 10 |
+
import json
|
| 11 |
+
import math
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
import random
|
| 14 |
+
import sqlite3
|
| 15 |
+
import statistics
|
| 16 |
+
import time
|
| 17 |
+
|
| 18 |
+
ROOT = Path('/root/xj/SpecPartition-MS/runs/ceir_r2_20261110')
|
| 19 |
+
SOURCE = Path('/workspace/xj/SpecPartition-MS/data/derived/post_training_evaluation_20261103')
|
| 20 |
+
KS = (1, 3, 5, 10, 20, 50, 100, 200)
|
| 21 |
+
FKS = (*range(1, 11), 20, 50, 100, 200)
|
| 22 |
+
MODELS = ('C03_002000', 'A0_003000', 'A1_003000', 'A2_003000', 'A3_003000')
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def load(path):
|
| 26 |
+
path = Path(path)
|
| 27 |
+
if path.suffix == '.gz':
|
| 28 |
+
with gzip.open(path, 'rt') as stream:
|
| 29 |
+
return json.load(stream)
|
| 30 |
+
return json.loads(path.read_text())
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def save(path, value):
|
| 34 |
+
path = Path(path)
|
| 35 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 36 |
+
temporary = path.with_suffix(path.suffix + '.tmp')
|
| 37 |
+
temporary.write_text(json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False) + '\n')
|
| 38 |
+
temporary.replace(path)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def sha(path):
|
| 42 |
+
result = hashlib.sha256()
|
| 43 |
+
with Path(path).open('rb') as stream:
|
| 44 |
+
for block in iter(lambda: stream.read(1024 * 1024), b''):
|
| 45 |
+
result.update(block)
|
| 46 |
+
return result.hexdigest()
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def close(actual, expected, context):
|
| 50 |
+
if not math.isclose(actual, expected, rel_tol=0., abs_tol=1e-12):
|
| 51 |
+
raise AssertionError((context, actual, expected))
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def independent_metrics(rows, field, ks):
|
| 55 |
+
if not rows:
|
| 56 |
+
return {}
|
| 57 |
+
answer = {}
|
| 58 |
+
for k in ks:
|
| 59 |
+
targets = defaultdict(list)
|
| 60 |
+
identities = defaultdict(list)
|
| 61 |
+
hits = 0
|
| 62 |
+
for row in rows:
|
| 63 |
+
rank = row[field]
|
| 64 |
+
if rank is not None and (not isinstance(rank, int) or isinstance(rank, bool) or rank < 1):
|
| 65 |
+
raise AssertionError(('invalid rank', row['identifier'], field, rank))
|
| 66 |
+
hit = rank is not None and rank <= k
|
| 67 |
+
hits += hit
|
| 68 |
+
targets[row['target']].append(hit)
|
| 69 |
+
identities[row['reference_identity']].append(hit)
|
| 70 |
+
answer[str(k)] = dict(hits=hits, denominator=len(rows), micro=hits / len(rows),
|
| 71 |
+
target_macro=statistics.mean(statistics.mean(v) for v in targets.values()),
|
| 72 |
+
key14_macro=statistics.mean(statistics.mean(v) for v in identities.values()))
|
| 73 |
+
return answer
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def compare_metric(actual, original, context):
|
| 77 |
+
for k, values in actual.items():
|
| 78 |
+
for key, value in values.items():
|
| 79 |
+
close(value, original[k][key], (context, k, key))
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def aggregate(directory, dataset):
|
| 83 |
+
original = load(directory / 'metrics.json')
|
| 84 |
+
rows = load(directory / 'per_spectrum_summary.json.gz')
|
| 85 |
+
denominator = {'validation': 19429, 'msg_test': 17556, 'casmi2022': 500}[dataset]
|
| 86 |
+
answer = {}
|
| 87 |
+
expected_views = {'mass', 'formula'} if dataset != 'casmi2022' else {r['view'] for r in rows}
|
| 88 |
+
if {r['view'] for r in rows} != expected_views or (dataset == 'casmi2022' and len(expected_views) != 1):
|
| 89 |
+
raise AssertionError('Incorrect views')
|
| 90 |
+
for view in sorted(expected_views):
|
| 91 |
+
selected = [r for r in rows if r['view'] == view]
|
| 92 |
+
if len(selected) != denominator or len({r['identifier'] for r in selected}) != denominator:
|
| 93 |
+
raise AssertionError(('Incorrect population', directory, view))
|
| 94 |
+
fields = [('rank', 'structure', KS), ('formula_rank', 'formula', FKS)]
|
| 95 |
+
if dataset != 'validation':
|
| 96 |
+
fields += [('canonical_rank', 'canonical_smiles', KS), ('inchikey_rank', 'full_inchikey', KS)]
|
| 97 |
+
source = original[view] if dataset == 'validation' else original['views'][view]
|
| 98 |
+
computed = {}
|
| 99 |
+
for field, name, ks in fields:
|
| 100 |
+
computed[name] = independent_metrics(selected, field, ks)
|
| 101 |
+
compare_metric(computed[name], source[name], (str(directory), view, name))
|
| 102 |
+
in_pool = 'reference_present_in_original_pool' if dataset == 'validation' else 'reference_in_pool'
|
| 103 |
+
scorable = 'reference_scoreable' if dataset == 'validation' else 'reference_scoreable_in_pool'
|
| 104 |
+
computed['original_pool_coverage'] = sum(r[in_pool] for r in selected)
|
| 105 |
+
computed['scoreable_coverage'] = sum(r[scorable] for r in selected)
|
| 106 |
+
for row in selected:
|
| 107 |
+
if row['rank'] is not None and not row[scorable]:
|
| 108 |
+
raise AssertionError('Unscoreable truth was assigned a hit')
|
| 109 |
+
if row['rank'] is not None and row['rank'] > row['candidate_count']:
|
| 110 |
+
raise AssertionError('Rank exceeds original candidate count')
|
| 111 |
+
for field, name, ks in fields:
|
| 112 |
+
flags = 'recall_at_k' if field == 'rank' else ('formula_recall_at_k' if field == 'formula_rank' else None)
|
| 113 |
+
if flags and flags in row:
|
| 114 |
+
for k in ks:
|
| 115 |
+
if row[flags][str(k)] != (row[field] is not None and row[field] <= k):
|
| 116 |
+
raise AssertionError('Per-spectrum boolean disagrees with rank')
|
| 117 |
+
if dataset == 'casmi2022':
|
| 118 |
+
if sum(r['candidate_count'] for r in selected) != 1765420 or computed['original_pool_coverage'] != 467:
|
| 119 |
+
raise AssertionError('Frozen CASMI full-pool protocol changed')
|
| 120 |
+
computed['by_adduct'] = {adduct: independent_metrics([r for r in selected if r['adduct'] == adduct], 'rank', KS)
|
| 121 |
+
for adduct in sorted({r['adduct'] for r in selected})}
|
| 122 |
+
computed['by_polarity'] = {polarity: independent_metrics([r for r in selected if
|
| 123 |
+
('negative' if r['adduct'].endswith('-') else 'positive') == polarity], 'rank', KS)
|
| 124 |
+
for polarity in sorted({'negative' if r['adduct'].endswith('-') else 'positive' for r in selected})}
|
| 125 |
+
computed['reference_not_in_pool'] = denominator - computed['original_pool_coverage']
|
| 126 |
+
computed['conditional_given_original_coverage'] = independent_metrics([r for r in selected if r[in_pool]], 'rank', KS)
|
| 127 |
+
answer[view] = computed
|
| 128 |
+
mces = load(directory / 'MCES.json')
|
| 129 |
+
details = load(directory / 'MCES_per_spectrum.json.gz')
|
| 130 |
+
expected_ids = {(r['identifier'], r['view']) for r in rows}
|
| 131 |
+
if {(r['identifier'], r['view']) for r in details} != expected_ids or len(details) != len(rows):
|
| 132 |
+
raise AssertionError('MCES population differs')
|
| 133 |
+
for view in expected_views:
|
| 134 |
+
data = [r for r in details if r['view'] == view]
|
| 135 |
+
values = [r['distance'] for r in data if r['distance'] is not None]
|
| 136 |
+
if any(not math.isfinite(x) or x < 0 for x in values):
|
| 137 |
+
raise AssertionError('Invalid MCES')
|
| 138 |
+
source = mces['views'][view]
|
| 139 |
+
if source['n'] != len(data) or source['valid'] != len(values) or source['missing'] != len(data) - len(values):
|
| 140 |
+
raise AssertionError('MCES denominators disagree')
|
| 141 |
+
if values:
|
| 142 |
+
close(statistics.mean(values), source['valid_mean'], ('MCES', directory, view))
|
| 143 |
+
if len(values) != len(data) and source['full_mean'] is not None:
|
| 144 |
+
raise AssertionError('Missing MCES was converted into a full-population mean')
|
| 145 |
+
answer[view]['MCES'] = source
|
| 146 |
+
lookup = {(r['identifier'], r['view']): r for r in rows}
|
| 147 |
+
for name in ('adduct', 'polarity'):
|
| 148 |
+
groups = defaultdict(list)
|
| 149 |
+
for item in data:
|
| 150 |
+
row = lookup[item['identifier'], item['view']]
|
| 151 |
+
key = row['adduct'] if name == 'adduct' else ('negative' if row['adduct'].endswith('-') else 'positive')
|
| 152 |
+
groups[key].append(item['distance'])
|
| 153 |
+
answer[view]['MCES_by_' + name] = {key: dict(n=len(group),
|
| 154 |
+
valid=sum(v is not None for v in group), missing=sum(v is None for v in group),
|
| 155 |
+
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,
|
| 156 |
+
full_mean=statistics.mean(group) if all(v is not None for v in group) else None)
|
| 157 |
+
for key, group in groups.items()}
|
| 158 |
+
return answer, rows
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def paired(base_rows, arm_rows, repetitions=2000):
|
| 162 |
+
import numpy as np
|
| 163 |
+
if {(r['identifier'], r['view']) for r in base_rows} != {(r['identifier'], r['view']) for r in arm_rows}:
|
| 164 |
+
raise AssertionError('Paired comparison populations differ')
|
| 165 |
+
lookup = {(r['identifier'], r['view']): r for r in base_rows}
|
| 166 |
+
answer = {}
|
| 167 |
+
for view in sorted({r['view'] for r in arm_rows}):
|
| 168 |
+
groups = defaultdict(lambda: [0, 0])
|
| 169 |
+
gained = lost = 0
|
| 170 |
+
for row in arm_rows:
|
| 171 |
+
if row['view'] != view:
|
| 172 |
+
continue
|
| 173 |
+
baseline = lookup[row['identifier'], view]
|
| 174 |
+
if (row['reference_identity'], row['candidate_count'], row['target']) != (
|
| 175 |
+
baseline['reference_identity'], baseline['candidate_count'], baseline['target']):
|
| 176 |
+
raise AssertionError('Paired query/candidate metadata changed')
|
| 177 |
+
hit = row['rank'] is not None and row['rank'] <= 1
|
| 178 |
+
before = baseline['rank'] is not None and baseline['rank'] <= 1
|
| 179 |
+
gained += hit and not before
|
| 180 |
+
lost += before and not hit
|
| 181 |
+
groups[row['reference_identity']][0] += int(hit) - int(before)
|
| 182 |
+
groups[row['reference_identity']][1] += 1
|
| 183 |
+
values = np.asarray([groups[k] for k in sorted(groups)], dtype=np.int64)
|
| 184 |
+
generator = np.random.default_rng(20261110)
|
| 185 |
+
draws = []
|
| 186 |
+
for start in range(0, repetitions, 100):
|
| 187 |
+
index = generator.integers(len(values), size=(min(100, repetitions - start), len(values)))
|
| 188 |
+
sampled = values[index].sum(axis=1)
|
| 189 |
+
draws.extend((sampled[:, 0] / sampled[:, 1] * 100).tolist())
|
| 190 |
+
answer[view] = dict(top1_gained=gained, top1_lost=lost,
|
| 191 |
+
top1_delta_pp=100 * (gained - lost) / int(values[:, 1].sum()),
|
| 192 |
+
key14_macro_top1_delta_pp=float(np.mean(values[:, 0] / values[:, 1]) * 100),
|
| 193 |
+
key14_groups_net_improved=int((values[:, 0] > 0).sum()),
|
| 194 |
+
key14_groups_net_worsened=int((values[:, 0] < 0).sum()),
|
| 195 |
+
key14_groups_net_tied=int((values[:, 0] == 0).sum()),
|
| 196 |
+
key14_cluster_bootstrap_95_percent_interval_pp=np.quantile(draws, [.025, .975]).tolist(),
|
| 197 |
+
bootstrap_repetitions=repetitions, inferential_unit='reference_key14',
|
| 198 |
+
limitation='one training seed; not protection from adaptive experiment design')
|
| 199 |
+
return answer
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def pool_and_prediction_audit(name, dataset, comparison_hashes):
|
| 203 |
+
"""All pool identities and scores, independently re-sorted without rank helper."""
|
| 204 |
+
directory = ROOT / 'test/inference' / name / dataset
|
| 205 |
+
db = sqlite3.connect('file:' + str(SOURCE / (dataset + '.sqlite')) + '?mode=ro', uri=True)
|
| 206 |
+
db.execute('PRAGMA query_only=ON')
|
| 207 |
+
actual_targets = set()
|
| 208 |
+
predictions_checked = aliases_checked = 0
|
| 209 |
+
summary = {(r['identifier'], r['view']): r for r in load(directory / 'per_spectrum_summary.json.gz')}
|
| 210 |
+
for path in sorted((directory / 'per_target').glob('*.json.gz')):
|
| 211 |
+
result = load(path)
|
| 212 |
+
target = result['target']
|
| 213 |
+
if target in actual_targets:
|
| 214 |
+
raise AssertionError('Duplicate target output')
|
| 215 |
+
actual_targets.add(target)
|
| 216 |
+
pool_path = ROOT / 'test/shared_pools' / dataset / path.name
|
| 217 |
+
shared = load(pool_path)
|
| 218 |
+
original = {v: json.loads(b) for v, b in db.execute('SELECT view,body FROM pools WHERE target=?', (target,))}
|
| 219 |
+
all_smiles = sorted({c['smiles'] for entries in shared['pools'].values() for c in entries})
|
| 220 |
+
source_aliases = {}
|
| 221 |
+
for start in range(0, len(all_smiles), 500):
|
| 222 |
+
block = all_smiles[start:start + 500]
|
| 223 |
+
command = 'SELECT smiles,graph_key,identity,formula,canonical,fullkey,error FROM aliases WHERE smiles IN (' + ','.join('?' for _ in block) + ')'
|
| 224 |
+
source_aliases.update({r[0]: r[1:] for r in db.execute(command, block)})
|
| 225 |
+
for view, entries in shared['pools'].items():
|
| 226 |
+
if [c['smiles'] for c in entries] != original[view]:
|
| 227 |
+
raise AssertionError('Candidate order or membership changed from frozen source')
|
| 228 |
+
for candidate in entries:
|
| 229 |
+
stored = tuple(candidate[k] for k in ('graph_key', 'key14', 'formula', 'canonical_smiles', 'full_inchikey', 'error'))
|
| 230 |
+
if stored != source_aliases[candidate['smiles']]:
|
| 231 |
+
raise AssertionError('Shared candidate identity differs from immutable source')
|
| 232 |
+
reported = result['candidate_order_sha256'][view]
|
| 233 |
+
if reported != shared['candidate_order_sha256'][view]:
|
| 234 |
+
raise AssertionError('Shared candidate binding disagrees')
|
| 235 |
+
key = dataset, target, view
|
| 236 |
+
if key in comparison_hashes and comparison_hashes[key] != reported:
|
| 237 |
+
raise AssertionError('Candidate identities changed across models')
|
| 238 |
+
comparison_hashes[key] = reported
|
| 239 |
+
aliases_checked += len(entries)
|
| 240 |
+
file_rows = {(r['identifier'], r['view']): r for r in result['rows']}
|
| 241 |
+
for prediction in result['predictions']:
|
| 242 |
+
key = prediction['identifier'], prediction['view']
|
| 243 |
+
row = summary[key]
|
| 244 |
+
if file_rows[key] != row:
|
| 245 |
+
raise AssertionError('Target and aggregate row disagree')
|
| 246 |
+
entries = shared['pools'][key[1]]
|
| 247 |
+
scores = prediction['scores_in_raw_pool_order']
|
| 248 |
+
if len(scores) != len(entries) or any(x is not None and not math.isfinite(x) for x in scores):
|
| 249 |
+
raise AssertionError('Incorrect score population or nonfinite score')
|
| 250 |
+
order = sorted(range(len(entries)), key=lambda j: (scores[j] is None,
|
| 251 |
+
-scores[j] if scores[j] is not None else 0., entries[j]['key14'] or '', entries[j]['smiles']))
|
| 252 |
+
if prediction['ranked_raw_pool_indices'] != order:
|
| 253 |
+
raise AssertionError('Saved sorted order disagrees with final scores')
|
| 254 |
+
for field, name in [('key14', 'rank'), ('canonical_smiles', 'canonical_rank'), ('full_inchikey', 'inchikey_rank')]:
|
| 255 |
+
if field == 'key14':
|
| 256 |
+
truth = row['reference_identity']
|
| 257 |
+
else:
|
| 258 |
+
truth_fields = db.execute('SELECT canonical,fullkey FROM aliases WHERE smiles=?', (row['reference_smiles'],)).fetchone()
|
| 259 |
+
truth = truth_fields[0 if field == 'canonical_smiles' else 1]
|
| 260 |
+
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)
|
| 261 |
+
if rank != row[name]:
|
| 262 |
+
raise AssertionError(('Rank mismatch', name, key))
|
| 263 |
+
top1 = entries[order[0]]['smiles'] if order and scores[order[0]] is not None else None
|
| 264 |
+
if top1 != row['top1_smiles']:
|
| 265 |
+
raise AssertionError('Top1 molecule differs')
|
| 266 |
+
formula_scores = prediction['formula_scores']
|
| 267 |
+
formulas = prediction['formulas']
|
| 268 |
+
if row['query_error'] is None:
|
| 269 |
+
if len(formula_scores) != len(formulas) or any(not math.isfinite(x) for x in formula_scores):
|
| 270 |
+
raise AssertionError('Invalid formula scores')
|
| 271 |
+
expected_order = sorted(range(len(formulas)), key=lambda j: (-formula_scores[j], formulas[j]))
|
| 272 |
+
if expected_order != prediction['ranked_formula_indices']:
|
| 273 |
+
raise AssertionError('Formula sorting differs')
|
| 274 |
+
truth = row['reference_formula']
|
| 275 |
+
# Formula string normalization is already frozen in source aliases;
|
| 276 |
+
# verify rank against stored supported truth without new RDKit parsing.
|
| 277 |
+
truth_alias = db.execute('SELECT formula FROM aliases WHERE smiles=?', (row['reference_smiles'],)).fetchone()
|
| 278 |
+
if truth_alias and truth_alias[0]:
|
| 279 |
+
truth = truth_alias[0]
|
| 280 |
+
computed = next((i + 1 for i, j in enumerate(expected_order) if formulas[j] == truth), None)
|
| 281 |
+
if computed != row['formula_rank']:
|
| 282 |
+
raise AssertionError(('Formula rank differs', key, truth, row['reference_formula'], computed, row['formula_rank']))
|
| 283 |
+
predictions_checked += 1
|
| 284 |
+
expected = {target for target, in db.execute('SELECT DISTINCT target FROM spectra')}
|
| 285 |
+
db.close()
|
| 286 |
+
if actual_targets != expected:
|
| 287 |
+
raise AssertionError('Missing/extra targets')
|
| 288 |
+
return dict(targets=len(actual_targets), spectral_view_predictions=predictions_checked,
|
| 289 |
+
raw_alias_memberships_checked=aliases_checked, all_ranked_scores_recomputed=True,
|
| 290 |
+
original_pools_identical=True, injected_reference_count=0)
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
|
code/snapshot/root/code/ceir_r3_20261110/audit_r3.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Independent full-ledger accounting and source-cursor overlap proof."""
|
| 2 |
+
from collections import Counter
|
| 3 |
+
from runtime_r2 import *
|
| 4 |
+
import features_r2 as ft
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def run():
|
| 8 |
+
db=readonly(PREP/'assets.sqlite');prior=readonly(Path(C['r2_output'])/'prepared/assets.sqlite')
|
| 9 |
+
hashes=json.loads((PREP/'ledger_hashes.json').read_text())['unique'];counts=Counter();views=Counter();checks=0
|
| 10 |
+
for i,b in db.execute('SELECT idx,body FROM batches WHERE mode="unique" ORDER BY idx'):
|
| 11 |
+
if hashlib.sha256(b).hexdigest()!=hashes[i]:raise RuntimeError('Ledger hash mismatch')
|
| 12 |
+
plan=ft.loads(b)
|
| 13 |
+
if i<1000:
|
| 14 |
+
expected=prior.execute('SELECT body FROM batches WHERE mode="unique" AND idx=?',(i+1000,)).fetchone()
|
| 15 |
+
if expected is None or ft.loads(expected[0])!=plan:raise RuntimeError('Original future cursor/sampling drift')
|
| 16 |
+
checks+=1
|
| 17 |
+
for r in plan['rows']:
|
| 18 |
+
counts['query_presentations']+=1;counts['candidate_views']+=len(r['pools'])
|
| 19 |
+
for p in r['pools']:
|
| 20 |
+
views[p['kind']]+=1;counts['negative_draws']+=p['negative_draws']
|
| 21 |
+
if p['reference_injected']:raise RuntimeError('Injected reference')
|
| 22 |
+
if len(hashes)!=3000 or checks!=1000:raise RuntimeError('Incomplete continuation audit')
|
| 23 |
+
missing=db.execute('SELECT count(*) FROM r3_features WHERE distance IS NULL').fetchone()[0]
|
| 24 |
+
if missing:raise RuntimeError('Offline structures missing')
|
| 25 |
+
result=dict(complete=True,steps=3000,source_update=3000,target_update=6000,original_future_batches_exactly_matched=checks,
|
| 26 |
+
counts=dict(counts),candidate_view_counts=dict(views),offline_structures=db.execute('SELECT count(*) FROM r3_features').fetchone()[0],
|
| 27 |
+
parent_sha256=C['parent_sha256'],ledger_sha256=sha(PREP/'ledger_hashes.json'),all_arms_same_ledger=True,original_data_modified=False)
|
| 28 |
+
save(PREP/'INDEPENDENT_LEDGER_AUDIT.json',result);print(json.dumps(result),flush=True)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
if __name__=='__main__':run()
|
code/snapshot/root/code/ceir_r3_20261110/compact.supervisor.conf
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[program:specpartition-r3-compact-20261110]
|
| 2 |
+
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
|
| 3 |
+
directory=/root/xj/SpecPartition-MS/code/ceir_r3_20261110
|
| 4 |
+
autostart=false
|
| 5 |
+
autorestart=false
|
| 6 |
+
startsecs=2
|
| 7 |
+
stopasgroup=true
|
| 8 |
+
killasgroup=true
|
| 9 |
+
redirect_stderr=true
|
| 10 |
+
stdout_logfile=/root/xj/SpecPartition-MS/runs/ceir_r3_20261110/compact.log
|
| 11 |
+
environment=OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1"
|
code/snapshot/root/code/ceir_r3_20261110/compact_r3.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""One-time lossless compaction of this release's NEW private feature overlay.
|
| 2 |
+
|
| 3 |
+
Never removes or overwrites the source. Publication is a separate audited step.
|
| 4 |
+
"""
|
| 5 |
+
import argparse
|
| 6 |
+
import hashlib
|
| 7 |
+
import json
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
import sqlite3
|
| 10 |
+
import time
|
| 11 |
+
import itertools
|
| 12 |
+
import multiprocessing
|
| 13 |
+
from concurrent.futures import ProcessPoolExecutor
|
| 14 |
+
import numpy as np
|
| 15 |
+
import features_r2 as ft
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def logical_update(h,row):
|
| 19 |
+
k,s,b,bh,d,dh=row
|
| 20 |
+
if b is not None and not ft.digest_matches(b,bh):raise RuntimeError('Fragment checksum mismatch')
|
| 21 |
+
if d is not None and not ft.digest_matches(d,dh):raise RuntimeError('Distance checksum mismatch')
|
| 22 |
+
values=[k.encode(),s.encode(),b,b'' if d is None else ft.distance_loads(d).tobytes()]
|
| 23 |
+
for value in values:
|
| 24 |
+
h.update(b'N' if value is None else b'V'+len(value).to_bytes(8,'little')+value)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def record_digest(row):
|
| 28 |
+
h=hashlib.sha256();logical_update(h,row);return h.digest()
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def convert(row):
|
| 32 |
+
digest=record_digest(row);k,s,blob,bh,d,dh=row
|
| 33 |
+
if d is not None:
|
| 34 |
+
before=ft.distance_loads(d);d=ft.distance_dumps(before)
|
| 35 |
+
if not np.array_equal(before,ft.distance_loads(d)):raise RuntimeError('Lossy topology conversion')
|
| 36 |
+
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
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def run(source,target):
|
| 40 |
+
if target.exists():raise RuntimeError('Refuse to overwrite compaction target')
|
| 41 |
+
a=sqlite3.connect('file:'+str(source)+'?mode=ro',uri=True);b=sqlite3.connect(target)
|
| 42 |
+
b.execute('PRAGMA page_size=16384')
|
| 43 |
+
b.execute('PRAGMA journal_mode=OFF');b.execute('PRAGMA synchronous=OFF')
|
| 44 |
+
b.execute('CREATE TABLE batches(mode TEXT,idx INTEGER,body BLOB,PRIMARY KEY(mode,idx)) WITHOUT ROWID')
|
| 45 |
+
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')
|
| 46 |
+
for row in a.execute('SELECT mode,idx,body FROM batches ORDER BY mode,idx'):b.execute('INSERT INTO batches VALUES (?,?,?)',row)
|
| 47 |
+
old=hashlib.sha256();count=0;start=time.time()
|
| 48 |
+
with ProcessPoolExecutor(max_workers=12,mp_context=multiprocessing.get_context('spawn')) as workers:
|
| 49 |
+
cursor=a.execute('SELECT feature_key,smiles,feature,feature_sha,distance,distance_sha FROM r3_features ORDER BY feature_key')
|
| 50 |
+
while rows:=list(itertools.islice(cursor,8192)):
|
| 51 |
+
for row,digest in workers.map(convert,rows,chunksize=128):
|
| 52 |
+
old.update(digest);b.execute('INSERT INTO r3_features VALUES (?,?,?,?,?,?)',row);count+=1
|
| 53 |
+
b.commit()
|
| 54 |
+
if count%98304==0:print(json.dumps(dict(phase='compact',records=count,seconds=time.time()-start,bytes=target.stat().st_size)),flush=True)
|
| 55 |
+
b.execute('CREATE INDEX pending_r3 ON r3_features(feature_key) WHERE distance IS NULL');b.commit()
|
| 56 |
+
check=hashlib.sha256()
|
| 57 |
+
with ProcessPoolExecutor(max_workers=12,mp_context=multiprocessing.get_context('spawn')) as workers:
|
| 58 |
+
cursor=b.execute('SELECT feature_key,smiles,feature,feature_sha,distance,distance_sha FROM r3_features ORDER BY feature_key')
|
| 59 |
+
while rows:=list(itertools.islice(cursor,8192)):
|
| 60 |
+
for digest in workers.map(record_digest,rows,chunksize=128):check.update(digest)
|
| 61 |
+
if old.digest()!=check.digest():raise RuntimeError('Independent logical checksum mismatch')
|
| 62 |
+
old_batches=list(a.execute('SELECT mode,idx,body FROM batches ORDER BY mode,idx'))
|
| 63 |
+
new_batches=list(b.execute('SELECT mode,idx,body FROM batches ORDER BY mode,idx'))
|
| 64 |
+
if old_batches!=new_batches:raise RuntimeError('Sampler ledger changed')
|
| 65 |
+
integrity=b.execute('PRAGMA integrity_check').fetchone()[0]
|
| 66 |
+
if integrity!='ok':raise RuntimeError(integrity)
|
| 67 |
+
b.execute('PRAGMA journal_mode=DELETE');b.close();a.close()
|
| 68 |
+
result=dict(complete=True,source=str(source),target=str(target),source_bytes=source.stat().st_size,target_bytes=target.stat().st_size,
|
| 69 |
+
structures=count,batches=len(old_batches),source_logical_sha256=old.hexdigest(),target_logical_sha256=check.hexdigest(),
|
| 70 |
+
all_distance_arrays_exact=True,all_fragment_blobs_unchanged=True,integrity=integrity,seconds=time.time()-start)
|
| 71 |
+
target.with_suffix('.audit.json').write_text(json.dumps(result,indent=2)+'\n');print(json.dumps(result),flush=True)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
if __name__=='__main__':
|
| 75 |
+
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)
|
code/snapshot/root/code/ceir_r3_20261110/config.json
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"release": "CEIR_R3_20261110",
|
| 3 |
+
"root": "/workspace/xj/SpecPartition-MS",
|
| 4 |
+
"source_r1": "/root/xj/SpecPartition-MS/code/ceir_r1_20261109",
|
| 5 |
+
"source_r2": "/root/xj/SpecPartition-MS/code/ceir_r2_20261110",
|
| 6 |
+
"r2_output": "/root/xj/SpecPartition-MS/runs/ceir_r2_20261110",
|
| 7 |
+
"output": "/root/xj/SpecPartition-MS/runs/ceir_r3_20261110",
|
| 8 |
+
"evaluation_output": "/workspace/xj/SpecPartition-MS/runs/ceir_r3_evaluations_20261110",
|
| 9 |
+
"parent_checkpoint": "/root/xj/SpecPartition-MS/runs/ceir_r2_20261110/A3/step_003000.pt",
|
| 10 |
+
"parent_sha256": "78841458441e38b260c076e75ccd06e0729e83887450eb8b64667edeab87aa46",
|
| 11 |
+
"arms": ["R3C", "R3M", "R3H", "R3D", "R3F"],
|
| 12 |
+
"source_update": 3000,
|
| 13 |
+
"pilot_target_update": 6000,
|
| 14 |
+
"manifest_updates": 3000,
|
| 15 |
+
"seed": 20261103,
|
| 16 |
+
"feature_version": "r3_spatial_distance_v1",
|
| 17 |
+
"chem_weight": 0.05,
|
| 18 |
+
"spectrum_weight": 0.05,
|
| 19 |
+
"prepare_workers": 12,
|
| 20 |
+
"spectrum_chunk": 16,
|
| 21 |
+
"graph_chunk": 256,
|
| 22 |
+
"local_chunk": 128,
|
| 23 |
+
"pool_micro_views": 8,
|
| 24 |
+
"max_atoms_per_microbatch": 12000,
|
| 25 |
+
"gpu_memory_fraction": 0.42,
|
| 26 |
+
"minimum_free_gpu_mib": 5500,
|
| 27 |
+
"gpu_slots": 2,
|
| 28 |
+
"minimum_output_disk_gib": 1.5,
|
| 29 |
+
"backbone_lr_multiplier": 1.0,
|
| 30 |
+
"new_head_lr": 0.0001,
|
| 31 |
+
"lr_ramp_updates": 100,
|
| 32 |
+
"save_interval": 100,
|
| 33 |
+
"validation_updates": [4000, 5000, 6000],
|
| 34 |
+
"validation_spectrum_batch": 16,
|
| 35 |
+
"validation_graph_chunk": 32,
|
| 36 |
+
"validation_local_chunk": 32,
|
| 37 |
+
"validation_degradation_tolerance_pp": 0.2,
|
| 38 |
+
"test_used_for_model_selection": false,
|
| 39 |
+
"test_development_exposure": "Prior Test/CASMI badcases informed design; not pristine holdouts",
|
| 40 |
+
"original_assets_read_only": true,
|
| 41 |
+
"negative_sampling": "same A3 unique-key14 random training draws in all arms; no mining change in this architecture ablation",
|
| 42 |
+
"formula_normalization": "bounded learned per-formula logmeanexp correction; no pruning; sample/full-pool discrepancy audited",
|
| 43 |
+
"test_checkpoint_policy": "all five fixed 6000-update endpoints, after Validation-only recommendation"
|
| 44 |
+
}
|
code/snapshot/root/code/ceir_r3_20261110/data_r2.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Frozen draw ledger: no PubChem, RDKit parsing, or pool JSON in training."""
|
| 2 |
+
from collections import Counter
|
| 3 |
+
from dataclasses import replace
|
| 4 |
+
import time
|
| 5 |
+
from runtime_r2 import *
|
| 6 |
+
import features_r2 as features
|
| 7 |
+
from data09 import Reader
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class Dataset:
|
| 11 |
+
def __init__(self,arm,start=0,stop=None,feature_path=None):
|
| 12 |
+
self.arm=arm;self.start=start;self.stop=C['manifest_updates'] if stop is None else stop
|
| 13 |
+
self.reader=None;self.db=None;self.features=None;self.feature_path=feature_path
|
| 14 |
+
self.ledger_hashes=None
|
| 15 |
+
|
| 16 |
+
def __len__(self):return self.stop-self.start
|
| 17 |
+
|
| 18 |
+
def __getitem__(self,index):
|
| 19 |
+
started=time.monotonic()
|
| 20 |
+
if self.reader is None:
|
| 21 |
+
self.reader=Reader();self.db=readonly(PREP/'assets.sqlite')
|
| 22 |
+
self.features=features.FeatureStore(self.feature_path or PREP/'assets.sqlite')
|
| 23 |
+
if self.feature_path is None:self.ledger_hashes=json.loads((PREP/'ledger_hashes.json').read_text())
|
| 24 |
+
mode='unique'
|
| 25 |
+
offset=self.start+index
|
| 26 |
+
ledger=self.db.execute('SELECT body FROM batches WHERE mode=? AND idx=?',(mode,offset)).fetchone()
|
| 27 |
+
if ledger is None:raise RuntimeError('Missing immutable R2 sampler batch')
|
| 28 |
+
digest=hashlib.sha256(ledger[0]).hexdigest()
|
| 29 |
+
if self.ledger_hashes is not None and digest!=self.ledger_hashes[mode][offset]:raise RuntimeError('Sampler ledger changed after acceptance')
|
| 30 |
+
plan=features.loads(ledger[0]);rows=[]
|
| 31 |
+
for selected in plan['rows']:
|
| 32 |
+
original=self.reader.db.execute('SELECT body FROM samples WHERE record_id=?',(selected['rid'],)).fetchone()
|
| 33 |
+
row=loads(original[0]);ref=self.reader.molecule(selected['ref'])
|
| 34 |
+
if ref.identity!=row['identity'] or ref.identity in self.reader.forbidden:raise RuntimeError('Unsafe reference')
|
| 35 |
+
row['ref']=ref;row['formulas']=tuple(selected['formulas']);row['pools']=[]
|
| 36 |
+
row['query']=replace(row['query'],formula_candidates=row['formulas'])
|
| 37 |
+
feature=self.features.get(ref.smiles)
|
| 38 |
+
if feature['layout']!=features.layout(ref.mol):raise RuntimeError('Reference atom layout changed')
|
| 39 |
+
row['chemical_counts']=feature['counts']
|
| 40 |
+
for p in selected['pools']:
|
| 41 |
+
mols=tuple(self.reader.molecule(g) for g in p['graphs'])
|
| 42 |
+
if mols[0].identity!=ref.identity or any(m.identity==ref.identity for m in mols[1:]):raise RuntimeError('Missing positive or false negative')
|
| 43 |
+
if any(m.identity in self.reader.forbidden for m in mols):raise RuntimeError('Heldout negative')
|
| 44 |
+
kind=p['kind'];q=replace(row['query'],candidates=mols,formula_candidates=tuple(p['formulas']),
|
| 45 |
+
candidate_view='odata_oracle' if kind=='odata' else 'msg_'+kind)
|
| 46 |
+
eligible=bool(row['mass_ok'] and features.supported_positive(q,self.features.get(mols[0].smiles)))
|
| 47 |
+
row['pools'].append(dict(**p,query=q,positive_index=0,truth_identity=ref.identity,
|
| 48 |
+
truth_formula=row['formula'],record_id=row['record_id'],quality_eligible=bool(row['mass_ok']),spectrum_eligible=eligible))
|
| 49 |
+
rows.append(row)
|
| 50 |
+
return dict(epoch=plan['epoch'],step=plan['step'],rows=rows,mode=mode,manifest_index=offset,
|
| 51 |
+
ledger_sha256=digest,data_seconds=time.monotonic()-started)
|
code/snapshot/root/code/ceir_r3_20261110/features_r2.py
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Versioned label-free static candidate descriptors and connected cut hypotheses."""
|
| 2 |
+
from functools import lru_cache
|
| 3 |
+
import hashlib
|
| 4 |
+
import itertools
|
| 5 |
+
import pickle
|
| 6 |
+
import sqlite3
|
| 7 |
+
import struct
|
| 8 |
+
import zlib
|
| 9 |
+
import numpy as np
|
| 10 |
+
from rdkit import Chem,RDLogger
|
| 11 |
+
from rdkit.Chem import rdMolDescriptors
|
| 12 |
+
|
| 13 |
+
VERSION='connected_cuts_r2_v1';K=32;TRAITS=7;CLASSES=33
|
| 14 |
+
RDLogger.DisableLog('rdApp.*')
|
| 15 |
+
PATTERNS=[Chem.MolFromSmarts(s) for s in ('[OX2H]','[CX3]=[OX1]','[#6][OX2][#6]')]
|
| 16 |
+
PT=Chem.GetPeriodicTable();H=PT.GetMostCommonIsotopeMass(1)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def dumps(value):return zlib.compress(pickle.dumps(value,protocol=5),1)
|
| 20 |
+
def loads(value):return pickle.loads(zlib.decompress(value))
|
| 21 |
+
def key(smiles):return hashlib.sha256(smiles.encode()).hexdigest()
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def digest_matches(blob,digest):
|
| 25 |
+
actual=hashlib.sha256(blob)
|
| 26 |
+
return actual.digest()==digest if isinstance(digest,bytes) else actual.hexdigest()==digest
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def distance_dumps(value):
|
| 30 |
+
"""Lossless symmetric, capped uint8 distances; two distances per byte."""
|
| 31 |
+
value=np.asarray(value,dtype=np.uint8);n=value.shape[0]
|
| 32 |
+
if value.shape!=(n,n) or np.any(value>15) or np.any(np.diag(value)) or not np.array_equal(value,value.T):
|
| 33 |
+
raise ValueError('Invalid symmetric capped distance matrix')
|
| 34 |
+
upper=value[np.triu_indices(n,1)]
|
| 35 |
+
if len(upper)%2:upper=np.pad(upper,(0,1))
|
| 36 |
+
packed=(upper[::2]<<4)|upper[1::2]
|
| 37 |
+
return b'R3D1'+struct.pack('<I',n)+zlib.compress(packed.tobytes(),9)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def distance_loads(blob):
|
| 41 |
+
if not blob.startswith(b'R3D1'):return loads(blob)
|
| 42 |
+
n=struct.unpack('<I',blob[4:8])[0];packed=np.frombuffer(zlib.decompress(blob[8:]),dtype=np.uint8)
|
| 43 |
+
upper=np.empty(len(packed)*2,dtype=np.uint8);upper[::2]=packed>>4;upper[1::2]=packed&15
|
| 44 |
+
upper=upper[:n*(n-1)//2];result=np.zeros((n,n),dtype=np.uint8);idx=np.triu_indices(n,1)
|
| 45 |
+
result[idx]=upper;result[(idx[1],idx[0])]=upper
|
| 46 |
+
return result
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def layout(mol):
|
| 50 |
+
atoms=[a.GetAtomicNum() for a in mol.GetAtoms()]
|
| 51 |
+
edges=sorted((min(b.GetBeginAtomIdx(),b.GetEndAtomIdx()),max(b.GetBeginAtomIdx(),b.GetEndAtomIdx()),str(b.GetBondType())) for b in mol.GetBonds())
|
| 52 |
+
return hashlib.sha256(repr((atoms,edges)).encode()).hexdigest()
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def components(n,adj,removed):
|
| 56 |
+
seen=set();result=[]
|
| 57 |
+
for first in range(n):
|
| 58 |
+
if first in seen:continue
|
| 59 |
+
todo=[first];seen.add(first);part=[]
|
| 60 |
+
while todo:
|
| 61 |
+
i=todo.pop();part.append(i)
|
| 62 |
+
for j,bid in adj[i]:
|
| 63 |
+
if bid not in removed and j not in seen:seen.add(j);todo.append(j)
|
| 64 |
+
result.append(tuple(sorted(part)))
|
| 65 |
+
return result
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def build(smiles):
|
| 69 |
+
mol=Chem.MolFromSmiles(smiles)
|
| 70 |
+
if mol is None:raise ValueError('Invalid candidate SMILES')
|
| 71 |
+
n=mol.GetNumAtoms();counts=[len(mol.GetSubstructMatches(p)) for p in PATTERNS]
|
| 72 |
+
counts += [rdMolDescriptors.CalcNumAromaticRings(mol),rdMolDescriptors.CalcNumAliphaticRings(mol),rdMolDescriptors.CalcNumHeterocycles(mol),len(Chem.GetMolFrags(mol))]
|
| 73 |
+
out=dict(version=VERSION,smiles=smiles,layout=layout(mol),atoms=n,
|
| 74 |
+
counts=np.asarray([min(32,v) for v in counts],dtype=np.int64),members=np.zeros((K,n),dtype=np.float32),
|
| 75 |
+
boundary=np.zeros((K,8),dtype=np.float32),
|
| 76 |
+
masses=np.zeros(K,dtype=np.float32),hydrogens=np.zeros(K,dtype=np.int16),valid=np.zeros(K,dtype=bool),
|
| 77 |
+
neutral_mass=rdMolDescriptors.CalcExactMolWt(mol),reason=None)
|
| 78 |
+
if len(Chem.GetMolFrags(mol))!=1 or Chem.GetFormalCharge(mol)!=0 or any(a.GetIsotope() for a in mol.GetAtoms()):
|
| 79 |
+
out['reason']='unsupported_fragment_hypothesis_structure';return out
|
| 80 |
+
adj=[[] for _ in range(n)]
|
| 81 |
+
for b in mol.GetBonds():
|
| 82 |
+
i,j=b.GetBeginAtomIdx(),b.GetEndAtomIdx();adj[i].append((j,b.GetIdx()));adj[j].append((i,b.GetIdx()))
|
| 83 |
+
bridges=[b for b in mol.GetBonds() if not b.IsInRing() and b.GetBondType()==Chem.BondType.SINGLE]
|
| 84 |
+
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()))
|
| 85 |
+
ring=[b.GetIdx() for b in mol.GetBonds() if b.IsInRing()]
|
| 86 |
+
pairs=list(itertools.combinations(ring,2))
|
| 87 |
+
pairs.sort(key=lambda p:hashlib.sha256(repr(p).encode()).digest())
|
| 88 |
+
cuts=[(b.GetIdx(),) for b in bridges[:20]]+pairs[:12]
|
| 89 |
+
parts=set()
|
| 90 |
+
for cut in cuts:
|
| 91 |
+
for part in components(n,adj,set(cut)):
|
| 92 |
+
if 3<=len(part)<=n-2:parts.add(part)
|
| 93 |
+
choices=sorted(parts,key=lambda p:(len(p),p))
|
| 94 |
+
if len(choices)>K:choices=[choices[int(i)] for i in np.linspace(0,len(choices)-1,K).round()]
|
| 95 |
+
masses=[];nh=[]
|
| 96 |
+
for a in mol.GetAtoms():
|
| 97 |
+
hydrogen=a.GetTotalNumHs();nh.append(hydrogen)
|
| 98 |
+
masses.append(PT.GetMostCommonIsotopeMass(a.GetAtomicNum())+hydrogen*H)
|
| 99 |
+
for j,part in enumerate(choices):
|
| 100 |
+
out['members'][j,list(part)]=1/len(part)
|
| 101 |
+
out['masses'][j]=sum(masses[i] for i in part);out['hydrogens'][j]=sum(nh[i] for i in part);out['valid'][j]=True
|
| 102 |
+
chosen=set(part);aa=[mol.GetAtomWithIdx(i) for i in part]
|
| 103 |
+
out['boundary'][j]=[len(part)/n,sum(a.GetAtomicNum()==8 for a in aa)/len(part),
|
| 104 |
+
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,
|
| 105 |
+
sum(a.IsInRing() for a in aa)/len(part),sum(a.GetIsAromatic() for a in aa)/len(part),
|
| 106 |
+
sum(nh[i] for i in part)/len(part),out['masses'][j]/max(out['neutral_mass'],1)]
|
| 107 |
+
out['reason']='ok' if choices else 'no_supported_connected_cut'
|
| 108 |
+
return out
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
class FeatureStore:
|
| 112 |
+
def __init__(self,path):
|
| 113 |
+
from runtime_r2 import C,PREP
|
| 114 |
+
self.db=sqlite3.connect('file:'+str(path)+'?mode=ro',uri=True)
|
| 115 |
+
self.overlay=self.db.execute("SELECT 1 FROM sqlite_master WHERE name='r3_features'").fetchone() is not None
|
| 116 |
+
self.parents=[]
|
| 117 |
+
if self.overlay:
|
| 118 |
+
paths=[C['r2_output']+'/prepared/assets.sqlite']
|
| 119 |
+
if str(path)!=str(PREP/'assets.sqlite'):paths.append(C['r2_output']+'/test/prepared/assets.sqlite')
|
| 120 |
+
for p in paths:
|
| 121 |
+
db=sqlite3.connect('file:'+p+'?mode=ro',uri=True)
|
| 122 |
+
table='canonical_features' if db.execute("SELECT 1 FROM sqlite_master WHERE name='canonical_features'").fetchone() else 'molecules'
|
| 123 |
+
self.parents.append((db,table))
|
| 124 |
+
self.table='canonical_features' if self.db.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='canonical_features'").fetchone() else 'molecules'
|
| 125 |
+
self.get=lru_cache(maxsize=12000)(self._get)
|
| 126 |
+
|
| 127 |
+
def _get(self,smiles):
|
| 128 |
+
if self.overlay:
|
| 129 |
+
item=self.db.execute('SELECT feature,feature_sha,distance,distance_sha FROM r3_features WHERE feature_key=?',(key(smiles),)).fetchone()
|
| 130 |
+
if item is None:raise RuntimeError('Missing offline R3 structure '+smiles[:100])
|
| 131 |
+
blob,digest,distance,dh=item
|
| 132 |
+
if blob is None:
|
| 133 |
+
for db,table in self.parents:
|
| 134 |
+
old=db.execute('SELECT feature,feature_sha FROM '+table+' WHERE feature_key=?',(key(smiles),)).fetchone()
|
| 135 |
+
if old is not None and old[0] is not None:blob,digest=old;break
|
| 136 |
+
if blob is None or not digest_matches(blob,digest):raise RuntimeError('Missing/changed R2 descriptor')
|
| 137 |
+
if distance is None or not digest_matches(distance,dh):raise RuntimeError('Missing/changed R3 topology')
|
| 138 |
+
value=loads(blob)
|
| 139 |
+
if value['smiles']!=smiles:raise RuntimeError('R3 feature identity mismatch')
|
| 140 |
+
value['distance']=distance_loads(distance)
|
| 141 |
+
return value
|
| 142 |
+
row=self.db.execute('SELECT feature,feature_sha FROM '+self.table+' WHERE feature_key=?',(key(smiles),)).fetchone()
|
| 143 |
+
if row is None or row[0] is None:raise RuntimeError('Missing preprocessed R2 candidate feature: '+smiles[:120])
|
| 144 |
+
if hashlib.sha256(row[0]).hexdigest()!=row[1]:raise RuntimeError('R2 feature hash mismatch')
|
| 145 |
+
value=loads(row[0])
|
| 146 |
+
if value['version']!=VERSION or value['smiles']!=smiles:raise RuntimeError('R2 feature identity mismatch')
|
| 147 |
+
return value
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def ion_offsets(adduct):
|
| 151 |
+
proton=1.007276452090935
|
| 152 |
+
if adduct=='[M+H]+':return (proton,None)
|
| 153 |
+
if adduct=='[M-H]-':return (-proton,None)
|
| 154 |
+
if adduct=='[M+Na]+':return (22.989220702090936,proton)
|
| 155 |
+
if adduct=='[M+NH4]+':return (proton,18.033825548090935)
|
| 156 |
+
if adduct=='[M+Cl]-':return (-proton,34.96940125990906)
|
| 157 |
+
if adduct=='[M+FA-H]-':return (-proton,44.99820285190906)
|
| 158 |
+
return (None,None)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def spectrum(query):
|
| 162 |
+
peaks=sorted(query.peaks,key=lambda p:(-p[1],p[0]))[:256];peaks.sort()
|
| 163 |
+
mz=np.asarray([p[0] for p in peaks],dtype=np.float32)
|
| 164 |
+
y=np.sqrt(np.asarray([p[1] for p in peaks],dtype=np.float32)/max(p[1] for p in peaks))
|
| 165 |
+
y[np.abs(mz-query.precursor_mz)<=max(.05,query.precursor_mz*20e-6)]=0
|
| 166 |
+
return mz,y
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def supported_positive(query,feature):
|
| 170 |
+
offsets=ion_offsets(query.adduct)
|
| 171 |
+
if offsets[0] is None:return False
|
| 172 |
+
mz,y=spectrum(query)
|
| 173 |
+
if not y.sum():return False
|
| 174 |
+
masses=[]
|
| 175 |
+
for j in range(K):
|
| 176 |
+
if not feature['valid'][j]:continue
|
| 177 |
+
for shift in (-2,-1,0,1,2):
|
| 178 |
+
if feature['hydrogens'][j]+shift<0:continue
|
| 179 |
+
masses.extend(feature['masses'][j]+shift*H+v for v in offsets if v is not None)
|
| 180 |
+
if not masses:return False
|
| 181 |
+
mass=np.asarray(masses,dtype=np.float32)
|
| 182 |
+
valid=(np.abs(mz[:,None]-mass[None,:])<=np.maximum(.02,mass[None,:]*20e-6)).any(1)
|
| 183 |
+
return bool((y[valid].sum()/y.sum())>=.05)
|
code/snapshot/root/code/ceir_r3_20261110/final_audit_r3.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Re-sort every saved score without training or evaluator ranking helpers."""
|
| 2 |
+
import json
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import audit_primitives as audit
|
| 5 |
+
HERE=Path(__file__).resolve().parent
|
| 6 |
+
C=json.loads((HERE/'config.json').read_text());OUT=Path(C['output'])
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def run():
|
| 10 |
+
frozen=audit.load(OUT/'test/FROZEN.json');result=dict(complete=False,arms={},paired_vs_A3={},paired_vs_control={})
|
| 11 |
+
for name,h in frozen['r3_binding']['code'].items():
|
| 12 |
+
if audit.sha(HERE/name)!=h:raise RuntimeError('Frozen R3 source changed')
|
| 13 |
+
for name,h in frozen['r3_binding']['external_evaluation_code'].items():
|
| 14 |
+
if audit.sha(name)!=h:raise RuntimeError('Dependency source changed')
|
| 15 |
+
for d in ('msg_test','casmi2022'):
|
| 16 |
+
if audit.sha(audit.SOURCE/(d+'_ready.json'))!=frozen['inputs'][d]['ready_sha256']:raise RuntimeError('Frozen candidate input changed')
|
| 17 |
+
parent=Path(C['r2_output']);hashes={};rows={};audit.ROOT=OUT
|
| 18 |
+
for a in C['arms']:
|
| 19 |
+
name=a+'_006000';checkpoint=frozen['models'][name]
|
| 20 |
+
if audit.sha(checkpoint['checkpoint'])!=checkpoint['sha256']:raise RuntimeError('Checkpoint changed')
|
| 21 |
+
value,_=audit.aggregate(OUT/a/'validation_006000','validation');result['arms'][a]=dict(Validation=value)
|
| 22 |
+
for d in ('msg_test','casmi2022'):
|
| 23 |
+
value,rr=audit.aggregate(OUT/'test/inference'/name/d,d)
|
| 24 |
+
value['all_scores_verified']=audit.pool_and_prediction_audit(name,d,hashes)
|
| 25 |
+
result['arms'][a][d]=value;rows[a,d]=rr
|
| 26 |
+
for d in ('msg_test','casmi2022'):
|
| 27 |
+
_,base=audit.aggregate(parent/'test/inference/A3_003000'/d,d)
|
| 28 |
+
result['paired_vs_A3'][d]={a:audit.paired(base,rows[a,d]) for a in C['arms']}
|
| 29 |
+
result['paired_vs_control'][d]={a:audit.paired(rows['R3C',d],rows[a,d]) for a in C['arms'] if a!='R3C'}
|
| 30 |
+
result.update(complete=True,all_scores_and_denominators_verified=True,candidate_identity_comparisons=len(hashes)*len(C['arms']),
|
| 31 |
+
original_data_or_weights_modified=False,one_training_seed=True,Test_development_exposed=True)
|
| 32 |
+
audit.save(OUT/'INDEPENDENT_ALL_RESULTS.json',result)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
if __name__=='__main__':run()
|
code/snapshot/root/code/ceir_r3_20261110/heads_r3.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Label-free residual evidence. No reference identity or score-based pruning."""
|
| 2 |
+
from collections import Counter,OrderedDict
|
| 3 |
+
import math
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
from torch import nn
|
| 7 |
+
from torch.nn import functional as F
|
| 8 |
+
import features_r2 as ft
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class Heads(nn.Module):
|
| 12 |
+
def __init__(self):
|
| 13 |
+
super().__init__()
|
| 14 |
+
self.mass=nn.Sequential(nn.Linear(19,64),nn.GELU(),nn.Linear(64,64))
|
| 15 |
+
self.query=nn.Linear(320,128)
|
| 16 |
+
self.atom=nn.Linear(256,128)
|
| 17 |
+
self.qkv=nn.Linear(128,384)
|
| 18 |
+
self.spatial=nn.Embedding(16,4)
|
| 19 |
+
self.norm=nn.LayerNorm(128)
|
| 20 |
+
self.topology=nn.Sequential(nn.Linear(256,128),nn.GELU(),nn.Linear(128,128))
|
| 21 |
+
self.difference=nn.Sequential(nn.Linear(4,32),nn.GELU(),nn.Linear(32,1))
|
| 22 |
+
self.formula_alpha=nn.Parameter(torch.zeros(()))
|
| 23 |
+
nn.init.zeros_(self.topology[-1].weight);nn.init.zeros_(self.topology[-1].bias)
|
| 24 |
+
nn.init.zeros_(self.difference[-1].weight);nn.init.zeros_(self.difference[-1].bias)
|
| 25 |
+
self._rarity_cache=OrderedDict()
|
| 26 |
+
|
| 27 |
+
def precision_query(self,q,query):
|
| 28 |
+
mz,w=ft.spectrum(query)
|
| 29 |
+
# Explicit FP32 trigonometry/MLP; precursor delta is NOT labelled as a
|
| 30 |
+
# neutral loss. Correct ion templates remain in the fragment branch.
|
| 31 |
+
with torch.autocast(q.device.type,enabled=False):
|
| 32 |
+
mz=torch.as_tensor(mz,device=q.device,dtype=torch.float32);w=torch.as_tensor(w,device=q.device)
|
| 33 |
+
angles=2*math.pi*mz[:,None]*mz.new_tensor([1,2,4,8,16,32,64,128])[None,:]
|
| 34 |
+
x=torch.cat((mz[:,None]/1000,(mz-mz.floor())[:,None],w[:,None],angles.sin(),angles.cos()),-1)
|
| 35 |
+
z=self.mass(x);pooled=(z*w[:,None]).sum(0)/w.sum().clamp_min(1e-8)
|
| 36 |
+
return F.normalize(self.query(torch.cat((q.float(),pooled))),dim=-1)
|
| 37 |
+
|
| 38 |
+
def topology_scores(self,q,query,atoms,assets):
|
| 39 |
+
zq=self.precision_query(q,query);parts=[]
|
| 40 |
+
for start in range(0,len(atoms),32):
|
| 41 |
+
aa=atoms[start:start+32];ff=assets[start:start+32];n=max(len(a) for a in aa);b=len(aa);device=q.device
|
| 42 |
+
# Differentiable padding keeps the current GNN's gradients.
|
| 43 |
+
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]
|
| 44 |
+
ds=np.full((b,n,n),15,dtype=np.int64)
|
| 45 |
+
for j,f in enumerate(ff):ds[j,:f['atoms'],:f['atoms']]=f['distance']
|
| 46 |
+
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)
|
| 47 |
+
bias=self.spatial(torch.as_tensor(ds,device=device)).permute(0,3,1,2)
|
| 48 |
+
weights=(qq@kk.transpose(-1,-2)/math.sqrt(32)+bias).float().masked_fill(mask[:,None,None,:],-1e9).softmax(-1)
|
| 49 |
+
mixed=(weights.to(vv.dtype)@vv).transpose(1,2).reshape(b,n,128);h=self.norm(h+mixed)
|
| 50 |
+
valid=(~mask).float();mean=(h.float()*valid[:,:,None]).sum(1)/valid.sum(1)[:,None]
|
| 51 |
+
maximum=h.float().masked_fill(mask[:,:,None],-1e9).max(1).values
|
| 52 |
+
z=self.topology(torch.cat((mean,maximum),-1)).float()
|
| 53 |
+
parts.append((z*zq).sum(-1)/math.sqrt(128))
|
| 54 |
+
return torch.cat(parts)
|
| 55 |
+
|
| 56 |
+
def rarity(self,mols,assets):
|
| 57 |
+
# Bounded CPU cache, no learned embeddings and no truth-derived keys.
|
| 58 |
+
key=tuple(m.smiles for m in mols)
|
| 59 |
+
if key in self._rarity_cache:
|
| 60 |
+
result=self._rarity_cache.pop(key);self._rarity_cache[key]=result;return result
|
| 61 |
+
bins=[np.rint(a['masses']/.02).astype(np.int64) for a in assets]
|
| 62 |
+
counts=Counter(v for bb,a in zip(bins,assets) for v in set(bb[a['valid']].tolist()))
|
| 63 |
+
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.
|
| 64 |
+
for v,valid in zip(bb,a['valid'])] for bb,a in zip(bins,assets)],dtype=np.float32)
|
| 65 |
+
self._rarity_cache[key]=result
|
| 66 |
+
while len(self._rarity_cache)>2:self._rarity_cache.popitem(last=False)
|
| 67 |
+
return result
|
| 68 |
+
|
| 69 |
+
def difference_scores(self,q,query,mols,assets):
|
| 70 |
+
off=ft.ion_offsets(query.adduct)
|
| 71 |
+
if off[0] is None:return q.float().sum().expand(len(mols))*0.
|
| 72 |
+
rarity=self.rarity(mols,assets);mz,y=ft.spectrum(query);device=q.device
|
| 73 |
+
mz=torch.as_tensor(mz,device=device);y=torch.as_tensor(y,device=device);out=[]
|
| 74 |
+
for start in range(0,len(mols),128):
|
| 75 |
+
ff=assets[start:start+128];m=torch.as_tensor(np.stack([a['masses'] for a in ff]),device=device)
|
| 76 |
+
valid=torch.as_tensor(np.stack([a['valid'] for a in ff]),device=device)
|
| 77 |
+
hh=torch.as_tensor(np.stack([a['hydrogens'] for a in ff]),device=device);rr=torch.as_tensor(rarity[start:start+128],device=device)
|
| 78 |
+
shifts=m.new_tensor([-2,-1,0,1,2]);offsets=m.new_tensor([v for v in off if v is not None])
|
| 79 |
+
hypothesis=m[:,:,None,None]+shifts[None,None,:,None]*ft.H+offsets[None,None,None,:]
|
| 80 |
+
supported=valid[:,:,None,None]&(hh[:,:,None,None]+shifts[None,None,:,None]>=0)&hypothesis.gt(0)
|
| 81 |
+
right=torch.searchsorted(mz,hypothesis.contiguous()).clamp(max=len(mz)-1);left=(right-1).clamp(min=0)
|
| 82 |
+
ix=torch.where((mz[right]-hypothesis).abs()<(mz[left]-hypothesis).abs(),right,left)
|
| 83 |
+
matched=((mz[ix]-hypothesis).abs()<=torch.maximum(hypothesis*20e-6,m.new_tensor(.02)))&supported
|
| 84 |
+
best=(y[ix]*matched).flatten(2).max(-1).values;hit=matched.flatten(2).any(-1).float()
|
| 85 |
+
denominator=rr.sum(-1).clamp_min(1e-8);number=valid.sum(-1).clamp_min(1)
|
| 86 |
+
evidence=torch.stack(((rr*best).sum(-1)/denominator,(rr*hit).sum(-1)/denominator,
|
| 87 |
+
(best*valid).sum(-1)/number,(rr*(1-hit)).sum(-1)/denominator),-1)
|
| 88 |
+
out.append(self.difference(evidence).float().squeeze(-1)*valid.any(-1))
|
| 89 |
+
return torch.cat(out)
|
| 90 |
+
|
| 91 |
+
def calibrate(self,base,direct,formulas):
|
| 92 |
+
groups={}
|
| 93 |
+
for j,f in enumerate(formulas):groups.setdefault(f,[]).append(j)
|
| 94 |
+
if len(groups)<=1:return base
|
| 95 |
+
correction=torch.zeros_like(base)
|
| 96 |
+
for indices in groups.values():
|
| 97 |
+
index=torch.tensor(indices,device=base.device);b=direct[index].float()
|
| 98 |
+
value=b.logsumexp(0)-math.log(len(indices))
|
| 99 |
+
correction=correction.index_copy(0,index,value.expand(len(indices)))
|
| 100 |
+
# Zero starts as exact A3; bounded signed correction is learnable.
|
| 101 |
+
# logmeanexp avoids a deterministic advantage merely from group size.
|
| 102 |
+
return base-.5*self.formula_alpha.tanh()*correction
|
code/snapshot/root/code/ceir_r3_20261110/mces_r2.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Validation MCES under the same R1 protocol, with a private resumable cache."""
|
| 2 |
+
import argparse
|
| 3 |
+
import fcntl
|
| 4 |
+
import importlib.util
|
| 5 |
+
import json
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import sqlite3
|
| 8 |
+
import sys
|
| 9 |
+
|
| 10 |
+
HERE=Path(__file__).resolve().parent;C=json.loads((HERE/'config.json').read_text());OUT=Path(C['output'])
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def run(directory):
|
| 14 |
+
path=Path(C['source_r1'])/'mces_ceir.py';name='r2_validation_mces_engine'
|
| 15 |
+
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)
|
| 16 |
+
own=OUT/'mces_validation';own.mkdir(parents=True,exist_ok=True)
|
| 17 |
+
lock=(own/'compute.lock').open('a+');fcntl.flock(lock,fcntl.LOCK_EX)
|
| 18 |
+
if (Path(directory)/'MCES.json').exists():return
|
| 19 |
+
target=own/'Validation_mces_pairs.sqlite'
|
| 20 |
+
if not target.exists():
|
| 21 |
+
source=Path(C['r2_output'])/'mces_validation/Validation_mces_pairs.sqlite'
|
| 22 |
+
if source.exists():
|
| 23 |
+
a=sqlite3.connect('file:'+str(source)+'?mode=ro',uri=True);b=sqlite3.connect(target);a.backup(b);a.close();b.close()
|
| 24 |
+
module.OUT=OUT;module.CACHE=own
|
| 25 |
+
module.evaluate(Path(directory))
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
if __name__=='__main__':
|
| 29 |
+
p=argparse.ArgumentParser();p.add_argument('--directory',required=True);a=p.parse_args();run(a.directory)
|
code/snapshot/root/code/ceir_r3_20261110/model_r2_new.py
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""C03-preserving discriminative chemistry and candidate-to-spectrum evidence.
|
| 2 |
+
|
| 3 |
+
Static connected cuts are hypotheses, NOT ground-truth fragment annotations.
|
| 4 |
+
Only training reference labels supervise the count and reconstructed spectrum
|
| 5 |
+
heads; scoring never receives the reference identity, its counts, or its formula.
|
| 6 |
+
"""
|
| 7 |
+
import numpy as np
|
| 8 |
+
import torch
|
| 9 |
+
from torch import nn
|
| 10 |
+
from torch.nn import functional as F
|
| 11 |
+
from runtime_r2 import *
|
| 12 |
+
import features_r2 as features
|
| 13 |
+
from specpartition_ms.model_v122 import BidirectionalRanker
|
| 14 |
+
from specpartition_ms.model import Encoded,metadata
|
| 15 |
+
from specpartition_ms.fast_formula_r2 import forward_batch as original_formula_forward
|
| 16 |
+
from coarse_losses import ProjectionBank
|
| 17 |
+
from kernels import install_graph_kernel
|
| 18 |
+
from heads_r3 import Heads
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class EvidenceHeads(nn.Module):
|
| 22 |
+
def __init__(self):
|
| 23 |
+
super().__init__()
|
| 24 |
+
self.counts=nn.Sequential(nn.Linear(256,256),nn.GELU(),nn.Linear(256,features.TRAITS*features.CLASSES))
|
| 25 |
+
self.fragment=nn.Sequential(nn.Linear(264,128),nn.GELU(),nn.LayerNorm(128))
|
| 26 |
+
self.meta=nn.Sequential(nn.Linear(17,128),nn.GELU(),nn.Linear(128,128))
|
| 27 |
+
self.intensity=nn.Linear(128,10)
|
| 28 |
+
self.fragment_key=nn.Linear(128,64);self.peak_key=nn.Linear(256,64)
|
| 29 |
+
self.fragment_score=nn.Sequential(nn.Linear(4,32),nn.GELU(),nn.Linear(32,1))
|
| 30 |
+
self.chemical_scale=nn.Parameter(torch.ones(()));self.fragment_scale=nn.Parameter(torch.ones(()))
|
| 31 |
+
nn.init.zeros_(self.counts[-1].weight);nn.init.zeros_(self.counts[-1].bias)
|
| 32 |
+
nn.init.zeros_(self.fragment_score[-1].weight);nn.init.zeros_(self.fragment_score[-1].bias)
|
| 33 |
+
|
| 34 |
+
def count_log_prob(self,q):
|
| 35 |
+
shape=(*q.shape[:-1],features.TRAITS,features.CLASSES)
|
| 36 |
+
return self.counts(q).float().reshape(shape).log_softmax(-1)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class R2Ranker(BidirectionalRanker):
|
| 40 |
+
def __init__(self,c,arm):
|
| 41 |
+
super().__init__(c);self.hierarchy=ProjectionBank();self.r2=EvidenceHeads();self.r3=Heads()
|
| 42 |
+
self.arm=arm;self.feature_store=None;self.layout_checked=set();install_graph_kernel(self)
|
| 43 |
+
|
| 44 |
+
def install_features(self,path=None):
|
| 45 |
+
self.feature_store=features.FeatureStore(path or PREP/'assets.sqlite')
|
| 46 |
+
|
| 47 |
+
def feature(self,mol):
|
| 48 |
+
if self.feature_store is None:raise RuntimeError('R2 offline features missing')
|
| 49 |
+
result=self.feature_store.get(mol.smiles)
|
| 50 |
+
if mol.smiles not in self.layout_checked:
|
| 51 |
+
if result['layout']!=features.layout(mol.mol) or result['atoms']!=len(mol.atom_features):
|
| 52 |
+
raise RuntimeError('Static fragment / trainable graph atom layout mismatch')
|
| 53 |
+
self.layout_checked.add(mol.smiles)
|
| 54 |
+
return result
|
| 55 |
+
|
| 56 |
+
def formula_batch(self,qs,queries,tokens,return_context=False):
|
| 57 |
+
values=original_formula_forward(self.formula_v07,qs,queries,tokens)
|
| 58 |
+
return (values,[None]*len(queries)) if return_context else values
|
| 59 |
+
|
| 60 |
+
def chemical_scores(self,q,assets):
|
| 61 |
+
counts=torch.as_tensor(np.stack([a['counts'] for a in assets]),device=q.device,dtype=torch.long)
|
| 62 |
+
logp=self.r2.count_log_prob(q.float())
|
| 63 |
+
selected=logp[torch.arange(features.TRAITS,device=q.device)[None,:],counts].mean(-1)
|
| 64 |
+
# The same log-softmax operation makes zero-initialization exactly zero.
|
| 65 |
+
uniform=torch.zeros_like(logp).log_softmax(-1)[0,0]
|
| 66 |
+
return self.r2.chemical_scale*(selected-uniform)
|
| 67 |
+
|
| 68 |
+
def fragment_scores(self,peaks,query,mols,atoms,assets):
|
| 69 |
+
device=peaks.device;n=len(mols);zero=peaks.float().sum()*0.
|
| 70 |
+
# No candidate-wise softmax across the pool: safe exact tiling for
|
| 71 |
+
# CASMI's >30k pools, not a 256-candidate truncation.
|
| 72 |
+
if n>128:
|
| 73 |
+
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)]
|
| 74 |
+
return tuple(torch.cat([p[k] for p in pieces]) for k in range(3))
|
| 75 |
+
offsets=features.ion_offsets(query.adduct)
|
| 76 |
+
if offsets[0] is None:
|
| 77 |
+
return zero.expand(n),zero.expand(n),torch.zeros(n,device=device,dtype=torch.bool)
|
| 78 |
+
mz_np,y_np=features.spectrum(query);mz=torch.as_tensor(mz_np,device=device);y=torch.as_tensor(y_np,device=device)
|
| 79 |
+
if len(mz)!=len(peaks):raise RuntimeError('R2 peak token alignment mismatch')
|
| 80 |
+
representations=[]
|
| 81 |
+
for atom,a in zip(atoms,assets):
|
| 82 |
+
members=torch.as_tensor(a['members'],device=device,dtype=torch.float32)
|
| 83 |
+
boundary=torch.as_tensor(a['boundary'],device=device,dtype=torch.float32)
|
| 84 |
+
representations.append(torch.cat((members@atom.float(),boundary),-1))
|
| 85 |
+
h=self.r2.fragment(torch.stack(representations))
|
| 86 |
+
meta=torch.as_tensor(metadata(query),device=device,dtype=torch.float32)
|
| 87 |
+
logits=self.r2.intensity(h+self.r2.meta(meta)[None,None,:]).float().reshape(n,features.K,5,2)
|
| 88 |
+
masses=torch.as_tensor(np.stack([a['masses'] for a in assets]),device=device)
|
| 89 |
+
hydrogens=torch.as_tensor(np.stack([a['hydrogens'] for a in assets]),device=device)
|
| 90 |
+
valid=torch.as_tensor(np.stack([a['valid'] for a in assets]),device=device,dtype=torch.bool)
|
| 91 |
+
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])
|
| 92 |
+
hypotheses=masses[:,:,None,None]+shifts[None,None,:,None]*features.H+adduct[None,None,None,:]
|
| 93 |
+
mask=valid[:,:,None,None]&(hydrogens[:,:,None,None]+shifts[None,None,:,None]>=0)
|
| 94 |
+
mask=mask.expand(-1,-1,-1,2)&hypotheses.gt(0)
|
| 95 |
+
if offsets[1] is None:
|
| 96 |
+
template=torch.tensor([True,False],device=device);mask=mask&template[None,None,None,:]
|
| 97 |
+
usable=mask.flatten(1).any(-1)
|
| 98 |
+
# Avoid all -inf softmax rows without inventing a supported fragment.
|
| 99 |
+
masked=logits.masked_fill(~mask,-1e9)
|
| 100 |
+
probability=masked.flatten(1).softmax(-1).reshape_as(masked)*mask
|
| 101 |
+
flat=hypotheses.flatten(1).contiguous();pp=probability.flatten(1)
|
| 102 |
+
right=torch.searchsorted(mz,flat).clamp(max=len(mz)-1);left=(right-1).clamp(min=0)
|
| 103 |
+
index=torch.where((mz[right]-flat).abs()<(mz[left]-flat).abs(),right,left)
|
| 104 |
+
delta=(mz[index]-flat).abs();tolerance=torch.maximum(flat*20e-6,flat.new_full((),.02))
|
| 105 |
+
matched=(delta<=tolerance)&mask.flatten(1)
|
| 106 |
+
explained=pp*matched;predicted=pp.new_zeros((n,len(mz))).scatter_add(1,index,explained)
|
| 107 |
+
outside=(pp*(~matched)).sum(-1)
|
| 108 |
+
norm=(predicted.square().sum(-1)+outside.square()).clamp_min(1e-12).sqrt()
|
| 109 |
+
cosine=(predicted*y[None,:]).sum(-1)/(norm*y.norm().clamp_min(1e-12))
|
| 110 |
+
present=pp.new_zeros((n,len(mz))).scatter_add(1,index,matched.float()).gt(0)
|
| 111 |
+
coverage=(present*y[None,:]).sum(-1)/y.sum().clamp_min(1e-12)
|
| 112 |
+
key=F.normalize(self.r2.fragment_key(h).float(),dim=-1)
|
| 113 |
+
peak=F.normalize(self.r2.peak_key(peaks).float(),dim=-1)
|
| 114 |
+
alignment=(key[:,:,None,:].expand(-1,-1,10,-1).reshape(n,-1,64)*peak[index]).sum(-1)
|
| 115 |
+
matched_alignment=(alignment*explained).sum(-1)
|
| 116 |
+
diagnostics=torch.stack((cosine,coverage,matched_alignment,1.-outside),-1)
|
| 117 |
+
correction=self.r2.fragment_scale*self.r2.fragment_score(diagnostics).float().squeeze(-1)*usable
|
| 118 |
+
spec_loss=(1.-cosine)*usable
|
| 119 |
+
return correction,spec_loss,usable
|
| 120 |
+
|
| 121 |
+
def score_encoded(self,q,peaks,query,mols,atoms,zm,formula_scores,context=None,return_aux=False):
|
| 122 |
+
conditional,joint,relation=self.conditioned(q,query,[m.formula for m in mols],zm,formula_scores)
|
| 123 |
+
local=self.local_weight*self.local_scores(peaks,atoms) if self.cfg.model.local_match else torch.zeros_like(joint)
|
| 124 |
+
base=joint+local;direct=conditional+local
|
| 125 |
+
diagnostic={}
|
| 126 |
+
collecting=self.training and getattr(self,'collect_score_diagnostics',False)
|
| 127 |
+
if collecting:
|
| 128 |
+
diagnostic['formula_prior_abs']=(joint-conditional).detach().float().abs().mean()
|
| 129 |
+
diagnostic['parent_structural_std']=direct.detach().float().std(unbiased=False)
|
| 130 |
+
aux=None
|
| 131 |
+
if self.arm in C['arms']:
|
| 132 |
+
assets=[self.feature(m) for m in mols]
|
| 133 |
+
chemistry=self.chemical_scores(q,assets)
|
| 134 |
+
base=base+chemistry;direct=direct+chemistry
|
| 135 |
+
if self.arm in C['arms']:
|
| 136 |
+
correction,spec_loss,usable=self.fragment_scores(peaks,query,mols,atoms,assets)
|
| 137 |
+
base=base+correction;direct=direct+correction
|
| 138 |
+
aux=(spec_loss,usable)
|
| 139 |
+
if self.arm in ('R3H','R3M'):
|
| 140 |
+
topology=self.r3.topology_scores(q,query,atoms,assets)
|
| 141 |
+
base=base+topology;direct=direct+topology
|
| 142 |
+
if collecting:diagnostic['topology_abs']=topology.detach().float().abs().mean()
|
| 143 |
+
if self.arm in ('R3D','R3M'):
|
| 144 |
+
difference=self.r3.difference_scores(q,query,mols,assets)
|
| 145 |
+
base=base+difference;direct=direct+difference
|
| 146 |
+
if collecting:diagnostic['difference_abs']=difference.detach().float().abs().mean()
|
| 147 |
+
if self.arm in ('R3F','R3M'):
|
| 148 |
+
calibrated=self.r3.calibrate(base,direct,[m.formula for m in mols])
|
| 149 |
+
if collecting:diagnostic['formula_calibration_abs']=(calibrated-base).detach().float().abs().mean()
|
| 150 |
+
base=calibrated
|
| 151 |
+
if collecting:
|
| 152 |
+
diagnostic['final_score_std']=base.detach().float().std(unbiased=False)
|
| 153 |
+
self.score_diagnostics.append(diagnostic)
|
| 154 |
+
result=(base,direct,relation)
|
| 155 |
+
return (*result,aux) if return_aux else result
|
| 156 |
+
|
| 157 |
+
def encode_batch(self,queries,extras=()):
|
| 158 |
+
tokens,qs,metas=self.spectrum.forward_batch(queries)
|
| 159 |
+
key=lambda m:(m.identity,m.smiles)
|
| 160 |
+
lookup={key(m):m for q in queries for m in q.candidates};lookup.update({key(m):m for m in extras})
|
| 161 |
+
keys=sorted(lookup);positions={k:i for i,k in enumerate(keys)}
|
| 162 |
+
u,atoms,zm=self.encode_molecules([lookup[k] for k in keys])
|
| 163 |
+
zq=F.normalize(self.query_projection(qs).float(),dim=-1)
|
| 164 |
+
fs=self.formula_batch(qs,queries,tokens);encs=[]
|
| 165 |
+
for i,q in enumerate(queries):
|
| 166 |
+
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]
|
| 167 |
+
base,direct,context,aux=self.score_encoded(qs[i],tokens[i],q,q.candidates,aa,zm[index],fs[i],return_aux=True)
|
| 168 |
+
whole=torch.as_tensor(np.stack([m.whole for m in q.candidates]),device=self.device)
|
| 169 |
+
anchors=torch.as_tensor(np.stack([m.anchors for m in q.candidates]),device=self.device)
|
| 170 |
+
enc=Encoded(q,tokens[i].float(),qs[i].float(),metas[i].float(),u[index].float(),zq[i],zm[index],
|
| 171 |
+
[a.float() for a in aa],whole,anchors,fs[i],base,direct)
|
| 172 |
+
enc.conditional_context_q=context;enc.r2_spectrum=aux;encs.append(enc)
|
| 173 |
+
extra_index=torch.tensor([positions[key(m)] for m in extras],device=self.device,dtype=torch.long)
|
| 174 |
+
return encs,zm[extra_index]
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def make_model_optimizer(arm,checkpoint_path=None):
|
| 178 |
+
state=parent_state() if checkpoint_path is None else torch.load(checkpoint_path,map_location='cpu',weights_only=False)
|
| 179 |
+
torch.manual_seed(C['seed']);model=R2Ranker(LEGACY.C,arm)
|
| 180 |
+
if checkpoint_path is not None and state.get('architecture')!='CEIR_R3':raise RuntimeError('Wrong resume architecture')
|
| 181 |
+
result=model.load_state_dict(state['model'],strict=checkpoint_path is not None)
|
| 182 |
+
if result.unexpected_keys or any(not k.startswith('r3.') for k in result.missing_keys):raise RuntimeError('Parent state keys differ '+str(result))
|
| 183 |
+
if checkpoint_path is None:
|
| 184 |
+
for k,v in state['model'].items():
|
| 185 |
+
if not torch.equal(model.state_dict()[k],v):raise RuntimeError('Old parameter changed '+k)
|
| 186 |
+
old=[p for n,p in model.named_parameters() if not n.startswith(('r2.','r3.'))]
|
| 187 |
+
evidence=[p for n,p in model.named_parameters() if n.startswith('r2.')]
|
| 188 |
+
new=[p for n,p in model.named_parameters() if n.startswith('r3.')]
|
| 189 |
+
source=parent_state() if checkpoint_path is not None else state
|
| 190 |
+
if [len(old),len(evidence)]!=[len(g['params']) for g in source['optimizer']['param_groups']]:raise RuntimeError('Old optimizer parameter ordering/count mismatch')
|
| 191 |
+
original_lr=float(source['optimizer']['param_groups'][0]['lr']);model.to(LEGACY.C['device'])
|
| 192 |
+
opt=torch.optim.AdamW(old,lr=original_lr,weight_decay=LEGACY.C['weight_decay'])
|
| 193 |
+
opt.add_param_group(dict(params=evidence,lr=float(source['optimizer']['param_groups'][1]['lr'])))
|
| 194 |
+
if checkpoint_path is None:
|
| 195 |
+
opt.load_state_dict(state['optimizer']);opt.add_param_group(dict(params=new,lr=C['new_head_lr']))
|
| 196 |
+
else:
|
| 197 |
+
opt.add_param_group(dict(params=new,lr=C['new_head_lr']));opt.load_state_dict(state['optimizer'])
|
| 198 |
+
for p,s in opt.state.items():
|
| 199 |
+
for k,v in s.items():
|
| 200 |
+
if torch.is_tensor(v) and k!='step':s[k]=v.to(p.device)
|
| 201 |
+
progress=dict(state['progress']);progress.setdefault('new_updates',progress['update']-C['source_update'])
|
| 202 |
+
if checkpoint_path is None:
|
| 203 |
+
progress.update(new_updates=0,r2_validated=[],r2_exposures={})
|
| 204 |
+
model.install_features();restore_rng(state)
|
| 205 |
+
return model,opt,progress,original_lr
|
code/snapshot/root/code/ceir_r3_20261110/objectives_r2.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Exact C03 active objectives, plus qualified chemistry / spectrum supervision."""
|
| 2 |
+
from collections import Counter
|
| 3 |
+
import time
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
from torch.nn import functional as F
|
| 7 |
+
from torch.utils.checkpoint import checkpoint as recompute
|
| 8 |
+
from runtime_r2 import *
|
| 9 |
+
from kernels import grouped_contrastive,formula_objective
|
| 10 |
+
from losses import ms_ms_supcon,molecule_molecule_two_view
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def molecular_views(model,mols,probability):
|
| 14 |
+
# Reinstate the dropout hook during activation recomputation. The original
|
| 15 |
+
# implementation removed it before backward; fix identically in all arms.
|
| 16 |
+
def one(dummy):
|
| 17 |
+
threshold=model.activation_checkpoint_atom_threshold
|
| 18 |
+
model.activation_checkpoint_atom_threshold=10**12
|
| 19 |
+
handle=model.graph.atom.register_forward_hook(lambda module,inputs,output:F.dropout(output,p=probability,training=True))
|
| 20 |
+
try:
|
| 21 |
+
with amp():return model.encode_molecules(mols)[0].float()
|
| 22 |
+
finally:handle.remove();model.activation_checkpoint_atom_threshold=threshold
|
| 23 |
+
return (recompute(one,model.graph.atom.weight,use_reentrant=False,preserve_rng_state=True),
|
| 24 |
+
recompute(one,model.graph.atom.weight,use_reentrant=False,preserve_rng_state=True))
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def auxiliary_loss(model,q,mols,rows,spec,step):
|
| 28 |
+
weights=spec['loss']['auxiliary']
|
| 29 |
+
if any(v for k,v in weights.items() if k not in ('ms_fine','mol_fine')):
|
| 30 |
+
raise RuntimeError('This release matches C03 fine-only auxiliaries; other arms require a separate release')
|
| 31 |
+
ids=[r['identity'] for r in rows];rids=[r['record_id'] for r in rows];head=model.hierarchy
|
| 32 |
+
v1,v2=molecular_views(model,mols,spec['views']['molecule']['dropout'])
|
| 33 |
+
temperature=spec['loss']['temperature']['identity'];ramp=min(1.,(step+1)/spec['loss']['auxiliary_ramp_steps'])
|
| 34 |
+
ms=ms_ms_supcon(head('ms_identity',q),ids,rids,temperature)
|
| 35 |
+
mol=molecule_molecule_two_view(head('mol_identity',v1),head('mol_identity',v2),[m.identity for m in mols],temperature)
|
| 36 |
+
total=ramp*(weights['ms_fine']*ms.loss+weights['mol_fine']*mol.loss)
|
| 37 |
+
# The original zero-weight coarse graphs produced zero (not None) grads.
|
| 38 |
+
# Preserve AdamW decay/moment semantics for those registered unused heads.
|
| 39 |
+
for name in ('ms_formula','mol_formula','ms_mass','mol_mass'):
|
| 40 |
+
total=total+sum(p.sum()*0. for p in head.heads[name].parameters())
|
| 41 |
+
out=dict(ms_fine_raw=ms.loss.detach(),mol_fine_raw=mol.loss.detach(),auxiliary_total=total.detach(),auxiliary_ramp=ramp,
|
| 42 |
+
molecule_view_mean_abs_difference=(v1.detach()-v2.detach()).abs().mean())
|
| 43 |
+
for name,item in [('ms_fine',ms),('mol_fine',mol)]:
|
| 44 |
+
for k,v in item.diagnostics.items():out[name+'_'+k]=v.detach() if torch.is_tensor(v) else v
|
| 45 |
+
return total,out
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def chemical_loss(model,q,rows):
|
| 49 |
+
if model.arm not in C['arms']:return q.sum()*0.
|
| 50 |
+
counts=torch.as_tensor(np.stack([r['chemical_counts'] for r in rows]),device=q.device,dtype=torch.long)
|
| 51 |
+
logp=model.r2.count_log_prob(q)
|
| 52 |
+
losses=-logp.gather(-1,counts[:,:,None]).squeeze(-1).mean(-1)
|
| 53 |
+
ids=[r['identity'] for r in rows];occurrences=Counter(ids)
|
| 54 |
+
w=q.new_tensor([1/occurrences[k]/len(occurrences) for k in ids])
|
| 55 |
+
return (losses*w).sum()
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def train_step(model,opt,batch,update,apply_update=True):
|
| 59 |
+
model.collect_score_diagnostics=True;model.score_diagnostics=[]
|
| 60 |
+
started=time.monotonic();rows=batch['rows'];queries=[r['query'] for r in rows];ids=[r['identity'] for r in rows]
|
| 61 |
+
reps={}
|
| 62 |
+
for r in rows:
|
| 63 |
+
if r['identity'] not in reps or r['ref'].smiles<reps[r['identity']].smiles:reps[r['identity']]=r['ref']
|
| 64 |
+
columns=sorted(reps);mols=[reps[k] for k in columns];w=LEGACY.C['loss_weights'];opt.zero_grad(set_to_none=True)
|
| 65 |
+
sc=LEGACY.C['spectrum_chunk'];gc=LEGACY.C['graph_chunk']
|
| 66 |
+
with torch.no_grad(),amp():
|
| 67 |
+
qc=torch.cat([model.spectrum.forward_batch(queries[a:a+sc])[1] for a in range(0,len(rows),sc)])
|
| 68 |
+
mc=torch.cat([model.encode_molecules(mols[a:a+gc])[0] for a in range(0,len(mols),gc)])
|
| 69 |
+
qc=qc.float().detach().requires_grad_();mc=mc.float().detach().requires_grad_()
|
| 70 |
+
with amp():
|
| 71 |
+
zq=F.normalize(model.query_projection(qc).float(),dim=-1);zm=F.normalize(model.mol_projection(mc).float(),dim=-1)
|
| 72 |
+
f,b=grouped_contrastive(zq@zm.T/LEGACY.C['contrastive_temperature'],ids,columns)
|
| 73 |
+
base=w['inbatch_ms_to_mol']*f+w['inbatch_mol_to_ms']*b
|
| 74 |
+
# Match the parent's FP32 auxiliary invocation, not R1's outer autocast.
|
| 75 |
+
auxiliary,details=auxiliary_loss(model,qc,mols,rows,SPEC,update)
|
| 76 |
+
chem=chemical_loss(model,qc,rows)
|
| 77 |
+
ramp=min(1.,(update-C['source_update']+1)/C['lr_ramp_updates'])
|
| 78 |
+
# A3 auxiliaries are already trained: retain their full weights, not a
|
| 79 |
+
# second accidental warm-up. New heads use final pool CE, not duplicate CE.
|
| 80 |
+
cw=C['chem_weight'];sw=C['spectrum_weight']
|
| 81 |
+
(base+auxiliary+cw*chem).backward();dq=qc.grad.detach();dm=mc.grad.detach()
|
| 82 |
+
metrics=dict(inbatch_ms_to_mol=f.detach(),inbatch_mol_to_ms=b.detach(),formula_loss=0.,formula_ce=0.,formula_gap=0.,element_ce=0.,formula_correct=0.,
|
| 83 |
+
chemical_loss=chem.detach(),chemical_weight=cw,spectrum_weight=sw)
|
| 84 |
+
valid=sum(r['mass_ok'] and len(r['formulas'])>1 and r['formula'] in r['formulas'] for r in rows)
|
| 85 |
+
for a in range(0,len(rows),sc):
|
| 86 |
+
block=rows[a:a+sc]
|
| 87 |
+
with amp():
|
| 88 |
+
tokens,q,_=model.spectrum.forward_batch([r['query'] for r in block])
|
| 89 |
+
lf,d=formula_objective(model,q,tokens,block,valid,len(rows))
|
| 90 |
+
loss=(q*dq[a:a+len(block)]).sum()+w['formula']*lf
|
| 91 |
+
loss.backward();metrics['formula_loss']+=lf.detach()
|
| 92 |
+
for k in ('formula_ce','formula_gap','element_ce','formula_correct'):metrics[k]+=d[k]
|
| 93 |
+
for a in range(0,len(mols),gc):
|
| 94 |
+
with amp():u=model.encode_molecules(mols[a:a+gc])[0];surrogate=(u*dm[a:a+len(u)]).sum()
|
| 95 |
+
surrogate.backward()
|
| 96 |
+
pools=[p for r in rows for p in r['pools']];counts=Counter(p['kind'] for p in pools)
|
| 97 |
+
pm={k:qc.new_zeros(()) for k in ('odata','mass','formula')};spec_total=qc.new_zeros(())
|
| 98 |
+
supervised={p['record_id'] for p in pools if p['spectrum_eligible']};seen=set();used=0
|
| 99 |
+
for a in range(0,len(pools),LEGACY.C['pool_micro_views']):
|
| 100 |
+
block=pools[a:a+LEGACY.C['pool_micro_views']]
|
| 101 |
+
with amp():
|
| 102 |
+
encs,_=model.encode_batch([p['query'] for p in block]);loss=encs[0].q.sum()*0.
|
| 103 |
+
for p,enc in zip(block,encs):
|
| 104 |
+
ce=enc.base.float().logsumexp(0)-enc.base[p['positive_index']].float();kind=p['kind']
|
| 105 |
+
pm[kind]+=ce.detach()/counts[kind]
|
| 106 |
+
loss+=w[{'odata':'odata_pool','mass':'msg_mass_pool','formula':'msg_formula_pool'}[kind]]*ce/counts[kind]
|
| 107 |
+
if p['spectrum_eligible'] and p['record_id'] not in seen:
|
| 108 |
+
if enc.r2_spectrum is None:raise RuntimeError('Qualified spectrum has no fragment predictions')
|
| 109 |
+
spec,usable=enc.r2_spectrum
|
| 110 |
+
if not bool(usable[p['positive_index']]):raise RuntimeError('CPU / GPU fragment eligibility disagrees')
|
| 111 |
+
sl=spec[p['positive_index']]/max(1,len(supervised));loss+=sw*sl;spec_total+=sl.detach()
|
| 112 |
+
seen.add(p['record_id']);used+=1
|
| 113 |
+
loss.backward()
|
| 114 |
+
total=base.detach()+auxiliary.detach()+cw*chem.detach()+sw*spec_total+w['formula']*metrics['formula_loss']
|
| 115 |
+
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
|
| 116 |
+
metrics.update(details);metrics.update(spectrum_loss=spec_total,loss=total)
|
| 117 |
+
if not torch.isfinite(total):raise RuntimeError('Nonfinite R2 objective')
|
| 118 |
+
for name,parameters in [('backbone',[p for n,p in model.named_parameters() if not n.startswith(('r2.','r3.'))]),
|
| 119 |
+
('chemical',model.r2.counts.parameters()),('fragment',[p for n,p in model.r2.named_parameters() if not n.startswith('counts.') and n!='chemical_scale']),
|
| 120 |
+
('r3',model.r3.parameters())]:
|
| 121 |
+
gs=[p.grad.detach().float().square().sum() for p in parameters if p.grad is not None]
|
| 122 |
+
metrics[name+'_gradient_norm']=torch.stack(gs).sum().sqrt() if gs else total*0.
|
| 123 |
+
norm=torch.nn.utils.clip_grad_norm_(model.parameters(),LEGACY.C['gradient_clip'],error_if_nonfinite=True)
|
| 124 |
+
metrics['gradient_norm']=norm.detach()
|
| 125 |
+
for name in ('formula_prior_abs','parent_structural_std','topology_abs','difference_abs','formula_calibration_abs','final_score_std'):
|
| 126 |
+
values=[r[name] for r in model.score_diagnostics if name in r]
|
| 127 |
+
metrics['score_'+name]=torch.stack(values).mean() if values else total*0.
|
| 128 |
+
metrics['formula_calibration_alpha']=.5*model.r3.formula_alpha.detach().tanh()
|
| 129 |
+
model.collect_score_diagnostics=False;model.score_diagnostics=[]
|
| 130 |
+
if apply_update:opt.step()
|
| 131 |
+
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()
|
| 132 |
+
result=dict(zip(metrics,packed));result.update(queries=len(rows),unique_connectivity=len(columns),formula_valid=valid,
|
| 133 |
+
pool_valid=dict(counts),spectrum_valid=used,chemical_valid=len(rows) if cw else 0,
|
| 134 |
+
source_counts=dict(Counter(r['source'] for r in rows)),negative_draws=sum(p['negative_draws'] for p in pools),
|
| 135 |
+
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}),
|
| 136 |
+
molecular_encoder_views=2,zero_weight_coarse_auxiliaries='not_computed',data_seconds=batch['data_seconds'],
|
| 137 |
+
step_compute_seconds=time.monotonic()-started,peak_allocated_mib=torch.cuda.max_memory_allocated()/2**20)
|
| 138 |
+
return result
|
code/snapshot/root/code/ceir_r3_20261110/pipeline.supervisor.conf
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[program:specpartition-r3-pipeline-20261110]
|
| 2 |
+
directory=/root/xj/SpecPartition-MS/code/ceir_r3_20261110
|
| 3 |
+
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
|
| 4 |
+
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"
|
| 5 |
+
autostart=false
|
| 6 |
+
autorestart=false
|
| 7 |
+
startsecs=2
|
| 8 |
+
stopasgroup=true
|
| 9 |
+
killasgroup=true
|
| 10 |
+
stdout_logfile=/dev/stdout
|
| 11 |
+
stdout_logfile_maxbytes=0
|
| 12 |
+
redirect_stderr=true
|
code/snapshot/root/code/ceir_r3_20261110/pipeline_r3.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Finite supervised execution: all arms +3000, Validation, fixed Test, MCES."""
|
| 2 |
+
from collections import deque
|
| 3 |
+
from runtime_r2 import *
|
| 4 |
+
PYTHON='/workspace/xj/SpecPartition-MS/.venv/bin/python'
|
| 5 |
+
MCES='/root/xj/SpecPartition-MS/evaluations/mces_all_20261106/.venv/bin/python'
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def launch(label,args,python=PYTHON):
|
| 9 |
+
folder=OUT/'service_logs';folder.mkdir(parents=True,exist_ok=True)
|
| 10 |
+
with (folder/(label+'.log')).open('a') as f:
|
| 11 |
+
process=subprocess.Popen([python,'-u',*map(str,args)],cwd=HERE,stdout=f,stderr=subprocess.STDOUT,
|
| 12 |
+
env=dict(os.environ,PROC_NAME='specpartition-r3-'+label+'-20261110',OMP_NUM_THREADS='1',OPENBLAS_NUM_THREADS='1',MKL_NUM_THREADS='1'))
|
| 13 |
+
log(OUT/'PIPELINE_EVENTS.jsonl',dict(event='child_started',label=label,pid=process.pid,args=list(map(str,args)),unix_time=time.time()))
|
| 14 |
+
return process
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def checked(label,args,python=PYTHON):
|
| 18 |
+
p=launch(label,args,python)
|
| 19 |
+
while p.poll() is None:time.sleep(3)
|
| 20 |
+
if p.returncode:raise RuntimeError(label+' failed; see service_logs; full checkpoints retained')
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def parallel(jobs):
|
| 24 |
+
queue=deque(jobs);active=[]
|
| 25 |
+
while queue or active:
|
| 26 |
+
while queue and len(active)<2:
|
| 27 |
+
label,args=queue.popleft();active.append((label,args,launch(label,args),0))
|
| 28 |
+
rest=[]
|
| 29 |
+
for label,args,p,retries in active:
|
| 30 |
+
if p.poll() is None:rest.append((label,args,p,retries))
|
| 31 |
+
elif p.returncode:
|
| 32 |
+
if retries>=2:raise RuntimeError('Repeated failure '+label)
|
| 33 |
+
time.sleep(5);rest.append((label,args,launch(label,args),retries+1))
|
| 34 |
+
active=rest
|
| 35 |
+
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()))
|
| 36 |
+
if active:time.sleep(5)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def run():
|
| 40 |
+
OUT.mkdir(parents=True,exist_ok=True);lock=(OUT/'pipeline.lock').open('a+');fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
|
| 41 |
+
test_path=Path(C['evaluation_output'])/'test';test_path.mkdir(parents=True,exist_ok=True)
|
| 42 |
+
if not (OUT/'test').exists():(OUT/'test').symlink_to(test_path,target_is_directory=True)
|
| 43 |
+
if (OUT/'test').resolve()!=test_path.resolve():raise RuntimeError('Unexpected Test output location')
|
| 44 |
+
if (OUT/'ALL_RESULTS.json').exists():return
|
| 45 |
+
while not (PREP/'DATA_ACCEPTANCE.json').exists():
|
| 46 |
+
if (PREP/'failure.json').exists():raise RuntimeError('Preparation failed')
|
| 47 |
+
save(OUT/'PIPELINE_STATUS.json',dict(phase='waiting_for_preparation',unix_time=time.time()));time.sleep(5)
|
| 48 |
+
if not (PREP/'INDEPENDENT_LEDGER_AUDIT.json').exists():checked('independent-data-audit',[HERE/'audit_r3.py'])
|
| 49 |
+
if not (OUT/'TRAIN_READY.json').exists():checked('GPU-acceptance',[HERE/'acceptance_r3.py'])
|
| 50 |
+
if json.loads((OUT/'TRAIN_READY.json').read_text())['binding']!=binding():raise RuntimeError('Acceptance binding changed')
|
| 51 |
+
parallel([(a+'-train',[HERE/'train_r2.py','--arm',a]) for a in C['arms']])
|
| 52 |
+
for a in C['arms']:
|
| 53 |
+
directory=run_dir(a)/'validation_006000'
|
| 54 |
+
if not (directory/'MCES.json').exists():checked(a+'-Validation-MCES',[HERE/'mces_r2.py','--directory',directory],MCES)
|
| 55 |
+
checked('Validation-selection',[HERE/'analyze_r3.py'])
|
| 56 |
+
checked('Test-features',[HERE/'test_r3.py','--prepare'])
|
| 57 |
+
parallel([(a+'-'+d,[HERE/'test_r3.py','--name',a+'_006000','--dataset',d]) for a in C['arms'] for d in ('msg_test','casmi2022')])
|
| 58 |
+
for a in C['arms']:
|
| 59 |
+
for d in ('msg_test','casmi2022'):
|
| 60 |
+
directory=OUT/'test/inference'/(a+'_006000')/d
|
| 61 |
+
if not (directory/'MCES.json').exists():checked(a+'-'+d+'-MCES',[HERE/'test_mces_r2.py','--directory',directory],MCES)
|
| 62 |
+
checked('complete-comparison',[HERE/'analyze_r3.py','--test'])
|
| 63 |
+
checked('independent-all-scores-audit',[HERE/'final_audit_r3.py'])
|
| 64 |
+
save(OUT/'PIPELINE_STATUS.json',dict(phase='all_3000_step_experiments_and_evaluations_complete',unix_time=time.time()))
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
if __name__=='__main__':
|
| 68 |
+
try:run()
|
| 69 |
+
except Exception:
|
| 70 |
+
import traceback
|
| 71 |
+
save(OUT/'PIPELINE_FAILURE.json',dict(traceback=traceback.format_exc(),unix_time=time.time()));raise
|
code/snapshot/root/code/ceir_r3_20261110/prepare.supervisor.conf
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[program:specpartition-r3-prepare-20261110]
|
| 2 |
+
directory=/root/xj/SpecPartition-MS/code/ceir_r3_20261110
|
| 3 |
+
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
|
| 4 |
+
environment=PROC_NAME="specpartition-r3-prepare-20261110",OMP_NUM_THREADS="1",MKL_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",PYTHONUNBUFFERED="1"
|
| 5 |
+
autostart=false
|
| 6 |
+
autorestart=false
|
| 7 |
+
startsecs=2
|
| 8 |
+
stopasgroup=true
|
| 9 |
+
killasgroup=true
|
| 10 |
+
stdout_logfile=/dev/stdout
|
| 11 |
+
stdout_logfile_maxbytes=0
|
| 12 |
+
redirect_stderr=true
|
code/snapshot/root/code/ceir_r3_20261110/prepare_r3.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Independent 3000-update ledger and compact read-only-parent feature overlay."""
|
| 2 |
+
from collections import Counter
|
| 3 |
+
from concurrent.futures import ProcessPoolExecutor
|
| 4 |
+
from functools import lru_cache
|
| 5 |
+
import multiprocessing
|
| 6 |
+
import random
|
| 7 |
+
import sqlite3
|
| 8 |
+
import time
|
| 9 |
+
import numpy as np
|
| 10 |
+
from rdkit import Chem
|
| 11 |
+
from runtime_r2 import *
|
| 12 |
+
import features_r2 as ft
|
| 13 |
+
from data09 import Reader
|
| 14 |
+
from prepare_ceir import entry_identity
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def db_open(path=None):
|
| 18 |
+
path=Path(path or PREP/'assets.sqlite');path.parent.mkdir(parents=True,exist_ok=True)
|
| 19 |
+
db=sqlite3.connect(path);db.execute('PRAGMA page_size=16384');db.execute('PRAGMA journal_mode=WAL')
|
| 20 |
+
db.execute('CREATE TABLE IF NOT EXISTS batches(mode TEXT,idx INTEGER,body BLOB,PRIMARY KEY(mode,idx))')
|
| 21 |
+
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')
|
| 22 |
+
db.execute('CREATE INDEX IF NOT EXISTS pending_r3 ON r3_features(feature_key) WHERE distance IS NULL')
|
| 23 |
+
return db
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def plans():
|
| 27 |
+
from sampling import epoch_plans,plan_hash
|
| 28 |
+
state=parent_state();progress=state['progress'];epoch=progress['epoch'];offset=progress['next_step'];out=[];audit=[]
|
| 29 |
+
while len(out)<C['manifest_updates']:
|
| 30 |
+
pp=epoch_plans(epoch,C['seed']);audit.append(dict(epoch=epoch,sha256=plan_hash(pp),start=offset))
|
| 31 |
+
out.extend(pp[offset:offset+C['manifest_updates']-len(out)]);epoch+=1;offset=0
|
| 32 |
+
return out,audit
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def planning():
|
| 36 |
+
if (PREP/'SAMPLING_READY.json').exists():return
|
| 37 |
+
db=db_open();reader=Reader();pp,epoch_audit=plans();stats=Counter()
|
| 38 |
+
@lru_cache(maxsize=160000)
|
| 39 |
+
def register(gh):
|
| 40 |
+
m=reader.molecule(gh)
|
| 41 |
+
if m.identity in reader.forbidden:raise RuntimeError('Heldout structure in training ledger')
|
| 42 |
+
db.execute('INSERT OR IGNORE INTO r3_features(feature_key,smiles) VALUES (?,?)',(ft.key(m.smiles),m.smiles))
|
| 43 |
+
return m.identity
|
| 44 |
+
@lru_cache(maxsize=160000)
|
| 45 |
+
def alias(s):
|
| 46 |
+
value=reader.assets.execute('SELECT graph_hash FROM smiles WHERE smiles=?',(s,)).fetchone()
|
| 47 |
+
if not value:raise RuntimeError('Missing offline graph')
|
| 48 |
+
return value[0]
|
| 49 |
+
def graph(e):
|
| 50 |
+
gh=e.get('graph_hash') or alias(e.get('canonical_smiles') or e.get('smiles'))
|
| 51 |
+
if register(gh)!=entry_identity(e):raise RuntimeError('Graph identity mismatch')
|
| 52 |
+
return gh
|
| 53 |
+
for index,(epoch,step,groups) in enumerate(pp):
|
| 54 |
+
if db.execute('SELECT 1 FROM batches WHERE idx=?',(index,)).fetchone():continue
|
| 55 |
+
rows=[]
|
| 56 |
+
for source,ids in groups.items():
|
| 57 |
+
for j,rid in enumerate(ids):
|
| 58 |
+
row=loads(reader.db.execute('SELECT body FROM samples WHERE record_id=?',(rid,)).fetchone()[0]);register(row['graph_hash'])
|
| 59 |
+
if row['identity'] in reader.forbidden:raise RuntimeError('Heldout training label')
|
| 60 |
+
seed=C['seed']+epoch*100000000+step*10000+j+(1000000 if source=='msg' else 0);rng=random.Random(seed)
|
| 61 |
+
kinds=('mass','formula') if row['source']=='MSG_Train' else (('odata',) if source=='odata' and j<16 else ())
|
| 62 |
+
forms=tuple(reader.official(row['target'],'mass')['formula_classes']) if row['source']=='MSG_Train' else tuple(row['view']['formulas'])
|
| 63 |
+
pools=[]
|
| 64 |
+
for kind in kinds:
|
| 65 |
+
if kind=='odata':
|
| 66 |
+
view=row['view'];pool=reader.pool(view['pool_path'],view['pool_sha256']);entries=pool['records']
|
| 67 |
+
allowed=pool['safe_mass_order'][view['mass_order_start']:view['mass_order_stop']]
|
| 68 |
+
else:
|
| 69 |
+
pool=reader.official(row['target'],kind);entries=pool['entries'];allowed=[i for i,e in enumerate(entries) if e['eligible_for_training']]
|
| 70 |
+
positives=[i for i in allowed if entry_identity(entries[i])==row['identity']];by_id={}
|
| 71 |
+
for i in allowed:
|
| 72 |
+
identity=entry_identity(entries[i])
|
| 73 |
+
if identity!=row['identity']:by_id.setdefault(identity,[]).append(i)
|
| 74 |
+
if not positives or not by_id:continue
|
| 75 |
+
rr=random.Random(seed) if kind=='odata' else rng;positive=rr.choice(positives)
|
| 76 |
+
budget=LEGACY.C['odata_negative_draws'] if kind=='odata' else LEGACY.C['msg_negative_draws']
|
| 77 |
+
identities=rr.sample(sorted(by_id),min(budget,len(by_id)));chosen=[rr.choice(by_id[k]) for k in identities]
|
| 78 |
+
selected=[positive,*chosen];gh=[graph(entries[i]) for i in selected]
|
| 79 |
+
fs=tuple(pool['formula_classes']) if kind!='odata' else tuple(sorted({entries[i]['formula'] for i in selected}))
|
| 80 |
+
pools.append(dict(kind=kind,graphs=gh,formulas=fs,negative_draws=len(chosen),unique_negative_key14=len(chosen),reference_injected=False))
|
| 81 |
+
rows.append(dict(rid=rid,ref=row['graph_hash'],formulas=forms,pools=pools));stats[row['source']]+=1
|
| 82 |
+
blob=ft.dumps(dict(epoch=epoch,step=step,rows=rows));db.execute('INSERT INTO batches VALUES (?,?,?)',('unique',index,blob));db.commit()
|
| 83 |
+
if index%10==0:
|
| 84 |
+
save(PREP/'status.json',dict(phase='training_ledger',completed=index+1,total=len(pp),unix_time=time.time()));disk_check()
|
| 85 |
+
hashes=[hashlib.sha256(b).hexdigest() for b, in db.execute('SELECT body FROM batches ORDER BY idx')]
|
| 86 |
+
if len(hashes)!=3000:raise RuntimeError('Incomplete 3000-step ledger')
|
| 87 |
+
save(PREP/'ledger_hashes.json',dict(unique=hashes))
|
| 88 |
+
save(PREP/'SAMPLING_READY.json',dict(complete=True,updates=3000,source_update=3000,target_update=6000,epochs=epoch_audit,
|
| 89 |
+
ledger_sha256=sha(PREP/'ledger_hashes.json'),candidate_pools_changed=False,source_counts_this_attempt=dict(stats)))
|
| 90 |
+
db.close()
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def add_validation():
|
| 94 |
+
marker=PREP/'VALIDATION_STRUCTURES_READY.json'
|
| 95 |
+
if marker.exists():return
|
| 96 |
+
db=db_open();source=readonly(LEGACY.PREP/'validation.sqlite');n=0
|
| 97 |
+
for b, in source.execute('SELECT body FROM graphs'):
|
| 98 |
+
m=loads(b);db.execute('INSERT OR IGNORE INTO r3_features(feature_key,smiles) VALUES (?,?)',(ft.key(m.smiles),m.smiles));n+=1
|
| 99 |
+
if n%10000==0:db.commit()
|
| 100 |
+
db.commit();db.close();save(marker,dict(complete=True,rows=n,labels_used_for_training=False))
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def distance_task(task):
|
| 104 |
+
key,smiles,need=task;mol=Chem.MolFromSmiles(smiles)
|
| 105 |
+
if mol is None:raise RuntimeError('Invalid pre-accepted graph')
|
| 106 |
+
dist=ft.distance_dumps(np.minimum(Chem.GetDistanceMatrix(mol),15).astype(np.uint8))
|
| 107 |
+
body=ft.dumps(ft.build(smiles)) if need else None
|
| 108 |
+
return key,body,hashlib.sha256(body).digest() if body else None,dist,hashlib.sha256(dist).digest()
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def build_features(path=None,test=False):
|
| 112 |
+
db=db_open(path);parents=[readonly(Path(C['r2_output'])/'prepared/assets.sqlite')]
|
| 113 |
+
if test:parents.append(readonly(Path(C['r2_output'])/'test/prepared/assets.sqlite'))
|
| 114 |
+
tables=['canonical_features' if d.execute("SELECT 1 FROM sqlite_master WHERE name='canonical_features'").fetchone() else 'molecules' for d in parents]
|
| 115 |
+
ctx=multiprocessing.get_context('spawn');count=0
|
| 116 |
+
with ProcessPoolExecutor(max_workers=C['prepare_workers'],mp_context=ctx) as executor:
|
| 117 |
+
while True:
|
| 118 |
+
pending=db.execute('SELECT feature_key,smiles FROM r3_features WHERE distance IS NULL ORDER BY feature_key LIMIT 1024').fetchall()
|
| 119 |
+
if not pending:break
|
| 120 |
+
tasks=[]
|
| 121 |
+
for k,s in pending:
|
| 122 |
+
exists=any(d.execute('SELECT 1 FROM '+t+' WHERE feature_key=? AND feature IS NOT NULL',(k,)).fetchone() for d,t in zip(parents,tables))
|
| 123 |
+
tasks.append((k,s,not exists))
|
| 124 |
+
for k,b,h,d,dh in executor.map(distance_task,tasks,chunksize=16):
|
| 125 |
+
db.execute('UPDATE r3_features SET feature=?,feature_sha=?,distance=?,distance_sha=? WHERE feature_key=?',(b,h,d,dh,k));count+=1
|
| 126 |
+
db.commit()
|
| 127 |
+
if count%8192==0:
|
| 128 |
+
save(Path(path).parent/'status.json' if path else PREP/'status.json',dict(phase='offline_incremental_topology',processed_this_attempt=count,unix_time=time.time()));disk_check()
|
| 129 |
+
total=db.execute('SELECT count(*) FROM r3_features').fetchone()[0];new=db.execute('SELECT count(*) FROM r3_features WHERE feature IS NOT NULL').fetchone()[0]
|
| 130 |
+
db.execute('PRAGMA wal_checkpoint(TRUNCATE)');db.close()
|
| 131 |
+
return dict(complete=True,features=total,new_fragment_descriptors=new,parent_caches_read_only=True)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def run():
|
| 135 |
+
OUT.mkdir(parents=True,exist_ok=True);disk_check();planning();add_validation();result=build_features()
|
| 136 |
+
save(PREP/'READY.json',dict(**result,sampling=json.loads((PREP/'SAMPLING_READY.json').read_text()),feature_version=C['feature_version']))
|
| 137 |
+
# Dataset re-verifies every sampled label/negative identity against the
|
| 138 |
+
# immutable heldout registry when it is read. Planning also checked all.
|
| 139 |
+
save(PREP/'DATA_ACCEPTANCE.json',dict(complete=True,all_training_graphs_checked_against_heldout_registry=True,
|
| 140 |
+
shared_ledger_all_five_arms=True,original_candidates_modified=False,ledger_hashes_sha256=sha(PREP/'ledger_hashes.json')))
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
if __name__=='__main__':
|
| 144 |
+
try:run()
|
| 145 |
+
except Exception:
|
| 146 |
+
import traceback
|
| 147 |
+
save(PREP/'failure.json',dict(traceback=traceback.format_exc(),unix_time=time.time()));raise
|
code/snapshot/root/code/ceir_r3_20261110/probe_r3.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Early real mixed-batch engineering probe; never grants training readiness."""
|
| 2 |
+
import sqlite3
|
| 3 |
+
from runtime_r2 import *
|
| 4 |
+
from prepare_r3 import db_open,build_features
|
| 5 |
+
from data09 import Reader
|
| 6 |
+
import features_r2 as ft
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def prepare():
|
| 10 |
+
source=readonly(PREP/'assets.sqlite');index=None;plan=None
|
| 11 |
+
for i,b in source.execute('SELECT idx,body FROM batches ORDER BY idx'):
|
| 12 |
+
candidate=ft.loads(b)
|
| 13 |
+
if len(candidate['rows'])==288:index=i;plan=candidate;break
|
| 14 |
+
if index is None:raise RuntimeError('No real mixed batch materialized yet')
|
| 15 |
+
path=PREP/'probe.sqlite';db=db_open(path);reader=Reader();graphs=set()
|
| 16 |
+
for row in plan['rows']:
|
| 17 |
+
graphs.add(row['ref'])
|
| 18 |
+
for p in row['pools']:graphs.update(p['graphs'])
|
| 19 |
+
for gh in graphs:
|
| 20 |
+
m=reader.molecule(gh)
|
| 21 |
+
if m.identity in reader.forbidden:raise RuntimeError('Heldout graph')
|
| 22 |
+
db.execute('INSERT OR IGNORE INTO r3_features(feature_key,smiles) VALUES (?,?)',(ft.key(m.smiles),m.smiles))
|
| 23 |
+
db.commit();db.close();build_features(path)
|
| 24 |
+
save(PREP/'PROBE_READY.json',dict(complete=True,index=index,graphs=len(graphs),formal_training_ready=False))
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
if __name__=='__main__':
|
| 28 |
+
prepare()
|
| 29 |
+
from acceptance_r3 import run
|
| 30 |
+
run(provisional=True)
|
code/snapshot/root/code/ceir_r3_20261110/runtime_r2.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Independent release and full-state continuation; old experiments are read-only."""
|
| 2 |
+
import contextlib
|
| 3 |
+
import fcntl
|
| 4 |
+
import hashlib
|
| 5 |
+
import json
|
| 6 |
+
import os
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
import random
|
| 9 |
+
import shutil
|
| 10 |
+
import subprocess
|
| 11 |
+
import sys
|
| 12 |
+
import time
|
| 13 |
+
|
| 14 |
+
os.environ.setdefault('CUBLAS_WORKSPACE_CONFIG',':4096:8')
|
| 15 |
+
|
| 16 |
+
HERE=Path(__file__).resolve().parent
|
| 17 |
+
C=json.loads((HERE/'config.json').read_text())
|
| 18 |
+
OUT=Path(C['output']);PREP=OUT/'prepared';ROOT=Path(C['root'])
|
| 19 |
+
sys.path.insert(0,C['source_r1'])
|
| 20 |
+
import runtime_ceir as OLD
|
| 21 |
+
LEGACY=OLD.LEGACY;SPEC=OLD.SPEC
|
| 22 |
+
LEGACY.C.update(spectrum_chunk=C['spectrum_chunk'],graph_chunk=C['graph_chunk'],local_chunk=C['local_chunk'],
|
| 23 |
+
pool_micro_views=C['pool_micro_views'],threads=1,workers=1,max_atoms_per_microbatch=C['max_atoms_per_microbatch'])
|
| 24 |
+
from runtime09 import readonly,save,sha
|
| 25 |
+
from data09 import loads
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def run_dir(arm):
|
| 29 |
+
if arm not in C['arms']:raise ValueError('Unknown R2 arm')
|
| 30 |
+
p=OUT/arm;p.mkdir(parents=True,exist_ok=True);return p
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def code_manifest():
|
| 34 |
+
return {p.name:sha(p) for p in sorted([*HERE.glob('*.py'),HERE/'config.json']) if not p.name.startswith('.')}
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def parent_state():
|
| 38 |
+
import torch
|
| 39 |
+
if sha(C['parent_checkpoint'])!=C['parent_sha256']:raise RuntimeError('Parent checkpoint hash changed')
|
| 40 |
+
state=torch.load(C['parent_checkpoint'],map_location='cpu',weights_only=False)
|
| 41 |
+
if state['progress']['update']!=C['source_update']:raise RuntimeError('Incorrect parent update')
|
| 42 |
+
if state['binding']['original_data']!=LEGACY.bind():raise RuntimeError('Original training data binding changed')
|
| 43 |
+
return state
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def binding():
|
| 47 |
+
ready=json.loads((PREP/'READY.json').read_text())
|
| 48 |
+
evaluation_code=Path('/root/xj/SpecPartition-MS/code/ceir_r1_test_comparison_20261110')
|
| 49 |
+
external={str(p):sha(p) for p in sorted(evaluation_code.glob('*.py'))}
|
| 50 |
+
external[str(Path(C['source_r1'])/'mces_ceir.py')]=sha(Path(C['source_r1'])/'mces_ceir.py')
|
| 51 |
+
external.update({str(p):sha(p) for p in Path(C['source_r2']).glob('*.py')})
|
| 52 |
+
return dict(code=code_manifest(),parent_sha256=C['parent_sha256'],prepared=ready,
|
| 53 |
+
original_data=LEGACY.bind(),feature_version=C['feature_version'],
|
| 54 |
+
dependency_sources=OLD.bind()['dependency_sources'],parent_formula_loss=LEGACY.C['r2'],
|
| 55 |
+
parent_loss_weights=LEGACY.C['loss_weights'],auxiliary=SPEC['loss']['auxiliary'],
|
| 56 |
+
data_acceptance=json.loads((PREP/'DATA_ACCEPTANCE.json').read_text()),external_evaluation_code=external)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def disk_check():
|
| 60 |
+
OUT.mkdir(parents=True,exist_ok=True)
|
| 61 |
+
if shutil.disk_usage(OUT).free<C['minimum_output_disk_gib']*2**30:
|
| 62 |
+
raise RuntimeError('R3 disk reserve insufficient; original files were not deleted')
|
| 63 |
+
evaluation=Path(C['evaluation_output']);evaluation.mkdir(parents=True,exist_ok=True)
|
| 64 |
+
if shutil.disk_usage(evaluation).free<.7*2**30:
|
| 65 |
+
raise RuntimeError('R3 evaluation filesystem reserve <0.7 GiB; all results retained')
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def evaluation_directory(arm,label):
|
| 69 |
+
destination=Path(C['evaluation_output'])/arm/label;destination.mkdir(parents=True,exist_ok=True)
|
| 70 |
+
link=run_dir(arm)/label
|
| 71 |
+
if not link.exists():link.symlink_to(destination,target_is_directory=True)
|
| 72 |
+
if link.resolve()!=destination.resolve():raise RuntimeError('Unexpected evaluation destination')
|
| 73 |
+
return link
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def log(path,row):
|
| 77 |
+
path=Path(path);path.parent.mkdir(parents=True,exist_ok=True)
|
| 78 |
+
with path.open('a') as f:f.write(json.dumps(row,ensure_ascii=False,allow_nan=False)+'\n')
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def setup_gpu():
|
| 82 |
+
import torch
|
| 83 |
+
torch.set_num_threads(1);torch.set_float32_matmul_precision('high');torch.use_deterministic_algorithms(True)
|
| 84 |
+
torch.cuda.set_per_process_memory_fraction(C['gpu_memory_fraction']);LEGACY.seed_all(C['seed'])
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
@contextlib.contextmanager
|
| 88 |
+
def gpu_work(directory,phase):
|
| 89 |
+
disk_check();locks=OUT/'gpu_slots';locks.mkdir(parents=True,exist_ok=True)
|
| 90 |
+
files=[(locks/f'{i}.lock').open('a+') for i in range(C['gpu_slots'])];held=None
|
| 91 |
+
try:
|
| 92 |
+
while held is None:
|
| 93 |
+
raw=subprocess.check_output(['nvidia-smi','--query-gpu=memory.free','--format=csv,noheader,nounits'],text=True)
|
| 94 |
+
if int(raw.strip().splitlines()[0])>=C['minimum_free_gpu_mib']:
|
| 95 |
+
for f in files:
|
| 96 |
+
try:fcntl.flock(f,fcntl.LOCK_EX|fcntl.LOCK_NB);held=f;break
|
| 97 |
+
except BlockingIOError:pass
|
| 98 |
+
if held is None:
|
| 99 |
+
save(Path(directory)/'resource_status.json',dict(phase=phase,state='waiting_for_R2_GPU_slot',unix_time=time.time()))
|
| 100 |
+
time.sleep(3)
|
| 101 |
+
yield
|
| 102 |
+
finally:
|
| 103 |
+
import torch
|
| 104 |
+
if torch.cuda.is_initialized():torch.cuda.empty_cache()
|
| 105 |
+
if held is not None:fcntl.flock(held,fcntl.LOCK_UN)
|
| 106 |
+
for f in files:f.close()
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def restore_rng(state):
|
| 110 |
+
import numpy as np
|
| 111 |
+
import torch
|
| 112 |
+
torch.set_rng_state(state['torch_rng']);torch.cuda.set_rng_state_all(state['cuda_rng'])
|
| 113 |
+
np.random.set_state(state['numpy_rng']);random.setstate(state['python_rng'])
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def checkpoint(path,model,opt,progress,bind):
|
| 117 |
+
import numpy as np
|
| 118 |
+
import torch
|
| 119 |
+
path=Path(path);temporary=path.with_suffix('.tmp')
|
| 120 |
+
torch.save(dict(architecture='CEIR_R3',model=model.state_dict(),optimizer=opt.state_dict(),progress=progress,
|
| 121 |
+
binding=bind,torch_rng=torch.get_rng_state(),cuda_rng=torch.cuda.get_rng_state_all(),
|
| 122 |
+
numpy_rng=np.random.get_state(),python_rng=random.getstate()),temporary)
|
| 123 |
+
temporary.replace(path)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def amp():
|
| 127 |
+
import torch
|
| 128 |
+
return torch.autocast('cuda',dtype=torch.bfloat16,enabled=LEGACY.C['bf16'])
|
code/snapshot/root/code/ceir_r3_20261110/test_mces_r2.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Post-hoc Test MCES, inherited fixed protocol and a private pair cache."""
|
| 2 |
+
import argparse
|
| 3 |
+
import fcntl
|
| 4 |
+
import importlib.util
|
| 5 |
+
import json
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import sys
|
| 8 |
+
import sqlite3
|
| 9 |
+
|
| 10 |
+
HERE=Path(__file__).resolve().parent;C=json.loads((HERE/'config.json').read_text());OUT=Path(C['output'])/'test'
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def run(directory):
|
| 14 |
+
own=OUT/'mces';own.mkdir(parents=True,exist_ok=True)
|
| 15 |
+
lock=(own/'compute.lock').open('a+');fcntl.flock(lock,fcntl.LOCK_EX)
|
| 16 |
+
path=Path('/root/xj/SpecPartition-MS/code/ceir_r1_test_comparison_20261110/mces.py')
|
| 17 |
+
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)
|
| 18 |
+
module.OUT=OUT;module.old.OUT=OUT/'mces' # workers may record solver state: never write the old run
|
| 19 |
+
previous=Path(C['r2_output'])/'test/mces/pairs.sqlite'
|
| 20 |
+
if not (own/'pairs.sqlite').exists() and previous.exists():
|
| 21 |
+
a=sqlite3.connect('file:'+str(previous)+'?mode=ro',uri=True);b=sqlite3.connect(own/'pairs.sqlite');a.backup(b);a.close();b.close()
|
| 22 |
+
db=module.initialize();module.compute(Path(directory),db);db.close()
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
if __name__=='__main__':
|
| 26 |
+
p=argparse.ArgumentParser();p.add_argument('--directory',required=True);a=p.parse_args();run(a.directory)
|
code/snapshot/root/code/ceir_r3_20261110/test_r3.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Full original pools, no Top256 restriction, no injected references."""
|
| 2 |
+
import argparse
|
| 3 |
+
from runtime_r2 import *
|
| 4 |
+
EVAL=OUT/'test'
|
| 5 |
+
EVAL_CODE=Path('/root/xj/SpecPartition-MS/code/ceir_r1_test_comparison_20261110')
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def prepare():
|
| 9 |
+
from prepare_r3 import db_open,build_features
|
| 10 |
+
if (EVAL/'prepared/READY.json').exists():return
|
| 11 |
+
import evaluation_runtime as original
|
| 12 |
+
path=EVAL/'prepared/assets.sqlite';db=db_open(path)
|
| 13 |
+
import features_r2 as ft
|
| 14 |
+
for dataset in ('msg_test','casmi2022'):
|
| 15 |
+
source=readonly(original.PREP/(dataset+'.sqlite'));n=0
|
| 16 |
+
for blob, in source.execute('SELECT body FROM graphs'):
|
| 17 |
+
m=loads(blob);db.execute('INSERT OR IGNORE INTO r3_features(feature_key,smiles) VALUES (?,?)',(ft.key(m.smiles),m.smiles));n+=1
|
| 18 |
+
if n%10000==0:db.commit()
|
| 19 |
+
db.commit();source.close()
|
| 20 |
+
db.close();result=build_features(path,test=True)
|
| 21 |
+
save(EVAL/'prepared/READY.json',dict(**result,labels_used_for_training=False,inputs={d:original.inputs(d) for d in ('msg_test','casmi2022')}))
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def freeze():
|
| 25 |
+
import evaluation_runtime as original
|
| 26 |
+
selected=json.loads((OUT/'SELECTION.json').read_text())
|
| 27 |
+
if not selected['complete'] or selected['test_used_for_selection']:raise RuntimeError('Unfrozen Validation decision')
|
| 28 |
+
models={}
|
| 29 |
+
for arm in C['arms']:
|
| 30 |
+
path=run_dir(arm)/'step_006000.pt';done=json.loads((run_dir(arm)/'COMPLETE.json').read_text())
|
| 31 |
+
if not done['complete'] or done['new_updates']!=3000:raise RuntimeError('Not all 3000 updates complete')
|
| 32 |
+
models[arm+'_006000']=dict(arm=arm,update=6000,checkpoint=str(path),sha256=sha(path),role='fixed_3000_new_update_endpoint')
|
| 33 |
+
frozen=dict(models=models,r3_binding=binding(),selection_sha256=sha(OUT/'SELECTION.json'),inputs={d:original.inputs(d) for d in ('msg_test','casmi2022')},
|
| 34 |
+
candidate_limit=None,truth_injection=False,Test_used_for_selection=False)
|
| 35 |
+
path=EVAL/'FROZEN.json'
|
| 36 |
+
if path.exists() and json.loads(path.read_text())!=frozen:raise RuntimeError('Frozen Test release changed')
|
| 37 |
+
save(path,frozen)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def make_model(name):
|
| 41 |
+
import torch
|
| 42 |
+
from model_r2_new import make_model_optimizer
|
| 43 |
+
frozen=json.loads((EVAL/'FROZEN.json').read_text());item=frozen['models'][name]
|
| 44 |
+
if sha(item['checkpoint'])!=item['sha256']:raise RuntimeError('Changed frozen checkpoint')
|
| 45 |
+
setup_gpu();model,opt,progress,_=make_model_optimizer(item['arm'],item['checkpoint']);del opt
|
| 46 |
+
if progress['update']!=6000:raise RuntimeError('Wrong endpoint')
|
| 47 |
+
model.graph_chunk=C['validation_graph_chunk'];model.local_chunk=C['validation_local_chunk']
|
| 48 |
+
model.install_features(EVAL/'prepared/assets.sqlite');model.eval();return model,item
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def run(name,dataset):
|
| 52 |
+
freeze();module=OLD.load_module('r3_fixed_Test_adapter',EVAL_CODE/'infer.py')
|
| 53 |
+
module.OUT=EVAL;module.make_model=make_model;module.gpu_slot=lambda d:gpu_work(d,'fixed_Test')
|
| 54 |
+
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'])
|
| 55 |
+
module.evaluate(name,dataset)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
if __name__=='__main__':
|
| 59 |
+
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()
|
| 60 |
+
prepare() if a.prepare else run(a.name,a.dataset)
|
code/snapshot/root/code/ceir_r3_20261110/tests_r3.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Small deterministic tests independent of private data / server imports."""
|
| 2 |
+
import unittest
|
| 3 |
+
from types import SimpleNamespace
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
from rdkit import Chem
|
| 7 |
+
from heads_r3 import Heads
|
| 8 |
+
import features_r2 as ft
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class Tests(unittest.TestCase):
|
| 12 |
+
def setUp(self):
|
| 13 |
+
torch.manual_seed(3);self.head=Heads();self.q=torch.randn(256)
|
| 14 |
+
self.query=SimpleNamespace(peaks=((50.1,20.),(76.2,80.),(120.3,100.)),precursor_mz=180.,adduct='[M+H]+')
|
| 15 |
+
self.assets=[];self.atoms=[];self.mols=[]
|
| 16 |
+
for s in ('CCOC(=O)c1ccccc1','CC(=O)Oc1ccccc1','CCN(CC)CC'):
|
| 17 |
+
f=ft.build(s);f['distance']=np.minimum(Chem.GetDistanceMatrix(Chem.MolFromSmiles(s)),15).astype(np.uint8)
|
| 18 |
+
self.assets.append(f);self.atoms.append(torch.randn(f['atoms'],256,requires_grad=True));self.mols.append(SimpleNamespace(smiles=s))
|
| 19 |
+
def test_initial_zero(self):
|
| 20 |
+
self.assertEqual(float(self.head.topology_scores(self.q,self.query,self.atoms,self.assets).abs().max()),0.)
|
| 21 |
+
self.assertEqual(float(self.head.difference_scores(self.q,self.query,self.mols,self.assets).abs().max()),0.)
|
| 22 |
+
base=torch.randn(3);self.assertTrue(torch.equal(self.head.calibrate(base,base,['A','A','B']),base))
|
| 23 |
+
def test_order(self):
|
| 24 |
+
with torch.no_grad():
|
| 25 |
+
self.head.topology[-1].weight.normal_(std=.1);self.head.difference[-1].weight.normal_(std=.1);self.head.formula_alpha.fill_(.5)
|
| 26 |
+
p=[2,0,1]
|
| 27 |
+
for name,items in [('topology_scores',self.atoms),('difference_scores',self.mols)]:
|
| 28 |
+
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])
|
| 29 |
+
self.assertTrue(torch.allclose(b,a[p],atol=1e-5))
|
| 30 |
+
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]))
|
| 31 |
+
def test_single_formula_unchanged(self):
|
| 32 |
+
self.head.formula_alpha.data.fill_(1.);b=torch.randn(8)
|
| 33 |
+
self.assertTrue(torch.equal(self.head.calibrate(b,b,['A']*8),b))
|
| 34 |
+
def test_current_graph_gradients(self):
|
| 35 |
+
self.head.topology[-1].weight.data.normal_(std=.1)
|
| 36 |
+
self.head.topology_scores(self.q,self.query,self.atoms,self.assets).sum().backward()
|
| 37 |
+
self.assertTrue(all(a.grad.norm()>0 for a in self.atoms))
|
| 38 |
+
self.assertGreater(float(self.head.mass[0].weight.grad.norm()),0.)
|
| 39 |
+
def test_unsupported_adduct_keeps_parent(self):
|
| 40 |
+
self.query.adduct='[M+2H]2+'
|
| 41 |
+
self.assertEqual(float(self.head.difference_scores(self.q,self.query,self.mols,self.assets).abs().max()),0.)
|
| 42 |
+
def test_lossless_distance_storage(self):
|
| 43 |
+
for n in (1,2,3,18,49):
|
| 44 |
+
a=np.minimum(np.abs(np.arange(n)[:,None]-np.arange(n)[None,:]),15).astype(np.uint8)
|
| 45 |
+
self.assertTrue(np.array_equal(a,ft.distance_loads(ft.distance_dumps(a))))
|
| 46 |
+
self.assertTrue(np.array_equal(a,ft.distance_loads(ft.dumps(a))))
|
| 47 |
+
import hashlib
|
| 48 |
+
b=b'unchanged'
|
| 49 |
+
self.assertTrue(ft.digest_matches(b,hashlib.sha256(b).digest()))
|
| 50 |
+
self.assertTrue(ft.digest_matches(b,hashlib.sha256(b).hexdigest()))
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
if __name__=='__main__':unittest.main()
|
code/snapshot/root/code/ceir_r3_20261110/train_r2.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Exactly +3000 updates from frozen A3 3k; joint objectives throughout."""
|
| 2 |
+
import argparse
|
| 3 |
+
import fcntl
|
| 4 |
+
import json
|
| 5 |
+
import math
|
| 6 |
+
import time
|
| 7 |
+
import traceback
|
| 8 |
+
import uuid
|
| 9 |
+
from runtime_r2 import *
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def train(arm):
|
| 13 |
+
import torch
|
| 14 |
+
from torch.utils.data import DataLoader
|
| 15 |
+
from data_r2 import Dataset
|
| 16 |
+
from model_r2_new import make_model_optimizer
|
| 17 |
+
from objectives_r2 import train_step
|
| 18 |
+
from validate_r2 import evaluate
|
| 19 |
+
directory=run_dir(arm);lock=(directory/'training.lock').open('a+');fcntl.flock(lock,fcntl.LOCK_EX)
|
| 20 |
+
ready=json.loads((OUT/'TRAIN_READY.json').read_text());bind=binding()
|
| 21 |
+
if ready['binding']!=bind or not ready['complete']:raise RuntimeError('Code/data/GPU acceptance binding changed')
|
| 22 |
+
if (directory/'COMPLETE.json').exists():return
|
| 23 |
+
target=C['pilot_target_update'];setup_gpu();last=directory/'last.pt'
|
| 24 |
+
source=parent_state();parent_lrs=[g['lr'] for g in source['optimizer']['param_groups']];del source
|
| 25 |
+
with gpu_work(directory,'restore'):
|
| 26 |
+
model,opt,progress,original_lr=make_model_optimizer(arm,last if last.exists() else None)
|
| 27 |
+
if last.exists():
|
| 28 |
+
state=torch.load(last,map_location='cpu',weights_only=False)
|
| 29 |
+
if state['binding']!=bind:raise RuntimeError('Resume binding differs')
|
| 30 |
+
del state
|
| 31 |
+
else:checkpoint(last,model,opt,progress,bind)
|
| 32 |
+
save(directory/'provenance.json',dict(arm=arm,source_update=C['source_update'],target_update=target,parent_checkpoint=C['parent_checkpoint'],
|
| 33 |
+
parent_sha256=C['parent_sha256'],parameters=sum(p.numel() for p in model.parameters()),binding=bind,
|
| 34 |
+
old_parameters_loaded_exactly=True,optimizer_moments_continued=True,source_data_cursor_preserved=True,
|
| 35 |
+
original_pools_modified=False,training_uses_Test_or_CASMI=False,
|
| 36 |
+
zero_weight_coarse_tasks_skipped=True,all_arms_receive_same_stochastic_view_checkpoint_fix=True))
|
| 37 |
+
attempt=uuid.uuid4().hex;resumed=progress['update']
|
| 38 |
+
prior_failure=directory/'failure.json'
|
| 39 |
+
if prior_failure.exists():prior_failure.rename(directory/('failure_recovered_'+attempt+'.json'))
|
| 40 |
+
log(directory/'events.jsonl',dict(event='resumed',attempt=attempt,update=resumed,unix_time=time.time()))
|
| 41 |
+
pending=[u for u in C['validation_updates'] if u<=progress['update'] and u not in progress.get('r2_validated',[])]
|
| 42 |
+
for u in pending:
|
| 43 |
+
if u!=progress['update']:raise RuntimeError('Pending historical Validation checkpoint must be evaluated explicitly')
|
| 44 |
+
snapshot=directory/('step_%06d.pt'%u)
|
| 45 |
+
if not snapshot.exists():shutil.copy2(last,snapshot)
|
| 46 |
+
evaluate(model,arm,u,128 if u<target else None,directory/('step_%06d.pt'%u))
|
| 47 |
+
progress.setdefault('r2_validated',[]).append(u)
|
| 48 |
+
with gpu_work(directory,'save_validated_progress'):checkpoint(last,model,opt,progress,bind)
|
| 49 |
+
offset=progress['update']-C['source_update']
|
| 50 |
+
dataset=Dataset(arm,offset,target-C['source_update'])
|
| 51 |
+
generator=torch.Generator().manual_seed(C['seed']+offset)
|
| 52 |
+
loader=DataLoader(dataset,batch_size=None,num_workers=1,prefetch_factor=2,multiprocessing_context='spawn',generator=generator)
|
| 53 |
+
previous=time.monotonic()
|
| 54 |
+
for batch in loader:
|
| 55 |
+
started=time.monotonic();waiting=started-previous;u=progress['update'];n=u-C['source_update']
|
| 56 |
+
if batch['manifest_index']!=n:raise RuntimeError('Data cursor changed')
|
| 57 |
+
# Predeclared +3000 schedule, identical in every arm. Test never selects
|
| 58 |
+
# an intermediate checkpoint or changes the number of updates.
|
| 59 |
+
ramp=min(1.,(n+1)/C['lr_ramp_updates']);decay=.2+.8*.5*(1+math.cos(math.pi*min(1.,n/C['manifest_updates'])))
|
| 60 |
+
opt.param_groups[0]['lr']=original_lr*C['backbone_lr_multiplier']*ramp*decay
|
| 61 |
+
opt.param_groups[1]['lr']=float(parent_lrs[1])*ramp*decay
|
| 62 |
+
opt.param_groups[2]['lr']=C['new_head_lr']*ramp*decay
|
| 63 |
+
with gpu_work(directory,'training'):
|
| 64 |
+
admission=time.monotonic()-started;model.train();torch.cuda.reset_peak_memory_stats()
|
| 65 |
+
metrics=train_step(model,opt,batch,u)
|
| 66 |
+
progress.update(update=u+1,new_updates=n+1,epoch=batch['epoch'],next_step=batch['step']+1)
|
| 67 |
+
for source,count in metrics['source_counts'].items():
|
| 68 |
+
exposures=progress.setdefault('r2_exposures',{});exposures[source]=exposures.get(source,0)+count
|
| 69 |
+
if progress['update']%C['save_interval']==0 or n==0:checkpoint(last,model,opt,progress,bind)
|
| 70 |
+
if progress['update'] in C['validation_updates']:
|
| 71 |
+
snapshot=directory/('step_%06d.pt'%progress['update'])
|
| 72 |
+
if progress['update']==target:
|
| 73 |
+
checkpoint(snapshot,model,opt,progress,bind)
|
| 74 |
+
else:
|
| 75 |
+
# Intermediate evaluation weights do not claim optimizer
|
| 76 |
+
# resume support. last.pt always retains complete state.
|
| 77 |
+
torch.save(dict(architecture='CEIR_R3_inference_only',model=model.state_dict(),progress=progress,binding=bind),snapshot)
|
| 78 |
+
metrics.update(update=progress['update'],new_updates=progress['new_updates'],arm=arm,attempt=attempt,
|
| 79 |
+
data_wait_seconds=waiting,gpu_admission_seconds=admission,wall_seconds=time.monotonic()-started,
|
| 80 |
+
backbone_lr=opt.param_groups[0]['lr'],A3_head_lr=opt.param_groups[1]['lr'],new_lr=opt.param_groups[2]['lr'],manifest_index=n,ledger_sha256=batch['ledger_sha256'],unix_time=time.time())
|
| 81 |
+
log(directory/'loss.jsonl',metrics)
|
| 82 |
+
if n<3 or (n+1)%10==0:
|
| 83 |
+
save(directory/'status.json',dict(phase='training',update=progress['update'],target_update=target,latest=metrics,unix_time=time.time()))
|
| 84 |
+
print(json.dumps(dict(arm=arm,update=progress['update'],loss=metrics['loss'],seconds=metrics['wall_seconds'])),flush=True)
|
| 85 |
+
if progress['update'] in C['validation_updates']:
|
| 86 |
+
save(directory/'status.json',dict(phase='Validation',update=progress['update'],unix_time=time.time()))
|
| 87 |
+
evaluate(model,arm,progress['update'],128 if progress['update']<target else None,directory/('step_%06d.pt'%progress['update']))
|
| 88 |
+
progress.setdefault('r2_validated',[]).append(progress['update'])
|
| 89 |
+
with gpu_work(directory,'save_after_Validation'):
|
| 90 |
+
if progress['update']==target:
|
| 91 |
+
# Preserve the exact endpoint SHA used by Validation.
|
| 92 |
+
# Validation completion is recorded in COMPLETE.json; a
|
| 93 |
+
# recovery reuses its idempotent metrics, without updates.
|
| 94 |
+
endpoint=directory/('step_%06d.pt'%target)
|
| 95 |
+
alias=directory/'last.link.tmp'
|
| 96 |
+
if alias.exists():alias.unlink()
|
| 97 |
+
os.link(endpoint,alias);os.replace(alias,last)
|
| 98 |
+
else:checkpoint(last,model,opt,progress,bind)
|
| 99 |
+
if progress['update']>=target:break
|
| 100 |
+
previous=time.monotonic()
|
| 101 |
+
if progress['update']!=target:raise RuntimeError('Training exhausted before target')
|
| 102 |
+
save(directory/'COMPLETE.json',dict(complete=True,source_update=C['source_update'],update=target,new_updates=target-C['source_update'],
|
| 103 |
+
checkpoint=str(directory/('step_%06d.pt'%target)),validated=progress['r2_validated'],exposures=progress['r2_exposures'],unix_time=time.time()))
|
| 104 |
+
save(directory/'status.json',dict(phase='completed',update=target,new_updates=target-C['source_update'],unix_time=time.time()))
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
if __name__=='__main__':
|
| 108 |
+
p=argparse.ArgumentParser();p.add_argument('--arm',choices=C['arms'],required=True);a=p.parse_args()
|
| 109 |
+
try:train(a.arm)
|
| 110 |
+
except Exception:
|
| 111 |
+
save(run_dir(a.arm)/'failure.json',dict(traceback=traceback.format_exc(),unix_time=time.time(),resume_checkpoint_preserved=True));raise
|
code/snapshot/root/code/ceir_r3_20261110/validate_r2.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Unchanged official Validation, fixed numerical batching, all ranked scores."""
|
| 2 |
+
from dataclasses import replace
|
| 3 |
+
import gzip
|
| 4 |
+
import fcntl
|
| 5 |
+
import hashlib
|
| 6 |
+
import json
|
| 7 |
+
import time
|
| 8 |
+
import torch
|
| 9 |
+
from runtime_r2 import *
|
| 10 |
+
from validation_ceir import metric,KS,FKS
|
| 11 |
+
from specpartition_ms.chemistry import canonical_formula,formula_vector
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def evaluate(model,arm,update,maximum_targets=None,checkpoint_path=None):
|
| 15 |
+
label='validation_%06d'%update if maximum_targets is None else 'probe_%06d_%04d'%(update,maximum_targets)
|
| 16 |
+
dest=evaluation_directory(arm,label)
|
| 17 |
+
lock=(dest/'evaluation.lock').open('a+');fcntl.flock(lock,fcntl.LOCK_EX)
|
| 18 |
+
protocol=dict(binding=binding(),arm=arm,update=update,maximum_targets=maximum_targets,
|
| 19 |
+
checkpoint_sha256=sha(checkpoint_path) if checkpoint_path else C['parent_sha256'],
|
| 20 |
+
spectrum_batch=C['validation_spectrum_batch'],graph_chunk=C['validation_graph_chunk'],
|
| 21 |
+
local_chunk=C['validation_local_chunk'],candidate_policy='original_official_raw_entries_no_injection',
|
| 22 |
+
structure_identity='key14',probe_selection='sha256(target)_ascending')
|
| 23 |
+
path=dest/'protocol.json'
|
| 24 |
+
if path.exists() and json.loads(path.read_text())!=protocol:raise RuntimeError('Validation binding changed')
|
| 25 |
+
save(path,protocol)
|
| 26 |
+
if (dest/'metrics.json').exists():return json.loads((dest/'metrics.json').read_text())
|
| 27 |
+
model.eval();old_gc,old_lc=model.graph_chunk,model.local_chunk
|
| 28 |
+
model.graph_chunk=C['validation_graph_chunk'];model.local_chunk=C['validation_local_chunk']
|
| 29 |
+
db=readonly(LEGACY.PREP/'validation.sqlite');summary=[];started=time.monotonic()
|
| 30 |
+
targets=[r[0] for r in db.execute('SELECT DISTINCT target FROM spectra ORDER BY target')]
|
| 31 |
+
if maximum_targets is not None:targets=sorted(targets,key=lambda s:hashlib.sha256(s.encode()).digest())[:maximum_targets]
|
| 32 |
+
for ti,target in enumerate(targets):
|
| 33 |
+
output=dest/(hashlib.sha256(target.encode()).hexdigest()+'.json.gz')
|
| 34 |
+
if output.exists():
|
| 35 |
+
with gzip.open(output,'rt') as f:summary.extend(json.load(f)['rows'])
|
| 36 |
+
continue
|
| 37 |
+
pools={v:json.loads(db.execute('SELECT body FROM pools WHERE target=? AND view=?',(target,v)).fetchone()[0]) for v in ('mass','formula')}
|
| 38 |
+
aliases={s:db.execute('SELECT graph_key,identity,formula,error FROM aliases WHERE smiles=?',(s,)).fetchone() for s in set(sum(pools.values(),[]))}
|
| 39 |
+
graphs={}
|
| 40 |
+
for g,identity,formula,error in aliases.values():
|
| 41 |
+
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])
|
| 42 |
+
keys=sorted(graphs);positions={g:i for i,g in enumerate(keys)};mols=[graphs[g] for g in keys]
|
| 43 |
+
data=[loads(r[0]) for r in db.execute('SELECT body FROM spectra WHERE target=? ORDER BY identifier',(target,))]
|
| 44 |
+
forms={}
|
| 45 |
+
for v in ('mass','formula'):
|
| 46 |
+
fs=set()
|
| 47 |
+
for s in pools[v]:
|
| 48 |
+
if aliases[s][2]:
|
| 49 |
+
try:formula_vector(aliases[s][2]);fs.add(canonical_formula(aliases[s][2]))
|
| 50 |
+
except ValueError:pass
|
| 51 |
+
forms[v]=tuple(sorted(fs))
|
| 52 |
+
rows=[];ranked={}
|
| 53 |
+
with gpu_work(dest,'Validation'),torch.inference_mode(),amp():
|
| 54 |
+
if mols:_,atoms,zm=model.encode_molecules(mols)
|
| 55 |
+
for start in range(0,len(data),C['validation_spectrum_batch']):
|
| 56 |
+
block=data[start:start+C['validation_spectrum_batch']]
|
| 57 |
+
tokens,qs,_=model.spectrum.forward_batch([r['query'] for r in block])
|
| 58 |
+
views=[(i,v,replace(r['query'],formula_candidates=forms[v])) for i,r in enumerate(block) for v in ('mass','formula')]
|
| 59 |
+
fs=model.formula_batch(torch.stack([qs[i] for i,_,_ in views]),[q for _,_,q in views],[tokens[i] for i,_,_ in views])
|
| 60 |
+
for vi,(i,v,q) in enumerate(views):
|
| 61 |
+
r=block[i];selected=sorted({aliases[s][0] for s in pools[v] if aliases[s][0] is not None})
|
| 62 |
+
index=[positions[g] for g in selected];scores={}
|
| 63 |
+
if index:
|
| 64 |
+
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])
|
| 65 |
+
if not torch.isfinite(values).all():raise RuntimeError('Nonfinite Validation score')
|
| 66 |
+
scores=dict(zip(selected,values.float().cpu().tolist()))
|
| 67 |
+
candidates=[dict(smiles=s,identity=aliases[s][1],formula=aliases[s][2],score=scores.get(aliases[s][0]),
|
| 68 |
+
scoreable=aliases[s][0] in scores) for s in pools[v]]
|
| 69 |
+
candidates.sort(key=lambda c:(not c['scoreable'],-c['score'] if c['scoreable'] else 0,c['identity'] or '',c['smiles']))
|
| 70 |
+
rank=next((j+1 for j,c in enumerate(candidates) if c['scoreable'] and c['identity']==r['identity']),None)
|
| 71 |
+
fv=fs[vi].float().cpu().tolist();order=sorted(range(len(fv)),key=lambda j:(-fv[j],q.formula_candidates[j]))
|
| 72 |
+
try:truth=canonical_formula(r['formula']);formula_vector(truth)
|
| 73 |
+
except ValueError:truth=None
|
| 74 |
+
frank=next((j+1 for j,k in enumerate(order) if q.formula_candidates[k]==truth),None)
|
| 75 |
+
rows.append(dict(identifier=r['identifier'],target=target,view=v,reference_identity=r['identity'],reference_formula=truth,
|
| 76 |
+
rank=rank,formula_rank=frank,candidate_count=len(candidates),formula_count=len(fv),
|
| 77 |
+
unscoreable=sum(not c['scoreable'] for c in candidates),adduct=q.adduct,peak_count=len(q.peaks),
|
| 78 |
+
collision_energy=q.collision_energy,instrument=q.instrument,
|
| 79 |
+
reference_present_in_original_pool=any(c['identity']==r['identity'] for c in candidates),
|
| 80 |
+
reference_scoreable=any(c['scoreable'] and c['identity']==r['identity'] for c in candidates),
|
| 81 |
+
top1_smiles=candidates[0]['smiles'] if candidates and candidates[0]['scoreable'] else None))
|
| 82 |
+
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)])
|
| 83 |
+
temporary=Path(str(output)+'.tmp')
|
| 84 |
+
with gzip.open(temporary,'wt',compresslevel=3) as f:json.dump(dict(rows=rows,ranked=ranked),f,separators=(',',':'))
|
| 85 |
+
temporary.replace(output);summary.extend(rows)
|
| 86 |
+
save(dest/'status.json',dict(targets=ti+1,total=len(targets),spectral_views=len(summary),seconds=time.monotonic()-started,unix_time=time.time()))
|
| 87 |
+
disk_check()
|
| 88 |
+
metrics={}
|
| 89 |
+
for view in ('mass','formula'):
|
| 90 |
+
rr=[r for r in summary if r['view']==view]
|
| 91 |
+
if maximum_targets is None and (len(rr)!=19429 or len({r['identifier'] for r in rr})!=19429):raise RuntimeError('Incomplete official Validation denominator')
|
| 92 |
+
metrics[view]=dict(spectra=len(rr),structure=metric(rr,'rank',KS),formula=metric(rr,'formula_rank',FKS),
|
| 93 |
+
original_pool_coverage=sum(r['reference_present_in_original_pool'] for r in rr),scoreable_coverage=sum(r['reference_scoreable'] for r in rr))
|
| 94 |
+
with gzip.open(dest/'per_spectrum_summary.json.gz','wt',compresslevel=3) as f:json.dump(summary,f,separators=(',',':'))
|
| 95 |
+
x=metrics['mass']['structure']['1']['micro'];y=metrics['formula']['structure']['1']['micro']
|
| 96 |
+
metrics.update(complete=True,update=update,full_Validation=maximum_targets is None,selection_harmonic_Top1=2*x*y/max(1e-12,x+y),
|
| 97 |
+
protocol=protocol,MCES='not_yet_computed_not_zero_filled',seconds=time.monotonic()-started)
|
| 98 |
+
save(dest/'metrics.json',metrics);db.close();model.graph_chunk=old_gc;model.local_chunk=old_lc;model.train()
|
| 99 |
+
return metrics
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
if __name__=='__main__':
|
| 103 |
+
import argparse
|
| 104 |
+
from model_r2_new import make_model_optimizer
|
| 105 |
+
p=argparse.ArgumentParser();p.add_argument('--arm',choices=C['arms'],required=True);p.add_argument('--checkpoint');p.add_argument('--targets',type=int)
|
| 106 |
+
a=p.parse_args();setup_gpu()
|
| 107 |
+
with gpu_work(run_dir(a.arm),'restore_for_evaluation'):model,opt,progress,_=make_model_optimizer(a.arm,a.checkpoint)
|
| 108 |
+
del opt
|
| 109 |
+
evaluate(model,a.arm,progress['update'],a.targets,a.checkpoint)
|
code/snapshot/root/code/ceir_r4_9000_20261112/README.md
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# R4: R3D 6k → 9k, four-arm matched continuation
|
| 2 |
+
|
| 3 |
+
Every arm starts from the same full R3D optimizer/model/RNG checkpoint
|
| 4 |
+
`e14cfa3819ba33141f92202686e5b02c5b8d6668b55d5c56e01806ae85d6ef4e`.
|
| 5 |
+
6,000 is the starting cumulative update, **not** the number of new steps:
|
| 6 |
+
each arm must make exactly 3,000 successful updates and finish at 9,000. A
|
| 7 |
+
disposable warm GPU probe and official GPU acceptance steps are not counted.
|
| 8 |
+
|
| 9 |
+
| Arm | Candidate score | Objective added on top of R3D |
|
| 10 |
+
| --- | --- | --- |
|
| 11 |
+
| A | inherited R3D | none; optimizer and parent group LRs carried forward |
|
| 12 |
+
| B | inherited R3D | same-formula hard gap |
|
| 13 |
+
| C | R3D + bounded differential-peak pair residual | none |
|
| 14 |
+
| D | R3D + bounded differential-peak pair residual | same-formula hard gap |
|
| 15 |
+
|
| 16 |
+
The complete-parent score still exists for every candidate. The pair residual
|
| 17 |
+
uses at most 32 model-selected distinct key14s, compares only rivals of the
|
| 18 |
+
same formula, and is initialized to exactly zero. It uses raw spectrum peaks,
|
| 19 |
+
their aligned encoder tokens, molecular embeddings and the inherited fragment
|
| 20 |
+
hypotheses (not CSI rankings or identities as learned features). Equivalent
|
| 21 |
+
aliases may share a residual, but the original official pool entries and ranks
|
| 22 |
+
are preserved. B and D use detached **pre-duel** scores to identify up to three
|
| 23 |
+
wrong key14s in each eligible same-formula competition; weight 0.1, margin 0.2.
|
| 24 |
+
The inherited whole-pool CE is counted once. Other tasks and candidate draws
|
| 25 |
+
are identical. There is no test-set mining or test-based checkpoint selection.
|
| 26 |
+
|
| 27 |
+
## Execution and validation
|
| 28 |
+
|
| 29 |
+
- Remote code: `/root/xj/SpecPartition-MS/code/ceir_r4_9000_20261112`.
|
| 30 |
+
- Logs, acceptance receipts, durable states, results: `/root/xj/SpecPartition-MS/runs/ceir_r4_9000_20261112`.
|
| 31 |
+
- Rebuildable offline features, hot checkpoints: `/dev/shm/specpartition_r4_9000_20261112`.
|
| 32 |
+
- 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.
|
| 33 |
+
|
| 34 |
+
The starting data cursor is **epoch 1, step 907 (zero-based)**; last
|
| 35 |
+
consumed batch is epoch 1, step 3906. The shared immutable batch hash is
|
| 36 |
+
`48c489b3cd16902afb2669ae0d65181206345fff1713771929f4ff9894db6edf`.
|
| 37 |
+
The data preparation verified 4,626,599 distinct graph IDs, 96,000 MSG Train
|
| 38 |
+
spectrum exposures, 149,599 MS2-SAN exposures and 133,537 MSP exposures per arm.
|
| 39 |
+
No evaluation labels or test candidate pools were introduced into the ledger.
|
| 40 |
+
Of the group views, 96,000 are MSG Mass, 95,852 MSG Formula and 16,901 external
|
| 41 |
+
same-formula pools. Counts are exposures, not counts of new unique spectra.
|
| 42 |
+
|
| 43 |
+
The supervisor queues paired GPU work on one 24-GiB RTX 4090; it does not run
|
| 44 |
+
four unconstrained CUDA contexts. All four arms first do a short *real* block,
|
| 45 |
+
then rotate in blocks of at most 250 updates. Checkpoints include AdamW moments,
|
| 46 |
+
RNG, ledger cursor and chain. Hot rolled states are replaced only after a new
|
| 47 |
+
state is saved; durable state copies are independently hash-checked. 7k and 8k
|
| 48 |
+
are separately retained inference snapshots; 9k is a fully resumable endpoint.
|
| 49 |
+
This is not a GitHub weight publication.
|
| 50 |
+
|
| 51 |
+
Release the result as **completed** only after `TRAIN_COMPLETE.json` exists for
|
| 52 |
+
each arm, independent ledger-chain/cursor checks pass, the full Validation,
|
| 53 |
+
fixed Test and MCES results exist, and `ALL_RESULTS.json` is present. Training
|
| 54 |
+
progress or lower training loss alone is not evidence of better retrieval.
|
| 55 |
+
Compare each arm against both A at the same update and the frozen 6k parent:
|
| 56 |
+
all original MSG Validation views at 7k/8k/9k; predeclared 9k MSG Test and
|
| 57 |
+
CASMI full-pool endpoints; paired wins, new failures, confidence intervals and
|
| 58 |
+
valid MCES denominators. Report ties/regressions explicitly.
|
| 59 |
+
|
| 60 |
+
The follow-up analysis script outside the frozen training release verifies all
|
| 61 |
+
four distinct 3,000-step ledgers and the raw endpoint comparisons. Before any
|
| 62 |
+
new full validation result was available, the effect audit was set to require
|
| 63 |
+
a positive fixed-endpoint Formula Top1 difference over A (key14-cluster bootstrap,
|
| 64 |
+
one-sided lower bound adjusted for three prespecified arms), positive difference
|
| 65 |
+
over the 6k parent, Mass Top1/5/20 and Formula Top5/20 loss of no more than
|
| 66 |
+
0.2 percentage points vs A, and per-view common-prediction MCES worsening of
|
| 67 |
+
at most 0.10 vs A. These are single-seed decision rules, not a guarantee
|
| 68 |
+
of efficacy or an instruction to continue tuning against the test split.
|
code/snapshot/root/code/ceir_r4_9000_20261112/accept4.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Disposable real GPU steps; only the final *new-ledger* gate authorizes training."""
|
| 2 |
+
import argparse,gc
|
| 3 |
+
from dataclasses import replace
|
| 4 |
+
import torch
|
| 5 |
+
from common4 import *
|
| 6 |
+
from model4 import make,setup
|
| 7 |
+
from run4 import lease,atomic_torch
|
| 8 |
+
from data4 import Batches
|
| 9 |
+
from objectives4 import train_step
|
| 10 |
+
def acceptance(warm):
|
| 11 |
+
if not warm and (OUT/'TRAIN_READY.json').exists() and get(OUT/'TRAIN_READY.json')['binding']==state_binding():return
|
| 12 |
+
setup()
|
| 13 |
+
if warm:
|
| 14 |
+
from data_r2 import Dataset
|
| 15 |
+
data=Dataset('R3D',0,30);bind={'probe':'historical real batch; no formal update'}
|
| 16 |
+
else:data=Batches(0,30);bind=state_binding()
|
| 17 |
+
for i in range(len(data)):
|
| 18 |
+
batch=data[i]
|
| 19 |
+
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
|
| 20 |
+
else:raise RuntimeError('No full multi-source GPU acceptance batch')
|
| 21 |
+
query=next(p['query'] for r in batch['rows'] for p in r['pools'] if p['kind']=='formula' and len(p['graphs'])>=3)
|
| 22 |
+
with lease('acceptance'):
|
| 23 |
+
from model_r2_new import make_model_optimizer
|
| 24 |
+
parent_model,oldopt,_,_=make_model_optimizer('R3D',PARENT)
|
| 25 |
+
del oldopt
|
| 26 |
+
if not warm:parent_model.feature_store=data.store
|
| 27 |
+
parent_model.eval()
|
| 28 |
+
with torch.inference_mode(),rt.amp():expected=parent_model.encode_batch([query])[0][0].base.float().cpu()
|
| 29 |
+
del parent_model;gc.collect();torch.cuda.empty_cache()
|
| 30 |
+
arms={};bases={}
|
| 31 |
+
for a in ('A','C','B','D'):
|
| 32 |
+
model,opt,p=make(a,provisional=warm);model.eval()
|
| 33 |
+
with torch.inference_mode(),rt.amp():
|
| 34 |
+
actual=model.encode_batch([query])[0][0].base.float().cpu()
|
| 35 |
+
order=list(range(len(query.candidates)-1,-1,-1))
|
| 36 |
+
changed=replace(query,candidates=tuple(query.candidates[j] for j in order))
|
| 37 |
+
flipped=model.encode_batch([changed])[0][0].base.float().cpu()
|
| 38 |
+
parity=float((actual-expected).abs().max());permutation=float((flipped-actual[order]).abs().max())
|
| 39 |
+
if parity>1e-5 or permutation>3e-4:raise RuntimeError(f'{a}: parent/permutation parity {parity} {permutation}')
|
| 40 |
+
rt.restore_rng(parent());model.train();torch.cuda.reset_peak_memory_stats()
|
| 41 |
+
m=train_step(model,opt,batch,6000)
|
| 42 |
+
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')
|
| 43 |
+
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)
|
| 44 |
+
bases[a]=m['loss'];resume_error=None
|
| 45 |
+
if a=='D' and not warm:
|
| 46 |
+
import random,numpy as np
|
| 47 |
+
snap=HOT/'acceptance'/'D_full_resume.pt'
|
| 48 |
+
atomic_torch(snap,dict(architecture='CEIR_R4',arm=a,model=model.state_dict(),optimizer=opt.state_dict(),progress=dict(p,update=6001),binding=bind,
|
| 49 |
+
torch_rng=torch.get_rng_state(),cuda_rng=torch.cuda.get_rng_state_all(),numpy_rng=np.random.get_state(),python_rng=random.getstate()))
|
| 50 |
+
before=train_step(model,opt,batch,6001,False)['loss']
|
| 51 |
+
del model,opt;gc.collect();torch.cuda.empty_cache()
|
| 52 |
+
model,opt,p=make(a,snap,expected_binding=bind);model.train()
|
| 53 |
+
after=train_step(model,opt,batch,6001,False)['loss'];resume_error=abs(after-before)
|
| 54 |
+
if resume_error>3e-4:raise RuntimeError('R4 continuation parity failed')
|
| 55 |
+
arms[a]=dict(parent_score_error=parity,permutation_error=permutation,full_state_resume_loss_error=resume_error,
|
| 56 |
+
metrics=m,parameter_count=sum(v.numel() for v in model.parameters()),groups=[len(g['params']) for g in opt.param_groups])
|
| 57 |
+
put(OUT/(('warm_' if warm else 'formal_')+'acceptance_'+a+'.json'),arms[a])
|
| 58 |
+
print(a,parity,permutation,m['loss'],m['r4_gradient_norm'],flush=True)
|
| 59 |
+
del model,opt;gc.collect();torch.cuda.empty_cache()
|
| 60 |
+
if abs(bases['A']-bases['C'])>3e-4 or abs(bases['B']-bases['D'])>3e-4:raise RuntimeError('Unequal initial factorial objectives')
|
| 61 |
+
if not warm:
|
| 62 |
+
from eval4 import acceptance_validation
|
| 63 |
+
val=acceptance_validation(bind)
|
| 64 |
+
else:val=None
|
| 65 |
+
put(OUT/('EARLY_GPU_PROBE.json' if warm else 'TRAIN_READY.json'),dict(passed=True,formal_steps=0,binding=bind,
|
| 66 |
+
batch_index=i,batch_sha=batch['ledger_sha256'],real_queries=len(batch['rows']),arms=arms,validation_adapter_probe=val,ts=time.time()))
|
| 67 |
+
if __name__=='__main__':
|
| 68 |
+
ap=argparse.ArgumentParser();ap.add_argument('--warm',action='store_true');a=ap.parse_args()
|
| 69 |
+
try:acceptance(a.warm)
|
| 70 |
+
except Exception:
|
| 71 |
+
import traceback
|
| 72 |
+
put(OUT/('EARLY_GPU_ERROR.json' if a.warm else 'GPU_ERROR.json'),dict(error=traceback.format_exc(),ts=time.time()));raise
|
code/snapshot/root/code/ceir_r4_9000_20261112/common4.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""R4 owns only its timestamped paths. Imports the immutable R3 implementation."""
|
| 2 |
+
import os,sys,json,time,hashlib,gzip,fcntl,shutil,tempfile,sqlite3
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
HERE=Path(__file__).resolve().parent
|
| 5 |
+
CFG=json.loads((HERE/'config.json').read_text());OUT=Path(CFG['output']);HOT=Path(CFG['scratch'])
|
| 6 |
+
R3=Path(CFG['r3_root']);R2=Path(CFG['r2_root']);PARENT=R3/CFG['parent']
|
| 7 |
+
sys.path.insert(0,CFG['r3_code'])
|
| 8 |
+
import runtime_r2 as rt
|
| 9 |
+
import features_r2 as ft
|
| 10 |
+
sys.path.insert(0,str(HERE))
|
| 11 |
+
def digest(b):return hashlib.sha256(b).hexdigest()
|
| 12 |
+
def filehash(p):
|
| 13 |
+
h=hashlib.sha256()
|
| 14 |
+
with Path(p).open('rb') as f:
|
| 15 |
+
for b in iter(lambda:f.read(2**20),b''):h.update(b)
|
| 16 |
+
return h.hexdigest()
|
| 17 |
+
def objhash(o):return digest(json.dumps(o,sort_keys=True,separators=(',',':')).encode())
|
| 18 |
+
def put(p,o):
|
| 19 |
+
p=Path(p);p.parent.mkdir(parents=True,exist_ok=True)
|
| 20 |
+
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)
|
| 21 |
+
def get(p):return json.loads(Path(p).read_text())
|
| 22 |
+
def event(p,o):
|
| 23 |
+
p=Path(p);p.parent.mkdir(parents=True,exist_ok=True)
|
| 24 |
+
with p.open('a') as f:f.write(json.dumps(dict(o,timestamp=time.time()),separators=(',',':'),allow_nan=False)+'\n')
|
| 25 |
+
def ro(path):
|
| 26 |
+
return sqlite3.connect('file:'+str(path)+'?mode=ro',uri=True,timeout=60)
|
| 27 |
+
def lock(p):
|
| 28 |
+
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
|
| 29 |
+
def parent():
|
| 30 |
+
import torch
|
| 31 |
+
if filehash(PARENT)!=CFG['parent_sha256']:raise RuntimeError('R3D parent hash mismatch')
|
| 32 |
+
x=torch.load(PARENT,map_location='cpu',weights_only=False)
|
| 33 |
+
if x['architecture']!='CEIR_R3' or x['progress']['update']!=6000 or x['binding']['original_data']!=rt.LEGACY.bind():
|
| 34 |
+
raise RuntimeError('Wrong parent state or data binding')
|
| 35 |
+
return x
|
| 36 |
+
def prep_root():return HOT/'prepared'
|
| 37 |
+
def scratch_check():
|
| 38 |
+
HOT.mkdir(exist_ok=True,parents=True)
|
| 39 |
+
if shutil.disk_usage(HOT).free<2*2**30:raise RuntimeError('R4 scratch reserve <2GiB; preserving all outputs')
|
| 40 |
+
def state_binding():
|
| 41 |
+
gate=get(OUT/'DATA_READY.json')
|
| 42 |
+
if not (prep_root()/'READY.json').is_file() or get(prep_root()/'READY.json')!=gate:raise RuntimeError('Cold or incomplete R4 cache')
|
| 43 |
+
return dict(config=filehash(HERE/'config.json'),parent=CFG['parent_sha256'],ledger=gate['ledger_hash'],
|
| 44 |
+
code={p.name:filehash(p) for p in sorted(HERE.glob('*.py')) if not p.name.startswith('.')},
|
| 45 |
+
original_r3=get(R3/'R3D/provenance.json')['binding']['code'])
|
code/snapshot/root/code/ceir_r4_9000_20261112/config.json
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"experiment": "CEIR_R4_9000_20261112",
|
| 3 |
+
"r3_code": "/root/xj/SpecPartition-MS/code/ceir_r3_20261110",
|
| 4 |
+
"r3_root": "/root/xj/SpecPartition-MS/runs/ceir_r3_20261110",
|
| 5 |
+
"r2_root": "/root/xj/SpecPartition-MS/runs/ceir_r2_20261110",
|
| 6 |
+
"output": "/root/xj/SpecPartition-MS/runs/ceir_r4_9000_20261112",
|
| 7 |
+
"scratch": "/dev/shm/specpartition_r4_9000_20261112",
|
| 8 |
+
"parent_sha256": "e14cfa3819ba33141f92202686e5b02c5b8d6668b55d5c56e01806ae85d6ef4e",
|
| 9 |
+
"parent": "R3D/step_006000.pt",
|
| 10 |
+
"source_update": 6000, "additional_updates": 3000, "target_update": 9000,
|
| 11 |
+
"checkpoints": [7000,8000,9000], "seed": 20261103, "hot_interval": 50, "durable_interval": 200,
|
| 12 |
+
"arms": {"A":{"gap":false,"duel":false},"B":{"gap":true,"duel":false},"C":{"gap":false,"duel":true},"D":{"gap":true,"duel":true}},
|
| 13 |
+
"gap":{"weight":0.10,"margin":0.2,"hard_k":3},
|
| 14 |
+
"duel":{"n":32,"hidden":64,"cap":1.0},
|
| 15 |
+
"learning_rate":{"existing":"constant inherited R3D e6 endpoint group LRs, all arms identical","new_head":0.0001,"new_warmup":100},
|
| 16 |
+
"validation":"Full official MSG Validation, separate untouched Mass and Formula views at 7000, 8000, 9000. Baseline full 6000 reused.",
|
| 17 |
+
"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.",
|
| 18 |
+
"heldout_evaluation":"All four fixed endpoints, original MSG Test Mass and Formula and uncapped CASMI blind full pool, post-hoc MCES; no truth injection.",
|
| 19 |
+
"max_training_processes":2, "gpu_fraction":0.42, "free_before_job_mib":5800,
|
| 20 |
+
"locals_on_tmpfs":true, "upload_new_weights":false
|
| 21 |
+
}
|
code/snapshot/root/code/ceir_r4_9000_20261112/data4.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections import Counter
|
| 2 |
+
from dataclasses import replace
|
| 3 |
+
from functools import lru_cache
|
| 4 |
+
from common4 import *
|
| 5 |
+
from data09 import Reader,loads
|
| 6 |
+
|
| 7 |
+
class Fragments:
|
| 8 |
+
"""No test features opened during training. D arm never uses R3H distances."""
|
| 9 |
+
def __init__(self,split='train',extra=None):
|
| 10 |
+
self.sources=[]
|
| 11 |
+
if extra is not None:self.sources.append((ro(extra),'SELECT b,h FROM extra WHERE k=?'))
|
| 12 |
+
for parent,table,where in [(R2,'canonical_features','prepared'),(R3,'r3_features','prepared')]:
|
| 13 |
+
self.sources.append((ro(parent/where/'assets.sqlite'),f'SELECT feature,feature_sha FROM {table} WHERE feature_key=?'))
|
| 14 |
+
if split=='test':
|
| 15 |
+
for parent in (R2,R3):
|
| 16 |
+
db=ro(parent/'test/prepared/assets.sqlite')
|
| 17 |
+
ts={v[0] for v in db.execute("SELECT name FROM sqlite_master WHERE type='table'")}
|
| 18 |
+
t=next(t for t in ('canonical_features','r3_features','molecules') if t in ts)
|
| 19 |
+
self.sources.append((db,'SELECT feature,feature_sha FROM '+t+' WHERE feature_key=?'))
|
| 20 |
+
self.get=lru_cache(maxsize=4096)(self.fetch)
|
| 21 |
+
def fetch(self,smiles):
|
| 22 |
+
k=ft.key(smiles)
|
| 23 |
+
for db,sql in self.sources:
|
| 24 |
+
row=db.execute(sql,(k,)).fetchone()
|
| 25 |
+
if row is None or row[0] is None:continue
|
| 26 |
+
b,h=row
|
| 27 |
+
if not ft.digest_matches(b,h):raise RuntimeError('Static fragment digest mismatch')
|
| 28 |
+
obj=ft.loads(b)
|
| 29 |
+
if obj['smiles']!=smiles or obj['version']!=ft.VERSION:raise RuntimeError('Static feature identity/version changed')
|
| 30 |
+
return obj
|
| 31 |
+
raise RuntimeError('Missing precomputed fragment data: '+k)
|
| 32 |
+
|
| 33 |
+
class Batches:
|
| 34 |
+
def __init__(self,start=0,stop=3000,provisional=False):
|
| 35 |
+
self.start=start;self.stop=stop;self.reader=None;self.provisional=provisional
|
| 36 |
+
def __len__(self):return self.stop-self.start
|
| 37 |
+
def __getitem__(self,j):
|
| 38 |
+
start=time.monotonic();n=self.start+j
|
| 39 |
+
if not self.reader:
|
| 40 |
+
self.reader=Reader();self.store=Fragments('train',prep_root()/'delta.sqlite' if not self.provisional else None)
|
| 41 |
+
self.hashes=None if self.provisional else get(prep_root()/'hashes.json')
|
| 42 |
+
blob=(prep_root()/'batches'/('%04d.z'%n)).read_bytes();h=digest(blob)
|
| 43 |
+
if self.hashes and h!=self.hashes[n]:raise RuntimeError('Changed ledger block')
|
| 44 |
+
plan=ft.loads(blob);rows=[];rdr=self.reader
|
| 45 |
+
for sel in plan['rows']:
|
| 46 |
+
row=loads(rdr.db.execute('SELECT body FROM samples WHERE record_id=?',(sel['rid'],)).fetchone()[0]);ref=rdr.molecule(sel['ref'])
|
| 47 |
+
if ref.identity!=row['identity'] or ref.identity!=sel['identity'] or ref.identity in rdr.forbidden:raise ValueError('Training identity/holdout check failed')
|
| 48 |
+
row.update(ref=ref,formulas=sel['formulas'],pools=[]);row['query']=replace(row['query'],formula_candidates=row['formulas'])
|
| 49 |
+
feature=self.store.get(ref.smiles)
|
| 50 |
+
if ft.layout(ref.mol)!=feature['layout']:raise ValueError('Atom order mismatch')
|
| 51 |
+
row['chemical_counts']=feature['counts']
|
| 52 |
+
for p in sel['pools']:
|
| 53 |
+
ms=tuple(rdr.molecule(g) for g in p['graphs'])
|
| 54 |
+
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')
|
| 55 |
+
kind=p['kind'];q=replace(row['query'],candidates=ms,formula_candidates=tuple(p['formulas']),
|
| 56 |
+
candidate_view='odata_oracle' if kind=='odata' else 'msg_'+kind)
|
| 57 |
+
eligible=bool(row['mass_ok'] and ft.supported_positive(q,self.store.get(ms[0].smiles)))
|
| 58 |
+
row['pools'].append(dict(**p,query=q,positive_index=0,truth_identity=ref.identity,truth_formula=row['formula'],
|
| 59 |
+
record_id=row['record_id'],quality_eligible=bool(row['mass_ok']),spectrum_eligible=eligible))
|
| 60 |
+
rows.append(row)
|
| 61 |
+
return dict(rows=rows,manifest_index=n,ledger_sha256=h,epoch=plan['epoch'],step=plan['step'],data_seconds=time.monotonic()-start)
|
code/snapshot/root/code/ceir_r4_9000_20261112/duel4.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Experimental CSI-free evidence reranker. One original pool per call.
|
| 2 |
+
|
| 3 |
+
peak_support[i,p] is label-free, adduct-aware candidate fragment support on
|
| 4 |
+
observed peak p (in [0,1]); it must come from the spectrum forward path.
|
| 5 |
+
No reference, CID, CSI score, or stored row position is a model input.
|
| 6 |
+
"""
|
| 7 |
+
import torch
|
| 8 |
+
from torch import nn
|
| 9 |
+
from torch.nn import functional as F
|
| 10 |
+
|
| 11 |
+
class CandidateDuels(nn.Module):
|
| 12 |
+
def __init__(self, query_dim=256, molecule_dim=256, hidden=64, max_competitors=32, residual_cap=1.0):
|
| 13 |
+
super().__init__();self.max_competitors=max_competitors;self.cap=residual_cap
|
| 14 |
+
self.q=nn.Linear(query_dim,hidden);self.m=nn.Linear(molecule_dim,hidden)
|
| 15 |
+
self.peak_reliability=nn.Sequential(nn.Linear(query_dim+2,hidden),nn.SiLU(),nn.Linear(hidden,1))
|
| 16 |
+
nn.init.zeros_(self.peak_reliability[-1].weight);nn.init.zeros_(self.peak_reliability[-1].bias)
|
| 17 |
+
self.duel=nn.Sequential(nn.Linear(2*hidden+4,hidden),nn.SiLU(),nn.Linear(hidden,1))
|
| 18 |
+
nn.init.zeros_(self.duel[-1].weight);nn.init.zeros_(self.duel[-1].bias)
|
| 19 |
+
|
| 20 |
+
def forward(self,base,query,molecules,formula_ids,stable_ids,peak_support,intensity,peak_context=None):
|
| 21 |
+
# Supply only finite/scorable candidates. Unscoreables remain in the external evaluator.
|
| 22 |
+
n=len(base)
|
| 23 |
+
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')
|
| 24 |
+
if not (torch.isfinite(base).all() and torch.isfinite(peak_support).all() and torch.isfinite(intensity).all()):raise ValueError('nonfinite input')
|
| 25 |
+
if stable_ids.unique().numel()!=n:raise ValueError('deduplicate connectivity before pair competition; keep alias mapping')
|
| 26 |
+
if n<2 or not len(intensity):return base
|
| 27 |
+
# Content-derived deterministic ID for exact ties only; never embed it.
|
| 28 |
+
t=stable_ids.argsort(stable=True)
|
| 29 |
+
idx=t[base[t].detach().argsort(descending=True,stable=True)[:self.max_competitors]]
|
| 30 |
+
h=self.m(molecules[idx]);q=self.q(query).view(1,1,-1).expand(len(idx),len(idx),-1)
|
| 31 |
+
support=peak_support[idx].clamp(0,1)
|
| 32 |
+
w=intensity.clamp_min(0).sqrt();w=w/w.sum().clamp_min(1e-8)
|
| 33 |
+
if peak_context is not None:
|
| 34 |
+
if peak_context.shape!=(len(w),query.numel()) or not torch.isfinite(peak_context).all():
|
| 35 |
+
raise ValueError('expected one aligned encoder token per observed peak')
|
| 36 |
+
# Common matches are less diagnostic; learn reliability from aligned
|
| 37 |
+
# spectrum tokens, measured intensity, and the support prevalence.
|
| 38 |
+
# No truth, winner ID, CSI rank, or supervised peak annotation.
|
| 39 |
+
a=torch.cat((peak_context,w[:,None],support.mean(0)[:,None]),dim=-1)
|
| 40 |
+
rel=self.peak_reliability(a).squeeze(-1).sigmoid()
|
| 41 |
+
w=w*rel
|
| 42 |
+
exclusive=(support[:,None,:]-support[None,:,:]).clamp_min(0)
|
| 43 |
+
own=(exclusive*w).sum(-1);other=own.T
|
| 44 |
+
evidence=torch.stack((own,other,own-other,own+other),dim=-1)
|
| 45 |
+
f=self.duel(torch.cat((q,h[:,None,:]-h[None,:,:],evidence),dim=-1)).squeeze(-1)
|
| 46 |
+
vote=(f-f.T).tanh() # d_ij = -d_ji
|
| 47 |
+
same=formula_ids[idx,None]==formula_ids[idx][None,:]
|
| 48 |
+
eligible=same & ~torch.eye(len(idx),dtype=torch.bool,device=base.device) & (formula_ids[idx,None]>=0)
|
| 49 |
+
gated=(own+other).clamp(0,1)*vote*eligible # exactly neutral if no discriminating peak
|
| 50 |
+
residual=self.cap*gated.sum(1)/eligible.sum(1).clamp_min(1)
|
| 51 |
+
return base.index_add(0,idx,residual.to(base.dtype))
|
| 52 |
+
|
| 53 |
+
def pool_objective(final,base,formula_ids,identities,truth_identity,margin=.2,hard_k=3,temperature=1.):
|
| 54 |
+
"""Reference is used here only. Aliases share probability mass; no false-negative stereoisomers."""
|
| 55 |
+
y=identities==truth_identity
|
| 56 |
+
zero=final.sum()*0
|
| 57 |
+
if not y.any() or not (~y).any():return zero,zero,{'pool_ce':0,'same_formula_gap':0}
|
| 58 |
+
if formula_ids[y].unique().numel()!=1:raise ValueError('conflicting positive formula')
|
| 59 |
+
if temperature<=0:raise ValueError('temperature must be positive')
|
| 60 |
+
logits=final/temperature
|
| 61 |
+
pos=logits[y].logsumexp(0)
|
| 62 |
+
ce=logits.logsumexp(0)-pos
|
| 63 |
+
negatives=(~y)&(formula_ids==formula_ids[y][0])&(formula_ids>=0)
|
| 64 |
+
if not negatives.any():return ce,zero,{'pool_ce':1,'same_formula_gap':0}
|
| 65 |
+
indices=negatives.nonzero().flatten()
|
| 66 |
+
# At most one representative per rival identity. Selection detached and training-only.
|
| 67 |
+
reprs=[]
|
| 68 |
+
for k in identities[indices].unique():
|
| 69 |
+
g=indices[identities[indices]==k];reprs.append(g[base[g].detach().argmax()])
|
| 70 |
+
ix=torch.stack(reprs);ix=ix[base[ix].detach().topk(min(hard_k,len(ix))).indices]
|
| 71 |
+
best_positive=final[y].max()
|
| 72 |
+
gap=F.softplus(margin+final[ix]-best_positive).mean()
|
| 73 |
+
return ce,gap,{'pool_ce':1,'same_formula_gap':1}
|
code/snapshot/root/code/ceir_r4_9000_20261112/eval4.py
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Exact raw official pools; compact float32 scores, stable raw order, null mask.
|
| 2 |
+
All rankings, reference labels and MCES inputs are computed AFTER model.forward.
|
| 3 |
+
"""
|
| 4 |
+
import argparse,sqlite3,zlib,struct,math
|
| 5 |
+
from dataclasses import replace
|
| 6 |
+
import torch
|
| 7 |
+
import numpy as np
|
| 8 |
+
from common4 import *
|
| 9 |
+
from model4 import setup,make
|
| 10 |
+
from run4 import lease
|
| 11 |
+
from data09 import loads
|
| 12 |
+
from validation_ceir import KS,FKS,metric
|
| 13 |
+
from specpartition_ms.chemistry import canonical_formula,formula_vector
|
| 14 |
+
EVAL_CODE=Path('/root/xj/SpecPartition-MS/code/ceir_r1_test_comparison_20261110')
|
| 15 |
+
sys.path.insert(0,str(EVAL_CODE))
|
| 16 |
+
import infer as engine
|
| 17 |
+
engine.C=dict(engine.C,spectrum_batch=16,graph_chunk=32,local_chunk=32)
|
| 18 |
+
EVAL=Path(rt.C['root'])/'runs'/'ceir_r4_compact_evaluations_20261112'
|
| 19 |
+
def target_val(model,db,target):
|
| 20 |
+
pools={v:json.loads(db.execute('SELECT body FROM pools WHERE target=? AND view=?',(target,v)).fetchone()[0]) for v in ('mass','formula')}
|
| 21 |
+
aliases={s:tuple(db.execute('SELECT graph_key,identity,formula,error FROM aliases WHERE smiles=?',(s,)).fetchone()) for s in set(sum(pools.values(),[]))}
|
| 22 |
+
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})}
|
| 23 |
+
keys=sorted(graphs);positions={g:i for i,g in enumerate(keys)}
|
| 24 |
+
data=[loads(r[0]) for r in db.execute('SELECT body FROM spectra WHERE target=? ORDER BY identifier',(target,))]
|
| 25 |
+
forms={}
|
| 26 |
+
for v in pools:
|
| 27 |
+
ff=set()
|
| 28 |
+
for s in pools[v]:
|
| 29 |
+
f=aliases[s][2]
|
| 30 |
+
if f:
|
| 31 |
+
try:formula_vector(f);ff.add(canonical_formula(f))
|
| 32 |
+
except ValueError:pass
|
| 33 |
+
forms[v]=tuple(sorted(ff))
|
| 34 |
+
values=[{} for r in data];fvals=[{} for r in data]
|
| 35 |
+
with torch.inference_mode(),rt.amp():
|
| 36 |
+
if keys:_,atoms,zm=model.encode_molecules([graphs[k] for k in keys])
|
| 37 |
+
for start in range(0,len(data),16):
|
| 38 |
+
block=data[start:start+16];tokens,qs,_=model.spectrum.forward_batch([r['query'] for r in block])
|
| 39 |
+
views=[(i,v,replace(r['query'],formula_candidates=forms[v])) for i,r in enumerate(block) for v in ('mass','formula')]
|
| 40 |
+
fs=model.formula_batch(torch.stack([qs[i] for i,_,_ in views]),[q for _,_,q in views],[tokens[i] for i,_,_ in views])
|
| 41 |
+
for vi,(i,v,q) in enumerate(views):
|
| 42 |
+
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={}
|
| 43 |
+
if selected:
|
| 44 |
+
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])
|
| 45 |
+
scores=dict(zip(selected,vls.float().cpu().tolist()))
|
| 46 |
+
values[start+i][v]=scores;fvals[start+i][v]=fs[vi].float().cpu().tolist()
|
| 47 |
+
aliases={s:(a[0],a[1],a[2],None,None,a[3]) for s,a in aliases.items()}
|
| 48 |
+
return pools,aliases,forms,data,values,fvals,[None]*len(data)
|
| 49 |
+
def target_test(model,db,target,dataset):
|
| 50 |
+
pools,aliases,forms,sources=engine.universe(db,target,dataset)
|
| 51 |
+
data=[loads(r[0]) for r in db.execute('SELECT body FROM spectra WHERE target=? ORDER BY identifier',(target,))]
|
| 52 |
+
values,fvals,errors=engine.score_group(model,db,data,pools,aliases,forms)
|
| 53 |
+
return pools,aliases,forms,data,values,fvals,errors
|
| 54 |
+
def table(model,db,target,dataset):
|
| 55 |
+
val=dataset=='validation'
|
| 56 |
+
pools,aliases,forms,data,values,fvals,errors=target_val(model,db,target) if val else target_test(model,db,target,dataset)
|
| 57 |
+
rows=[];buffers=[];nfloat=0;static={v:objhash(list(pool)) for v,pool in pools.items()}
|
| 58 |
+
for i,r in enumerate(data):
|
| 59 |
+
for v,pool in pools.items():
|
| 60 |
+
vv=[values[i][v].get(aliases[s][0]) for s in pool]
|
| 61 |
+
if any(x is not None and not math.isfinite(x) for x in vv):raise RuntimeError('Nonfinite compact score')
|
| 62 |
+
arr=np.asarray(vv,dtype='<f4');order=sorted(range(len(pool)),key=lambda j:(vv[j] is None,-vv[j] if vv[j] is not None else 0.,aliases[pool[j]][1] or '',pool[j]))
|
| 63 |
+
def rank(k,ref):return next((z+1 for z,j in enumerate(order) if vv[j] is not None and ref is not None and aliases[pool[j]][k]==ref),None)
|
| 64 |
+
truth=engine.supported_formula(r['formula']);fs=fvals[i][v];fs=list(fs)
|
| 65 |
+
if any(not math.isfinite(x) for x in fs):raise RuntimeError('Nonfinite formula score')
|
| 66 |
+
fo=sorted(range(len(fs)),key=lambda j:(-fs[j],forms[v][j]))
|
| 67 |
+
row=dict(identifier=r['identifier'],target=target,view=v,reference_identity=r['identity'],
|
| 68 |
+
reference_smiles=r.get('reference_smiles') or target,reference_formula=truth,
|
| 69 |
+
rank=rank(1,r['identity']),formula_rank=next((j+1 for j,k in enumerate(fo) if forms[v][k]==truth),None),
|
| 70 |
+
candidate_count=len(vv),formula_count=len(forms[v]),scored_formulas=len(fs),
|
| 71 |
+
reference_in_pool=any(aliases[s][1]==r['identity'] for s in pool),
|
| 72 |
+
reference_scoreable_in_pool=any(vv[j] is not None and aliases[s][1]==r['identity'] for j,s in enumerate(pool)),
|
| 73 |
+
top1_smiles=pool[order[0]] if order and vv[order[0]] is not None else None,
|
| 74 |
+
unscoreable=sum(x is None for x in vv),adduct=r['query'].adduct,
|
| 75 |
+
polarity='negative' if r['query'].adduct.endswith('-') else 'positive',
|
| 76 |
+
peak_count=len(r['query'].peaks),collision_energy=r['query'].collision_energy,instrument=r['query'].instrument,
|
| 77 |
+
query_error=errors[i],float_offset=nfloat)
|
| 78 |
+
if not val:
|
| 79 |
+
ref=db.execute('SELECT canonical,fullkey FROM aliases WHERE smiles=?',(r['reference_smiles'],)).fetchone()
|
| 80 |
+
if ref is None:raise RuntimeError('Missing evaluation reference alias')
|
| 81 |
+
row.update(canonical_rank=rank(3,ref[0]),inchikey_rank=rank(4,ref[1]))
|
| 82 |
+
if (row['rank'] is not None)!=row['reference_scoreable_in_pool']:raise RuntimeError('Invalid rank/mask')
|
| 83 |
+
buffers.append(arr.tobytes());buffers.append(np.array(fs,dtype='<f4').tobytes());nfloat+=len(arr)+len(fs);rows.append(row)
|
| 84 |
+
raw=b''.join(buffers);assert len(raw)==4*nfloat
|
| 85 |
+
meta=dict(target=target,pool_order_hash=static,formula_names=forms,rows=rows,score_sha256=digest(raw))
|
| 86 |
+
return meta,raw
|
| 87 |
+
def dbpath(dataset):return rt.LEGACY.PREP/'validation.sqlite' if dataset=='validation' else engine.PREP/(dataset+'.sqlite')
|
| 88 |
+
def acceptance_validation(bind):
|
| 89 |
+
with lease('validation_preflight'):
|
| 90 |
+
model,_,_=make('D',split='validation',optimizer=False);model.graph_chunk=32;model.local_chunk=32;model.eval()
|
| 91 |
+
db=ro(dbpath('validation'));target=db.execute('SELECT DISTINCT target FROM spectra ORDER BY target LIMIT 1').fetchone()[0]
|
| 92 |
+
meta,raw=table(model,db,target,'validation')
|
| 93 |
+
source=R3/'R3D/validation_006000'/(digest(target.encode())+'.json.gz')
|
| 94 |
+
with gzip.open(source,'rt') as f:prior=json.load(f)
|
| 95 |
+
vals=np.frombuffer(raw,dtype='<f4');n=0;mx=0.
|
| 96 |
+
for row,old in zip(meta['rows'],prior['rows'],strict=True):
|
| 97 |
+
for k in ['identifier','view','rank','formula_rank','candidate_count','top1_smiles']:
|
| 98 |
+
if row[k]!=old[k]:raise RuntimeError('Frozen Validation parity mismatch: '+k)
|
| 99 |
+
v=row['view'];pool=json.loads(db.execute('SELECT body FROM pools WHERE target=? AND view=?',(target,v)).fetchone()[0])
|
| 100 |
+
expected={c['smiles']:c['score'] for c in prior['ranked'][row['identifier']+'/'+v]['candidates']}
|
| 101 |
+
actual=vals[row['float_offset']:row['float_offset']+len(pool)]
|
| 102 |
+
for s,x in zip(pool,actual):
|
| 103 |
+
if (expected[s] is None)!=bool(np.isnan(x)):raise RuntimeError('Scorability drift')
|
| 104 |
+
if expected[s] is not None:mx=max(mx,abs(expected[s]-float(x)));n+=1
|
| 105 |
+
if mx>1e-5 or not n:raise RuntimeError('Numerical validation parity mismatch: '+str(mx))
|
| 106 |
+
db.close();return dict(passed=True,targets=1,rows=len(meta['rows']),scored_comparisons=n,max_error=mx,checkpoint_sha=CFG['parent_sha256'])
|
| 107 |
+
def eval_dir(arm,update,dataset):return OUT/arm/('%s_%06d'%(dataset,update))
|
| 108 |
+
def run(arm,update,dataset):
|
| 109 |
+
dest=eval_dir(arm,update,dataset);hold=lock(dest/'eval.lock');bind=state_binding()
|
| 110 |
+
if dataset!='validation' and (update!=9000 or not (OUT/'FROZEN_TEST.json').exists()):raise RuntimeError('Test is not frozen')
|
| 111 |
+
ck=OUT/arm/('step_%06d.pt'%update);check=get(ck.with_suffix('.json'))
|
| 112 |
+
if check['sha256']!=filehash(ck):raise RuntimeError('Invalid evaluation checkpoint')
|
| 113 |
+
protocol=dict(dataset=dataset,arm=arm,update=update,checkpoint_sha=check['sha256'],binding_sha=objhash(bind),
|
| 114 |
+
encoding='Per target: float32 little-endian in source order; NaN means no score; formulas follow each structure block. No pruning or substitution.',
|
| 115 |
+
input_path=str(dbpath(dataset)),official_order_hash_per_target=True,
|
| 116 |
+
fixed_input=engine.inputs(dataset) if dataset!='validation' else rt.LEGACY.bind(),truth_injection=False,limit=None)
|
| 117 |
+
if (dest/'protocol.json').exists() and protocol!=get(dest/'protocol.json'):raise RuntimeError('Mixed evaluation binding')
|
| 118 |
+
put(dest/'protocol.json',protocol)
|
| 119 |
+
if (dest/'metrics.json').exists():return
|
| 120 |
+
EVAL.mkdir(parents=True,exist_ok=True)
|
| 121 |
+
compact=EVAL/arm/('%s_%06d.sqlite'%(dataset,update));compact.parent.mkdir(parents=True,exist_ok=True)
|
| 122 |
+
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')
|
| 123 |
+
out.execute('CREATE TABLE IF NOT EXISTS binding(hash TEXT PRIMARY KEY)')
|
| 124 |
+
oid=objhash(protocol);old=out.execute('SELECT hash FROM binding').fetchall()
|
| 125 |
+
if old and old!=[(oid,)]:raise ValueError('Stale compact predictions')
|
| 126 |
+
out.execute('INSERT OR IGNORE INTO binding VALUES(?)',(oid,));out.commit()
|
| 127 |
+
db=ro(dbpath(dataset));targets=[x[0] for x in db.execute('SELECT DISTINCT target FROM spectra ORDER BY target')]
|
| 128 |
+
done={k[0] for k in out.execute('SELECT target FROM predictions')};assert done<=set(targets)
|
| 129 |
+
with lease('eval_'+arm):
|
| 130 |
+
setup();model,_,_=make(arm,ck,split='validation' if dataset=='validation' else 'test',optimizer=False,expected_binding=bind);model.eval()
|
| 131 |
+
model.graph_chunk=32;model.local_chunk=32
|
| 132 |
+
for j,target in enumerate(targets):
|
| 133 |
+
if target in done:continue
|
| 134 |
+
if j%40==0 and shutil.disk_usage(compact.parent).free<75*2**20:raise RuntimeError('Compact output filesystem reserve; source unchanged')
|
| 135 |
+
meta,raw=table(model,db,target,dataset)
|
| 136 |
+
out.execute('INSERT INTO predictions VALUES(?,?,?)',(target,zlib.compress(json.dumps(meta,separators=(',',':'),allow_nan=False).encode(),3),zlib.compress(raw,3)))
|
| 137 |
+
if j%16==0:out.commit();put(dest/'status.json',dict(targets=j+1,total=len(targets),ts=time.time()))
|
| 138 |
+
out.commit()
|
| 139 |
+
rows=[]
|
| 140 |
+
for m,s in out.execute('SELECT meta,scores FROM predictions ORDER BY target'):
|
| 141 |
+
v=json.loads(zlib.decompress(m));raw=zlib.decompress(s)
|
| 142 |
+
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')
|
| 143 |
+
rows.extend(v['rows'])
|
| 144 |
+
out.execute('PRAGMA wal_checkpoint(TRUNCATE)');out.close();db.close()
|
| 145 |
+
expected={'msg_test':17556,'validation':19429,'casmi2022':500}[dataset];views=sorted({r['view'] for r in rows})
|
| 146 |
+
assert len(rows)==expected*len(views) and set(views)==({'top10_blind'} if dataset=='casmi2022' else {'mass','formula'})
|
| 147 |
+
if dataset=='casmi2022':assert sum(r['candidate_count'] for r in rows)==1765420 and sum(r['reference_in_pool'] for r in rows)==467
|
| 148 |
+
results={}
|
| 149 |
+
for v in views:
|
| 150 |
+
rr=[r for r in rows if r['view']==v];assert len(rr)==len({r['identifier'] for r in rr})==expected
|
| 151 |
+
results[v]=dict(n=expected,structure=metric(rr,'rank',KS),formula=metric(rr,'formula_rank',FKS),
|
| 152 |
+
coverage=sum(r['reference_in_pool'] for r in rr),scoreable=sum(r['reference_scoreable_in_pool'] for r in rr))
|
| 153 |
+
if dataset!='validation':
|
| 154 |
+
results[v].update(canonical=metric(rr,'canonical_rank',KS),full_inchikey=metric(rr,'inchikey_rank',KS))
|
| 155 |
+
tmp=dest/'rows.tmp.gz'
|
| 156 |
+
with gzip.open(tmp,'wt',compresslevel=4) as f:json.dump(rows,f,separators=(',',':'),allow_nan=False)
|
| 157 |
+
os.replace(tmp,dest/'per_spectrum_summary.json.gz')
|
| 158 |
+
put(dest/'metrics.json',dict(complete=True,results=results,checkpoint=check,compact=str(compact),compact_sha256=filehash(compact),ts=time.time()))
|
| 159 |
+
if __name__=='__main__':
|
| 160 |
+
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'])
|
| 161 |
+
a=ap.parse_args();run(a.arm,a.update,a.dataset)
|
code/snapshot/root/code/ceir_r4_9000_20261112/mces4.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Dedicated CPU environment; inherited validated MCES protocols, private caches only."""
|
| 2 |
+
import argparse,fcntl,importlib.util,json,os,sqlite3,sys
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
HERE=Path(__file__).resolve().parent;C=json.loads((HERE/'config.json').read_text())
|
| 5 |
+
OUT=Path(C['output']);R3=Path(C['r3_root'])
|
| 6 |
+
def load(name,p):
|
| 7 |
+
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
|
| 8 |
+
def copydb(src,dst):
|
| 9 |
+
if dst.exists():return
|
| 10 |
+
tmp=dst.with_suffix('.pending')
|
| 11 |
+
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)
|
| 12 |
+
def run(arm,u,dataset):
|
| 13 |
+
dest=OUT/arm/('%s_%06d'%(dataset,u))
|
| 14 |
+
cache=OUT/'mces_private';cache.mkdir(exist_ok=True);fd=(cache/'serial.lock').open('a+');fcntl.flock(fd,fcntl.LOCK_EX)
|
| 15 |
+
if (dest/'MCES.json').exists():return
|
| 16 |
+
if not (dest/'metrics.json').exists():raise RuntimeError('Missing full ranking result')
|
| 17 |
+
if dataset=='validation':
|
| 18 |
+
m=load('frozen_R4_val_mces',Path('/root/xj/SpecPartition-MS/code/ceir_r1_20261109/mces_ceir.py'))
|
| 19 |
+
m.OUT=OUT;m.CACHE=cache;copydb(R3/'mces_validation/Validation_mces_pairs.sqlite',cache/'Validation_mces_pairs.sqlite');m.evaluate(dest)
|
| 20 |
+
else:
|
| 21 |
+
m=load('frozen_R4_test_mces',Path('/root/xj/SpecPartition-MS/code/ceir_r1_test_comparison_20261110/mces.py'))
|
| 22 |
+
m.OUT=cache;m.old.OUT=cache/'mces';m.old.OUT.mkdir(exist_ok=True)
|
| 23 |
+
copydb(R3/'test/mces/pairs.sqlite',m.old.OUT/'pairs.sqlite')
|
| 24 |
+
db=m.initialize();m.compute(dest,db);db.close()
|
| 25 |
+
if __name__=='__main__':
|
| 26 |
+
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'])
|
| 27 |
+
a=p.parse_args();run(a.arm,a.update,a.dataset)
|
code/snapshot/root/code/ceir_r4_9000_20261112/model4.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Base R3D scores for every candidate, with optional bounded pair evidence."""
|
| 2 |
+
import gc
|
| 3 |
+
import numpy as np
|
| 4 |
+
import torch
|
| 5 |
+
from torch.nn import functional as F
|
| 6 |
+
from common4 import *
|
| 7 |
+
from data4 import Fragments
|
| 8 |
+
from model_r2_new import R2Ranker
|
| 9 |
+
from duel4 import CandidateDuels
|
| 10 |
+
|
| 11 |
+
def setup():
|
| 12 |
+
torch.set_num_threads(1);torch.set_float32_matmul_precision('high');torch.use_deterministic_algorithms(True)
|
| 13 |
+
torch.cuda.set_per_process_memory_fraction(CFG['gpu_fraction']);rt.LEGACY.seed_all(CFG['seed'])
|
| 14 |
+
|
| 15 |
+
def true_peak_support(assets,query,peak_tokens,max_peaks):
|
| 16 |
+
raw=sorted(sorted(query.peaks,key=lambda p:(-p[1],p[0]))[:max_peaks])
|
| 17 |
+
if len(raw)!=len(peak_tokens) or max_peaks!=256:raise ValueError('R4 token to original peak alignment mismatch')
|
| 18 |
+
dev=peak_tokens.device
|
| 19 |
+
p=torch.as_tensor(raw,dtype=torch.float32,device=dev)
|
| 20 |
+
mz=p[:,0].contiguous();y=p[:,1].clamp_min(0)
|
| 21 |
+
y=y.masked_fill((mz-query.precursor_mz).abs()<=max(.05,query.precursor_mz*20e-6),0)
|
| 22 |
+
offsets=[v for v in ft.ion_offsets(query.adduct) if v is not None]
|
| 23 |
+
if not offsets:return mz.new_zeros((len(assets),len(mz))),y
|
| 24 |
+
to=lambda k:torch.as_tensor(np.stack([a[k] for a in assets]),device=dev)
|
| 25 |
+
m=to('masses').float();h=to('hydrogens');valid=to('valid').bool();shift=m.new_tensor([-2,-1,0,1,2])
|
| 26 |
+
f=m[:,:,None,None]+shift[None,None,:,None]*ft.H+m.new_tensor(offsets)[None,None,None,:]
|
| 27 |
+
mask=valid[:,:,None,None]&(h[:,:,None,None]+shift[None,None,:,None]>=0)&f.gt(0)
|
| 28 |
+
ordered=f.masked_fill(~mask,float('inf')).flatten(1).sort(1).values.contiguous()
|
| 29 |
+
grid=mz[None,:].expand(len(assets),-1).contiguous()
|
| 30 |
+
j=torch.searchsorted(ordered,grid);ix=j.clamp(max=ordered.shape[1]-1);ix2=(j-1).clamp(min=0,max=ordered.shape[1]-1)
|
| 31 |
+
def matched(idx):
|
| 32 |
+
x=ordered.gather(1,idx)
|
| 33 |
+
return x.isfinite() & ((grid-x).abs()<=torch.maximum(.00002*x,mz.new_tensor(.02)))
|
| 34 |
+
return ((matched(ix)|matched(ix2))&(y>0)).float(),y
|
| 35 |
+
|
| 36 |
+
class Model(R2Ranker):
|
| 37 |
+
def __init__(self,arm):
|
| 38 |
+
super().__init__(rt.LEGACY.C,'R3D') # always execute all inherited R3D branches and losses
|
| 39 |
+
self.r4_arm=arm;self.has_duel=CFG['arms'][arm]['duel'];self._trace=None
|
| 40 |
+
if self.has_duel:
|
| 41 |
+
self.r4=CandidateDuels(256,256,CFG['duel']['hidden'],CFG['duel']['n'],CFG['duel']['cap'])
|
| 42 |
+
def install_store(self,split,provisional=False):
|
| 43 |
+
self.feature_store=Fragments(split,prep_root()/'delta.sqlite' if split=='train' and not provisional else None)
|
| 44 |
+
def encode_batch(self,queries,extras=()):
|
| 45 |
+
self._trace=[]
|
| 46 |
+
try:
|
| 47 |
+
encs,u=super().encode_batch(queries,extras)
|
| 48 |
+
for enc,(base,info) in zip(encs,self._trace,strict=True):
|
| 49 |
+
enc.r4_base=base;enc.r4_info=info
|
| 50 |
+
return encs,u
|
| 51 |
+
finally:self._trace=None
|
| 52 |
+
def score_encoded(self,q,peaks,query,mols,atoms,zm,formula_scores,context=None,return_aux=False):
|
| 53 |
+
orig=super().score_encoded(q,peaks,query,mols,atoms,zm,formula_scores,context,return_aux)
|
| 54 |
+
base=orig[0];final=base;info=None
|
| 55 |
+
if self.has_duel and len(mols)>1:
|
| 56 |
+
# Choose the best base-scored representative per identity. Exact ties
|
| 57 |
+
# use stable structure/SMILES content. All original aliases retain
|
| 58 |
+
# their scores and receive the same identity-level residual.
|
| 59 |
+
ids=[m.identity for m in mols];forms=[m.formula for m in mols]
|
| 60 |
+
if not all(ids):raise ValueError('Scoreable graph without structure identity')
|
| 61 |
+
base_np=base.detach().float().cpu().numpy()
|
| 62 |
+
reps={}
|
| 63 |
+
for j,k in enumerate(ids):
|
| 64 |
+
old=reps.get(k)
|
| 65 |
+
if old is None or (-base_np[j],mols[j].smiles)<(-base_np[old],mols[old].smiles):reps[k]=j
|
| 66 |
+
if old is not None and forms[old]!=forms[j]:raise ValueError('Aliased identity with conflicting formula')
|
| 67 |
+
chosen=sorted(reps.values(),key=lambda i:(-base_np[i],ids[i]))[:CFG['duel']['n']]
|
| 68 |
+
selected=[mols[i] for i in chosen];fs=sorted({m.formula for m in selected})
|
| 69 |
+
fi=torch.tensor([fs.index(m.formula) for m in selected],device=q.device)
|
| 70 |
+
ii=torch.tensor(chosen,device=q.device)
|
| 71 |
+
si={v:i for i,v in enumerate(sorted(m.identity for m in selected))}
|
| 72 |
+
stable=torch.tensor([si[m.identity] for m in selected],device=q.device)
|
| 73 |
+
assets=[self.feature(m) for m in selected]
|
| 74 |
+
with torch.no_grad():support,y=true_peak_support(assets,query,peaks,self.spectrum.max_peaks)
|
| 75 |
+
with torch.autocast(q.device.type,enabled=False):
|
| 76 |
+
loc=self.r4(base[ii].float(),q.float(),zm[ii].float(),fi,stable,support,y,peaks.float())
|
| 77 |
+
delta=loc-base[ii].float()
|
| 78 |
+
if len(reps)==len(mols):
|
| 79 |
+
final=base.float().index_add(0,ii,delta)
|
| 80 |
+
else:
|
| 81 |
+
positions={m.identity:i for i,m in enumerate(selected)};n=len(chosen)
|
| 82 |
+
mapping=torch.tensor([positions.get(x,n) for x in ids],device=q.device);final=base.float()+F.pad(delta,(0,1))[mapping]
|
| 83 |
+
if self._trace is not None:info=(delta.abs().mean().detach(),len(chosen))
|
| 84 |
+
if self._trace is not None:self._trace.append((base.detach(),info))
|
| 85 |
+
return (final,*orig[1:])
|
| 86 |
+
|
| 87 |
+
def make(arm,path=None,split='train',provisional=False,optimizer=True,expected_binding=None):
|
| 88 |
+
if arm not in CFG['arms']:raise ValueError(arm)
|
| 89 |
+
state=parent() if path is None else torch.load(path,map_location='cpu',weights_only=False)
|
| 90 |
+
if path is not None and (state.get('architecture')!='CEIR_R4' or state['arm']!=arm or
|
| 91 |
+
(expected_binding is not None and state['binding']!=expected_binding)):raise RuntimeError('Wrong R4 resume binding')
|
| 92 |
+
torch.manual_seed(CFG['seed']);model=Model(arm)
|
| 93 |
+
keys=model.load_state_dict(state['model'],strict=path is not None)
|
| 94 |
+
if keys.unexpected_keys or any(not k.startswith('r4.') for k in keys.missing_keys):raise RuntimeError('Unmatched parent parameters')
|
| 95 |
+
model.to('cuda');model.install_store(split,provisional)
|
| 96 |
+
progress=dict(state['progress'])
|
| 97 |
+
if path is None:progress.update(new_updates=0,r4_exposures={},r4_chain='',r4_validated=[])
|
| 98 |
+
if not optimizer:
|
| 99 |
+
model.eval();return model,None,progress
|
| 100 |
+
groups=[[],[],[],[]]
|
| 101 |
+
for name,p in model.named_parameters():
|
| 102 |
+
g=3 if name.startswith('r4.') else 2 if name.startswith('r3.') else 1 if name.startswith('r2.') else 0
|
| 103 |
+
groups[g].append(p)
|
| 104 |
+
old=state['optimizer']['param_groups']
|
| 105 |
+
if [len(g['params']) for g in old[:3]]!=[len(g) for g in groups[:3]]:raise RuntimeError('Optimizer ordering mismatch')
|
| 106 |
+
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'])
|
| 107 |
+
if path is None:
|
| 108 |
+
opt.load_state_dict(state['optimizer'])
|
| 109 |
+
if groups[3]:opt.add_param_group(dict(params=groups[3],lr=CFG['learning_rate']['new_head']))
|
| 110 |
+
else:
|
| 111 |
+
if groups[3]:opt.add_param_group(dict(params=groups[3],lr=CFG['learning_rate']['new_head']))
|
| 112 |
+
opt.load_state_dict(state['optimizer'])
|
| 113 |
+
for p,st in opt.state.items():
|
| 114 |
+
for k,v in st.items():
|
| 115 |
+
if torch.is_tensor(v) and k!='step':st[k]=v.to(p.device)
|
| 116 |
+
rt.restore_rng(state)
|
| 117 |
+
return model,opt,progress
|
code/snapshot/root/code/ceir_r4_9000_20261112/objectives4.py
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Exact C03 active objectives, plus qualified chemistry / spectrum supervision."""
|
| 2 |
+
from collections import Counter
|
| 3 |
+
import time
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
from torch.nn import functional as F
|
| 7 |
+
from torch.utils.checkpoint import checkpoint as recompute
|
| 8 |
+
from common4 import CFG,rt
|
| 9 |
+
from runtime_r2 import *
|
| 10 |
+
from kernels import grouped_contrastive,formula_objective
|
| 11 |
+
from losses import ms_ms_supcon,molecule_molecule_two_view
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def molecular_views(model,mols,probability):
|
| 15 |
+
# Reinstate the dropout hook during activation recomputation. The original
|
| 16 |
+
# implementation removed it before backward; fix identically in all arms.
|
| 17 |
+
def one(dummy):
|
| 18 |
+
threshold=model.activation_checkpoint_atom_threshold
|
| 19 |
+
model.activation_checkpoint_atom_threshold=10**12
|
| 20 |
+
handle=model.graph.atom.register_forward_hook(lambda module,inputs,output:F.dropout(output,p=probability,training=True))
|
| 21 |
+
try:
|
| 22 |
+
with amp():return model.encode_molecules(mols)[0].float()
|
| 23 |
+
finally:handle.remove();model.activation_checkpoint_atom_threshold=threshold
|
| 24 |
+
return (recompute(one,model.graph.atom.weight,use_reentrant=False,preserve_rng_state=True),
|
| 25 |
+
recompute(one,model.graph.atom.weight,use_reentrant=False,preserve_rng_state=True))
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def auxiliary_loss(model,q,mols,rows,spec,step):
|
| 29 |
+
weights=spec['loss']['auxiliary']
|
| 30 |
+
if any(v for k,v in weights.items() if k not in ('ms_fine','mol_fine')):
|
| 31 |
+
raise RuntimeError('This release matches C03 fine-only auxiliaries; other arms require a separate release')
|
| 32 |
+
ids=[r['identity'] for r in rows];rids=[r['record_id'] for r in rows];head=model.hierarchy
|
| 33 |
+
v1,v2=molecular_views(model,mols,spec['views']['molecule']['dropout'])
|
| 34 |
+
temperature=spec['loss']['temperature']['identity'];ramp=min(1.,(step+1)/spec['loss']['auxiliary_ramp_steps'])
|
| 35 |
+
ms=ms_ms_supcon(head('ms_identity',q),ids,rids,temperature)
|
| 36 |
+
mol=molecule_molecule_two_view(head('mol_identity',v1),head('mol_identity',v2),[m.identity for m in mols],temperature)
|
| 37 |
+
total=ramp*(weights['ms_fine']*ms.loss+weights['mol_fine']*mol.loss)
|
| 38 |
+
# The original zero-weight coarse graphs produced zero (not None) grads.
|
| 39 |
+
# Preserve AdamW decay/moment semantics for those registered unused heads.
|
| 40 |
+
for name in ('ms_formula','mol_formula','ms_mass','mol_mass'):
|
| 41 |
+
total=total+sum(p.sum()*0. for p in head.heads[name].parameters())
|
| 42 |
+
out=dict(ms_fine_raw=ms.loss.detach(),mol_fine_raw=mol.loss.detach(),auxiliary_total=total.detach(),auxiliary_ramp=ramp,
|
| 43 |
+
molecule_view_mean_abs_difference=(v1.detach()-v2.detach()).abs().mean())
|
| 44 |
+
for name,item in [('ms_fine',ms),('mol_fine',mol)]:
|
| 45 |
+
for k,v in item.diagnostics.items():out[name+'_'+k]=v.detach() if torch.is_tensor(v) else v
|
| 46 |
+
return total,out
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def chemical_loss(model,q,rows):
|
| 50 |
+
if model.arm not in C['arms']:return q.sum()*0.
|
| 51 |
+
counts=torch.as_tensor(np.stack([r['chemical_counts'] for r in rows]),device=q.device,dtype=torch.long)
|
| 52 |
+
logp=model.r2.count_log_prob(q)
|
| 53 |
+
losses=-logp.gather(-1,counts[:,:,None]).squeeze(-1).mean(-1)
|
| 54 |
+
ids=[r['identity'] for r in rows];occurrences=Counter(ids)
|
| 55 |
+
w=q.new_tensor([1/occurrences[k]/len(occurrences) for k in ids])
|
| 56 |
+
return (losses*w).sum()
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def train_step(model,opt,batch,update,apply_update=True):
|
| 60 |
+
model.collect_score_diagnostics=True;model.score_diagnostics=[]
|
| 61 |
+
started=time.monotonic();rows=batch['rows'];queries=[r['query'] for r in rows];ids=[r['identity'] for r in rows]
|
| 62 |
+
reps={}
|
| 63 |
+
for r in rows:
|
| 64 |
+
if r['identity'] not in reps or r['ref'].smiles<reps[r['identity']].smiles:reps[r['identity']]=r['ref']
|
| 65 |
+
columns=sorted(reps);mols=[reps[k] for k in columns];w=LEGACY.C['loss_weights'];opt.zero_grad(set_to_none=True)
|
| 66 |
+
sc=LEGACY.C['spectrum_chunk'];gc=LEGACY.C['graph_chunk']
|
| 67 |
+
with torch.no_grad(),amp():
|
| 68 |
+
qc=torch.cat([model.spectrum.forward_batch(queries[a:a+sc])[1] for a in range(0,len(rows),sc)])
|
| 69 |
+
mc=torch.cat([model.encode_molecules(mols[a:a+gc])[0] for a in range(0,len(mols),gc)])
|
| 70 |
+
qc=qc.float().detach().requires_grad_();mc=mc.float().detach().requires_grad_()
|
| 71 |
+
with amp():
|
| 72 |
+
zq=F.normalize(model.query_projection(qc).float(),dim=-1);zm=F.normalize(model.mol_projection(mc).float(),dim=-1)
|
| 73 |
+
f,b=grouped_contrastive(zq@zm.T/LEGACY.C['contrastive_temperature'],ids,columns)
|
| 74 |
+
base=w['inbatch_ms_to_mol']*f+w['inbatch_mol_to_ms']*b
|
| 75 |
+
# Match the parent's FP32 auxiliary invocation, not R1's outer autocast.
|
| 76 |
+
auxiliary,details=auxiliary_loss(model,qc,mols,rows,SPEC,update)
|
| 77 |
+
chem=chemical_loss(model,qc,rows)
|
| 78 |
+
ramp=min(1.,(update-C['source_update']+1)/C['lr_ramp_updates'])
|
| 79 |
+
# A3 auxiliaries are already trained: retain their full weights, not a
|
| 80 |
+
# second accidental warm-up. New heads use final pool CE, not duplicate CE.
|
| 81 |
+
cw=C['chem_weight'];sw=C['spectrum_weight']
|
| 82 |
+
(base+auxiliary+cw*chem).backward();dq=qc.grad.detach();dm=mc.grad.detach()
|
| 83 |
+
metrics=dict(inbatch_ms_to_mol=f.detach(),inbatch_mol_to_ms=b.detach(),formula_loss=0.,formula_ce=0.,formula_gap=0.,element_ce=0.,formula_correct=0.,
|
| 84 |
+
chemical_loss=chem.detach(),chemical_weight=cw,spectrum_weight=sw)
|
| 85 |
+
valid=sum(r['mass_ok'] and len(r['formulas'])>1 and r['formula'] in r['formulas'] for r in rows)
|
| 86 |
+
for a in range(0,len(rows),sc):
|
| 87 |
+
block=rows[a:a+sc]
|
| 88 |
+
with amp():
|
| 89 |
+
tokens,q,_=model.spectrum.forward_batch([r['query'] for r in block])
|
| 90 |
+
lf,d=formula_objective(model,q,tokens,block,valid,len(rows))
|
| 91 |
+
loss=(q*dq[a:a+len(block)]).sum()+w['formula']*lf
|
| 92 |
+
loss.backward();metrics['formula_loss']+=lf.detach()
|
| 93 |
+
for k in ('formula_ce','formula_gap','element_ce','formula_correct'):metrics[k]+=d[k]
|
| 94 |
+
for a in range(0,len(mols),gc):
|
| 95 |
+
with amp():u=model.encode_molecules(mols[a:a+gc])[0];surrogate=(u*dm[a:a+len(u)]).sum()
|
| 96 |
+
surrogate.backward()
|
| 97 |
+
pools=[p for r in rows for p in r['pools']];counts=Counter(p['kind'] for p in pools)
|
| 98 |
+
pm={k:qc.new_zeros(()) for k in ('odata','mass','formula')};spec_total=qc.new_zeros(())
|
| 99 |
+
supervised={p['record_id'] for p in pools if p['spectrum_eligible']};seen=set();used=0
|
| 100 |
+
gap_total=qc.new_zeros(());delta_total=qc.new_zeros(());delta_n=0
|
| 101 |
+
def same_negatives(p):
|
| 102 |
+
if not p['quality_eligible']:return []
|
| 103 |
+
truth=p['truth_identity'];f=p['query'].candidates[p['positive_index']].formula
|
| 104 |
+
return [i for i,m in enumerate(p['query'].candidates) if m.identity!=truth and m.formula==f]
|
| 105 |
+
gap_eligible=sum(bool(same_negatives(p)) for p in pools);gap_on=CFG['arms'][model.r4_arm]['gap']
|
| 106 |
+
for a in range(0,len(pools),LEGACY.C['pool_micro_views']):
|
| 107 |
+
block=pools[a:a+LEGACY.C['pool_micro_views']]
|
| 108 |
+
with amp():
|
| 109 |
+
encs,_=model.encode_batch([p['query'] for p in block]);loss=encs[0].q.sum()*0.
|
| 110 |
+
for p,enc in zip(block,encs):
|
| 111 |
+
ce=enc.base.float().logsumexp(0)-enc.base[p['positive_index']].float();kind=p['kind']
|
| 112 |
+
pm[kind]+=ce.detach()/counts[kind]
|
| 113 |
+
loss+=w[{'odata':'odata_pool','mass':'msg_mass_pool','formula':'msg_formula_pool'}[kind]]*ce/counts[kind]
|
| 114 |
+
if gap_on:
|
| 115 |
+
jj=same_negatives(p)
|
| 116 |
+
if jj:
|
| 117 |
+
ix=torch.tensor(jj,device=enc.base.device);mining_scores=enc.r4_base.float()
|
| 118 |
+
# The draw ledger already has unique key14; choose top
|
| 119 |
+
# errors by detached, pre-duel scores. Stable chemical
|
| 120 |
+
# tie-breaks, never use stored candidate position.
|
| 121 |
+
ss=sorted(range(len(jj)),key=lambda i:p['query'].candidates[jj[i]].identity)
|
| 122 |
+
ix=ix[torch.tensor(ss,device=ix.device)]
|
| 123 |
+
hard=ix[mining_scores[ix].argsort(descending=True,stable=True)[:CFG['gap']['hard_k']]]
|
| 124 |
+
gap=F.softplus(CFG['gap']['margin']+enc.base[hard].float()-enc.base[p['positive_index']].float()).mean()/gap_eligible
|
| 125 |
+
loss+=CFG['gap']['weight']*gap;gap_total+=gap.detach()
|
| 126 |
+
if enc.r4_info is not None:
|
| 127 |
+
delta_total+=enc.r4_info[0];delta_n+=1
|
| 128 |
+
if p['spectrum_eligible'] and p['record_id'] not in seen:
|
| 129 |
+
if enc.r2_spectrum is None:raise RuntimeError('Qualified spectrum has no fragment predictions')
|
| 130 |
+
spec,usable=enc.r2_spectrum
|
| 131 |
+
if not bool(usable[p['positive_index']]):raise RuntimeError('CPU / GPU fragment eligibility disagrees')
|
| 132 |
+
sl=spec[p['positive_index']]/max(1,len(supervised));loss+=sw*sl;spec_total+=sl.detach()
|
| 133 |
+
seen.add(p['record_id']);used+=1
|
| 134 |
+
loss.backward()
|
| 135 |
+
total=base.detach()+auxiliary.detach()+cw*chem.detach()+sw*spec_total+w['formula']*metrics['formula_loss']
|
| 136 |
+
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
|
| 137 |
+
total=total+CFG['gap']['weight']*gap_total
|
| 138 |
+
metrics.update(details);metrics.update(spectrum_loss=spec_total,loss=total,r4_gap_loss=gap_total,
|
| 139 |
+
r4_gap_eligible=gap_eligible,r4_duel_residual=delta_total/max(1,delta_n),r4_duel_pools=delta_n)
|
| 140 |
+
if not torch.isfinite(total):raise RuntimeError('Nonfinite R2 objective')
|
| 141 |
+
for name,parameters in [('backbone',[p for n,p in model.named_parameters() if not n.startswith(('r2.','r3.'))]),
|
| 142 |
+
('chemical',model.r2.counts.parameters()),('fragment',[p for n,p in model.r2.named_parameters() if not n.startswith('counts.') and n!='chemical_scale']),
|
| 143 |
+
('r3',model.r3.parameters()),('r4',[p for n,p in model.named_parameters() if n.startswith('r4.')])]:
|
| 144 |
+
gs=[p.grad.detach().float().square().sum() for p in parameters if p.grad is not None]
|
| 145 |
+
metrics[name+'_gradient_norm']=torch.stack(gs).sum().sqrt() if gs else total*0.
|
| 146 |
+
norm=torch.nn.utils.clip_grad_norm_(model.parameters(),LEGACY.C['gradient_clip'],error_if_nonfinite=True)
|
| 147 |
+
metrics['gradient_norm']=norm.detach()
|
| 148 |
+
for name in ('formula_prior_abs','parent_structural_std','topology_abs','difference_abs','formula_calibration_abs','final_score_std'):
|
| 149 |
+
values=[r[name] for r in model.score_diagnostics if name in r]
|
| 150 |
+
metrics['score_'+name]=torch.stack(values).mean() if values else total*0.
|
| 151 |
+
metrics['formula_calibration_alpha']=.5*model.r3.formula_alpha.detach().tanh()
|
| 152 |
+
model.collect_score_diagnostics=False;model.score_diagnostics=[]
|
| 153 |
+
if apply_update:opt.step()
|
| 154 |
+
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()
|
| 155 |
+
result=dict(zip(metrics,packed));result.update(queries=len(rows),unique_connectivity=len(columns),formula_valid=valid,
|
| 156 |
+
pool_valid=dict(counts),spectrum_valid=used,chemical_valid=len(rows) if cw else 0,
|
| 157 |
+
source_counts=dict(Counter(r['source'] for r in rows)),negative_draws=sum(p['negative_draws'] for p in pools),
|
| 158 |
+
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}),
|
| 159 |
+
molecular_encoder_views=2,zero_weight_coarse_auxiliaries='not_computed',data_seconds=batch['data_seconds'],
|
| 160 |
+
step_compute_seconds=time.monotonic()-started,peak_allocated_mib=torch.cuda.max_memory_allocated()/2**20)
|
| 161 |
+
return result
|
code/snapshot/root/code/ceir_r4_9000_20261112/pipeline.supervisor.conf
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[program:specpartition-r4-9000-pipeline-20261112]
|
| 2 |
+
directory=/root/xj/SpecPartition-MS/code/ceir_r4_9000_20261112
|
| 3 |
+
command=/usr/bin/nice -n 12 /workspace/xj/SpecPartition-MS/.venv/bin/python -B -u pipeline4.py
|
| 4 |
+
environment=PYTHONUNBUFFERED="1",OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1",CUBLAS_WORKSPACE_CONFIG=":4096:8"
|
| 5 |
+
autostart=true
|
| 6 |
+
autorestart=unexpected
|
| 7 |
+
exitcodes=0,2
|
| 8 |
+
startsecs=2
|
| 9 |
+
stopasgroup=true
|
| 10 |
+
killasgroup=true
|
| 11 |
+
stdout_logfile=/root/xj/SpecPartition-MS/runs/ceir_r4_9000_20261112/pipeline.log
|
| 12 |
+
stdout_logfile_maxbytes=20MB
|
| 13 |
+
redirect_stderr=true
|
code/snapshot/root/code/ceir_r4_9000_20261112/pipeline4.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Managed queue. All four get a real starting block, then alternate two GPU slots.
|
| 2 |
+
Statistical failures/flat metrics are results, not an excuse to train on Test.
|
| 3 |
+
"""
|
| 4 |
+
import concurrent.futures as cf,subprocess,traceback
|
| 5 |
+
from common4 import *
|
| 6 |
+
PY='/workspace/xj/SpecPartition-MS/.venv/bin/python'
|
| 7 |
+
MP='/root/xj/SpecPartition-MS/evaluations/mces_all_20261106/.venv/bin/python'
|
| 8 |
+
ORDER=('A','C','B','D')
|
| 9 |
+
def launch(name,script,*args,cpu=False):
|
| 10 |
+
logs=OUT/'logs';logs.mkdir(exist_ok=True)
|
| 11 |
+
for i in range(3):
|
| 12 |
+
with (logs/(name+'.log')).open('a') as f:
|
| 13 |
+
p=subprocess.Popen([MP if cpu else PY,'-B','-u',str(HERE/script),*map(str,args)],cwd=HERE,stdout=f,stderr=subprocess.STDOUT,
|
| 14 |
+
env={**os.environ,'OMP_NUM_THREADS':'1','OPENBLAS_NUM_THREADS':'1','MKL_NUM_THREADS':'1','CUBLAS_WORKSPACE_CONFIG':':4096:8'})
|
| 15 |
+
event(OUT/'pipeline_events.jsonl',dict(event='start',job=name,pid=p.pid,attempt=i+1));rc=p.wait()
|
| 16 |
+
event(OUT/'pipeline_events.jsonl',dict(event='exit',job=name,returncode=rc))
|
| 17 |
+
if rc==0:return
|
| 18 |
+
if i<2:time.sleep(8*(i+1))
|
| 19 |
+
raise RuntimeError('R4 job failed after bounded retries: '+name)
|
| 20 |
+
def jobs(items,limit=2):
|
| 21 |
+
with cf.ThreadPoolExecutor(max_workers=limit) as ex:
|
| 22 |
+
fs=[ex.submit(launch,*s) for s in items]
|
| 23 |
+
for f in cf.as_completed(fs):f.result()
|
| 24 |
+
def status(phase,**kw):put(OUT/'PIPELINE_STATUS.json',dict(phase=phase,ts=time.time(),**kw))
|
| 25 |
+
def main():
|
| 26 |
+
held=lock(OUT/'pipeline.lock')
|
| 27 |
+
if (OUT/'ALL_RESULTS.json').exists():status('completed');return
|
| 28 |
+
while not (prep_root()/'READY.json').is_file():
|
| 29 |
+
status('waiting_for_offline_preparation')
|
| 30 |
+
if (OUT/'PREP_FAILURE.json').is_file():raise RuntimeError('Preparation failed; no formal updates')
|
| 31 |
+
# On a cold restart tmpfs needs rebuilding. Do not duplicate a live coordinator.
|
| 32 |
+
state=subprocess.run(['supervisorctl','status','specpartition-r4-9000-prepare-20261112'],capture_output=True,text=True).stdout
|
| 33 |
+
if 'RUNNING' not in state and 'STARTING' not in state:
|
| 34 |
+
subprocess.run(['supervisorctl','start','specpartition-r4-9000-prepare-20261112'],check=True)
|
| 35 |
+
time.sleep(8)
|
| 36 |
+
if not (OUT/'TRAIN_READY.json').exists():status('real_GPU_acceptance');launch('formal_gpu_acceptance','accept4.py')
|
| 37 |
+
if get(OUT/'TRAIN_READY.json')['binding']!=state_binding():raise RuntimeError('Accepted code/data drift')
|
| 38 |
+
from report4 import val,freeze,final
|
| 39 |
+
# CPU MCES overlaps later training without taking a GPU slot.
|
| 40 |
+
with cf.ThreadPoolExecutor(max_workers=1) as cpu:
|
| 41 |
+
cpu_jobs=[]
|
| 42 |
+
for u in [6004,6250,6500,6750,7000,7250,7500,7750,8000,8250,8500,8750,9000]:
|
| 43 |
+
work=[]
|
| 44 |
+
for a in ORDER:
|
| 45 |
+
pointer=OUT/a/'resume/LAST.json'
|
| 46 |
+
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
|
| 47 |
+
work.append((a+'_train_'+str(u),'run4.py',a,u))
|
| 48 |
+
if work:status('training',round_end=u,queue=[w[0] for w in work]);jobs(work)
|
| 49 |
+
if u not in CFG['checkpoints']:continue
|
| 50 |
+
work=[(a+'_validation_'+str(u),'eval4.py',a,u,'validation') for a in ORDER if not (OUT/a/('validation_%06d/metrics.json'%u)).exists()]
|
| 51 |
+
if work:status('full_validation',update=u,queue=[w[0] for w in work]);jobs(work)
|
| 52 |
+
val(u)
|
| 53 |
+
for a in ORDER:
|
| 54 |
+
if not (OUT/a/('validation_%06d/MCES.json'%u)).exists():
|
| 55 |
+
cpu_jobs.append(cpu.submit(launch,a+'_MCES_validation_'+str(u),'mces4.py',a,u,'validation',cpu=True))
|
| 56 |
+
freeze()
|
| 57 |
+
for d in ('msg_test','casmi2022'):
|
| 58 |
+
status('fixed_endpoint_test',dataset=d)
|
| 59 |
+
work=[(a+'_'+d,'eval4.py',a,9000,d) for a in ORDER if not (OUT/a/(d+'_009000/metrics.json')).exists()]
|
| 60 |
+
jobs(work)
|
| 61 |
+
for a in ORDER:
|
| 62 |
+
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))
|
| 63 |
+
status('posthoc_cpu_MCES')
|
| 64 |
+
for f in cpu_jobs:f.result()
|
| 65 |
+
final();status('completed',actual_updates={a:3000 for a in ORDER})
|
| 66 |
+
if __name__=='__main__':
|
| 67 |
+
try:main()
|
| 68 |
+
except Exception:
|
| 69 |
+
put(OUT/'PIPELINE_ERROR.json',dict(error=traceback.format_exc(),ts=time.time()));status('blocked_check_logs');sys.exit(2)
|
code/snapshot/root/code/ceir_r4_9000_20261112/prep.supervisor.conf
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[program:specpartition-r4-9000-prepare-20261112]
|
| 2 |
+
directory=/root/xj/SpecPartition-MS/code/ceir_r4_9000_20261112
|
| 3 |
+
command=/usr/bin/nice -n 12 /workspace/xj/SpecPartition-MS/.venv/bin/python -B -u prepare4.py
|
| 4 |
+
environment=PYTHONUNBUFFERED="1",OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1",CUDA_VISIBLE_DEVICES=""
|
| 5 |
+
autostart=false
|
| 6 |
+
autorestart=false
|
| 7 |
+
startsecs=1
|
| 8 |
+
stopasgroup=true
|
| 9 |
+
killasgroup=true
|
| 10 |
+
stdout_logfile=/root/xj/SpecPartition-MS/runs/ceir_r4_9000_20261112/prep.log
|
| 11 |
+
stdout_logfile_maxbytes=20MB
|
| 12 |
+
redirect_stderr=true
|
code/snapshot/root/code/ceir_r4_9000_20261112/prepare4.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Rebuildable offline ledger for *next* 3000 updates, plus missing train-only fragments.
|
| 2 |
+
Physical batches/pools are not replaced by the previous R3 3000-step ledger.
|
| 3 |
+
"""
|
| 4 |
+
import collections,random,concurrent.futures as futures,multiprocessing as mp
|
| 5 |
+
from functools import lru_cache
|
| 6 |
+
from common4 import *
|
| 7 |
+
from data09 import Reader,loads
|
| 8 |
+
from sampling import epoch_plans,plan_hash
|
| 9 |
+
from prepare_ceir import entry_identity
|
| 10 |
+
START=6000; N=3000
|
| 11 |
+
def init():
|
| 12 |
+
global reader,lookup,fragments
|
| 13 |
+
reader=Reader()
|
| 14 |
+
@lru_cache(65536)
|
| 15 |
+
def alias(s):
|
| 16 |
+
row=reader.assets.execute('SELECT graph_hash FROM smiles WHERE smiles=?',(s,)).fetchone()
|
| 17 |
+
if not row:raise RuntimeError('Unmapped training alias')
|
| 18 |
+
return row[0]
|
| 19 |
+
lookup=alias
|
| 20 |
+
fragments=[ro(R2/'prepared/assets.sqlite'),ro(R3/'prepared/assets.sqlite')]
|
| 21 |
+
def batchfile(i):return prep_root()/'batches'/('%04d.z'%i)
|
| 22 |
+
def make_batch(task):
|
| 23 |
+
idx,(epoch,step,groups)=task;path=batchfile(idx)
|
| 24 |
+
if path.is_file():return idx
|
| 25 |
+
rows=[]
|
| 26 |
+
for source,rids in groups.items():
|
| 27 |
+
for j,rid in enumerate(rids):
|
| 28 |
+
r=loads(reader.db.execute('SELECT body FROM samples WHERE record_id=?',(rid,)).fetchone()[0])
|
| 29 |
+
if r['identity'] in reader.forbidden:raise RuntimeError('Heldout label')
|
| 30 |
+
seed=CFG['seed']+epoch*100000000+step*10000+j+(1000000 if source=='msg' else 0);rng=random.Random(seed)
|
| 31 |
+
msg=r['source']=='MSG_Train'; kinds=('mass','formula') if msg else (('odata',) if source=='odata' and j<16 else ())
|
| 32 |
+
forms=tuple(reader.official(r['target'],'mass')['formula_classes']) if msg else tuple(r['view']['formulas'])
|
| 33 |
+
pools=[]
|
| 34 |
+
for kind in kinds:
|
| 35 |
+
if kind=='odata':
|
| 36 |
+
v=r['view'];pool=reader.pool(v['pool_path'],v['pool_sha256']);entries=pool['records']
|
| 37 |
+
allowed=pool['safe_mass_order'][v['mass_order_start']:v['mass_order_stop']]
|
| 38 |
+
else:
|
| 39 |
+
pool=reader.official(r['target'],kind);entries=pool['entries'];allowed=[i for i,e in enumerate(entries) if e['eligible_for_training']]
|
| 40 |
+
pos=[];neg={}
|
| 41 |
+
for i in allowed:
|
| 42 |
+
key=entry_identity(entries[i])
|
| 43 |
+
if key==r['identity']:pos.append(i)
|
| 44 |
+
else:neg.setdefault(key,[]).append(i)
|
| 45 |
+
if not pos or not neg:continue
|
| 46 |
+
rr=random.Random(seed) if kind=='odata' else rng
|
| 47 |
+
positive=rr.choice(pos);budget=rt.LEGACY.C['odata_negative_draws' if kind=='odata' else 'msg_negative_draws']
|
| 48 |
+
keys=rr.sample(sorted(neg),min(budget,len(neg)))
|
| 49 |
+
selected=[positive]+[rr.choice(neg[k]) for k in keys]
|
| 50 |
+
ids=[entry_identity(entries[i]) for i in selected]
|
| 51 |
+
if len(set(ids))!=len(ids) or set(ids)&reader.forbidden:raise RuntimeError('Forbidden/duplicate sampled candidate')
|
| 52 |
+
graphs=[e.get('graph_hash') or lookup(e.get('canonical_smiles') or e['smiles']) for e in (entries[i] for i in selected)]
|
| 53 |
+
fs=tuple(pool['formula_classes']) if kind!='odata' else tuple(sorted({entries[i]['formula'] for i in selected}))
|
| 54 |
+
pools.append(dict(kind=kind,graphs=graphs,ids=ids,formulas=fs,negative_draws=len(keys),unique_negative_key14=len(keys),reference_injected=False))
|
| 55 |
+
rows.append(dict(rid=rid,ref=r['graph_hash'],identity=r['identity'],source=r['source'],formulas=forms,pools=pools))
|
| 56 |
+
tmp=path.with_suffix('.tmp');tmp.write_bytes(ft.dumps(dict(epoch=epoch,step=step,rows=rows)));os.replace(tmp,path);return idx
|
| 57 |
+
def asset_block(items):
|
| 58 |
+
# Actual checkpoint-compatible Molecule.smiles, not an assumed raw SMILES literal.
|
| 59 |
+
results=[];counts=collections.Counter()
|
| 60 |
+
for gh,expected in items:
|
| 61 |
+
m=reader.molecule(gh)
|
| 62 |
+
if m.identity!=expected:raise RuntimeError('Graph/key14 binding mismatch')
|
| 63 |
+
fk=ft.key(m.smiles)
|
| 64 |
+
if fragments[0].execute('SELECT 1 FROM canonical_features WHERE feature_key=? AND feature_sha IS NOT NULL',(fk,)).fetchone():counts['r2']+=1;continue
|
| 65 |
+
if fragments[1].execute('SELECT 1 FROM r3_features WHERE feature_key=? AND feature_sha IS NOT NULL',(fk,)).fetchone():counts['r3']+=1;continue
|
| 66 |
+
value=ft.build(m.smiles)
|
| 67 |
+
if value['layout']!=ft.layout(m.mol):raise RuntimeError('Offline fragment layout inconsistent')
|
| 68 |
+
b=ft.dumps(value);results.append((fk,b,digest(b)));counts['new']+=1
|
| 69 |
+
return results,counts
|
| 70 |
+
def run():
|
| 71 |
+
live=lock(OUT/'prep.lock');scratch_check();pr=prep_root();pr.mkdir(exist_ok=True)
|
| 72 |
+
if (pr/'READY.json').exists() and (OUT/'DATA_READY.json').exists() and get(pr/'READY.json')==get(OUT/'DATA_READY.json'):return
|
| 73 |
+
x=parent();prog=x['progress'];del x
|
| 74 |
+
epoch=prog['epoch'];first=prog['next_step'];plans=[];aud=[]
|
| 75 |
+
while len(plans)<N:
|
| 76 |
+
ep=epoch_plans(epoch,CFG['seed']);aud.append([epoch,first,plan_hash(ep)])
|
| 77 |
+
plans.extend(ep[first:first+N-len(plans)]);epoch+=1;first=0
|
| 78 |
+
assert len(plans)==N and plans[0][:2]==(prog['epoch'],prog['next_step'])
|
| 79 |
+
tag=dict(parent=CFG['parent_sha256'],plans=aud,script=filehash(__file__),next_updates=N)
|
| 80 |
+
if (pr/'PLAN.json').exists() and get(pr/'PLAN.json')!=tag:raise RuntimeError('Stale private ledger')
|
| 81 |
+
put(pr/'PLAN.json',tag);(pr/'batches').mkdir(exist_ok=True)
|
| 82 |
+
ctx=mp.get_context('fork')
|
| 83 |
+
def status(phase,done,total):put(OUT/'prep_status.json',dict(phase=phase,done=done,total=total,ts=time.time()))
|
| 84 |
+
status('next_cursor_sampling',0,N)
|
| 85 |
+
with futures.ProcessPoolExecutor(8,mp_context=ctx,initializer=init) as ex:
|
| 86 |
+
for j,_ in enumerate(ex.map(make_batch,enumerate(plans),chunksize=3),1):
|
| 87 |
+
if j%30==0:status('next_cursor_sampling',j,N);scratch_check()
|
| 88 |
+
# One global identity audit; batches are identical in all four arms.
|
| 89 |
+
required={};hashes=[];sources=collections.Counter();pool_counts=collections.Counter()
|
| 90 |
+
def verify(gh,key):
|
| 91 |
+
if required.setdefault(gh,key)!=key:raise RuntimeError('Conflicting graph identity')
|
| 92 |
+
for i,(e,s,groups) in enumerate(plans):
|
| 93 |
+
b=batchfile(i).read_bytes();hashes.append(digest(b));v=ft.loads(b)
|
| 94 |
+
if (v['epoch'],v['step'])!=(e,s) or [r['rid'] for r in v['rows']] != [rid for group in groups.values() for rid in group]:raise RuntimeError('Wrong epoch cursor/order')
|
| 95 |
+
for r in v['rows']:
|
| 96 |
+
verify(r['ref'],r['identity']);sources[r['source']]+=1
|
| 97 |
+
for p in r['pools']:
|
| 98 |
+
if len(set(p['ids']))!=len(p['ids']) or p['ids'][0]!=r['identity']:raise RuntimeError('Invalid negatives')
|
| 99 |
+
pool_counts[p['kind']]+=1
|
| 100 |
+
for gh,key in zip(p['graphs'],p['ids']):verify(gh,key)
|
| 101 |
+
put(pr/'hashes.json',hashes);req=sorted(required.items());del required
|
| 102 |
+
db=sqlite3.connect(pr/'delta.sqlite');db.execute('PRAGMA journal_mode=WAL')
|
| 103 |
+
db.execute('CREATE TABLE IF NOT EXISTS extra(k TEXT PRIMARY KEY,b BLOB NOT NULL,h TEXT NOT NULL) WITHOUT ROWID')
|
| 104 |
+
db.execute('CREATE TABLE IF NOT EXISTS blocks(i INTEGER PRIMARY KEY,hash TEXT,counts TEXT)')
|
| 105 |
+
blocksize=1024;count=(len(req)+blocksize-1)//blocksize
|
| 106 |
+
processed={i:h for i,h in db.execute('SELECT i,hash FROM blocks')}
|
| 107 |
+
pending=[];blockhash={}
|
| 108 |
+
for i in range(count):
|
| 109 |
+
h=objhash(req[i*blocksize:(i+1)*blocksize]);blockhash[i]=h
|
| 110 |
+
if i in processed:
|
| 111 |
+
if processed[i]!=h:raise RuntimeError('Stale feature resume block')
|
| 112 |
+
else:pending.append(i)
|
| 113 |
+
status('offline_feature_identity_check',len(processed)*blocksize,len(req))
|
| 114 |
+
# Bound in-flight results; completed chunks survive process restarts.
|
| 115 |
+
it=iter(pending);jobs={}
|
| 116 |
+
with futures.ProcessPoolExecutor(8,mp_context=ctx,initializer=init) as ex:
|
| 117 |
+
while True:
|
| 118 |
+
while len(jobs)<16:
|
| 119 |
+
i=next(it,None)
|
| 120 |
+
if i is None:break
|
| 121 |
+
jobs[ex.submit(asset_block,req[i*blocksize:(i+1)*blocksize])]=i
|
| 122 |
+
if not jobs:break
|
| 123 |
+
for done in futures.wait(jobs,return_when=futures.FIRST_COMPLETED).done:
|
| 124 |
+
i=jobs.pop(done);extra,stats=done.result()
|
| 125 |
+
db.executemany('INSERT OR IGNORE INTO extra VALUES(?,?,?)',extra);db.execute('INSERT INTO blocks VALUES(?,?,?)',(i,blockhash[i],json.dumps(stats)));db.commit();processed[i]=blockhash[i]
|
| 126 |
+
if len(processed)%32==0:status('offline_feature_identity_check',min(len(req),len(processed)*blocksize),len(req));scratch_check()
|
| 127 |
+
counts=collections.Counter()
|
| 128 |
+
for s, in db.execute('SELECT counts FROM blocks'):counts.update(json.loads(s))
|
| 129 |
+
assert sum(counts.values())==len(req) and len(processed)==count
|
| 130 |
+
db.execute('PRAGMA wal_checkpoint(TRUNCATE)');db.close()
|
| 131 |
+
ready=dict(complete=True,parent_sha256=CFG['parent_sha256'],new_updates=N,first_cursor=plans[0][:2],last_cursor=plans[-1][:2],
|
| 132 |
+
epoch_binding=aud,ledger_hash=objhash(hashes),unique_graphs=len(req),source_counts=dict(sources),pool_counts=dict(pool_counts),
|
| 133 |
+
descriptor_sources=dict(counts),delta_sha256=filehash(pr/'delta.sqlite'),heldout_labels_and_negatives_checked=True)
|
| 134 |
+
if (OUT/'DATA_READY.json').exists():
|
| 135 |
+
old=get(OUT/'DATA_READY.json')
|
| 136 |
+
for key in ('ledger_hash','unique_graphs','descriptor_sources','epoch_binding','source_counts','pool_counts'):
|
| 137 |
+
if old[key]!=ready[key]:raise RuntimeError('Reconstructed ledger differs: '+key)
|
| 138 |
+
put(pr/'READY.json',ready);put(OUT/'DATA_READY.json',ready);status('ready',N,N)
|
| 139 |
+
if __name__=='__main__':
|
| 140 |
+
try:run()
|
| 141 |
+
except Exception:
|
| 142 |
+
import traceback
|
| 143 |
+
put(OUT/'PREP_FAILURE.json',dict(traceback=traceback.format_exc(),time=time.time()));raise
|
code/snapshot/root/code/ceir_r4_9000_20261112/report4.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Paired target-key14 cluster bootstrap, wins AND regressions; no Test selection."""
|
| 2 |
+
from collections import defaultdict
|
| 3 |
+
import numpy as np
|
| 4 |
+
from common4 import *
|
| 5 |
+
def rows(p):
|
| 6 |
+
with gzip.open(p/'per_spectrum_summary.json.gz','rt') as f:rr=json.load(f)
|
| 7 |
+
out={(r['identifier'],r['view']):r for r in rr}
|
| 8 |
+
if len(rr)!=len(out):raise RuntimeError('Duplicate spectrum/view row')
|
| 9 |
+
return out
|
| 10 |
+
def compare(left,right):
|
| 11 |
+
if left.keys()!=right.keys():raise RuntimeError('Unmatched evaluation splits')
|
| 12 |
+
out={}
|
| 13 |
+
for view in sorted({v for i,v in left}):
|
| 14 |
+
report={}
|
| 15 |
+
for k in (1,5,20):
|
| 16 |
+
grouped=defaultdict(lambda:[0,0]);wins=losses=0
|
| 17 |
+
for i,r in left.items():
|
| 18 |
+
if i[1]!=view:continue
|
| 19 |
+
o=right[i]
|
| 20 |
+
if (o['target'],o['candidate_count'],o['reference_identity'])!=(r['target'],r['candidate_count'],r['reference_identity']):raise RuntimeError('Changed paired candidate population')
|
| 21 |
+
d=int(r['rank'] is not None and r['rank']<=k)-int(o['rank'] is not None and o['rank']<=k)
|
| 22 |
+
wins+=int(d==1);losses+=int(d==-1);g=grouped[r['reference_identity']];g[0]+=d;g[1]+=1
|
| 23 |
+
a=np.array(list(grouped.values()));rng=np.random.default_rng(47011);est=[]
|
| 24 |
+
for _ in range(20):
|
| 25 |
+
ix=rng.integers(0,len(a),(100,len(a)));d,n=a[ix].sum(1).T;est.extend(100*d/n)
|
| 26 |
+
report[str(k)]=dict(added=wins,lost=losses,denominator=int(a[:,1].sum()),net_pp=100*(wins-losses)/a[:,1].sum(),
|
| 27 |
+
ci95_pp=np.quantile(est,[.025,.975]).tolist(),unit='paired target key14; single training seed')
|
| 28 |
+
out[view]=report
|
| 29 |
+
return out
|
| 30 |
+
def directory(arm,u,dataset):return OUT/arm/(dataset+'_%06d'%u)
|
| 31 |
+
def val(u):
|
| 32 |
+
parentdir=R3/'R3D/validation_006000';original=rows(parentdir);control=rows(directory('A',u,'validation'))
|
| 33 |
+
arms={};comp={}
|
| 34 |
+
for arm in CFG['arms']:
|
| 35 |
+
d=directory(arm,u,'validation');row=rows(d);metric=get(d/'metrics.json')['results']
|
| 36 |
+
arms[arm]=metric;comp[arm]=dict(vs_control=compare(row,control),vs_parent=compare(row,original))
|
| 37 |
+
recommended=max(arms,key=lambda a:arms[a]['formula']['structure']['1']['hits'])
|
| 38 |
+
report=dict(complete=True,update=u,arms=arms,paired=comp,validation_formula_top1_leader=recommended,
|
| 39 |
+
exploratory='Report alongside Mass, MCES, effect uncertainty and harm; a point estimate alone is not verified superiority',
|
| 40 |
+
test_used_for_selection=False)
|
| 41 |
+
put(OUT/('VALIDATION_%06d.json'%u),report)
|
| 42 |
+
return report
|
| 43 |
+
def freeze():
|
| 44 |
+
val9=get(OUT/'VALIDATION_009000.json')
|
| 45 |
+
eps={a:get(OUT/a/'TRAIN_COMPLETE.json') for a in CFG['arms']}
|
| 46 |
+
assert len({v['ledger_chain'] for v in eps.values()})==1 and all(v['actual_new_updates']==3000 for v in eps.values())
|
| 47 |
+
put(OUT/'FROZEN_TEST.json',dict(arms={a:e['endpoint_sha'] for a,e in eps.items()},weights_policy='all four predetermined 9000-step endpoints',
|
| 48 |
+
validation_sha=filehash(OUT/'VALIDATION_009000.json'),test_used_for_selection=False,validation_point_leader=val9['validation_formula_top1_leader']))
|
| 49 |
+
def final():
|
| 50 |
+
result={}
|
| 51 |
+
for d in ('msg_test','casmi2022','validation'):
|
| 52 |
+
parentdir=R3/'test/inference/R3D_006000'/d if d!='validation' else R3/'R3D/validation_006000'
|
| 53 |
+
control=rows(directory('A',9000,d));old=rows(parentdir);summary={}
|
| 54 |
+
for a in CFG['arms']:
|
| 55 |
+
p=directory(a,9000,d);rr=rows(p);metrics=get(p/'metrics.json');mces=get(p/'MCES.json')
|
| 56 |
+
summary[a]=dict(results=metrics['results'],MCES=mces,vs_matched_A=compare(rr,control),vs_R3D_6000=compare(rr,old))
|
| 57 |
+
result[d]=summary
|
| 58 |
+
put(OUT/'ALL_RESULTS.json',dict(complete=True,actual_updates={a:3000 for a in CFG['arms']},test_choice=get(OUT/'FROZEN_TEST.json'),
|
| 59 |
+
results=result,validation_checkpoints=CFG['checkpoints'],public_baselines='literature, not rerun',ts=time.time()))
|
code/snapshot/root/code/ceir_r4_9000_20261112/run4.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Finite R3D -> R4 continuation. Atomic rolling state, no old run writes."""
|
| 2 |
+
import argparse,gc,math,random,contextlib,subprocess
|
| 3 |
+
import numpy as np
|
| 4 |
+
import torch
|
| 5 |
+
from common4 import *
|
| 6 |
+
from model4 import make,setup
|
| 7 |
+
from data4 import Batches
|
| 8 |
+
from objectives4 import train_step
|
| 9 |
+
|
| 10 |
+
def synced_file(src,dest):
|
| 11 |
+
dest.parent.mkdir(parents=True,exist_ok=True)
|
| 12 |
+
tmp=dest.with_name(dest.name+'.copy.tmp')
|
| 13 |
+
with open(src,'rb') as a,open(tmp,'wb') as b:shutil.copyfileobj(a,b,4*2**20);b.flush();os.fsync(b.fileno())
|
| 14 |
+
if filehash(tmp)!=filehash(src):raise RuntimeError('Checkpoint copy did not verify')
|
| 15 |
+
os.replace(tmp,dest);fd=os.open(dest.parent,os.O_RDONLY);os.fsync(fd);os.close(fd)
|
| 16 |
+
|
| 17 |
+
def atomic_torch(dest,value):
|
| 18 |
+
dest.parent.mkdir(parents=True,exist_ok=True);tmp=dest.with_name(dest.name+'.write.tmp')
|
| 19 |
+
with tmp.open('wb') as f:torch.save(value,f);f.flush();os.fsync(f.fileno())
|
| 20 |
+
os.replace(tmp,dest)
|
| 21 |
+
|
| 22 |
+
def save_state(model,opt,pg,bind,arm,durable):
|
| 23 |
+
up=pg['update']; hot=HOT/'runs'/arm/'resume'; cold=OUT/arm/'resume'
|
| 24 |
+
p=hot/('state_%06d.pt'%up)
|
| 25 |
+
value=dict(architecture='CEIR_R4',arm=arm,model=model.state_dict(),optimizer=opt.state_dict(),progress=dict(pg),
|
| 26 |
+
binding=bind,torch_rng=torch.get_rng_state(),cuda_rng=torch.cuda.get_rng_state_all(),
|
| 27 |
+
numpy_rng=np.random.get_state(),python_rng=random.getstate())
|
| 28 |
+
atomic_torch(p,value);meta=dict(update=up,name=p.name,sha256=filehash(p),bytes=p.stat().st_size,binding_sha=objhash(bind))
|
| 29 |
+
def publish(folder):
|
| 30 |
+
old=get(folder/'LAST.json') if (folder/'LAST.json').is_file() else None
|
| 31 |
+
put(folder/'LAST.json',meta)
|
| 32 |
+
# Rotate ONLY this arm's superseded private rolling cache. Permanent
|
| 33 |
+
# milestone snapshots and the parent checkpoint never enter this folder.
|
| 34 |
+
if old and old['update']!=up and old['name']=='state_%06d.pt'%old['update'] and old['update']<up:
|
| 35 |
+
older=folder/old['name']
|
| 36 |
+
if older.is_file():older.unlink()
|
| 37 |
+
publish(hot)
|
| 38 |
+
if durable:
|
| 39 |
+
if shutil.disk_usage(OUT).free<max(320*2**20,meta['bytes']+96*2**20):raise RuntimeError('Durable capacity guard: hot state preserved')
|
| 40 |
+
synced_file(p,cold/p.name);publish(cold)
|
| 41 |
+
return p,meta
|
| 42 |
+
|
| 43 |
+
def resume(arm,bind):
|
| 44 |
+
candidates=[]
|
| 45 |
+
for box in [OUT/arm/'resume',HOT/'runs'/arm/'resume']:
|
| 46 |
+
if (box/'LAST.json').exists():
|
| 47 |
+
m=get(box/'LAST.json');p=box/m['name']
|
| 48 |
+
if m['name']!='state_%06d.pt'%m['update'] or m['binding_sha']!=objhash(bind):raise RuntimeError('Wrong rolling state binding')
|
| 49 |
+
candidates.append((m['update'],box==OUT/arm/'resume',m,p))
|
| 50 |
+
for u,_,m,p in sorted(candidates,reverse=True):
|
| 51 |
+
if p.exists() and filehash(p)==m['sha256']:return p
|
| 52 |
+
if candidates:raise RuntimeError('No verified recoverable checkpoint')
|
| 53 |
+
return None
|
| 54 |
+
|
| 55 |
+
def milestone(model,pg,bind,arm,meta):
|
| 56 |
+
u=pg['update'];dest=OUT/arm/('step_%06d.pt'%u)
|
| 57 |
+
if not dest.exists():
|
| 58 |
+
if u==CFG['target_update']:os.link(OUT/arm/'resume'/meta['name'],dest)
|
| 59 |
+
else:atomic_torch(dest,dict(architecture='CEIR_R4',arm=arm,model=model.state_dict(),progress=dict(pg),binding=bind))
|
| 60 |
+
h=filehash(dest)
|
| 61 |
+
if u==CFG['target_update'] and h!=meta['sha256']:raise RuntimeError('Endpoint hardlink not identical to durable full state')
|
| 62 |
+
put(dest.with_suffix('.json'),dict(update=u,sha256=h,size=dest.stat().st_size,inference_only=u!=CFG['target_update'],arm=arm))
|
| 63 |
+
|
| 64 |
+
@contextlib.contextmanager
|
| 65 |
+
def lease(label):
|
| 66 |
+
status=OUT/'admission'/label;status.parent.mkdir(parents=True,exist_ok=True)
|
| 67 |
+
folder=OUT/'gpu_leases';folder.mkdir(exist_ok=True)
|
| 68 |
+
handles=[(folder/(str(i)+'.lock')).open('a+') for i in range(CFG['max_training_processes'])];mine=None
|
| 69 |
+
try:
|
| 70 |
+
while mine is None:
|
| 71 |
+
free=int(subprocess.check_output(['nvidia-smi','--query-gpu=memory.free','--format=csv,noheader,nounits'],text=True).strip().splitlines()[0])
|
| 72 |
+
if free>=CFG['free_before_job_mib']:
|
| 73 |
+
for f in handles:
|
| 74 |
+
try:fcntl.flock(f,fcntl.LOCK_EX|fcntl.LOCK_NB);mine=f;break
|
| 75 |
+
except BlockingIOError:pass
|
| 76 |
+
if mine is None:put(status,dict(state='waiting_for_free_resources',free_mib=free,ts=time.time()));time.sleep(6)
|
| 77 |
+
put(status,dict(state='admitted',ts=time.time()));yield
|
| 78 |
+
finally:
|
| 79 |
+
for f in handles:f.close()
|
| 80 |
+
put(status,dict(state='released',ts=time.time()))
|
| 81 |
+
|
| 82 |
+
def accepted():
|
| 83 |
+
bind=state_binding();r=get(OUT/'TRAIN_READY.json')
|
| 84 |
+
if not r['passed'] or r['binding']!=bind:raise RuntimeError('Formal real-GPU acceptance missing or changed')
|
| 85 |
+
return bind
|
| 86 |
+
|
| 87 |
+
def train(arm,until):
|
| 88 |
+
if arm not in CFG['arms'] or not 6000<until<=9000:raise ValueError('Invalid R4 request')
|
| 89 |
+
dest=OUT/arm;held=lock(dest/'training.lock');bind=accepted()
|
| 90 |
+
with lease('train_'+arm):
|
| 91 |
+
setup();path=resume(arm,bind);model,opt,pg=make(arm,path,expected_binding=bind)
|
| 92 |
+
if path is None and (pg['epoch'],pg['next_step'])!=(1,907):raise RuntimeError('Wrong cold data cursor')
|
| 93 |
+
if pg['update'] in CFG['checkpoints'] and not (dest/('step_%06d.json'%pg['update'])).exists():
|
| 94 |
+
_,m=save_state(model,opt,pg,bind,arm,True);milestone(model,pg,bind,arm,m)
|
| 95 |
+
if pg['update']>=until:
|
| 96 |
+
if pg['update']==9000:finish(dest,pg,bind)
|
| 97 |
+
return
|
| 98 |
+
begin=pg['update']-6000;dataset=Batches(begin,until-6000)
|
| 99 |
+
loader=torch.utils.data.DataLoader(dataset,batch_size=None,num_workers=1,prefetch_factor=2,
|
| 100 |
+
multiprocessing_context='spawn',generator=torch.Generator().manual_seed(CFG['seed']+begin))
|
| 101 |
+
event(dest/'events.jsonl',dict(event='train_continue',from_update=pg['update'],until=until,source='verified_state' if path else 'R3D_006000'))
|
| 102 |
+
put(dest/'status.json',dict(phase='training',update=pg['update'],target=9000,ts=time.time()))
|
| 103 |
+
last_clock=time.monotonic()
|
| 104 |
+
for batch in loader:
|
| 105 |
+
u=pg['update'];n=u-6000;ts=time.monotonic();wait=ts-last_clock
|
| 106 |
+
if (n!=batch['manifest_index'] or (batch['epoch'],batch['step'])!=(pg['epoch'],pg['next_step'])):raise RuntimeError('Training cursor mismatch')
|
| 107 |
+
if model.has_duel:opt.param_groups[3]['lr']=CFG['learning_rate']['new_head']*min(1.,(n+1)/CFG['learning_rate']['new_warmup'])
|
| 108 |
+
model.train();torch.cuda.reset_peak_memory_stats();m=train_step(model,opt,batch,u)
|
| 109 |
+
pg.update(update=u+1,new_updates=n+1,epoch=batch['epoch'],next_step=batch['step']+1,
|
| 110 |
+
r4_chain=digest((pg['r4_chain']+batch['ledger_sha256']).encode()))
|
| 111 |
+
for k,v in m['source_counts'].items():pg['r4_exposures'][k]=pg['r4_exposures'].get(k,0)+v
|
| 112 |
+
u=pg['update'];durable=(u%CFG['durable_interval']==0 or u in CFG['checkpoints'] or u==until)
|
| 113 |
+
if durable or u%CFG['hot_interval']==0:
|
| 114 |
+
_,receipt=save_state(model,opt,pg,bind,arm,durable)
|
| 115 |
+
if u in CFG['checkpoints']:milestone(model,pg,bind,arm,receipt)
|
| 116 |
+
m.update(update=u,new_updates=u-6000,arm=arm,epoch=pg['epoch'],data_step=batch['step'],
|
| 117 |
+
ledger_sha256=batch['ledger_sha256'],batch_chain=pg['r4_chain'],lr=[g['lr'] for g in opt.param_groups],
|
| 118 |
+
data_wait_seconds=wait,wall_seconds=time.monotonic()-ts+wait,timestamp=time.time())
|
| 119 |
+
event(dest/'loss.jsonl',m)
|
| 120 |
+
if u%10==0 or u<=6003 or u==until:
|
| 121 |
+
put(dest/'status.json',dict(phase='training' if u<9000 else 'endpoint_saved',update=u,target=9000,
|
| 122 |
+
new_updates=u-6000,loss=m['loss'],gap=m['r4_gap_loss'],residual=m['r4_duel_residual'],
|
| 123 |
+
seconds=m['wall_seconds'],peak_mib=m['peak_allocated_mib'],ts=time.time()))
|
| 124 |
+
last_clock=time.monotonic()
|
| 125 |
+
if pg['update']!=until:raise RuntimeError('Incomplete training block')
|
| 126 |
+
if until==9000:finish(dest,pg,bind)
|
| 127 |
+
def finish(dest,pg,bind):
|
| 128 |
+
ledger=get(prep_root()/'hashes.json');h=''
|
| 129 |
+
for d in ledger:h=digest((h+d).encode())
|
| 130 |
+
assert len(ledger)==3000 and pg['update']==9000 and pg['new_updates']==3000 and pg['r4_chain']==h
|
| 131 |
+
ep=dest/'step_009000.pt';rc=get(ep.with_suffix('.json'));assert rc['sha256']==filehash(ep)
|
| 132 |
+
assert pg['r4_exposures']==get(OUT/'DATA_READY.json')['source_counts']
|
| 133 |
+
put(dest/'TRAIN_COMPLETE.json',dict(complete=True,source=6000,endpoint=9000,actual_new_updates=3000,
|
| 134 |
+
ledger_chain=h,sources=pg['r4_exposures'],endpoint_sha=rc['sha256'],binding_sha=objhash(bind)))
|
| 135 |
+
if __name__=='__main__':
|
| 136 |
+
p=argparse.ArgumentParser();p.add_argument('arm',choices=list(CFG['arms']));p.add_argument('until',type=int);a=p.parse_args()
|
| 137 |
+
try:train(a.arm,a.until)
|
| 138 |
+
except Exception:
|
| 139 |
+
import traceback
|
| 140 |
+
put(OUT/a.arm/'last_error.json',dict(error=traceback.format_exc(),time=time.time()));raise
|
code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/README.md
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# R5: R4-D 9k → 12k,五组独立续训
|
| 2 |
+
|
| 3 |
+
这不是从 R3D 再开五个分支。共同父文件是服务器
|
| 4 |
+
`/root/xj/SpecPartition-MS/runs/ceir_r4_9000_20261112/D/step_009000.pt`,
|
| 5 |
+
SHA-256 `dd23af7370c35caee1d4f154fd52a2bc5b21c3e53c0f06df1beb368f274ea7b6`。
|
| 6 |
+
复制的是权重、四个参数组(301/24/22/12 个参数张量)、304 份非空 AdamW 状态、训练数据游标、Python/NumPy/PyTorch/CUDA RNG。C 仅把新参数加入第五组,不重置已有优化器。
|
| 7 |
+
|
| 8 |
+
每组固定 **9,001~12,000 共 3,000 次新更新**。一次性验收不计步,五组总数 15,000。原 R4-D 的全候选直接分数、Top32 差异峰精排及同公式困难负例 Loss 所有组都保留。R3D 6k 是效果历史参照,不是任何一组的训练起点。
|
| 9 |
+
|
| 10 |
+
| 分支 | 相对 R4-D 的唯一主要改动 |
|
| 11 |
+
|---|---|
|
| 12 |
+
| A | 原样续训。匹配同一起点、数据游标、步数、优化器;比较新设计不能只比 9k 父权重。 |
|
| 13 |
+
| B | 每步对每种存在的训练视图轮换至多两个真实谱池,从同池扩大 reservoir 后按冻结 R4-D 高分的同公式异骨架、同/近骨架化学邻居和随机候选重采样;Mass 预留跨公式配额。每个池仍用原训练抽样预算,其他池不变。教师不参与推理。 |
|
| 14 |
+
| C | 在 R4-D 最终分数上增加全池、同公式、候选专属峰强度的有界加分。生产提案是已有两个单边界连通片段之间的新的双桥内部碎片;区别于小试中更广的双切/开环枚举。预测离子强度包含未匹配通道;相同 key14 在支持计数中只投一票,无支持就不改分。使用融合后的最终分数计算一次候选池 CE,增加弱正例谱强度监督,初始分数等于父模型。 |
|
| 15 |
+
| D | 每步扩大一个真实训练池,其余保留原样。连续四个 750 步阶段的**训练**上限为 256、512、2048、5000;只用真实合格候选,没有那么多就不补。激活按块重算,所有候选只用一个最终分数 softmax 分母;不按块各算一份 CE。 |
|
| 16 |
+
| E | 对轮换的真实训练池,用冻结 R4-D 判定“原本排对、分差足够、正确候选及最强对手均无新增独占峰”时,单侧保护父模型分差。允许纠正父模型原本的错误;没有分差缩小时该新损失可以为零。教师和标签都不进入评测模型。 |
|
| 17 |
+
|
| 18 |
+
训练侧随机池、扩展抽样、静态分子图、参考结构 key14 与 heldout 注册表分别检查;不合格真值不人工补入。正式进程在 `GPU_READY.json` 存在且训练代码/数据哈希匹配时才可运行。验收包括从正式游标取真实 batch,旧模型分数/置换一致性、新机制活动、C 的优化器恢复、四档真实池梯度及统一分母、官方 Validation 输入回放。大池验收是工程和数值检查;**不等于已在独立大池提高召回**。启动五个验证性实验不代表通过科学晋级。
|
| 19 |
+
|
| 20 |
+
### 本次训练数据修正
|
| 21 |
+
|
| 22 |
+
新抽样的 6,729,969 个图映射中发现 1 个声明 key14 与图结构不一致。数据服务主动停止,总审计确认只涉及一次 D 扩展池负例(批次索引 2731),不涉及任何正例、其他四组基础抽样或官方评测。独立修订层保存原始与修正批次双哈希。尝试在原池内等额补取;因为该池合法候选已经用尽,**实际少一个负例**,没有复制候选或换标签凑数。尚未发现的错例不能因为修正这一个而宣称不存在;正式运行继续校验图和样本绑定。
|
| 23 |
+
|
| 24 |
+
### 保存位置与检查
|
| 25 |
+
|
| 26 |
+
- 热权重、优化器、分批训练日志、验证数据、逐候选分数:
|
| 27 |
+
`/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 的完整断点。大文件只放用户指定的内存盘,**重启实例会丢失**;此处不承诺跨重启恢复。
|
| 28 |
+
- 服务器代码:`/root/xj/SpecPartition-MS/code/ceir_r5_from_r4d_12000_20261112/`。
|
| 29 |
+
- 小型持续记录、数据/验收哈希、状态和最终指标:
|
| 30 |
+
`/root/xj/SpecPartition-MS/runs/ceir_r5_from_r4d_12000_20261112/`。这些不含完整训练权重。
|
| 31 |
+
- 运行状态只读命令(服务器项目代码目录内):
|
| 32 |
+
`/workspace/xj/SpecPartition-MS/.venv/bin/python -B status5.py`。区分 observed、committed 和已完成评测;`supervisorctl status specpartition-r5-from-r4d-train-20261112` 只描述调度进程,不代表五组都完成。
|
| 33 |
+
- 监督器同卡最多两组轮转,不启动五个无保护 GPU 进程。每组每 100 步和轮转边界原子保存新断点及可核验的连续训练日志;只轮换该组自己已被替代的临时文件。任何哈希/游标/数据身份问题都停在错误记录处,不静默从头重跑。
|
| 34 |
+
|
| 35 |
+
### 效果判定
|
| 36 |
+
|
| 37 |
+
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 特征或分数训练。
|
| 38 |
+
|
| 39 |
+
最终对齐候选顺序哈希,核验每组连续 3,000 个更新、父模型哈希、抽样链和源数据曝光。主比较为 Validation Formula 结构 Top1,基于 target key14 配对重采样,并对四个对照比较报告调整的区间下界;同时检验 Mass、Formula 其他 K 和共同有效样本的 MCES。Test 和 CASMI 不选超参/权重,不把单种子结果当成反复训练均有效。训练 Loss 下降或任务运行成功均**不是效果提升证据**。若各组未达到标准,保留负结果和原 R4-D;本次不向 GitHub 上传权重。
|
code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/accept5.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Independent checks on full copied states and real batches. No formal updates."""
|
| 2 |
+
import argparse,contextlib,gc,math,os,sys,time,traceback
|
| 3 |
+
from dataclasses import replace
|
| 4 |
+
from paths5 import *
|
| 5 |
+
import numpy as np,torch
|
| 6 |
+
from train5 import Batches,binding,lease,make,original,prior,step,teacher
|
| 7 |
+
from model5 import H
|
| 8 |
+
from teacher5 import annotate
|
| 9 |
+
from forward5 import Evidence
|
| 10 |
+
def free():
|
| 11 |
+
gc.collect();torch.cuda.empty_cache()
|
| 12 |
+
def parity(q,model,original_values):
|
| 13 |
+
model.eval()
|
| 14 |
+
with torch.inference_mode(),prior.rt.amp():
|
| 15 |
+
a=model.encode_batch([q])[0][0].base.float().cpu()
|
| 16 |
+
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()
|
| 17 |
+
p=float((a-original_values).abs().max());order=float((a[rev]-b).abs().max())
|
| 18 |
+
if p>1e-5 or order>4e-4:raise RuntimeError(f'parent/permutation {p=} {order=}')
|
| 19 |
+
return p,order
|
| 20 |
+
def one(arm,warm,idx,q,s,bind):
|
| 21 |
+
pt,det=teacher(arm,warm);model,opt,pg=make(arm,warm=warm)
|
| 22 |
+
assert pg['update']==9000 and pg['next_step']==3907 and len(opt.state)==304
|
| 23 |
+
a,b=parity(q,model,s)
|
| 24 |
+
batch=Batches(arm,idx,idx+1,warm)[0]
|
| 25 |
+
if arm=='C':
|
| 26 |
+
# Independently verify the newly registered head both preserves the
|
| 27 |
+
# parent at zero and receives real gradients without affecting labels.
|
| 28 |
+
assert model.r5.gain.item()==0
|
| 29 |
+
mt=step(arm,model,opt,batch,9000,pt,det)
|
| 30 |
+
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')
|
| 31 |
+
if arm=='B' and mt['intervention'].get('actually_changed_identities',0)==0:raise RuntimeError('no actual negative changed')
|
| 32 |
+
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')
|
| 33 |
+
if arm=='D' and mt['r5_expanded_views']==0:raise RuntimeError('no expanded denominator')
|
| 34 |
+
if arm=='E' and not mt['intervention'].get('teacher_views'):raise RuntimeError('no teacher observations')
|
| 35 |
+
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()))
|
| 36 |
+
if arm=='E':
|
| 37 |
+
x=torch.tensor([1.,.9],requires_grad=True);pen=(.75+x[1]-x[0]).relu();pen.backward()
|
| 38 |
+
assert x.grad.tolist()==[-1.,1.];z['synthetic_anchor_derivative']=x.grad.tolist()
|
| 39 |
+
if arm=='C' and not warm:
|
| 40 |
+
# Check optimizer moments and RNG on a real training update, not just saved logits.
|
| 41 |
+
import random
|
| 42 |
+
from train5 import atomicstate
|
| 43 |
+
path=ROOT/'acceptance/C_full_state.pt'
|
| 44 |
+
state=dict(architecture='CEIR_R5',arm=arm,binding=bind,progress=dict(pg,update=9001),model=model.state_dict(),optimizer=opt.state_dict(),
|
| 45 |
+
numpy_rng=np.random.get_state(),python_rng=random.getstate(),torch_rng=torch.get_rng_state(),cuda_rng=torch.cuda.get_rng_state_all())
|
| 46 |
+
atomicstate(path,state);del state
|
| 47 |
+
from objectives5 import train_step
|
| 48 |
+
model.train();before=train_step(model,opt,batch,9001,False)['loss'];del model,opt;free()
|
| 49 |
+
model,opt,rr=make(arm,path,optimizer=True,binding=bind);model.train();after=train_step(model,opt,batch,9001,False)['loss']
|
| 50 |
+
if rr['update']!=9001 or abs(before-after)>5e-4:raise RuntimeError(f'resume parity {before} vs {after}')
|
| 51 |
+
z['resume_loss_max_error']=abs(before-after)
|
| 52 |
+
return z
|
| 53 |
+
def large_checks(warm):
|
| 54 |
+
# Real, train-only, parent-score and full-denominator checks across target
|
| 55 |
+
# sizes. Use no Test/CASMI queries. These are engineering/stability checks,
|
| 56 |
+
# not generalization measurements on parent-unseen structures.
|
| 57 |
+
out=[]
|
| 58 |
+
for start,cap in ((0,256),(750,512),(1500,2048),(2250,5000)):
|
| 59 |
+
best=None
|
| 60 |
+
for i in range(start,start+750):
|
| 61 |
+
row=prior.ft.loads(current_batch(LARGE,'%04d.z'%i).read_bytes())['expanded']
|
| 62 |
+
if row and len(row['ids'])==cap:best=(i,row['rid'],row['kind']);break
|
| 63 |
+
if not best:raise RuntimeError('No real eligible large-pool batch of size '+str(cap))
|
| 64 |
+
i,rid,kind=best;bb=Batches('D',i,i+1,warm)[0]
|
| 65 |
+
p=next(p for r in bb['rows'] if r['record_id']==rid for p in r['pools'] if p['kind']==kind)
|
| 66 |
+
q=p['query'];assert len(q.candidates)==cap and len(set(p['ids']))==cap
|
| 67 |
+
net,op,_=make('D',warm=warm);net.train();op.zero_grad(set_to_none=True);torch.cuda.reset_peak_memory_stats()
|
| 68 |
+
# A single softmax across the entire real query; streamed graph tiles
|
| 69 |
+
# are only activation checkpoints. Every candidate remains in the denominator.
|
| 70 |
+
with prior.rt.amp():
|
| 71 |
+
enc=net.encode_batch([q])[0][0];sc=enc.base.float();loss=sc.logsumexp(0)-sc[0]
|
| 72 |
+
tiled=torch.stack([s.logsumexp(0) for s in sc.split(37)]).logsumexp(0)-sc[0]
|
| 73 |
+
err=abs(float(loss.detach()-tiled.detach()));loss.backward()
|
| 74 |
+
norm=torch.nn.utils.clip_grad_norm_(net.parameters(),100.,error_if_nonfinite=True).item()
|
| 75 |
+
if err>2e-5 or not math.isfinite(norm) or norm<=0:raise RuntimeError('invalid global denominator/gradient')
|
| 76 |
+
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))
|
| 77 |
+
del net,op,enc,sc,loss,tiled,bb,q,p;free()
|
| 78 |
+
save(SMALL/'LARGE_GPU_PROBE.json',dict(complete=len(out)==4,rows=out,formal_updates=0))
|
| 79 |
+
return out
|
| 80 |
+
def run(warm=False):
|
| 81 |
+
bind=None if warm else binding();dest=SMALL/('WARM_GPU.json' if warm else 'GPU_READY.json')
|
| 82 |
+
if not warm and dest.exists() and read(dest)['binding']==bind and read(dest)['passed']:return
|
| 83 |
+
with lease('accept'):
|
| 84 |
+
original.setup();idx=None
|
| 85 |
+
for i in range(20):
|
| 86 |
+
p=prior.ft.loads(current_batch(BASE,'%04d.z'%i).read_bytes())
|
| 87 |
+
if len(p['rows'])>=256 and any(x['kind']=='odata' for r in p['rows'] for x in r['pools']):
|
| 88 |
+
alt=prior.ft.loads(current_batch(LARGE,'%04d.z'%i).read_bytes())
|
| 89 |
+
if alt['expanded'] and len(alt['expanded']['ids'])>alt['expanded']['base_n']:idx=i;break
|
| 90 |
+
if idx is None:raise RuntimeError('no complete real mixed batch for acceptance')
|
| 91 |
+
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)
|
| 92 |
+
old,_,_=original.make('D',C['parent'],split='train',optimizer=False);old.feature_store=__import__('batch5').Store('train',warm);old.eval()
|
| 93 |
+
with torch.inference_mode(),prior.rt.amp():s=old.encode_batch([q])[0][0].base.float().cpu()
|
| 94 |
+
del old;free();arms={}
|
| 95 |
+
for arm in C['arms']:
|
| 96 |
+
arms[arm]=one(arm,warm,idx,q,s,bind);free()
|
| 97 |
+
save(SMALL/('warm_'+arm+'.json' if warm else 'accept_'+arm+'.json'),arms[arm])
|
| 98 |
+
if not warm:
|
| 99 |
+
lg=large_checks(False)
|
| 100 |
+
import eval5
|
| 101 |
+
v=eval5.parent_validation_parity()
|
| 102 |
+
else:lg=[];v=None
|
| 103 |
+
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()))
|
| 104 |
+
if __name__=='__main__':
|
| 105 |
+
ap=argparse.ArgumentParser();ap.add_argument('--warm',action='store_true');args=ap.parse_args()
|
| 106 |
+
try:run(args.warm)
|
| 107 |
+
except Exception:save(SMALL/('WARM_ERROR.json' if args.warm else 'GPU_ERROR.json'),dict(error=traceback.format_exc(),ts=time.time()));raise
|
code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/addendum.supervisor.conf
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[program:specpartition-r5-from-r4d-posthoc-20261112]
|
| 2 |
+
directory=/root/xj/SpecPartition-MS/code/ceir_r5_from_r4d_12000_20261112
|
| 3 |
+
command=/usr/bin/nice -n 12 /workspace/xj/SpecPartition-MS/.venv/bin/python -B -u addendum5.py
|
| 4 |
+
environment=OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1",CUDA_VISIBLE_DEVICES=""
|
| 5 |
+
autostart=false
|
| 6 |
+
autorestart=false
|
| 7 |
+
startsecs=1
|
| 8 |
+
stopasgroup=true
|
| 9 |
+
killasgroup=true
|
| 10 |
+
stdout_logfile=/root/xj/SpecPartition-MS/runs/ceir_r5_from_r4d_12000_20261112/posthoc.log
|
| 11 |
+
stdout_logfile_maxbytes=1MB
|
| 12 |
+
stdout_logfile_backups=1
|
| 13 |
+
redirect_stderr=true
|
code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/addendum5.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""One-shot postprocessing: never changes the weights, release or primary metrics."""
|
| 2 |
+
from collections import defaultdict
|
| 3 |
+
import sys,time,traceback
|
| 4 |
+
from paths5 import *
|
| 5 |
+
def strata(rows,parent):
|
| 6 |
+
buckets=defaultdict(lambda:dict(n=0,covered=0,gained=0,lost=0,parent_top1=0,model_top1=0,parent_top32=0,model_top32=0))
|
| 7 |
+
for key,r in rows.items():
|
| 8 |
+
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'
|
| 9 |
+
def hit(z,k):return z['rank'] is not None and z['rank']<=k
|
| 10 |
+
for name in ('pool_size:'+tag,'adduct:'+str(r.get('adduct')),'polarity:'+str(r.get('polarity'))):
|
| 11 |
+
b=buckets[r['view']+' | '+name];b['n']+=1;b['covered']+=int(r['reference_in_pool']);p=hit(oldrow,1);c=hit(r,1)
|
| 12 |
+
b['gained']+=int(c and not p);b['lost']+=int(p and not c);b['parent_top1']+=int(p);b['model_top1']+=int(c)
|
| 13 |
+
b['parent_top32']+=int(hit(oldrow,32));b['model_top32']+=int(hit(r,32))
|
| 14 |
+
return dict(buckets)
|
| 15 |
+
def follow():
|
| 16 |
+
while not (SMALL/'FINAL_VERIFIED.json').exists():
|
| 17 |
+
if (SMALL/'PIPELINE_STATUS.json').exists() and read(SMALL/'PIPELINE_STATUS.json')['stage']=='blocked_see_error':raise RuntimeError('formal pipeline not complete')
|
| 18 |
+
time.sleep(50)
|
| 19 |
+
import report5 as rep
|
| 20 |
+
source=read(SMALL/'FINAL_VERIFIED.json');assert source['complete'] and set(source['new_updates'].values())=={3000}
|
| 21 |
+
splits={}
|
| 22 |
+
for split in ('validation','msg_test','casmi2022'):
|
| 23 |
+
p=rep.old.rows(rep.reference('R4-D_9000',split))
|
| 24 |
+
splits[split]={a:strata(rep.old.rows(rep.folder(a,12000,split)),p) for a in C['arms']}
|
| 25 |
+
out=dict(final_file_sha=hashfile(SMALL/'FINAL_VERIFIED.json'),strata_vs_R4D=splits,promotion_deferred=True,
|
| 26 |
+
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.',
|
| 27 |
+
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],
|
| 28 |
+
'mces_mass_formula':[7.84,9.00],'uses_known_precursor_formula':True,'not_rerun':True,'source':'https://pmc.ncbi.nlm.nih.gov/articles/PMC12873900/'}},
|
| 29 |
+
ts=time.time())
|
| 30 |
+
save(SMALL/'EXTENDED_STRATA.json',out)
|
| 31 |
+
from format_report5 import publish
|
| 32 |
+
publish(SMALL)
|
| 33 |
+
if __name__=='__main__':
|
| 34 |
+
try:follow()
|
| 35 |
+
except Exception:save(SMALL/'ADDENDUM_ERROR.json',dict(error=traceback.format_exc(),ts=time.time()));raise
|
code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/assets5.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Build verified new static descriptors, sharing R4/R3/R2 read-only. Lossless
|
| 2 |
+
packed representation avoids megabytes of float-zero padding in small fragments.
|
| 3 |
+
"""
|
| 4 |
+
import collections,concurrent.futures as cf,fcntl,multiprocessing as mp,os,shutil,sqlite3,sys,time,traceback,zlib,pickle
|
| 5 |
+
import numpy as np
|
| 6 |
+
from paths5 import *
|
| 7 |
+
sys.path.insert(0,C['r4_code']);import prepare4 as old
|
| 8 |
+
def pack(x):
|
| 9 |
+
y=dict(x);m=y.pop('members');used=m>0
|
| 10 |
+
# Each non-zero entry is identical within a row. Keep that float32 bit
|
| 11 |
+
# pattern explicitly instead of recomputing 1/n in a different dtype.
|
| 12 |
+
y['_bits']=np.packbits(used,axis=1);y['_weight']=m.max(1) if m.shape[1] else np.zeros(len(m),np.float32)
|
| 13 |
+
return zlib.compress(pickle.dumps(y,protocol=5),3)
|
| 14 |
+
def unpack(b):
|
| 15 |
+
y=pickle.loads(zlib.decompress(b));bits=y.pop('_bits');w=y.pop('_weight')
|
| 16 |
+
y['members']=np.unpackbits(bits,axis=1,count=y['atoms']).astype('float32')*w[:,None];return y
|
| 17 |
+
def init():
|
| 18 |
+
global rd,parents
|
| 19 |
+
rd=old.Reader();parents=[(old.ro(C['r4_train_fragments']),'SELECT 1 FROM extra WHERE k=?'),
|
| 20 |
+
(old.ro(old.R2/'prepared/assets.sqlite'),'SELECT 1 FROM canonical_features WHERE feature_key=? AND feature_sha IS NOT NULL'),
|
| 21 |
+
(old.ro(old.R3/'prepared/assets.sqlite'),'SELECT 1 FROM r3_features WHERE feature_key=? AND feature_sha IS NOT NULL')]
|
| 22 |
+
def block(pairs):
|
| 23 |
+
rows=[];stats=collections.Counter()
|
| 24 |
+
for gh,k in pairs:
|
| 25 |
+
m=rd.molecule(gh)
|
| 26 |
+
if m.identity!=k:raise ValueError('training structure key drift')
|
| 27 |
+
fk=old.ft.key(m.smiles)
|
| 28 |
+
for j,(db,q) in enumerate(parents):
|
| 29 |
+
if db.execute(q,(fk,)).fetchone():stats[['r4','r2','r3'][j]]+=1;break
|
| 30 |
+
else:
|
| 31 |
+
v=old.ft.build(m.smiles)
|
| 32 |
+
if old.ft.layout(m.mol)!=v['layout']:raise ValueError('unsafe feature atom layout')
|
| 33 |
+
b=pack(v)
|
| 34 |
+
if len(rows)==0 and not np.array_equal(unpack(b)['members'],v['members']):raise RuntimeError('packing changed features')
|
| 35 |
+
rows.append((fk,b,bytes.fromhex(sha(b))));stats['new']+=1
|
| 36 |
+
return rows,stats
|
| 37 |
+
def run():
|
| 38 |
+
while not (LARGE/'READY.json').exists():
|
| 39 |
+
if (SMALL/'AUGMENT_ERROR.json').exists():raise RuntimeError('alternative pools not ready')
|
| 40 |
+
time.sleep(4)
|
| 41 |
+
FRESH.mkdir(parents=True,exist_ok=True);fd=(FRESH/'prepare.lock').open('a+');fcntl.flock(fd,fcntl.LOCK_EX|fcntl.LOCK_NB)
|
| 42 |
+
bind=dict(random=read(BASE/'READY.json')['ledger_hash'],augmented=read(LARGE/'READY.json')['hash'],builder=hashfile(__file__))
|
| 43 |
+
if (FRESH/'PLAN.json').exists() and read(FRESH/'PLAN.json')!=bind:raise RuntimeError('stale feature cache')
|
| 44 |
+
if (FRESH/'READY.json').exists() and read(FRESH/'READY.json')['binding']==bind:return
|
| 45 |
+
save(FRESH/'PLAN.json',bind);store={};h0=read(BASE/'hashes.json');h1=read(LARGE/'hashes.json')
|
| 46 |
+
def add(a,b):
|
| 47 |
+
if store.setdefault(a,b)!=b:raise RuntimeError('conflicting graph key')
|
| 48 |
+
for i in range(3000):
|
| 49 |
+
name='%04d.z'%i;b=(BASE/'batches'/name).read_bytes();z=(LARGE/'batches'/name).read_bytes()
|
| 50 |
+
if sha(b)!=h0[i] or sha(z)!=h1[i]:raise ValueError('changed data ledger')
|
| 51 |
+
rr=old.ft.loads(b)['rows'];special=old.ft.loads(z)
|
| 52 |
+
for r in rr:
|
| 53 |
+
add(r['ref'],r['identity'])
|
| 54 |
+
for p in r['pools']:
|
| 55 |
+
for g,k in zip(p['graphs'],p['ids'],strict=True):add(g,k)
|
| 56 |
+
for p in list(special['teacher'].values())+([special['expanded']] if special['expanded'] else []):
|
| 57 |
+
for g,k in zip(p['graphs'],p['ids'],strict=True):add(g,k)
|
| 58 |
+
if i%150==0:save(SMALL/'ASSET_STATUS.json',dict(phase='unique_candidate_index',batches=i,graphs=len(store),ts=time.time()))
|
| 59 |
+
pairs=sorted(store.items());del store;bsize=768;n=(len(pairs)+bsize-1)//bsize
|
| 60 |
+
db=sqlite3.connect(FRESH/'delta.sqlite',timeout=90);db.execute('PRAGMA page_size=32768');db.execute('PRAGMA journal_mode=WAL')
|
| 61 |
+
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')
|
| 62 |
+
db.execute('CREATE TABLE IF NOT EXISTS blocks(i INTEGER PRIMARY KEY, hash TEXT, stats TEXT)');db.commit()
|
| 63 |
+
before=dict(db.execute('select i,hash from blocks'));starts=[]
|
| 64 |
+
for i in range(n):
|
| 65 |
+
if i in before:
|
| 66 |
+
if before[i]!=old.objhash(pairs[i*bsize:(i+1)*bsize]):raise RuntimeError('block receipt changed')
|
| 67 |
+
else:starts.append(i)
|
| 68 |
+
it=iter(starts);jobs={};done=len(before);beg=time.monotonic()
|
| 69 |
+
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))
|
| 70 |
+
status()
|
| 71 |
+
with cf.ProcessPoolExecutor(8,mp_context=mp.get_context('fork'),initializer=init) as ex:
|
| 72 |
+
while True:
|
| 73 |
+
while len(jobs)<16:
|
| 74 |
+
i=next(it,None)
|
| 75 |
+
if i is None:break
|
| 76 |
+
pp=pairs[i*bsize:(i+1)*bsize];jobs[ex.submit(block,pp)]=(i,old.objhash(pp))
|
| 77 |
+
if not jobs:break
|
| 78 |
+
for f in cf.wait(jobs,return_when=cf.FIRST_COMPLETED).done:
|
| 79 |
+
i,h=jobs.pop(f);rows,stats=f.result()
|
| 80 |
+
db.executemany('insert or ignore into extra values(?,?,?)',rows);db.execute('insert into blocks values(?,?,?)',(i,h,json.dumps(stats)));db.commit();done+=1
|
| 81 |
+
if done%30==0:
|
| 82 |
+
status()
|
| 83 |
+
if shutil.disk_usage(ROOT).free<C['min_tmpfs_free_mib']*2**20:raise RuntimeError('tmpfs reserve; no old data removed')
|
| 84 |
+
counts=collections.Counter()
|
| 85 |
+
for s, in db.execute('select stats from blocks'):counts.update(json.loads(s))
|
| 86 |
+
assert done==n and sum(counts.values())==len(pairs)
|
| 87 |
+
db.execute('PRAGMA wal_checkpoint(TRUNCATE)');db.close()
|
| 88 |
+
ready=dict(binding=bind,complete=True,graphs=len(pairs),counts=dict(counts),sha256=hashfile(FRESH/'delta.sqlite'))
|
| 89 |
+
save(FRESH/'READY.json',ready);save(SMALL/'ASSETS_READY.json',ready);status()
|
| 90 |
+
if __name__=='__main__':
|
| 91 |
+
try:run()
|
| 92 |
+
except Exception:save(SMALL/'ASSET_ERROR.json',dict(error=traceback.format_exc(),ts=time.time()));raise
|
code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/audit_identity5.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Identify *all* mismatched accepted-candidate record -> graph key bindings.
|
| 2 |
+
No repair of a label by trusting an unrelated graph. Read only published source.
|
| 3 |
+
"""
|
| 4 |
+
import json,sys,time
|
| 5 |
+
from collections import Counter,defaultdict
|
| 6 |
+
from paths5 import *
|
| 7 |
+
sys.path.insert(0,C['r4_code']);import prepare4 as old
|
| 8 |
+
def main():
|
| 9 |
+
expected={};bad={};r=old.Reader();st=time.time()
|
| 10 |
+
def index(g,k):
|
| 11 |
+
if g in expected and expected[g]!=k:raise ValueError('graph used with two distinct recorded identities')
|
| 12 |
+
expected[g]=k
|
| 13 |
+
for j in range(3000):
|
| 14 |
+
nm='%04d.z'%j;aa=old.ft.loads((BASE/'batches'/nm).read_bytes());bb=old.ft.loads((LARGE/'batches'/nm).read_bytes())
|
| 15 |
+
for row in aa['rows']:
|
| 16 |
+
index(row['ref'],row['identity'])
|
| 17 |
+
for p in row['pools']:
|
| 18 |
+
for g,k in zip(p['graphs'],p['ids'],strict=True):index(g,k)
|
| 19 |
+
for p in list(bb['teacher'].values())+([bb['expanded']] if bb['expanded'] else []):
|
| 20 |
+
for g,k in zip(p['graphs'],p['ids'],strict=True):index(g,k)
|
| 21 |
+
keys=sorted(expected)
|
| 22 |
+
for i in range(0,len(keys),512):
|
| 23 |
+
kk=keys[i:i+512];q='select graph_hash,identity,safety from graphs where graph_hash in ('+','.join(['?']*len(kk))+')'
|
| 24 |
+
rows=list(r.assets.execute(q,kk));assert len(rows)==len(kk)
|
| 25 |
+
for g,k,safety in rows:
|
| 26 |
+
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}
|
| 27 |
+
occurrences=Counter();detail=[];files=set()
|
| 28 |
+
for j in range(3000):
|
| 29 |
+
nm='%04d.z'%j;aa=old.ft.loads((BASE/'batches'/nm).read_bytes());bb=old.ft.loads((LARGE/'batches'/nm).read_bytes())
|
| 30 |
+
def test(g,k,role,typ,rid):
|
| 31 |
+
if g in bad:
|
| 32 |
+
assert k==bad[g]['declared'];occurrences[role]+=1;files.add(j)
|
| 33 |
+
detail.append(dict(batch=j,rid=rid,role=role,kind=typ,graph=g))
|
| 34 |
+
for row in aa['rows']:
|
| 35 |
+
test(row['ref'],row['identity'],'label','label',row['rid'])
|
| 36 |
+
for p in row['pools']:
|
| 37 |
+
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'])
|
| 38 |
+
for typ,ps in [('mining',bb['teacher'].values()),('large',[bb['expanded']] if bb['expanded'] else [])]:
|
| 39 |
+
for p in ps:
|
| 40 |
+
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'])
|
| 41 |
+
out=dict(complete=True,total_graphs=len(keys),mismatches=list(bad.values()),occurrences=dict(occurrences),affected_batches=sorted(files),
|
| 42 |
+
detail=detail,original_draw_ledger=read(BASE/'READY.json')['ledger_hash'],original_alternatives=read(LARGE/'READY.json')['hash'],seconds=time.time()-st)
|
| 43 |
+
save(SMALL/'IDENTITY_AUDIT_V1.json',out)
|
| 44 |
+
print(json.dumps({k:v for k,v in out.items() if k not in ('detail','affected_batches')})[:2500],flush=True)
|
| 45 |
+
if __name__=='__main__':main()
|
code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/augment5.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Training-only offline alternative pools, preserving query IDs and cursor."""
|
| 2 |
+
import concurrent.futures as cf, multiprocessing as mp,random,sys,time,os,traceback,fcntl
|
| 3 |
+
from collections import Counter
|
| 4 |
+
from functools import lru_cache
|
| 5 |
+
from paths5 import *
|
| 6 |
+
sys.path.insert(0,C['r4_code'])
|
| 7 |
+
import prepare4 as old
|
| 8 |
+
from data09 import Reader,loads
|
| 9 |
+
H=read(HERE/'interventions.json')
|
| 10 |
+
def u64(t):return int(sha(t.encode())[:16],16)
|
| 11 |
+
def order_key(r,p):return (u64('R5/view/'+r['rid']+p['kind']),r['rid'])
|
| 12 |
+
def init():
|
| 13 |
+
global rd,lookup
|
| 14 |
+
rd=Reader()
|
| 15 |
+
@lru_cache(maxsize=32768)
|
| 16 |
+
def alias(s):
|
| 17 |
+
v=rd.assets.execute('SELECT graph_hash FROM smiles WHERE smiles=?',(s,)).fetchone()
|
| 18 |
+
if not v:raise RuntimeError('Missing accepted alias')
|
| 19 |
+
return v[0]
|
| 20 |
+
lookup=alias
|
| 21 |
+
def universe(r,p):
|
| 22 |
+
v=loads(rd.db.execute('SELECT body FROM samples WHERE record_id=?',(r['rid'],)).fetchone()[0])
|
| 23 |
+
if p['kind']=='odata':
|
| 24 |
+
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']]
|
| 25 |
+
else:
|
| 26 |
+
o=rd.official(v['target'],p['kind']);es=o['entries'];allowed=[j for j,e in enumerate(es) if e['eligible_for_training']]
|
| 27 |
+
by={}
|
| 28 |
+
for j in allowed:
|
| 29 |
+
ident=old.entry_identity(es[j])
|
| 30 |
+
if ident in rd.forbidden:raise ValueError('heldout candidate in accepted training view')
|
| 31 |
+
if ident!=r['identity']:by.setdefault(ident,j)
|
| 32 |
+
return es,by
|
| 33 |
+
def select(r,p,maxn,scope):
|
| 34 |
+
es,by=universe(r,p);base=list(p['ids']);orig=set(base)
|
| 35 |
+
if not set(base[1:])<=set(by):raise ValueError('base draw not in unmodified pool')
|
| 36 |
+
extra=sorted(set(by)-orig)
|
| 37 |
+
rng=random.Random(u64(f'R5/draw/{scope}/{r["rid"]}/{p["kind"]}'))
|
| 38 |
+
if len(extra)>max(0,maxn-len(base)):extra=rng.sample(extra,max(0,maxn-len(base)))
|
| 39 |
+
graphs=list(p['graphs'])
|
| 40 |
+
for k in extra:
|
| 41 |
+
e=es[by[k]];graphs.append(e.get('graph_hash') or lookup(e.get('canonical_smiles') or e['smiles']))
|
| 42 |
+
ids=base+extra
|
| 43 |
+
assert len(ids)==len(set(ids))==len(graphs) and not(set(ids)&rd.forbidden)
|
| 44 |
+
return dict(ids=ids,graphs=graphs,base_n=len(base),available=len(by)+1,kind=p['kind'],rid=r['rid'],truth=r['identity'],
|
| 45 |
+
formulas=p['formulas'],negative_draws=len(ids)-1,unique_negative_key14=len(ids)-1,reference_injected=False)
|
| 46 |
+
def make(i):
|
| 47 |
+
dest=LARGE/'batches'/('%04d.z'%i);base=BASE/'batches'/dest.name
|
| 48 |
+
if dest.exists():return i
|
| 49 |
+
plan=old.ft.loads(base.read_bytes());by={k:[] for k in ('odata','mass','formula')}
|
| 50 |
+
for r in plan['rows']:
|
| 51 |
+
for p in r['pools']:by[p['kind']].append((r,p))
|
| 52 |
+
cands={}
|
| 53 |
+
for k,rr in by.items():
|
| 54 |
+
for r,p in sorted(rr,key=lambda tup:order_key(*tup))[:H['B']['pools_per_kind']]:
|
| 55 |
+
cands[(r['rid'],k)]=select(r,p,1+H['B']['mining_multiplier']*(len(p['ids'])-1),'mining')
|
| 56 |
+
cap=H['D']['caps'][min(i//750,3)];large=None
|
| 57 |
+
# Inspect real available sizes; choose without any model score. Base positives
|
| 58 |
+
# were originally in pool. At most one expanded view per step.
|
| 59 |
+
options=[]
|
| 60 |
+
for k in ('odata','mass','formula'):
|
| 61 |
+
for r,p in sorted(by[k],key=lambda tup:order_key(*tup))[:4]:
|
| 62 |
+
item=cands.get((r['rid'],k));avail=item['available'] if item is not None else len(universe(r,p)[1])+1
|
| 63 |
+
if avail>len(p['ids']):options.append((min(avail,cap),k=='odata',-order_key(r,p)[0],r,p))
|
| 64 |
+
if options:
|
| 65 |
+
_,_,_,r,p=max(options,key=lambda z:z[:3]);large=select(r,p,cap,'larger')
|
| 66 |
+
b=old.ft.dumps(dict(index=i,base_sha=hashfile(base),teacher=cands,expanded=large,cap=cap))
|
| 67 |
+
t=dest.with_suffix('.tmp');t.write_bytes(b);os.replace(t,dest);return i
|
| 68 |
+
def main():
|
| 69 |
+
while not (BASE/'READY.json').exists():
|
| 70 |
+
if (SMALL/'LEDGER_ERROR.json').exists():raise RuntimeError('base preparation error')
|
| 71 |
+
time.sleep(4)
|
| 72 |
+
LARGE.mkdir(exist_ok=True,parents=True);(LARGE/'batches').mkdir(exist_ok=True)
|
| 73 |
+
fd=(LARGE/'prep.lock').open('a+');fcntl.flock(fd,fcntl.LOCK_EX|fcntl.LOCK_NB)
|
| 74 |
+
binding=dict(ledger=read(BASE/'READY.json')['ledger_hash'],source=hashfile(__file__),settings=hashfile(HERE/'interventions.json'))
|
| 75 |
+
if (LARGE/'PLAN.json').exists() and read(LARGE/'PLAN.json')!=binding:raise RuntimeError('changed prepared input binding')
|
| 76 |
+
save(LARGE/'PLAN.json',binding)
|
| 77 |
+
if (LARGE/'READY.json').exists() and read(LARGE/'READY.json')['binding']==binding:return
|
| 78 |
+
with cf.ProcessPoolExecutor(6,mp_context=mp.get_context('fork'),initializer=init) as ex:
|
| 79 |
+
for j,_ in enumerate(ex.map(make,range(3000),chunksize=4),1):
|
| 80 |
+
if j%60==0:save(SMALL/'AUGMENT_STATUS.json',dict(done=j,total=3000,phase='training_only_alternative_draws',ts=time.time()))
|
| 81 |
+
hs=[];views=Counter();stats={c:[] for c in H['D']['caps']};oldhash=read(BASE/'hashes.json')
|
| 82 |
+
for i in range(3000):
|
| 83 |
+
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
|
| 84 |
+
for _,p in item['teacher'].items():views[p['kind']]+=1
|
| 85 |
+
p=item['expanded'];stats[item['cap']].append(len(p['ids']) if p else 0)
|
| 86 |
+
import numpy as np
|
| 87 |
+
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()}
|
| 88 |
+
out=dict(binding=binding,hash=old.objhash(hs),teacher_views=dict(views),larger_windows=diag)
|
| 89 |
+
save(LARGE/'hashes.json',hs);save(LARGE/'READY.json',out);save(SMALL/'ALTERNATIVES_READY.json',out)
|
| 90 |
+
if __name__=='__main__':
|
| 91 |
+
try:main()
|
| 92 |
+
except Exception:save(SMALL/'AUGMENT_ERROR.json',dict(error=traceback.format_exc(),ts=time.time()));raise
|
code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/batch5.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import replace
|
| 2 |
+
from functools import lru_cache
|
| 3 |
+
import sys,time
|
| 4 |
+
from paths5 import *
|
| 5 |
+
sys.path.insert(0,C['r4_code'])
|
| 6 |
+
import common4 as old
|
| 7 |
+
from data09 import Reader,loads
|
| 8 |
+
from data4 import Fragments as Prior
|
| 9 |
+
from assets5 import unpack
|
| 10 |
+
|
| 11 |
+
class Store(Prior):
|
| 12 |
+
def __init__(self,split='train',warm=False):
|
| 13 |
+
super().__init__(split,Path(C['r4_train_fragments']) if split=='train' else None)
|
| 14 |
+
self.extras=[]
|
| 15 |
+
if split=='train' and (NEWASSET/'READY.json').exists():
|
| 16 |
+
self.extras=[old.ro(s/'delta.sqlite') for s in (NEWASSET,FRESH)]
|
| 17 |
+
elif split=='train' and (FRESH/'READY.json').exists():self.extras=[old.ro(FRESH/'delta.sqlite')]
|
| 18 |
+
self.warm=warm
|
| 19 |
+
if split=='train' and not warm and not self.extras:raise RuntimeError('unverified training cache')
|
| 20 |
+
self.get=lru_cache(8192)(self.fetch)
|
| 21 |
+
def fetch(self,smi):
|
| 22 |
+
for ex in self.extras:
|
| 23 |
+
rows=ex.execute('select b,h from extra where k=?',(old.ft.key(smi),)).fetchone()
|
| 24 |
+
if rows:
|
| 25 |
+
if not old.ft.digest_matches(rows[0],rows[1]):raise RuntimeError('altered static features')
|
| 26 |
+
a=unpack(rows[0])
|
| 27 |
+
if a['smiles']!=smi or a['version']!=old.ft.VERSION:raise RuntimeError('feature identity mismatch')
|
| 28 |
+
return a
|
| 29 |
+
try:return super().fetch(smi)
|
| 30 |
+
except RuntimeError as e:
|
| 31 |
+
if self.warm and str(e).startswith('Missing precomputed fragment data'):return old.ft.build(smi)
|
| 32 |
+
raise
|
| 33 |
+
|
| 34 |
+
class Batches:
|
| 35 |
+
def __init__(self,arm,start,end,warm=False):
|
| 36 |
+
self.arm=arm;self.start=start;self.end=end;self.rd=None;self.warm=warm
|
| 37 |
+
def __len__(self):return self.end-self.start
|
| 38 |
+
def __getitem__(self,j):
|
| 39 |
+
if j>=len(self):raise IndexError(j)
|
| 40 |
+
beg=time.monotonic();i=self.start+j;name='%04d.z'%i
|
| 41 |
+
if self.rd is None:
|
| 42 |
+
self.rd=Reader();self.store=Store('train',self.warm);self.hs=current_hashes(BASE)
|
| 43 |
+
self.alt=current_hashes(LARGE) if self.arm in 'BDE' and (LARGE/'READY.json').exists() else None
|
| 44 |
+
b=current_batch(BASE,name).read_bytes()
|
| 45 |
+
if sha(b)!=self.hs[i]:raise RuntimeError('random batch hash drift')
|
| 46 |
+
sel=old.ft.loads(b);alt={}
|
| 47 |
+
if self.arm in 'BDE':
|
| 48 |
+
z=current_batch(LARGE,name).read_bytes()
|
| 49 |
+
if self.alt and self.alt[i]!=sha(z):raise RuntimeError('alternative batch hash drift')
|
| 50 |
+
if not self.alt and not self.warm:raise RuntimeError('unverified alternative batch')
|
| 51 |
+
alt=old.ft.loads(z)
|
| 52 |
+
assert alt['base_sha']==self.hs[i] and alt['index']==i
|
| 53 |
+
rows=[];rd=self.rd
|
| 54 |
+
for s in sel['rows']:
|
| 55 |
+
row=loads(rd.db.execute('select body from samples where record_id=?',(s['rid'],)).fetchone()[0])
|
| 56 |
+
ref=rd.molecule(s['ref']);assert ref.identity==row['identity']==s['identity'] and ref.identity not in rd.forbidden
|
| 57 |
+
row.update(ref=ref,formulas=s['formulas'],pools=[]);row['query']=replace(row['query'],formula_candidates=row['formulas'])
|
| 58 |
+
feat=self.store.get(ref.smiles)
|
| 59 |
+
if old.ft.layout(ref.mol)!=feat['layout']:raise RuntimeError('wrong atom layout')
|
| 60 |
+
row['chemical_counts']=feat['counts']
|
| 61 |
+
for p0 in s['pools']:
|
| 62 |
+
p=p0;key=(s['rid'],p0['kind']);expanded=False
|
| 63 |
+
if self.arm=='D' and alt.get('expanded') and key==(alt['expanded']['rid'],alt['expanded']['kind']):
|
| 64 |
+
p=alt['expanded'];expanded=len(p['ids'])>len(p0['ids'])
|
| 65 |
+
ms=tuple(rd.molecule(g) for g in p['graphs']);ids=[m.identity for m in ms]
|
| 66 |
+
if ids!=p['ids'] or ids[0]!=ref.identity or len(set(ids))!=len(ids):raise RuntimeError('false negative')
|
| 67 |
+
view='odata_oracle' if p['kind']=='odata' else 'msg_'+p['kind']
|
| 68 |
+
q=replace(row['query'],candidates=ms,formula_candidates=tuple(p['formulas']),candidate_view=view)
|
| 69 |
+
item=dict(**p,query=q,positive_index=0,truth_identity=ref.identity,truth_formula=row['formula'],record_id=s['rid'],
|
| 70 |
+
quality_eligible=bool(row['mass_ok']),spectrum_eligible=bool(row['mass_ok'] and old.ft.supported_positive(q,feat)),
|
| 71 |
+
r5_expanded=expanded,r5_retention=False,r5_teacher_bank=None)
|
| 72 |
+
if self.arm=='B' and key in alt['teacher']:
|
| 73 |
+
t=alt['teacher'][key];tm=tuple(rd.molecule(g) for g in t['graphs'])
|
| 74 |
+
if [m.identity for m in tm]!=t['ids'] or t['ids'][:len(ids)]!=ids:raise RuntimeError('changed teacher source')
|
| 75 |
+
item['r5_teacher_bank']=(replace(q,candidates=tm),t['graphs'])
|
| 76 |
+
if self.arm=='E' and key in alt['teacher']:item['r5_retention']=True
|
| 77 |
+
row['pools'].append(item)
|
| 78 |
+
rows.append(row)
|
| 79 |
+
return dict(rows=rows,manifest_index=i,ledger_sha256=self.hs[i],epoch=sel['epoch'],step=sel['step'],
|
| 80 |
+
data_seconds=time.monotonic()-beg)
|
code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/data.supervisor.conf
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[program:specpartition-r5-from-r4d-data-20261112]
|
| 2 |
+
directory=/root/xj/SpecPartition-MS/code/ceir_r5_from_r4d_12000_20261112
|
| 3 |
+
command=/usr/bin/nice -n 10 /workspace/xj/SpecPartition-MS/.venv/bin/python -B -u data_pipeline.py
|
| 4 |
+
environment=PYTHONUNBUFFERED="1",OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1",CUDA_VISIBLE_DEVICES=""
|
| 5 |
+
autostart=false
|
| 6 |
+
autorestart=false
|
| 7 |
+
startsecs=1
|
| 8 |
+
stopasgroup=true
|
| 9 |
+
killasgroup=true
|
| 10 |
+
stdout_logfile=/root/xj/SpecPartition-MS/runs/ceir_r5_from_r4d_12000_20261112/data.log
|
| 11 |
+
stdout_logfile_maxbytes=2MB
|
| 12 |
+
stdout_logfile_backups=1
|
| 13 |
+
redirect_stderr=true
|
code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/data_pipeline.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os,subprocess,sys,time,traceback
|
| 2 |
+
from paths5 import *
|
| 3 |
+
def main():
|
| 4 |
+
for script in ['augment5.py','assets5.py']:
|
| 5 |
+
job=subprocess.run([sys.executable,'-B','-u',str(HERE/script)],cwd=HERE)
|
| 6 |
+
if job.returncode:raise RuntimeError(f'{script} failed: {job.returncode}')
|
| 7 |
+
save(SMALL/'DATA_READY.json',dict(complete=True,storage='tmpfs',ledger=read(BASE/'READY.json')['ledger_hash'],
|
| 8 |
+
augmented=read(LARGE/'READY.json')['hash'],assets=read(FRESH/'READY.json')['sha256'],ts=time.time()))
|
| 9 |
+
if __name__=='__main__':
|
| 10 |
+
try:main()
|
| 11 |
+
except Exception:save(SMALL/'DATA_ERROR.json',dict(error=traceback.format_exc(),ts=time.time()));raise
|
code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/eval5.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""R5-only outputs; the frozen R4 official pool adapter is reused verbatim."""
|
| 2 |
+
import argparse,gzip,json,math,os,sqlite3,sys,time,zlib,shutil
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import numpy as np,torch
|
| 5 |
+
from paths5 import *
|
| 6 |
+
sys.path.insert(0,C['r4_code'])
|
| 7 |
+
from common4 import lock,get,put,filehash,objhash,digest,ro,rt,R3
|
| 8 |
+
from eval4 import table,dbpath,KS,FKS,metric,engine
|
| 9 |
+
from train5 import binding,lease,make,original
|
| 10 |
+
OUT=ROOT/'arms';EVAL=ROOT/'evaluation_scores'
|
| 11 |
+
def eval_dir(arm,u,dataset):return OUT/arm/('%s_%06d'%(dataset,u))
|
| 12 |
+
def parent_validation_parity():
|
| 13 |
+
root=Path(C['parent']).parent/'validation_009000'
|
| 14 |
+
d=get(root/'metrics.json');db=ro(dbpath('validation'))
|
| 15 |
+
target=db.execute('select distinct target from spectra order by target limit 1').fetchone()[0]
|
| 16 |
+
cache=sqlite3.connect('file:'+d['compact']+'?mode=ro&immutable=1',uri=True)
|
| 17 |
+
z,b=cache.execute('select meta,scores from predictions where target=?',(target,)).fetchone();meta=json.loads(zlib.decompress(z));exp=np.frombuffer(zlib.decompress(b),dtype='<f4')
|
| 18 |
+
errors={};counts={}
|
| 19 |
+
for a in C['arms']:
|
| 20 |
+
m,_,_=make(a,split='validation',optimizer=False);m.graph_chunk=32;m.local_chunk=32;m.eval()
|
| 21 |
+
out,raw=table(m,db,target,'validation');act=np.frombuffer(raw,dtype='<f4')
|
| 22 |
+
assert out['pool_order_hash']==meta['pool_order_hash'] and np.array_equal(np.isnan(exp),np.isnan(act))
|
| 23 |
+
for r,t in zip(out['rows'],meta['rows'],strict=True):
|
| 24 |
+
assert all(r[k]==t[k] for k in ('identifier','view','rank','formula_rank','candidate_count','top1_smiles'))
|
| 25 |
+
errors[a]=float(np.nanmax(abs(act-exp)));counts[a]=int(np.isfinite(act).sum())
|
| 26 |
+
if errors[a]>1e-5:raise RuntimeError('official unchanged parent path mismatch '+str((a,errors[a])))
|
| 27 |
+
del m;torch.cuda.empty_cache()
|
| 28 |
+
cache.close();db.close();return dict(n_targets=1,real_validation_rows=len(meta['rows']),finite_scores=counts,max_error=errors)
|
| 29 |
+
def run(arm,update,dataset):
|
| 30 |
+
dest=eval_dir(arm,update,dataset);hold=lock(dest/'eval.lock');bind=binding()
|
| 31 |
+
if dataset!='validation' and (update!=12000 or not (ROOT/'FROZEN_TEST.json').exists()):raise RuntimeError('Test is not frozen')
|
| 32 |
+
ck=OUT/arm/('step_%06d.pt'%update);check=get(ck.with_suffix('.json'))
|
| 33 |
+
if check['sha256']!=filehash(ck):raise RuntimeError('Invalid evaluation checkpoint')
|
| 34 |
+
protocol=dict(dataset=dataset,arm=arm,update=update,checkpoint_sha=check['sha256'],binding_sha=objhash(bind),
|
| 35 |
+
encoding='Per target: float32 little-endian in source order; NaN means no score; formulas follow each structure block. No pruning or substitution.',
|
| 36 |
+
input_path=str(dbpath(dataset)),official_order_hash_per_target=True,
|
| 37 |
+
fixed_input=engine.inputs(dataset) if dataset!='validation' else rt.LEGACY.bind(),truth_injection=False,limit=None)
|
| 38 |
+
if (dest/'protocol.json').exists() and protocol!=get(dest/'protocol.json'):raise RuntimeError('Mixed evaluation binding')
|
| 39 |
+
put(dest/'protocol.json',protocol)
|
| 40 |
+
if (dest/'metrics.json').exists():return
|
| 41 |
+
EVAL.mkdir(parents=True,exist_ok=True)
|
| 42 |
+
compact=EVAL/arm/('%s_%06d.sqlite'%(dataset,update));compact.parent.mkdir(parents=True,exist_ok=True)
|
| 43 |
+
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')
|
| 44 |
+
out.execute('CREATE TABLE IF NOT EXISTS binding(hash TEXT PRIMARY KEY)')
|
| 45 |
+
oid=objhash(protocol);old=out.execute('SELECT hash FROM binding').fetchall()
|
| 46 |
+
if old and old!=[(oid,)]:raise ValueError('Stale compact predictions')
|
| 47 |
+
out.execute('INSERT OR IGNORE INTO binding VALUES(?)',(oid,));out.commit()
|
| 48 |
+
db=ro(dbpath(dataset));targets=[x[0] for x in db.execute('SELECT DISTINCT target FROM spectra ORDER BY target')]
|
| 49 |
+
done={k[0] for k in out.execute('SELECT target FROM predictions')};assert done<=set(targets)
|
| 50 |
+
with lease('eval_'+arm):
|
| 51 |
+
original.setup();model,_,_=make(arm,ck,split='validation' if dataset=='validation' else 'test',optimizer=False,binding=bind);model.eval()
|
| 52 |
+
model.graph_chunk=32;model.local_chunk=32
|
| 53 |
+
for j,target in enumerate(targets):
|
| 54 |
+
if target in done:continue
|
| 55 |
+
if j%40==0 and shutil.disk_usage(compact.parent).free<75*2**20:raise RuntimeError('Compact output filesystem reserve; source unchanged')
|
| 56 |
+
meta,raw=table(model,db,target,dataset)
|
| 57 |
+
out.execute('INSERT INTO predictions VALUES(?,?,?)',(target,zlib.compress(json.dumps(meta,separators=(',',':'),allow_nan=False).encode(),3),zlib.compress(raw,3)))
|
| 58 |
+
if j%16==0:out.commit();put(dest/'status.json',dict(targets=j+1,total=len(targets),ts=time.time()))
|
| 59 |
+
out.commit()
|
| 60 |
+
rows=[]
|
| 61 |
+
for m,s in out.execute('SELECT meta,scores FROM predictions ORDER BY target'):
|
| 62 |
+
v=json.loads(zlib.decompress(m));raw=zlib.decompress(s)
|
| 63 |
+
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')
|
| 64 |
+
rows.extend(v['rows'])
|
| 65 |
+
out.execute('PRAGMA wal_checkpoint(TRUNCATE)');out.close();db.close()
|
| 66 |
+
expected={'msg_test':17556,'validation':19429,'casmi2022':500}[dataset];views=sorted({r['view'] for r in rows})
|
| 67 |
+
assert len(rows)==expected*len(views) and set(views)==({'top10_blind'} if dataset=='casmi2022' else {'mass','formula'})
|
| 68 |
+
if dataset=='casmi2022':assert sum(r['candidate_count'] for r in rows)==1765420 and sum(r['reference_in_pool'] for r in rows)==467
|
| 69 |
+
results={}
|
| 70 |
+
for v in views:
|
| 71 |
+
rr=[r for r in rows if r['view']==v];assert len(rr)==len({r['identifier'] for r in rr})==expected
|
| 72 |
+
results[v]=dict(n=expected,structure=metric(rr,'rank',KS),formula=metric(rr,'formula_rank',FKS),
|
| 73 |
+
coverage=sum(r['reference_in_pool'] for r in rr),scoreable=sum(r['reference_scoreable_in_pool'] for r in rr))
|
| 74 |
+
if dataset!='validation':
|
| 75 |
+
results[v].update(canonical=metric(rr,'canonical_rank',KS),full_inchikey=metric(rr,'inchikey_rank',KS))
|
| 76 |
+
tmp=dest/'rows.tmp.gz'
|
| 77 |
+
with gzip.open(tmp,'wt',compresslevel=4) as f:json.dump(rows,f,separators=(',',':'),allow_nan=False)
|
| 78 |
+
os.replace(tmp,dest/'per_spectrum_summary.json.gz')
|
| 79 |
+
put(dest/'metrics.json',dict(complete=True,results=results,checkpoint=check,compact=str(compact),compact_sha256=filehash(compact),ts=time.time()))
|
| 80 |
+
|
| 81 |
+
if __name__=='__main__':
|
| 82 |
+
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'])
|
| 83 |
+
a=p.parse_args();run(a.arm,a.update,a.dataset)
|