Add exact model code and documentation (4/7)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/verify_live_lineage.pyAdded+44
- code/snapshot/root/code/r5_evidence_pilot_20261112/confirm.pyAdded+74
- code/snapshot/root/code/r5_evidence_pilot_20261112/confirmation_protocol.jsonAdded+12
- code/snapshot/root/code/r5_evidence_pilot_20261112/evidence.pyAdded+82
- code/snapshot/root/code/r5_evidence_pilot_20261112/guard.pyAdded+80
- code/snapshot/root/code/r5_evidence_pilot_20261112/ions.pyAdded+95
- code/snapshot/root/code/r5_evidence_pilot_20261112/pilot.pyAdded+89
- code/snapshot/root/code/r5_evidence_pilot_20261112/pilot_protocol.jsonAdded+9
- code/snapshot/root/code/r5_evidence_pilot_20261112/test_evidence.pyAdded+47
- code/snapshot/root/code/r5_evidence_pilot_20261112/test_guard.pyAdded+45
- code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/configs/capacity_server_v03.jsonAdded+34
- code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/configs/download_parallel_v041.jsonAdded+7
- code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/configs/epoch_server_v06.jsonAdded+47
- code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/configs/inbatch_server_v05.jsonAdded+35
- code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/configs/joint_server_v08.jsonAdded+23
- code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/configs/multiview_server_v02.jsonAdded+41
- code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/configs/offline_server_v04.jsonAdded+42
- code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/configs/scratch_server_v09.jsonAdded+24
- code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/configs/validation_suite_v071.jsonAdded+42
- code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/__init__.pyAdded+2
- code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/benchmark_epoch.pyAdded+113
- code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/chemistry.pyAdded+247
- code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/cli.pyAdded+113
- code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/config.pyAdded+103
- code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/data_v03.pyAdded+192
- code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/engine.pyAdded+257
- code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/epoch_data.pyAdded+224
- code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/epoch_features.pyAdded+65
- code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/evaluate.pyAdded+44
- code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/feature_store.pyAdded+77
- code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/forest.pyAdded+154
- code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/formula_v07.pyAdded+156
- code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/inbatch_data.pyAdded+93
- code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/joint_losses_v08.pyAdded+193
- code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/joint_model_v08.pyAdded+88
- code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/losses.pyAdded+110
- code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/model.pyAdded+275
- code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/model_v03.pyAdded+177
- code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/multiview_data.pyAdded+286
- code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/multiview_pools.pyAdded+166
- code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/multiview_train.pyAdded+265
- code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/negatives.pyAdded+185
- code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/offline_data.pyAdded+372
- code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/parallel_download.pyAdded+266
- code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/pipeline_epoch.pyAdded+94
- code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/prefetch.pyAdded+66
- code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/prepare_epoch.pyAdded+260
- code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/resource_guard_v09.pyAdded+19
- code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/retrieval.pyAdded+164
- code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/schema.pyAdded+127
1234567891011121314151617181920212223242526272829303132333435363738394041424344"""Read-only inspection of the first available *formal* rolling state per arm.Pin the inode open across rotation; this never loads a model onto the GPU."""import sys,time,torchfrom paths5 import *def run(): torch.set_num_threads(1) p=Path(C['parent']);assert hashfile(p)==C['parent_sha256'] par=torch.load(p,map_location='cpu',weights_only=False);po=par['optimizer'];base=par['model'] assert par['arm']=='D' and par['progress']['update']==9000 check={} for arm in C['arms']: folder=ROOT/'arms'/arm/'resume' if not (folder/'LAST.json').exists():continue for _ in range(3): met=read(folder/'LAST.json') path=folder/met['file'] try:f=path.open('rb') except FileNotFoundError:continue break else:raise RuntimeError('could not inspect stable checkpoint') with f: h=_hash(f);assert h==met['sha256'];f.seek(0);x=torch.load(f,map_location='cpu',weights_only=False) assert x['architecture']=='CEIR_R5' and x['arm']==arm and x['binding']['parent']==C['parent_sha256'] n=x['progress']['r5_updates'];assert 0<n<=3000 and x['progress']['update']==n+9000 changed=[k for k,v in base.items() if not torch.equal(v,x['model'][k])] assert any(k.startswith('r4.') for k in changed) and any(not k.startswith(('r2.','r3.','r4.')) for k in changed) moments=x['optimizer'];gs=po['param_groups'] assert all(moments['param_groups'][j]['params']==g['params'] for j,g in enumerate(gs)) steps=[int(moments['state'][k]['step'])-int(v['step']) for k,v in po['state'].items() if 'step' in v] assert max(steps)==n and min(steps)>=0 new=[k for k in x['model'] if k not in base] assert all(k.startswith('r5.') for k in new) and bool(new)==(arm=='C') check[arm]=dict(update=9000+n,actual_new_updates=n,rolling_sha256=h,changed_inherited_state_tensors=len(changed), inherited_r4_duel_tensors_changed=sum(k.startswith('r4.') for k in changed),new_state_tensors=len(new),optimizer_groups=len(moments['param_groups']), inherited_moment_step_increment_min=min(steps),inherited_moment_step_increment_max=max(steps),r4_parent_ledger_chain_unchanged=x['progress']['r4_chain']==par['progress']['r4_chain']) del x receipt=dict(complete=len(check)==len(C['arms']),parent=C['parent_sha256'],verified=check,ts=time.time(),storage='weights in tmpfs; evidence only is persistent') save(SMALL/'LIVE_FORMAL_LINEAGE.json',receipt);print(json.dumps(receipt))def _hash(f): h=hashlib.sha256() for s in iter(lambda:f.read(4*2**20),b''):h.update(s) return h.hexdigest()if __name__=='__main__':run()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374"""Fit on the first 384 train triples, compare on 192 new disjoint triples."""import argparse,gzip,hashlib,json,sysfrom pathlib import Pathfrom collections import Counterimport numpy as npimport torchfrom torch.nn import functional as Ffrom pilot import batch,example,hashedfrom evidence import ForwardEvidencefrom guard import novel_evidence,apply_bounded_bonus
def fit(rows,mode,cfg): torch.manual_seed(cfg['seed']);rng=np.random.default_rng(cfg['seed']) model=ForwardEvidence(hidden=cfg['hidden']);opt=torch.optim.AdamW(model.parameters(),lr=cfg['learning_rate']) for _ in range(cfg['updates_per_fold']): rec=[rows[j] for j in rng.choice(len(rows),cfg['batch'],replace=False)] inp,y=batch(rec);logit,cos,z=model.prototype_logits(*inp,mode) i=torch.arange(len(y));ok=z[i,y,:-1].sum(-1).detach()>1e-9 loss=F.cross_entropy(logit,y)+cfg['lambda_positive_spectrum']*((1.-cos[i,y])*ok).sum()/ok.sum().clamp_min(1) if not torch.isfinite(loss):raise ValueError('nonfinite') opt.zero_grad();loss.backward() torch.nn.utils.clip_grad_norm_(model.parameters(),5.,error_if_nonfinite=True);opt.step() return model.eval()
def main(): ap=argparse.ArgumentParser() for key in ['fit_data','heldout_data','r3_code','output']:ap.add_argument(key,type=Path) args=ap.parse_args();sys.path.insert(0,str(args.r3_code.resolve()));import features_r2 as ft here=Path(__file__).resolve().parent cfg=json.loads((here/'pilot_protocol.json').read_text());p=json.loads((here/'confirmation_protocol.json').read_text()) a,b=[json.load(gzip.open(path,'rt')) for path in (args.fit_data,args.heldout_data)] primary_sha=hashlib.sha256(args.fit_data.read_bytes()).hexdigest() assert b['primary_cohort_sha256']==primary_sha ta,tb=a['rows'],b['rows'];ka={k for r in ta for k in r['keys']};kb={k for r in tb for k in r['keys']} assert len(ta)==p['train_n'] and len(tb)==p['heldout_n'] and len(ka)==3*len(ta) and len(kb)==3*len(tb) and not ka&kb assert not (a['heldout_registry_intersection'] or b['heldout_registry_intersection']) and not ({x['rid'] for x in ta}&{x['rid'] for x in tb}) assert set(Counter(x['stratum'] for x in tb).values())=={p['heldout_per_stratum']} torch.set_num_threads(2);torch.use_deterministic_algorithms(True) dev={};nets={} for kind,mode in [('legacy','absolute'),('diverse','relative')]: tr=[example(r,kind,ft,cfg['proposal_budget']) for r in ta];dev[kind]=[example(r,kind,ft,cfg['proposal_budget']) for r in tb] nets[kind]=fit(tr,mode,cfg) rows=[] with torch.no_grad(): for j,r in enumerate(tb): lh,_=batch([dev['legacy'][j]]);dh,_=batch([dev['diverse'][j]]) _,cos,z0=nets['legacy'].prototype_logits(*lh,'absolute');other,_,z1=nets['diverse'].prototype_logits(*dh,'relative') bonus=novel_evidence(z0[0],z1[0],dh[3][0],[r['formula']]*3,r['keys'],p['saturation']) s=cos[0];guard=apply_bounded_bonus(s,bonus,p['max_addition_on_cosine_scale']) def rank(x): ids=sorted(range(3),key=lambda k:(-float(x[k]),hashed('candidate-id|'+r['keys'][k]))) return ids[0],ids.index(r['positive'])+1 j0,base=rank(s);jg,safe=rank(guard);_,alt=rank(other[0]) rows.append(dict(rid=r['rid'],stratum=r['stratum'],base=base,guard=safe,expanded=alt,winning_identity_changed=j0!=jg, any_novel=bool((bonus>0).any()),raw_base=s.tolist(),raw_bonus=bonus.tolist(),positive=r['positive'],keys=r['keys'])) def stats(rr): return dict(n=len(rr),base=sum(r['base']==1 for r in rr),guard=sum(r['guard']==1 for r in rr),expanded=sum(r['expanded']==1 for r in rr), gains=sum(r['guard']==1 and r['base']!=1 for r in rr),losses=sum(r['guard']!=1 and r['base']==1 for r in rr), any_novel=sum(r['any_novel'] for r in rr),winner_changes=sum(r['winning_identity_changed'] for r in rr)) rng=np.random.default_rng(cfg['seed']);rep=np.zeros(4000);strata=sorted({r['stratum'] for r in rows}) for group in strata: x=np.array([int(r['guard']==1)-int(r['base']==1) for r in rows if r['stratum']==group]) rep+=x[rng.integers(len(x),size=(len(rep),len(x)))].sum(1) out=dict(protocol=p,all=stats(rows),per_stratum={s:stats([r for r in rows if r['stratum']==s]) for s in strata}, delta_paired_descriptive_ci95_pp=(100*np.quantile(rep/len(rows),[.025,.975])).tolist(), primary_cohort_sha256=primary_sha,confirm_sha256=hashlib.sha256(args.heldout_data.read_bytes()).hexdigest(), key14_train_eval_overlap=len(ka&kb),official_keys_overlap=0,rows=rows) with args.output.open('x') as f:json.dump(out,f,indent=2,allow_nan=False) print(json.dumps(out['all']))
if __name__=='__main__':main()123456789101112{ "scope":"Independent train-source confirmation of a bounded physical-evidence component, not a benchmark or production R4 checkpoint", "train_n":384,"heldout_n":192,"heldout_per_stratum":32, "exclusion":"All positive and negative key14s of the initial 384 triples and official held-out registry are forbidden in confirmation. Underlying pretrained R4 is not used.", "fit":"Fit incumbent legacy/absolute and expanded/relative components once, on the same 384 primary triples; same seed 20261112 and 48 updates, batch 8; fit procedure identical to the pilot, no selection on new 192.", "comparison":["legacy absolute cosine, fixed","same cosine plus a bounded novel peak bonus","expanded/relative score alone (context only)"], "new_evidence":"one eligible peak = matched by expanded but not legacy for this candidate AND absent from all other same-formula distinct identities' legacy and expanded proposals; sqrt normalized observed intensity times predicted_mass/(predicted_mass+0.02)", "max_addition_on_cosine_scale":0.10,"saturation":0.02, "ties":"Stable candidate-key hash; candidate order independent of true identity.", "primary_measure":"paired corrected vs damaged top1 count; also report score changes, winner changes, any eligible evidence, uncertainty and missing evidence; all outcomes retained", "limit":"Synthetic three-way competition from experimental train spectra; a separate check, not the large-pool criterion for a full 3000-step experiment. New branch costs additional compute."}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182"""Trainable forward-proposal/residual prototype. No CSI/rank/reference inputs.One candidate identity per context vote. All official entries keep base scores."""import torchfrom torch import nnfrom torch.nn import functional as F
class ForwardEvidence(nn.Module): def __init__(self,feature_dim=24,hidden=48,adducts=6,cap=1.): super().__init__();self.cap=cap self.adduct=nn.Embedding(adducts,8) self.intensity=nn.Sequential(nn.Linear(feature_dim+8,hidden),nn.SiLU(),nn.Linear(hidden,hidden),nn.SiLU(),nn.Linear(hidden,1)) self.other=nn.Linear(8,1);self.gain=nn.Parameter(torch.zeros(())) def ion_prior(self,features,valid,adduct): """Predict ion probabilities from molecular features and acquisition mode ONLY. features [B,M,H,F]; padding cannot consume probability mass. Last bin is unmodelled. """ cond=self.adduct(adduct) ctx=cond[:,None,None,:].expand(*features.shape[:-1],-1) logits=self.intensity(torch.cat((features,ctx),-1)).squeeze(-1).float().masked_fill(~valid,-torch.inf) other=self.other(cond).float()[:,None,:].expand(-1,features.shape[1],-1) return torch.cat((logits,other),-1).softmax(-1) @staticmethod def matched_distribution(prior,index,peak_count): if index.shape!=prior[...,:-1].shape:raise ValueError('ion assignment shape') hist=prior.new_zeros((*prior.shape[:-1],peak_count+1)).scatter_add(-1,index,prior[...,:-1]) return hist+F.pad(prior[...,-1:],(peak_count,0)) @staticmethod def group_readout(hist,observed,groups): """One query [M,P+1]. Use global formula sums, not per-compute-chunk sums. No MxM comparisons. Singletons get zero new evidence; a common explanation cannot distinguish two candidates. Last bin is unmatched probability. """ evidence=hist[:,0]*0 if not observed.numel() or observed.sum().item()<=0:return evidence for g in torch.unique(groups): idx=(groups==g).nonzero().flatten();n=len(idx) if n<2 or int(g)<0:continue z=hist[idx];background=(z.sum(0)-z)/(n-1) # Nonlinear peak-specific contrast; not an additive common formula constant. contrast=(z[:,:-1]-background[:,:-1])/(.02+z[:,:-1]+background[:,:-1]) shift=(contrast*observed).sum(-1)+.25*(background[:,-1]-z[:,-1]) centered=shift.tanh();centered=.5*(centered-centered.mean()) evidence=evidence.index_copy(0,idx,centered) return evidence @staticmethod def absolute_readout(hist,observed): target=F.pad(observed,(0,1)) return F.cosine_similarity(hist,target.expand_as(hist),dim=-1,eps=1e-8) def identity_scores(self,base,distribution,observed,formulas,identities): """Reusable single-pool adapter. Aliases retain their original rank positions. Consuming code must map the same key14 to the same canonical hypothesis bank. """ if len(base)!=len(identities) or len(formulas)!=len(base) or len(base)!=len(distribution):raise ValueError('pool alignment') if not len(base):return base reps={};reverse=[];names=sorted(set(identities));pos={x:i for i,x in enumerate(names)} for i,key in enumerate(identities): if not key:raise ValueError('only scoreable identities in adapter') if key in reps: j=reps[key] if formulas[i]!=formulas[j] or not torch.allclose(distribution[i],distribution[j],atol=1e-6,rtol=0): raise ValueError('inconsistent alias asset; canonicalize before scoring') else:reps[key]=i reverse.append(pos[key]) idx=[reps[k] for k in names];fs=torch.as_tensor([formulas[i] for i in idx],device=base.device) w=observed/observed.sum().clamp_min(1e-12) e=self.group_readout(distribution[idx],w,fs) return base+self.cap*self.gain.tanh()*e[reverse] def prototype_logits(self,features,valid,indices,observed,adduct,mode): """Mechanism-only triples (all same formula); not the production R4D score.""" prior=self.ion_prior(features,valid,adduct) z=self.matched_distribution(prior,indices,observed.shape[-1]) t=F.pad(observed,(0,1));cos=F.cosine_similarity(z,t[:,None,:],dim=-1,eps=1e-8) if mode=='absolute':ev=cos elif mode=='relative': # Vectorized equivalent of group_readout for exactly one formula per triple. bg=(z.sum(1,keepdim=True)-z)/(z.shape[1]-1) con=(z[:,:,:-1]-bg[:,:,:-1])/(.02+z[:,:,:-1]+bg[:,:,:-1]) u=((con*observed[:,None,:]).sum(-1)+.25*(bg[:,:,-1]-z[:,:,-1])).tanh() ev=.5*(u-u.mean(1,keepdim=True)) else:raise ValueError(mode) return 4*ev,cos,z1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980"""Inference-only new-evidence check. No truth, teacher predictions or stored ranks.
One row per distinct scoreable identity; include all competitors across computechunks before reducing. Do not silently treat incomplete contexts as complete.Unscoreables keep their original status outside this adapter."""from collections import Counterimport torch
def novel_evidence(old_hist, new_hist, observed, formulas, ids, strength_scale=.02): """Histograms include an unmatched bin last. Return [0,1] per molecule.
A peak may contribute only if absent from the molecule's old proposals AND absent from EVERY other identity's old and new proposals in its formula. """ if (old_hist.ndim!=2 or old_hist.shape!=new_hist.shape or old_hist.shape!=(len(ids),observed.numel()+1) or len(formulas)!=len(ids)): raise ValueError("misaligned query, isotope/adduct context or histogram") if strength_scale<=0 or not observed.isfinite().all() or (observed<0).any(): raise ValueError("invalid observed intensities") if not all(x is not None and x!='' for x in ids) or len(ids)!=len(set(ids)): raise ValueError("give one canonical row per scoreable identity; broadcast aliases afterwards") if not torch.isfinite(old_hist).all() or not torch.isfinite(new_hist).all() or (old_hist<0).any() or (new_hist<0).any(): raise ValueError("invalid evidence distribution") w=observed/observed.sum().clamp_min(1e-12) a,b=old_hist[:,:-1],new_hist[:,:-1] out=b.new_zeros(len(ids)) grouped={} for j,f in enumerate(formulas): if f is not None and f!='' and f!=-1:grouped.setdefault(f,[]).append(j) for js in grouped.values(): if len(js)<2:continue # Count presence once per identity, not once per ionization channel/CID. aj,bj=a[js],b[js] union=(aj>0)|(bj>0) eligible=(aj==0)&(bj>0)&(union.sum(0)==1) out[js]=(w*eligible*(bj/(strength_scale+bj))).sum(-1) return out
def apply_bounded_bonus(original, bonus, cap): if cap<0 or original.shape!=bonus.shape or not torch.isfinite(bonus).all() or (bonus<0).any() or (bonus>1.00001).any(): raise ValueError("invalid bounded residual") # A gap strictly larger than cap cannot be reversed. return original+cap*bonus.clamp(0,1)
@torch.no_grad()def stream_novelty(observed,formulas,ids,load,block_size=1024,strength_scale=.02): """Exact two-pass inference; load(start,end) returns deterministic old/new distributions for the requested slice of *unique scoreable* identities. Count the entire formula before evaluating any block. Peak storage O((F+B)*P), not O(N^2). The output and identity metadata require O(N). """ n=len(ids);d=observed.numel() if block_size<=0 or strength_scale<=0 or observed.ndim!=1 or not observed.isfinite().all() or (observed<0).any(): raise ValueError('invalid input') if len(formulas)!=n or len(set(ids))!=n or any(k is None or k=='' for k in ids): raise ValueError('use unique scoreable identities with aligned formulas') counts={};sizes=Counter(f for f in formulas if f not in ('',None,-1)) w=observed/observed.sum().clamp_min(1e-12);result=observed.new_zeros(n) for phase in (0,1): for start in range(0,n,block_size): end=min(start+block_size,n);a,b=load(start,end) if (a.shape!=b.shape or a.shape!=(end-start,d+1) or a.device!=observed.device or b.device!=observed.device or not a.isfinite().all() or not b.isfinite().all() or (a<0).any() or (b<0).any()): raise ValueError('malformed cached hypothesis block') a,b=a[:,:-1],b[:,:-1];groups={} for j,f in enumerate(formulas[start:end]): if sizes.get(f,0)>=2:groups.setdefault(f,[]).append(j) for f,ix in groups.items(): ai,bi=a[ix],b[ix] if not phase: hits=((ai>0)|(bi>0)).sum(0,dtype=torch.int32) counts[f]=(counts[f]+hits).clamp_max_(2) if f in counts else hits.clamp_max_(2) else: valid=(ai==0)&(bi>0)&(counts[f]==1) result[[j+start for j in ix]]=(w*valid*(bi/(strength_scale+bi))).sum(-1) return result1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495"""Candidate-only ion proposals; spectrum m/z/intensity never enters enumeration.Frozen R3 legacy descriptor supplied by caller. Proposed layouts are hypotheses,not experimental fragment labels. Supports the six inherited singly charged adducts."""from collections import defaultdictfrom itertools import combinationsimport numpy as npfrom rdkit import Chem
ADDUCTS=('[M+H]+','[M+Na]+','[M+NH4]+','[M-H]-','[M+Cl]-','[M+FA-H]-')FEATURE_DIM=24def canon(smi): m=Chem.MolFromSmiles(smi) if m is None or Chem.GetFormalCharge(m) or any(a.GetIsotope() for a in m.GetAtoms()) or len(Chem.GetMolFrags(m))!=1: raise ValueError('unsupported structure') Chem.RemoveStereochemistry(m);return Chem.MolToSmiles(m,canonical=True,isomericSmiles=False)def generate(smi,adduct,variant,ft,budget=32): if variant not in ('legacy','diverse'):raise ValueError(variant) s=canon(smi);m=Chem.MolFromSmiles(s);n=m.GetNumAtoms() empty=lambda:(np.empty(0,np.float32),np.empty((0,FEATURE_DIM),np.float32),0) if n<5 or adduct not in ADDUCTS:return empty() atoms=list(m.GetAtoms());zs=np.array([a.GetAtomicNum() for a in atoms]);hs=np.array([a.GetTotalNumHs() for a in atoms],int) atom_mass=np.array([ft.PT.GetMostCommonIsotopeMass(int(z)) for z in zs])+hs*ft.H ar=np.array([a.GetIsAromatic() for a in atoms]);rin=np.array([a.IsInRing() for a in atoms]) bonds=list(m.GetBonds());edges=[(b.GetBeginAtomIdx(),b.GetEndAtomIdx()) for b in bonds] adj=[[] for _ in atoms] for j,(a,b) in enumerate(edges):adj[a].append((b,j));adj[b].append((a,j)) neutral=float(atom_mass.sum()) parent=ft.build(s);parts={tuple(np.flatnonzero(bits>0)) for bits,valid in zip(parent['members'],parent['valid']) if valid} def hetero(j):return sum(zs[u] in (7,8,15,16) for u in edges[j]) if variant=='diverse': bridge=sorted((b.GetIdx() for b in bonds if not b.IsInRing() and b.GetBondType()==Chem.BondType.SINGLE),key=lambda j:(-hetero(j),j))[:24] ring_pairs=set(p for ring in m.GetRingInfo().BondRings() for p in combinations(sorted(ring),2)) # Paired cuts in the same ring, and internal fragments bounded by two # acyclic single bonds. Fixed budgets; no spectral or label-dependent cuts. priority=lambda pair:(sum(bonds[j].GetIsAromatic() for j in pair),-sum(hetero(j) for j in pair),pair) cuts=[(j,) for j in bridge]+sorted(combinations(bridge,2),key=priority)[:48]+sorted(ring_pairs,key=priority)[:48] for cut in cuts: for comp in ft.components(n,adj,set(cut)): if not 3<=len(comp)<=n-2:continue aset=set(comp) if all((edges[j][0] in aset)!=(edges[j][1] in aset) for j in cut):parts.add(tuple(comp)) # Avoid counting identical subformula masses as multiple independent peaks. # The representative is chosen deterministically; this small prototype does # not learn the alternative cleavage mechanisms giving the same composition. uniq={} for part in sorted(parts): idx=list(part);aset=set(part);cut=[j for j,(a,b) in enumerate(edges) if (a in aset)!=(b in aset)];z=zs[idx] mass=float(atom_mass[idx].sum());h=int(hs[idx].sum());size=len(idx) if not cut:continue ring=sum(bonds[j].IsInRing() for j in cut);het=sum(hetero(j) for j in cut) key=tuple(sorted(z.tolist()))+(0,h) prio=(len(cut),sum(bonds[j].GetIsAromatic() for j in cut),-het,part) if key in uniq and uniq[key][0]<=prio:continue vals=[mass/600,mass/neutral,size/n,size/40,h/60,h/max(size,1)/3, *[float((z==el).sum())/size for el in (6,7,8,15,16,9,17,35)], ar[idx].mean(),rin[idx].mean(),len(cut)/3,ring/2,het/max(1,2*len(cut)), float(sum(bonds[j].GetIsAromatic() for j in cut))/len(cut)] uniq[key]=(prio, mass, h, vals) selected=list(uniq.values()) if len(selected)>budget: buckets=defaultdict(list) for item in selected:buckets[min(7,int(8*item[1]/neutral))].append(item) for b in buckets.values():b.sort(key=lambda item:item[0]) selected=[];depth=0 while len(selected)<budget: for k in sorted(buckets): if depth<len(buckets[k]):selected.append(buckets[k][depth]) if len(selected)==budget:break depth+=1 ions={};offsets=[o for o in ft.ion_offsets(adduct) if o is not None] for prio,mass,h,features in selected: for shift in (-2,-1,0,1,2): if h+shift<0:continue for channel,offset in enumerate(offsets): mz=mass+shift*ft.H+offset if mz<=0:continue k=round(mz,5);quality=(abs(shift),channel,prio) if k not in ions or quality<ions[k][0]: ions[k]=(quality,mz,features+[shift/2,float(channel),mz/600,float(adduct.endswith('-'))]) if not ions:return empty() ordered=[ions[k] for k in sorted(ions)] features=np.asarray([x[2] for x in ordered],np.float32);assert features.shape[1]==FEATURE_DIM return np.array([x[1] for x in ordered],np.float32),features,len(selected)def observed(peaks,precursor): x=np.array(sorted(sorted(peaks,key=lambda v:(-v[1],v[0]))[:256]),float).reshape(-1,2) if np.any(~np.isfinite(x)) or np.any(x[:,1]<0):raise ValueError('invalid spectrum') x=x[(x[:,1]>0)&(abs(x[:,0]-precursor)>max(.05,precursor*2e-5))] return x[:,0],np.sqrt(x[:,1])/max(1e-12,np.sqrt(x[:,1]).sum())def assign(ions,mz): # A theoretical ion votes for at most one experimental peak. P means off-spectrum. if not len(mz):return np.full(len(ions),0,int) k=np.searchsorted(mz,ions);l=np.clip(k-1,0,len(mz)-1);r=np.clip(k,0,len(mz)-1) ix=np.where(abs(mz[l]-ions)<=abs(mz[r]-ions),l,r) return np.where(abs(mz[ix]-ions)<=np.maximum(.02,2e-5*ions),ix,len(mz))1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889import argparse,collections,gzip,hashlib,json,sys,timefrom pathlib import Pathimport numpy as npimport torchfrom torch.nn import functional as Ffrom evidence import ForwardEvidencefrom ions import ADDUCTS,FEATURE_DIM,generate,observed,assign
def hashed(v):return hashlib.sha256(v.encode()).hexdigest()def example(row,var,ft,K): mz,w=observed(row['peaks'],row['precursor']);ff=[];ii=[];nn=[];counts=[] for sm in row['smiles']: ions,features,n=generate(sm,row['adduct'],var,ft,K);ff.append(features);ii.append(assign(ions,mz));nn.append(n);counts.append(len(ions)) matched=np.zeros((3,len(w)),bool) for j,idx in enumerate(ii): matched[j,idx[idx<len(w)]]=True pos=row['positive'];other=matched[[j for j in range(3) if j!=pos]] return dict(ff=ff,ii=ii,w=w.astype(np.float32),ad=ADDUCTS.index(row['adduct']),pos=pos,keys=row['keys'],rid=row['rid'],stratum=row['stratum'], n=nn,ions=counts,truth_any_mass=float(w@matched[pos]),have_differential=bool((other!=matched[pos]).any()), truth_exclusive_against_both=float(w@(matched[pos]&~other.any(0))))def batch(records,shuffled=False): B=len(records);H=max(1,max(len(v) for r in records for v in r['ii']));P=max(1,max(len(r['w']) for r in records)) ff=np.zeros((B,3,H,FEATURE_DIM),np.float32);mask=np.zeros((B,3,H),bool);ii=np.full((B,3,H),P,np.int64);w=np.zeros((B,P),np.float32) for b,r in enumerate(records): wp=r['w'] if shuffled:wp=np.random.default_rng(int(hashed('intensity-null|'+r['rid'])[:12],16)).permutation(wp) w[b,:len(wp)]=wp for j,(x,ind) in enumerate(zip(r['ff'],r['ii'])): h=len(ind);ff[b,j,:h]=x;mask[b,j,:h]=True;ii[b,j,:h]=np.where(ind<len(wp),ind,P) return tuple(torch.from_numpy(x) for x in (ff,mask,ii,w,np.array([r['ad'] for r in records],np.int64))),torch.tensor([r['pos'] for r in records])def train_predict(train,dev,mode,fold,cfg): torch.manual_seed(cfg['seed']+fold);rng=np.random.default_rng(cfg['seed']+fold) model=ForwardEvidence(hidden=cfg['hidden']);opt=torch.optim.AdamW(model.parameters(),lr=cfg['learning_rate']) for step in range(cfg['updates_per_fold']): rec=[train[j] for j in rng.choice(len(train),cfg['batch'],replace=False)] inp,y=batch(rec);logits,cos,z=model.prototype_logits(*inp,mode) ids=torch.arange(len(y));eligible=z[ids,y,:-1].sum(-1).detach()>1e-9 loss=F.cross_entropy(logits,y)+cfg['lambda_positive_spectrum']*((1.-cos[ids,y])*eligible).sum()/eligible.sum().clamp_min(1) if not torch.isfinite(loss):raise ValueError('nonfinite loss') opt.zero_grad();loss.backward();torch.nn.utils.clip_grad_norm_(model.parameters(),5.,error_if_nonfinite=True);opt.step() rows=[] with torch.no_grad(): for start in range(0,len(dev),cfg['batch']): rec=dev[start:start+cfg['batch']];inp,y=batch(rec);null,_=batch(rec,True) actual,_,_=model.prototype_logits(*inp,mode);shifted,_,_=model.prototype_logits(*null,mode) for i,r in enumerate(rec): s=actual[i].tolist();n=shifted[i].tolist();order=lambda vals:sorted(range(3),key=lambda j:(-vals[j],hashed('candidate-id|'+r['keys'][j]))) rows.append(dict(rid=r['rid'],stratum=r['stratum'],fold=fold,rank=order(s).index(r['pos'])+1,intensity_null_rank=order(n).index(r['pos'])+1, tie_at_max=s.count(max(s))>1,truth_margin=s[r['pos']]-max(t for j,t in enumerate(s) if j!=r['pos']))) return rowsdef main(): ap=argparse.ArgumentParser();ap.add_argument('data',type=Path);ap.add_argument('--r3-code',type=Path,required=True);ap.add_argument('--output',type=Path,required=True) a=ap.parse_args();sys.path.insert(0,str(a.r3_code.resolve()));import features_r2 as ft base=Path(__file__).resolve().parent;cfg=json.loads((base/'pilot_protocol.json').read_text());obj=json.load(gzip.open(a.data,'rt'));rr=obj['rows'] assert len(rr)==384 and len({x for r in rr for x in r['keys']})==3*len(rr) and obj['heldout_registry_intersection']==0 fold={};groups=sorted({r['stratum'] for r in rr}) for group in groups: subset=sorted([r for r in rr if r['stratum']==group],key=lambda r:hashed('r5/folds/v1/'+r['rid'])) for j,r in enumerate(subset):fold[r['rid']]=j%4 torch.set_num_threads(2);torch.use_deterministic_algorithms(True);out={};diag={} for variant in ['legacy','diverse']: examples=[example(r,variant,ft,cfg['proposal_budget']) for r in rr] diag[variant]=dict(mean_truth_explained_intensity=float(np.mean([s['truth_any_mass'] for s in examples])), any_differential=sum(s['have_differential'] for s in examples),mean_exclusive_against_both=float(np.mean([s['truth_exclusive_against_both'] for s in examples])), mean_proposals=float(np.mean([k for s in examples for k in s['n']])),mean_ions=float(np.mean([k for s in examples for k in s['ions']]))) for mode in ['absolute','relative']: records=[] for f in range(4): train=[r for r in examples if fold[r['rid']]!=f];dev=[r for r in examples if fold[r['rid']]==f] assert not ({k for r in train for k in r['keys']}&{k for r in dev for k in r['keys']}) and len(dev)==96 records+=train_predict(train,dev,mode,f,cfg) assert len(records)==len({v['rid'] for v in records})==384 method=variant+':'+mode out[method]=dict(correct=sum(r['rank']==1 for r in records),intensity_null=sum(r['intensity_null_rank']==1 for r in records), ties=sum(r['tie_at_max'] for r in records),per_stratum={g:sum(r['rank']==1 for r in records if r['stratum']==g) for g in groups},rows=records) print(method,out[method]['correct'],out[method]['intensity_null'],flush=True) old={r['rid']:r['rank'] for r in out['legacy:absolute']['rows']};pairs={} for name,cohort in out.items(): diff=np.array([int(r['rank']==1)-int(old[r['rid']]==1) for r in cohort['rows']]);strata=np.array([r['stratum'] for r in cohort['rows']]) rng=np.random.default_rng(cfg['seed']);rep=np.zeros(3000) for g in groups: x=diff[strata==g];rep+=x[rng.integers(0,len(x),size=(len(rep),len(x)))].sum(1) pairs[name]=dict(wins=int((diff==1).sum()),losses=int((diff==-1).sum()),difference_pp=100*float(diff.mean()), paired_descriptive_ci95_pp=(100*np.quantile(rep/len(diff),[.025,.975])).tolist()) report=dict(scope=cfg['scope'],protocol=cfg,n=len(rr),cohort_sha256=hashlib.sha256(a.data.read_bytes()).hexdigest(), key14_disjoint_across_fit_holdout=True,official_split_used_in_fit=False,budget=cfg['proposal_budget'],diagnostics=diag, results=out,paired_vs_matched_legacy_absolute=pairs) a.output.write_text(json.dumps(report,allow_nan=False,indent=2)+'\n')if __name__=='__main__':main()123456789{ "scope":"train-source-only CPU mechanism pilot; not an R5 benchmark result", "cohort":"384 experimental spectra, one true + one uniform same-formula decoy + one nearest among up to eight other hash-sampled same-formula decoys; disjoint key14s across all triples", "split":"4 deterministic folds within each of the 6 equally sized strata; positive and all decoy keys disjoint between fit and holdout", "arms":["legacy:absolute","legacy:relative","diverse:absolute","diverse:relative"], "proposal_budget":32, "updates_per_fold":48, "batch":8, "seed":20261112, "hidden":32, "learning_rate":0.002, "lambda_positive_spectrum":0.15, "ties":"Resolve exact score ties by stable hashed candidate key14 independent of labels; also count ties.", "interpretation":"No R3D/R4 embeddings or scores and no official Validation/Test/CASMI used to fit. Does not simulate a 256- or 20000-candidate test pool. All arms and null results retained. Hyperparameters not selected by holdout performance."}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647import importlib.util,os,sys,unittestfrom pathlib import Pathimport numpy as npimport torchfrom evidence import ForwardEvidencefrom ions import generate,FEATURE_DIM,assign
class ModelChecks(unittest.TestCase): def test_parent_exact_and_gradient(self): m=ForwardEvidence();b=torch.tensor([.8,.7]);z=torch.tensor([[.8,.2],[.1,.9]]) out=m.identity_scores(b,z,torch.ones(1),[1,1],['a','b']) torch.testing.assert_close(out,b,atol=0,rtol=0);out[0].backward();self.assertGreater(abs(m.gain.grad.item()),0) def test_outside_top32_permutation_and_alias(self): m=ForwardEvidence();m.gain.data.fill_(1) z=torch.tensor([[.1,.9]]*39+[[.9,.1]]);base=torch.arange(40,0,-1).float() ids=['identity-%02d'%j for j in range(40)];f=[1]*40 s=m.identity_scores(base,z,torch.ones(1),f,ids) self.assertGreater(s[-1],base[-1]);order=list(range(39,-1,-1)) torch.testing.assert_close(m.identity_scores(base[order],z[order],torch.ones(1),f,ids[::-1]),s[order]) sb=m.identity_scores(torch.cat([base,base[-1:]]),torch.cat([z,z[-1:]]),torch.ones(1),f+[1],ids+[ids[-1]]) torch.testing.assert_close(sb[:-1],s);torch.testing.assert_close(sb[-1],s[-1]) def test_neutral_when_no_evidence_or_singleton(self): m=ForwardEvidence();m.gain.data.fill_(1.) b=torch.randn(3);ids=['a','b','c'] for z,w,fs in [(torch.tensor([[0.,1.]]*3),torch.ones(1),[1]*3), (torch.tensor([[.1,.9],[.4,.6],[.3,.7]]),torch.ones(1),[1,2,-1]), (torch.tensor([[.1,.9],[.4,.6],[.3,.7]]),torch.zeros(1),[1]*3)]: torch.testing.assert_close(m.identity_scores(b,z,w,fs,ids),b) def test_mass_conservation_padding_and_backward(self): torch.manual_seed(7);m=ForwardEvidence();x=torch.randn(2,3,7,FEATURE_DIM);v=torch.ones(2,3,7,dtype=torch.bool) v[0,0,:]=False;v[:,:,5:]=False;idx=torch.arange(7).expand(2,3,-1)%4;ad=torch.tensor([1,3]);obs=torch.tensor([[.5,.3,.2],[.3,.6,.1]]) prob=m.ion_prior(x,v,ad);self.assertTrue((prob[...,:-1][~v]==0).all()) l,c,z=m.prototype_logits(x,v,idx,obs,ad,'relative') torch.testing.assert_close(z.sum(-1),torch.ones(2,3));self.assertEqual(float(z[0,0,-1]),1.) independent=m.group_readout(z[1],obs[1],torch.zeros(3,dtype=torch.long));torch.testing.assert_close(4*independent,l[1]) (-l[1,0]-c[1,1]).backward();self.assertGreater(m.intensity[-1].weight.grad.abs().sum(),0) def test_ion_order_and_assignment(self): here=Path(__file__).resolve().parent code=Path(os.environ.get('R3_FEATURE_SOURCE',str(here.parent/'specpartition-ceir-r3-20261110/features_r2.py'))) spec=importlib.util.spec_from_file_location('legacy_r3_features_for_test',code);ft=importlib.util.module_from_spec(spec);spec.loader.exec_module(ft) a=generate('COc1ccc(CCO)cc1','[M+H]+','diverse',ft);b=generate('OCCc1ccc(OC)cc1','[M+H]+','diverse',ft) np.testing.assert_array_equal(a[0],b[0]);np.testing.assert_array_equal(a[1],b[1]);self.assertGreater(len(a[0]),0) self.assertEqual(len(a[0]),len(set(np.round(a[0].astype(float),5))));self.assertLessEqual(a[2],32) np.testing.assert_array_equal(assign(np.array([100.,101.,103.]),np.array([100.01,100.99])),[0,1,2]) self.assertEqual(len(generate('CCCCC','unsupported','legacy',ft)[0]),0) with self.assertRaises(ValueError):generate('[13CH3]CCCCC','[M+H]+','legacy',ft)if __name__=='__main__':unittest.main()123456789101112131415161718192021222324252627282930313233343536373839404142434445import unittestimport torchfrom guard import novel_evidence,apply_bounded_bonus,stream_novelty
class GuardTests(unittest.TestCase): def setUp(self): self.old=torch.tensor([[.2,0.,0.,.8],[.1,0.,0.,.9],[0.,0.,.4,.6]]) self.new=torch.tensor([[.1,.2,0.,.7],[0.,0.,.2,.8],[0.,0.,.3,.7]]) self.obs=torch.tensor([.1,.6,.3]);self.form=['F','F','F'];self.ids=['a','b','c'] def test_unique_and_permutation(self): f=novel_evidence(self.old,self.new,self.obs,self.form,self.ids) self.assertAlmostEqual(float(f[0]),.6*.2/.22,places=6) self.assertTrue((f[1:]==0).all()) ix=[2,0,1];g=novel_evidence(self.old[ix],self.new[ix],self.obs,self.form,[self.ids[i] for i in ix]) torch.testing.assert_close(g,f[ix]) def test_missing_and_singleton(self): for fs,obs in [(['a','b','c'],self.obs),([None]*3,self.obs),(self.form,self.obs*0)]: self.assertTrue((novel_evidence(self.old,self.new,obs,fs,self.ids)==0).all()) with self.assertRaises(ValueError):novel_evidence(self.old,self.new,self.obs,self.form,['a','a','c']) def test_guaranteed_margin_and_cap(self): s=torch.tensor([.61,.50,.49]);b=torch.tensor([0.,1.,.9]) self.assertEqual(int(apply_bounded_bonus(s,b,.1).argmax()),0) torch.testing.assert_close(apply_bounded_bonus(s,b,0),s) with self.assertRaises(ValueError):apply_bounded_bonus(s,torch.tensor([-1.,0.,0.]),.1) def test_cross_formula_presence_is_not_a_same_formula_vote(self): fs=['F','F','G'] v=novel_evidence(self.old,self.new,self.obs,fs,self.ids) self.assertGreater(float(v[1]),0) self.assertEqual(float(v[2]),0) def test_stream_same_as_global_even_when_competitors_in_other_blocks(self): f=novel_evidence(self.old,self.new,self.obs,self.form,self.ids) for k in (1,2,20): g=stream_novelty(self.obs,self.form,self.ids,lambda i,j:(self.old[i:j],self.new[i:j]),k) torch.testing.assert_close(g,f) def test_large_pool_synthetic(self): n=33350;form=['F']*n def load(i,j): a=torch.zeros(j-i,3);b=torch.zeros_like(a);a[:,-1]=1;b[:,0]=.3;b[:,-1]=.7 if j==n:b[-1]=torch.tensor([.3,.2,.5]) return a,b g=stream_novelty(torch.tensor([.4,.6]),form,list(range(n)),load,256) self.assertEqual(int((g>0).sum()),1);self.assertAlmostEqual(float(g[-1]),.6*.2/.22,places=6)
if __name__=='__main__':unittest.main()12345678910111213141516171819202122232425262728293031323334{ "release_id": "capacity_20260909_v03", "work_dir": "/root/autodl-tmp/SpecPartition-MS/data/multiview_20260909_v02", "run_dir": "/root/autodl-tmp/SpecPartition-MS/runs/capacity_20260909_v03", "proposal_formula_checkpoint": "/root/autodl-tmp/SpecPartition-MS/runs/multiview_20260909_v02/formula_selector_frozen.pt", "seed": 20260910, "device": "cuda:0", "threads": 4, "workers": 8, "prefetch_batches": 16, "feature_cache_dir": "/root/autodl-tmp/SpecPartition-MS/data/derived_features_v03_optimization", "worker_restart_limit": 3, "preparation_timeout_seconds": 600, "batch_size": 16, "bf16": true, "gpu_memory_fraction": 0.55, "min_free_gb": 8, "model": {"dim": 256, "heads": 8, "spectrum_layers": 6, "graph_layers": 6, "max_peaks": 256}, "gated_graph": true, "graph_chunk": 128, "local_chunk": 64, "max_atoms_per_microbatch": 90000, "cuda_phase_sync": true, "negative_budget": 64, "global_negative_proposals": 64, "training_candidate_cap": 256, "ready_odata_fraction": 0.75, "predicted_view_fraction": 0.20, "learning_rate": 0.0001, "teacher_refresh_steps": 100, "checkpoint_interval": 25, "min_rank_before_relations": 500, "stages": {"warmup": 100, "direct": 1500, "fixed_relation": 200, "joint": 1000}}1234567{ "formula_workers": 16, "http_connections": 4, "min_interval_seconds": 0.26, "policy": "One coordinator, one shared request-start clock, pooled HTTPS, global worst-case throttle feedback and Retry-After. Max 4 live network requests; never 16 independent rate limits.", "candidate_protocol": "unchanged: all required formulas, all CIDs, 500 IDs/property request, full validation; no candidate truncation"}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647{ "release_id": "epoch_20260910_v06", "work_dir": "/root/autodl-tmp/SpecPartition-MS/data/multiview_20260909_v02", "prepared_dir": "/root/autodl-tmp/SpecPartition-MS/data/epoch_20260910_v06", "run_dir": "/root/autodl-tmp/SpecPartition-MS/runs/epoch_20260910_v06", "initial_checkpoint": "/root/autodl-tmp/SpecPartition-MS/backups/20260910_before_epoch_v06/inbatch_v05_last.pt", "seed": 20260913, "device": "cuda:0", "threads": 4, "prepare_workers": 6, "workers": 2, "prefetch_batches": 3, "epochs": 5, "odata_base_batch_size": 128, "odata_batch_multiplier": 2, "odata_batch_size": 256, "odata_micro_batch_size": 128, "odata_gradient_cache": false, "msg_batch_size": 8, "msg_views": ["msg_mass", "msg_formula"], "msg_negative_count": 63, "msg_negative_sampling": "uniform_without_replacement", "small_pool_policy": "all_unique_masked_padding", "epoch_schedule": "full_sources_interleaved_no_replacement", "runtime_sweep": [{"max_atoms_per_microbatch":70000,"odata_micro_batch_size":128,"odata_gradient_cache":true}, {"max_atoms_per_microbatch":120000,"odata_micro_batch_size":256,"odata_gradient_cache":true}, {"max_atoms_per_microbatch":120000,"odata_micro_batch_size":256,"odata_gradient_cache":false}], "bf16": true, "gpu_memory_fraction": 0.85, "min_free_gb": 32, "model": {"dim":256,"heads":8,"spectrum_layers":6,"graph_layers":6,"max_peaks":256}, "gated_graph": true, "graph_chunk": 128, "local_chunk": 64, "max_atoms_per_microbatch": 120000, "cuda_phase_sync": false, "negative_budget": 63, "global_negative_proposals": 0, "training_candidate_cap": 64, "learning_rate": 0.0001, "minimum_learning_rate": 0.00001, "warmup_steps": 100, "teacher_refresh_steps": 100, "checkpoint_interval": 100, "molecule_lru_size": 100000, "pool_lru_size": 8192, "network_disabled": true, "epoch_stages": ["direct","fixed_relation","joint","joint","joint"]}1234567891011121314151617181920212223242526272829303132333435{ "release_id": "inbatch_20260909_v05", "work_dir": "/root/autodl-tmp/SpecPartition-MS/data/multiview_20260909_v02", "run_dir": "/root/autodl-tmp/SpecPartition-MS/runs/inbatch_20260909_v05", "initial_checkpoint": "/root/autodl-tmp/SpecPartition-MS/runs/capacity_20260909_v03/last.pt", "seed": 20260913, "device": "cuda:0", "threads": 4, "workers": 3, "prefetch_batches": 4, "worker_restart_limit": 2, "preparation_timeout_seconds": 900, "odata_batch_size": 128, "msg_batch_size": 8, "bf16": true, "gpu_memory_fraction": 0.65, "min_free_gb": 32, "model": {"dim": 256, "heads": 8, "spectrum_layers": 6, "graph_layers": 6, "max_peaks": 256}, "gated_graph": true, "graph_chunk": 128, "local_chunk": 64, "max_atoms_per_microbatch": 70000, "cuda_phase_sync": true, "negative_budget": 64, "global_negative_proposals": 64, "training_candidate_cap": 256, "ready_odata_fraction": 0.0, "learning_rate": 0.0001, "teacher_refresh_steps": 100, "checkpoint_interval": 25, "min_msg_rank_before_relations": 500, "stages": {"warmup": 100, "direct": 1500, "fixed_relation": 200, "joint": 1000}, "network_disabled": true, "scope": "2800 joint optimizer updates; 358400 o_data and 22400 MSG exposures; initial continuation curriculum, not full-corpus epoch or convergence claim"}1234567891011121314151617181920212223{ "release_id":"joint_20260911_v08","joint_v08":true, "work_dir":"/root/autodl-tmp/SpecPartition-MS/data/multiview_20260909_v02", "prepared_dir":"/root/autodl-tmp/SpecPartition-MS/data/epoch_20260910_v06", "frozen_preparation_source_dir":"/root/autodl-tmp/SpecPartition-MS/releases/epoch_20260910_v06/src/specpartition_ms", "run_dir":"/root/autodl-tmp/SpecPartition-MS/runs/joint_20260911_v08", "initial_checkpoint":"/root/autodl-tmp/SpecPartition-MS/runs/validation_20260911_v071/formula_head/last.pt", "initial_checkpoint_sha256":"1c51858644d965317126eff85cae66c02994a9a60a5caba9be712ce4090f7c0c", "seed":20260913,"device":"cuda:0","threads":4,"prepare_workers":6,"workers":2,"prefetch_batches":3, "epochs":3,"epoch_stages":["joint","joint","joint"], "odata_base_batch_size":128,"odata_batch_multiplier":2,"odata_batch_size":256,"odata_micro_batch_size":64,"odata_gradient_cache":true, "msg_batch_size":32,"msg_views":["msg_mass","msg_formula"],"msg_negative_count":63, "msg_negative_sampling":"uniform_without_replacement","small_pool_policy":"all_unique_masked_padding", "epoch_schedule":"full_sources_interleaved_no_replacement","bf16":true,"gpu_memory_fraction":0.85,"min_free_gb":32, "model":{"dim":256,"heads":8,"spectrum_layers":6,"graph_layers":6,"max_peaks":256}, "gated_graph":true,"graph_chunk":128,"local_chunk":128,"max_atoms_per_microbatch":40000, "negative_budget":63,"global_negative_proposals":0,"training_candidate_cap":64,"network_disabled":true, "learning_rate":0.00003,"minimum_learning_rate":0.000003,"warmup_steps":200,"teacher_refresh_steps":100,"checkpoint_interval":100, "molecule_lru_size":100000,"pool_lru_size":8192,"condition_bound":0.25, "cut_queries_per_batch":2,"cut_nodes_per_query":8,"cut_epsilon":0.005,"same_formula_hard_topk":8, "joint_loss_weights":{"formula":1.0,"contrastive":1.0,"direct_anchor":0.25,"rank":1.0,"hard":0.1,"cut":0.1,"cost":0.001}, "formula_v07":{"enabled":true,"loss_weight":1.0,"presence_weight":0.2,"count_weight":0.2,"initial_mass_weight":1.0,"ppm_scale":1.0,"residual_bound":4.0,"ranking_presence_weight":0.2,"ranking_count_weight":0.2,"hard_formula_weight":0.2,"hard_formula_count":8,"hard_formula_margin":0.2}}1234567891011121314151617181920212223242526272829303132333435363738394041{ "release_id": "multiview_20260909_v02", "work_dir": "/root/autodl-tmp/SpecPartition-MS/data/multiview_20260909_v02", "run_dir": "/root/autodl-tmp/SpecPartition-MS/runs/multiview_20260909_v02", "training": { "odata": "/root/autodl-tmp/o_data_training_multispectra_20260909/release_v1/train.json", "msg_train": "/root/autodl-tmp/llm_v2/llm_ms_slime_v2/data/server_packages/massspecgym_v1_5_official_test_bundle/data/splits/MassSpecGym1.5_train.tsv" }, "heldout": { "msg_validation": "/root/autodl-tmp/llm_v2/llm_ms_slime_v2/data/server_packages/massspecgym_v1_5_official_test_bundle/data/splits/MassSpecGym1.5_val.tsv", "msg_test": "/root/autodl-tmp/llm_v2/llm_ms_slime_v2/data/server_packages/massspecgym_v1_5_official_test_bundle/data/splits/MassSpecGym1.5_test.tsv", "casmi2022": "/root/autodl-tmp/dataset_distribution_overview_20260909/verified/casmi2022_full_metadata_reference.json" }, "official_pools": { "msg_mass": "/root/autodl-tmp/llm_v2/llm_ms_slime_v2/data/server_packages/massspecgym_v1_5_official_test_bundle/data/molecules/MassSpecGym1.5_retrieval_candidates_mass.json", "msg_formula": "/root/autodl-tmp/llm_v2/llm_ms_slime_v2/data/server_packages/massspecgym_v1_5_official_test_bundle/data/molecules/MassSpecGym1.5_retrieval_candidates_formula.json" }, "seed": 20260909, "device": "cuda:0", "threads": 4, "stages": {"warmup_steps": 2000, "direct_steps": 10000, "fixed_relation_steps": 2000, "joint_steps": 10000}, "checkpoint_interval": 100, "teacher_refresh_steps": 500, "predicted_pool_refresh": "frozen post-warmup checkpoint; not test selected", "negative_budget": 32, "negative_proposal_budget": 128, "training_candidate_cap": 512, "candidate_cap_scope": "training proposals only; full stored and evaluation pools never truncated", "pubchem_online": true, "pubchem_max_attempts": 5, "pubchem_min_free_gb": 12, "train_min_free_gb": 5, "minimum_indexed_train_rows": 1000, "formula_policy": "training_catalog_mass_filtered", "formula_ppm": 10.0, "cost_weight": 0.0, "cut_cost_tradeoff": 0.0, "cut_epsilon": 0.005, "training_isolation": "exclude evaluation connectivity from labels and training negative projection; official raw pools preserved", "casmi_use": "final evaluation and oracle control only; never training or checkpoint selection"}123456789101112131415161718192021222324252627282930313233343536373839404142{ "release_id": "offline_20260909_v04", "pipeline_dir": "/root/autodl-tmp/SpecPartition-MS/data/offline_20260909_v04", "work_dir": "/root/autodl-tmp/SpecPartition-MS/data/multiview_20260909_v02", "run_dir": "/root/autodl-tmp/SpecPartition-MS/runs/offline_20260909_v04", "proposal_formula_checkpoint": "/root/autodl-tmp/SpecPartition-MS/runs/multiview_20260909_v02/formula_selector_frozen.pt", "auto_train_after_validation": true, "property_batch_size": 500, "pubchem_max_attempts": 5, "download_min_free_gib": 20, "preprocess_min_free_gib": 16, "seed": 20260911, "device": "cuda:0", "threads": 4, "workers": 4, "prefetch_batches": 8, "worker_restart_limit": 2, "preparation_timeout_seconds": 1200, "batch_size": 16, "bf16": true, "gpu_memory_fraction": 0.55, "min_free_gb": 12, "model": {"dim": 256, "heads": 8, "spectrum_layers": 6, "graph_layers": 6, "max_peaks": 256}, "gated_graph": true, "graph_chunk": 128, "local_chunk": 64, "max_atoms_per_microbatch": 90000, "cuda_phase_sync": true, "negative_budget": 64, "global_negative_proposals": 64, "training_candidate_cap": 256, "ready_odata_fraction": 0.0, "predicted_view_fraction": 0.20, "learning_rate": 0.0001, "teacher_refresh_steps": 100, "checkpoint_interval": 25, "min_rank_before_relations": 500, "stages": {"warmup": 100, "direct": 1500, "fixed_relation": 200, "joint": 1000}, "scope": "all eligible-source formulas downloaded; next 44800 exposures prepacked before a new initial curriculum, not a full corpus epoch", "empty_pool_policy": "retain and audit; no invented positive, no LR or cut target without true candidate; valid LC/LF remain", "initialization": "new independent model seed; old v03 checkpoint preserved, no silent optimizer resume"}123456789101112131415161718192021222324{ "release_id":"scratch_wr_20260912_v09","joint_v08":true,"scratch_v09":true, "work_dir":"/root/autodl-tmp/SpecPartition-MS/data/multiview_20260909_v02", "prepared_dir":"/root/autodl-tmp/SpecPartition-MS/data/epoch_20260910_v06", "frozen_preparation_source_dir":"/root/autodl-tmp/SpecPartition-MS/releases/epoch_20260910_v06/src/specpartition_ms", "run_dir":"/root/autodl-tmp/SpecPartition-MS/runs/scratch_wr_20260912_v09", "initial_checkpoint":null,"initial_checkpoint_sha256":null, "seed":20260913,"device":"cuda:0","threads":4,"prepare_workers":6,"workers":2,"prefetch_batches":3, "epochs":3,"epoch_stages":["joint","joint","joint"], "odata_base_batch_size":128,"odata_batch_multiplier":2,"odata_batch_size":256,"odata_micro_batch_size":64,"odata_gradient_cache":true, "msg_batch_size":32,"msg_views":["msg_mass","msg_formula"],"msg_negative_count":63, "msg_negative_sampling":"uniform_with_replacement","small_pool_policy":"replacement_counts_no_positive_resampling", "epoch_schedule":"full_sources_interleaved_no_replacement","bf16":true,"gpu_memory_fraction":0.32,"min_free_gb":32, "model":{"dim":256,"heads":8,"spectrum_layers":6,"graph_layers":6,"max_peaks":256}, "gated_graph":true,"graph_chunk":64,"local_chunk":64,"max_atoms_per_microbatch":24000, "negative_budget":63,"global_negative_proposals":0,"training_candidate_cap":64,"network_disabled":true, "learning_rate":0.00003,"minimum_learning_rate":0.000003,"warmup_steps":200,"teacher_refresh_steps":100,"checkpoint_interval":100, "molecule_lru_size":100000,"pool_lru_size":8192,"condition_bound":0.25, "cut_queries_per_batch":2,"cut_nodes_per_query":8,"cut_epsilon":0.005,"same_formula_hard_topk":8, "joint_loss_weights":{"formula":1.0,"contrastive":1.0,"direct_anchor":0.25,"rank":1.0,"hard":0.1,"cut":0.1,"cost":0.001}, "formula_v07":{"enabled":true,"loss_weight":1.0,"presence_weight":0.2,"count_weight":0.2,"initial_mass_weight":1.0,"ppm_scale":1.0,"residual_bound":4.0,"ranking_presence_weight":0.2,"ranking_count_weight":0.2,"hard_formula_weight":0.2,"hard_formula_count":8,"hard_formula_margin":0.2}, "experiment":{"initialization":"scratch","baseline":"joint_20260911_v08","protected_run":"/root/autodl-tmp/SpecPartition-MS/runs/joint_20260911_v08","interpretation":"Initialization and sampling both differ; not a pure sampling ablation.","cpu_affinity":"16-31","nice":10, "validation_probe_targets":128,"validation_batch_views":4,"validation_mces_workers":2,"validation_gpu_memory_fraction":0.28,"admission_free_mib":12000,"max_transient_retries":3}}123456789101112131415161718192021222324252627282930313233343536373839404142{ "base_config": "formula_server_v07.json", "release_id": "validation_20260911_v071", "root": "/root/autodl-tmp/SpecPartition-MS", "evaluation_root": "/root/autodl-tmp/SpecPartition-MS/evaluations/msg_val_v071_20260911", "run_root": "/root/autodl-tmp/SpecPartition-MS/runs/validation_20260911_v071", "seed": 20260913, "formula_steps": 2000, "rank_steps_per_arm": 800, "formula_learning_rate": 0.0002, "rank_learning_rate": 0.00001, "evaluation_batch_views": 4, "mces_workers": 4, "formula_v07": { "enabled": true, "loss_weight": 1.0, "presence_weight": 0.2, "count_weight": 0.2, "initial_mass_weight": 1.0, "ppm_scale": 1.0, "residual_bound": 4.0, "ranking_presence_weight": 0.2, "ranking_count_weight": 0.2, "hard_formula_weight": 0.2, "hard_formula_count": 8, "hard_formula_margin": 0.2 }, "matched_teacher_probe": true, "cut_queries_per_batch": 2, "cut_nodes_per_query": 8, "cut_epsilon": 0.005, "chemical_risk_weight": 0.1, "arms": [ {"name": "direct_uniform", "phase": "direct", "strategy": "uniform", "mode": "none"}, {"name": "direct_hard", "phase": "direct", "strategy": "mixed", "mode": "none"}, {"name": "fixed_hard", "phase": "fixed_relation", "strategy": "mixed", "mode": "fixed"}, {"name": "cut_hard", "phase": "joint", "strategy": "mixed", "mode": "learned"} ], "selection": { "split": "val", "primary": "mass.formula.10.micro", "tie_break": "mass.formula.1.micro", "require_formula_top10_above_old": true, "require_formula_top10_above_mass_prior_for_promotion": true, "report_gain_over_abs_ppm_separately": true, "structure_guardrail": "Both views: Top1, Top5 and Top20 >= frozen v06, MCES evaluated mean <= frozen v06; identical no-prediction denominator required", "promotion": "Only report eligible checkpoints; never overwrite the v06/v07 checkpoints or automatically rerun Test" }, "budget_definition": "Same initialization, seed, spectrum ids, optimizer updates, both MSG views, 63 negatives, full-pool teacher proposals and counterfactual probe budget. NOT a claim of identical FLOPs/wall-clock. Log measured time and memory.", "scope": "Finite development pilot, not a full-corpus epoch or proven final improvement. Official Validation only; Test and CASMI forbidden. PubChem downloader untouched."}12"""Original research implementation. No experimental performance claims."""__version__ = "0.1.0"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113"""Fresh-process GPU batch sweep over cached real inputs, with audited acceptance.
OOM is a failed batch trial, not authorization to omit candidates or samples.Unknown numerical/CUDA errors stop the sweep. Benchmark weights never becomethe production checkpoint; every trial loads the same preserved v05 weights."""import argparsefrom copy import deepcopyimport jsonimport mathfrom pathlib import Pathimport statisticsimport subprocessimport sysimport timeimport torchfrom .epoch_data import PreparedReader, CachedPrefetchfrom .train_epoch import make_model, joint_step, validate_training_configfrom .prepare_epoch import validatefrom .multiview_data import save, utc, sha
def trial(c,output): validate_training_config(c) validate(c,False) torch.set_num_threads(c['threads']);torch.manual_seed(c['seed']);torch.set_float32_matmul_precision('high') torch.cuda.set_device(c['device']);torch.cuda.set_per_process_memory_fraction(c['gpu_memory_fraction']) model=make_model(c).to(c['device']) state=torch.load(c['initial_checkpoint'],map_location='cpu',weights_only=True) model.load_state_dict(state['model']);del state teacher=deepcopy(model).eval() for p in teacher.parameters():p.requires_grad_(False) opt=torch.optim.AdamW(model.parameters(),lr=c['learning_rate'],weight_decay=.01,fused=True) reader=PreparedReader(c);records=[] # Cold + prefetch overlap + relation stages; both official views guaranteed. steps=list(range(8)) loader=CachedPrefetch(reader,0,8) try: for step in steps: tick=time.monotonic();batch=loader.get(step);wait=time.monotonic()-tick stage=['direct','direct','direct','fixed_relation','fixed_relation','joint','joint','joint'][step] mode={'direct':'none','fixed_relation':'fixed','joint':'learned'}[stage] model.cfg.model.relation_mode=teacher.cfg.model.relation_mode=mode model.train();torch.cuda.synchronize();torch.cuda.reset_peak_memory_stats();tick=time.monotonic() diagnostics={} result=joint_step(model,teacher,opt,batch,c,step,stage,diagnostics) torch.cuda.synchronize();seconds=time.monotonic()-tick samples=result.pop('samples') record={'step':step,'stage':stage,'data_wait_seconds':wait,'compute_seconds':seconds, 'peak_allocated_mib':torch.cuda.max_memory_allocated()/1024**2, 'peak_reserved_mib':torch.cuda.max_memory_reserved()/1024**2, 'false_negatives':sum(not s['negative']['positive_excluded'] for s in samples), 'both_views_in_every_spectrum':all({s['view'] for s in samples if s['spectrum_id']==sid}==set(c['msg_views']) for sid in {s['spectrum_id'] for s in samples}), 'negative_budget_valid':all(s['selected_negative_count']==min(c['msg_negative_count'],s['available_negative_count']) for s in samples), 'padding_slots':sum(s['padding_slots'] for s in samples), 'max_spectrum_peaks':max(len(b['example'].query.spectrum_arrays[0]) for b in batch['odata']+batch['msg']), 'max_candidate_count':max(len(b['example'].query.candidates) for b in batch['msg']),**result} records.append(record);print(json.dumps(record),flush=True) checks={'finite_loss_grad':all(math.isfinite(r['loss']) and math.isfinite(r['gradient_norm_before_clip']) for r in records), 'no_false_negatives':all(r['false_negatives']==0 for r in records), 'both_views':all(r['both_views_in_every_spectrum'] for r in records), 'negative_budget':all(r['negative_budget_valid'] for r in records), 'all_stages':{r['stage'] for r in records}=={'direct','fixed_relation','joint'}, 'full_requested_batch':all(r['odata_exposures'] in (0,c['odata_batch_size']) and r['msg_exposures']==c['msg_batch_size'] and r['msg_view_exposures']==2*c['msg_batch_size'] for r in records) and any(r['odata_exposures']==c['odata_batch_size'] for r in records), 'finite_parameters':all(torch.isfinite(p).all().item() for p in model.parameters())} selected=records[1:] result={'utc':utc(),'passed':all(checks.values()),'checks':checks,'config':c,'records':records, 'samples_per_second':sum(r['odata_exposures']+r['msg_exposures'] for r in selected)/sum(r['compute_seconds']+r['data_wait_seconds'] for r in selected), 'peak_allocated_mib':max(r['peak_allocated_mib'] for r in records), 'mean_data_wait_seconds':statistics.mean(r['data_wait_seconds'] for r in selected), 'mean_compute_seconds':statistics.mean(r['compute_seconds'] for r in selected)} save(output,result) if not result['passed']:raise RuntimeError('Real-data acceptance checks failed') finally:loader.close()
def sweep(c,root): root=Path(root);root.mkdir(parents=True,exist_ok=True);validate(c,True) results=[] for i,runtime in enumerate(c['runtime_sweep']): if set(runtime)-{'max_atoms_per_microbatch','odata_micro_batch_size','odata_gradient_cache'}:raise ValueError('Runtime sweep cannot change user batch/view/negative parameters') trial_config={**c,**runtime} path=root/f'runtime_{i}.json';output=root/f'runtime_{i}_result.json' save(path,trial_config) with (root/f'runtime_{i}.log').open('w') as log: proc=subprocess.run([sys.executable,'-u','-m','specpartition_ms.benchmark_epoch','--config',str(path),'--trial-output',str(output)],stdout=log,stderr=subprocess.STDOUT) r=json.loads(output.read_text()) if output.exists() else {'passed':False,'error':'trial did not produce receipt'} r.update(returncode=proc.returncode,runtime=runtime) results.append(r);save(root/'batch_sweep_progress.json',{'utc':utc(),'results':results}) if not r.get('passed') and not r.get('oom'): raise RuntimeError('Non-OOM batch acceptance failure; no automatic production launch') candidates=[r for r in results if r.get('passed')] if not candidates:raise RuntimeError('All larger batches failed; no automatic training launch') best=max(candidates,key=lambda r:r['samples_per_second']) selected={**c,**best['runtime']} save(root/'selected_config.json',selected) save(root/'batch_selection.json',{'utc':utc(),'reason':'highest measured real-data samples/s; user batch256/8 and both64-candidate views are never changed', 'results':results,'selected_batch':[selected['odata_batch_size'],selected['msg_batch_size']], 'selected_config_sha256':sha(root/'selected_config.json'),'test_set_used':False, 'source_hashes':{p.name:sha(p) for p in Path(__file__).parent.glob('*.py')}}) return root/'selected_config.json'
if __name__=='__main__': p=argparse.ArgumentParser();p.add_argument('--config',required=True);p.add_argument('--trial-output');p.add_argument('--sweep-dir') a=p.parse_args();c=json.loads(Path(a.config).read_text()) if a.trial_output: try:trial(c,a.trial_output) except BaseException as e: oom=isinstance(e,torch.OutOfMemoryError) or 'out of memory' in str(e).lower() save(a.trial_output,{'utc':utc(),'passed':False,'error':repr(e),'oom':oom}) raise else:sweep(c,a.sweep_dir)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247"""Chemical identities and physics; no reference-dependent features or SIRIUS calls."""from dataclasses import dataclassfrom functools import lru_cacheimport hashlibimport osimport reimport timeimport numpy as npfrom rdkit import Chem, DataStructsfrom rdkit.Chem import Descriptors, rdFingerprintGenerator, rdMolDescriptorsfrom rdkit.Chem.Scaffolds import MurckoScaffold
ELEMENTS = ("C", "H", "N", "O", "P", "S", "F", "Cl", "Br", "I", "B", "Si")MASSES = {e: Chem.GetPeriodicTable().GetMostCommonIsotopeMass(e) for e in ELEMENTS}ELECTRON_MASS = 0.000548579909065FP_SIZE = 2048GENERATOR = rdFingerprintGenerator.GetMorganGenerator(radius=2, fpSize=FP_SIZE, includeChirality=False)# Mass added to a neutral molecule, divided by absolute charge afterwards.ADDUCTS = { "[M+H]+": (MASSES["H"] - ELECTRON_MASS, 1), "[M-H]-": (-MASSES["H"] + ELECTRON_MASS, -1), "[M+Na]+": (22.989769282 - ELECTRON_MASS, 1), "[M+NH4]+": (MASSES["N"] + 4 * MASSES["H"] - ELECTRON_MASS, 1), "[M+Cl]-": (MASSES["Cl"] + ELECTRON_MASS, -1), "[M+FA-H]-": (MASSES["C"] + MASSES["H"] + 2 * MASSES["O"] + ELECTRON_MASS, -1), "[M+2H]2+": (2 * (MASSES["H"] - ELECTRON_MASS), 2), "[M-2H]2-": (-2 * (MASSES["H"] - ELECTRON_MASS), -2),}
def formula_counts(formula): tokens = re.findall(r"([A-Z][a-z]?)(\d*)", formula) if not tokens or "".join(a+b for a, b in tokens) != formula: raise ValueError(f"Unsupported neutral formula: {formula!r}") result = {} for e, n in tokens: if e not in MASSES or e in result or (n and int(n) < 1): raise ValueError(f"Unsupported/repeated element or count: {formula}") result[e] = int(n or 1) return result
def canonical_formula(formula): d = formula_counts(formula) if isinstance(formula, str) else formula order = (["C", "H"] + sorted(set(d) - {"C", "H"})) if "C" in d else sorted(d) return "".join(e + (str(d[e]) if d[e] != 1 else "") for e in order if d.get(e, 0))
def formula_vector(formula): d = formula_counts(formula) return np.array([d.get(e, 0) for e in ELEMENTS], dtype=np.float32)
def exact_mass(formula): return sum(MASSES[e] * n for e, n in formula_counts(formula).items())
def precursor_mz(neutral_mass, adduct): delta, charge = ADDUCTS[adduct] return (neutral_mass + delta) / abs(charge)
def neutral_mass_from_mz(mz, adduct): delta, charge = ADDUCTS[adduct] return mz * abs(charge) - delta
def ppm_error(neutral_mass, mz, adduct): if not np.isfinite(mz) or mz <= 0: raise ValueError("experimental precursor_mz must be positive and finite") return (precursor_mz(neutral_mass, adduct) - mz) / mz * 1e6
def bit_array(fp): a = np.zeros(FP_SIZE, dtype=np.float32) DataStructs.ConvertToNumpyArray(fp, a) return a
def tanimoto(a, b): inter = float(np.dot(a, b)) union = float(a.sum() + b.sum() - inter) return inter / union if union else 0.0 # empties are not identical scaffolds
@dataclass(frozen=True)class Molecule: smiles: str identity: str inchikey: str formula: str mass: float charge: int mol: object whole: np.ndarray scaffold: np.ndarray scaffold_smiles: str atom_features: np.ndarray edge_index: np.ndarray bond_features: np.ndarray anchors: np.ndarray
def __reduce__(self): # Lossless wire/cache format: binary fingerprints need 256 bytes, not # 8192 bytes each. Keep float32 in memory (uint8 dot products overflow). return (_restore_molecule, (self.smiles, self.identity, self.inchikey, self.formula, self.mass, self.charge, self.mol.ToBinary(), np.packbits(self.whole.astype(np.uint8)), np.packbits(self.scaffold.astype(np.uint8)), self.scaffold_smiles, self.atom_features, self.edge_index, self.bond_features, self.anchors))
def _restore_molecule(smiles, identity, inchikey, formula, mass, charge, binary, whole, scaffold, scaffold_smiles, atoms, edges, bonds, anchors): return Molecule(smiles, identity, inchikey, formula, mass, charge, Chem.Mol(binary), np.unpackbits(whole)[:FP_SIZE].astype(np.float32), np.unpackbits(scaffold)[:FP_SIZE].astype(np.float32), scaffold_smiles, atoms, edges, bonds, anchors)
ATOM_TYPES = (6, 7, 8, 9, 15, 16, 17, 35, 53, 5, 14)ATOM_DIM = len(ATOM_TYPES) + 1 + 9BOND_DIM = 6ANCHOR_DIM = 128
def murcko_with_core(m): """Track surviving atoms through scaffold extraction, without NP-hard matching.
RDKit preserves atom properties on scaffold atoms. The returned mask is the actual extraction provenance, not an arbitrary isomorphic embedding. """ marked=Chem.Mol(m) prop='_specpartition_original_atom_index' for atom in marked.GetAtoms():atom.SetIntProp(prop,atom.GetIdx()) scaffold=MurckoScaffold.GetScaffoldForMol(marked) core=set() for atom in scaffold.GetAtoms(): if not atom.HasProp(prop):raise ValueError('Scaffold atom provenance was not preserved') core.add(atom.GetIntProp(prop));atom.ClearProp(prop) return scaffold,core
_FEATURE_STORE = None
def configure_feature_store(store): """Opt-in worker-local handle to a shared, versioned derived cache.""" global _FEATURE_STORE _FEATURE_STORE = store
@lru_cache(maxsize=int(os.environ.get('SPECPARTITION_MOLECULE_CACHE_SIZE','8192')))def molecule(smiles): if _FEATURE_STORE is None: return _calculate_molecule(smiles) return _FEATURE_STORE.get_or_compute(smiles, _calculate_molecule)
def _calculate_molecule(smiles): m = Chem.MolFromSmiles(smiles) if m is None or m.GetNumAtoms() == 0: raise ValueError(f"Invalid SMILES: {smiles!r}") if any(a.GetIsotope() for a in m.GetAtoms()): raise ValueError("Isotope-labelled candidates require an explicit isotope-aware adapter") key = Chem.MolToInchiKey(m) if not key: raise ValueError("Cannot obtain candidate identity") formula = canonical_formula(rdMolDescriptors.CalcMolFormula(m)) # Connectivity task: canonicalize without stereochemistry. Preserve full key separately. Chem.RemoveStereochemistry(m) smi = Chem.MolToSmiles(m, canonical=True, isomericSmiles=False) m = Chem.MolFromSmiles(smi) scaffold,core = murcko_with_core(m) ss = Chem.MolToSmiles(scaffold) sfp = bit_array(GENERATOR.GetFingerprint(scaffold)) if scaffold.GetNumAtoms() else np.zeros(FP_SIZE, np.float32) # The extraction-derived core is invariant under atom renumbering and does # not enumerate potentially explosive subgraph automorphisms. atoms, anchors = [], np.zeros(ANCHOR_DIM, np.float32) for a in m.GetAtoms(): onehot = [float(a.GetAtomicNum() == x) for x in ATOM_TYPES] + [float(a.GetAtomicNum() not in ATOM_TYPES)] iscore = a.GetIdx() in core attach = iscore and any(n.GetIdx() not in core for n in a.GetNeighbors()) atoms.append(onehot + [a.GetDegree()/4, a.GetFormalCharge()/2, float(a.GetIsAromatic()), float(a.IsInRing()), a.GetTotalNumHs()/4, float(iscore), float(attach), float(a.GetHybridization() == Chem.HybridizationType.SP2), a.GetMass()/100]) if attach or (not core and a.GetDegree() > 1): env = Chem.FindAtomEnvironmentOfRadiusN(m, 2, a.GetIdx()) sub = Chem.PathToSubmol(m, env) label = Chem.MolToSmiles(sub, canonical=True, isomericSmiles=False) pos = int(hashlib.sha256(label.encode()).hexdigest()[:16], 16) % ANCHOR_DIM anchors[pos] += 1 edges, bonds = [], [] for b in m.GetBonds(): f = [float(b.GetBondTypeAsDouble() == x) for x in (1, 2, 3, 1.5)] f += [float(b.GetIsConjugated()), float(b.IsInRing())] for u, v in ((b.GetBeginAtomIdx(), b.GetEndAtomIdx()), (b.GetEndAtomIdx(), b.GetBeginAtomIdx())): edges.append((u, v)); bonds.append(f) return Molecule(smi, key.split("-")[0], key, formula, Descriptors.ExactMolWt(m), Chem.GetFormalCharge(m), m, bit_array(GENERATOR.GetFingerprint(m)), sfp, ss, np.asarray(atoms, np.float32), np.asarray(edges, np.int64).reshape(-1, 2).T, np.asarray(bonds, np.float32).reshape(-1, BOND_DIM), np.log1p(anchors))
def scaffold_similarity(a, b): if not a.scaffold_smiles or not b.scaffold_smiles: return None return tanimoto(a.scaffold, b.scaffold)
def identity_hash(mols): return hashlib.sha256("\n".join(sorted(m.identity for m in mols)).encode()).hexdigest()
def enumerate_formulas(mz, adduct, bounds, ppm=10.0, max_nodes=2_000_000, timeout=30.0): """Bounded exhaustive mass enumeration. Raises on exhaustion, never silently returns a partial Top10.
Bounds are trained/validation-selected element maxima, not derived from a query's truth. No valence heuristic is silently used. More selective chemistry can be added as an audited adapter. """ if ppm <= 0 or not bounds or any(e not in MASSES or not isinstance(n, int) or n < 0 for e,n in bounds.items()): raise ValueError("Invalid enumeration bounds") center = neutral_mass_from_mz(mz, adduct) tol = mz * abs(ADDUCTS[adduct][1]) * ppm / 1e6 order = sorted(bounds, key=lambda e: -MASSES[e]) remaining = [sum(bounds[e] * MASSES[e] for e in order[i:]) for i in range(len(order)+1)] result, visited, started = [], 0, time.monotonic()
def visit(i, mass, counts): nonlocal visited visited += 1 if visited > max_nodes or (visited % 1024 == 0 and time.monotonic()-started > timeout): raise RuntimeError("Formula enumeration budget exhausted; increase bounds budget or use a faster enumerator") if mass > center+tol or mass+remaining[i] < center-tol: return if i == len(order): if counts and abs(mass-center) <= tol: result.append(canonical_formula(counts)) return e = order[i] lo = max(0, int(np.ceil((center-tol-mass-remaining[i+1])/MASSES[e]))) hi = min(bounds[e], int(np.floor((center+tol-mass)/MASSES[e]))) for n in range(lo, hi+1): visit(i+1, mass+n*MASSES[e], {**counts, **({e:n} if n else {})}) visit(0, 0.0, {}) return sorted(set(result)), {"visited_nodes": visited, "complete_within_bounds": True, "seconds": time.monotonic()-started, "bounds": bounds}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113import argparsefrom copy import deepcopyimport jsonfrom pathlib import Pathimport sysfrom .config import Configfrom .engine import load_model,predict_dataset,seed_everything,train,write_jsonfrom .forest import build_forestfrom .schema import iter_records,parse_record
def main(argv=None): p = argparse.ArgumentParser(description="SpecPartition-MS v0.1: data-independent reference implementation") sub = p.add_subparsers(dest="command",required=True) s = sub.add_parser("smoke",help="Generate artificial fixtures and run real CPU optimizer steps") s.add_argument("--out",required=True); s.add_argument("--epochs",type=int,default=3) t = sub.add_parser("train") t.add_argument("--input",required=True);t.add_argument("--config");t.add_argument("--out",required=True) t.add_argument("--heldout",action="append",default=[]);t.add_argument("--resume") t.add_argument("--allow-unregistered-holdouts",action="store_true") r = sub.add_parser("predict") r.add_argument("--input",required=True);r.add_argument("--checkpoint",required=True);r.add_argument("--out",required=True) r.add_argument("--device",default="cpu");r.add_argument("--bootstrap",type=int,default=1000) a = sub.add_parser("audit-input") a.add_argument("--input",required=True);a.add_argument("--out",required=True);a.add_argument("--config") c = sub.add_parser("config") c.add_argument("--out",required=True) ab = sub.add_parser("ablation-configs") ab.add_argument("--out",required=True);ab.add_argument("--config") prep = sub.add_parser("prepare-casmi") prep.add_argument("--input",required=True);prep.add_argument("--checkpoint",required=True) prep.add_argument("--out",required=True);prep.add_argument("--cache",required=True) prep.add_argument("--bounds",required=True,help='JSON element maxima, e.g. {"C":40,"H":80,"N":8,"O":12}') prep.add_argument("--online",action="store_true");prep.add_argument("--ppm",type=float,default=10.) args = p.parse_args(argv) if args.command=="config": write_json(args.out,Config().to_dict()); return if args.command=="smoke": from .synthetic import records root = Path(args.out) if root.exists() and any(root.iterdir()): raise FileExistsError("Smoke output must be a new directory") root.mkdir(parents=True,exist_ok=True) raw = records() with (root/"synthetic.jsonl").open("w") as fh: for d in raw: fh.write(json.dumps(d)+"\n") cfg = Config() cfg.model.dim=32;cfg.model.spectrum_layers=1;cfg.model.graph_layers=2 cfg.chemistry.whole_threshold=.30;cfg.chemistry.acyclic_threshold=.30 cfg.train.epochs=args.epochs;cfg.train.negative_budget=8;cfg.train.cut_nodes=6 examples = [parse_record(d) for d in raw] model,diagnostics = train(examples,cfg,root/"train") metrics = predict_dataset(model,examples,root/"inference",bootstrap=50) write_json(root/"SMOKE_RESULT.json",{"status":"software_smoke_completed","real_benchmark":False, "last_epoch":diagnostics,"queries":metrics["total_queries"],"checkpoint":"train/last.pt", "warning":"Artificial peaks, training-set predictions; recall is NOT scientific evidence"}) print(json.dumps({"status":"software_smoke_completed","out":str(root)}));return if args.command=="train": examples = list(iter_records(args.input)) heldout = [e for path in args.heldout for e in iter_records(path)] if not heldout and not args.allow_unregistered_holdouts and any(e.query.dataset_mode!="synthetic" for e in examples): raise ValueError("Real training requires --heldout registry, or explicit --allow-unregistered-holdouts acknowledgement") train(examples,Config.load(args.config),args.out,heldout,args.resume);return if args.command=="predict": model,_ = load_model(args.checkpoint,args.device) seed_everything(model.cfg.train.seed,model.cfg.train.threads) metrics = predict_dataset(model,iter_records(args.input),args.out,args.bootstrap) print(json.dumps(metrics,indent=2));return if args.command=="audit-input": cfg = Config.load(args.config) rows = [] for e in iter_records(args.input): f = build_forest(e.query.candidates,cfg.chemistry) rows.append({"sample_id":e.sample_id,"forest":f.to_dict(),"source_records":sum(len(x) for x in e.aliases.values())}) write_json(args.out,{"samples":rows,"count":len(rows)});return if args.command=="ablation-configs": cfg = Config.load(args.config) root = Path(args.out) if root.exists() and any(root.iterdir()): raise FileExistsError("Ablation config output must be new") controls = [] for mode in ("none","fixed","learned","knn","set","softpool"): for negatives in ("static","partition"): c = deepcopy(cfg);c.model.relation_mode=mode;c.train.negative_strategy=negatives name = mode+"__"+negatives write_json(root/(name+".json"),c.to_dict());controls.append(name) for key,value in (("local_match",False),("relative_difference",False),("formula_score",False),("controller_input","metadata")): c = deepcopy(cfg);setattr(c.model,key,value) name = "control_"+key;write_json(root/(name+".json"),c.to_dict());controls.append(name) write_json(root/"manifest.json",{"configs":controls,"executed":False, "note":"knn/set/softpool are original adaptation controls, not claimed reproductions of DiffPool/MinCut/SetTransformer papers"});return if args.command=="prepare-casmi": from .retrieval import PubChemCache,prepare_casmi_record model,_ = load_model(args.checkpoint) seed_everything(model.cfg.train.seed,model.cfg.train.threads) out = Path(args.out) if out.exists(): raise FileExistsError(out) out.parent.mkdir(parents=True,exist_ok=True) cache = PubChemCache(args.cache,args.online) try: with open(args.input) as source,out.open("w") as dest: for line in source: if line.strip(): result = prepare_casmi_record(json.loads(line),model,cache,json.loads(args.bounds),args.ppm) dest.write(json.dumps(result,allow_nan=False)+"\n");dest.flush() finally: cache.close()
if __name__=="__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103from dataclasses import asdict, dataclass, fieldimport jsonfrom pathlib import Path
@dataclassclass ChemistryConfig: whole_threshold: float = 0.55 scaffold_threshold: float = 0.65 acyclic_threshold: float = 0.60 max_cluster_size: int = 32 neighbors: int = 16 exact_pool_limit: int = 1024 proposal_bucket_cap: int = 128
@dataclassclass ModelConfig: dim: int = 64 heads: int = 4 spectrum_layers: int = 2 graph_layers: int = 3 max_peaks: int = 128 local_match: bool = True formula_score: bool = True relative_difference: bool = True relation_mode: str = "learned" # none/fixed/learned/knn/set/softpool controller_input: str = "spectrum" # spectrum/metadata residual_bound: float = 2.0
@dataclassclass TrainConfig: seed: int = 20260908 epochs: int = 4 warmup_epochs: int = 1 learning_rate: float = 0.0003 weight_decay: float = 0.0001 negative_budget: int = 16 negative_strategy: str = "partition" # random/static/dynamic/feedback/partition proposal_budget: int = 256 probe_size: int = 32 probe_margin: float = 0.10 teacher_refresh: int = 1 cut_nodes: int = 8 cut_epsilon: float = 0.00001 cut_cost_tradeoff: float = 0.001 cost_node_overhead: float = 16.0 temperature: float = 0.10 formula_weight: float = 0.3 contrastive_weight: float = 1.0 rank_weight: float = 1.0 cut_weight: float = 0.1 cost_weight: float = 0.001 gradient_clip: float = 5.0 threads: int = 2 device: str = "cpu"
@dataclassclass Config: chemistry: ChemistryConfig = field(default_factory=ChemistryConfig) model: ModelConfig = field(default_factory=ModelConfig) train: TrainConfig = field(default_factory=TrainConfig)
def validate(self): for name in ("whole_threshold", "scaffold_threshold", "acyclic_threshold"): if not 0 <= getattr(self.chemistry, name) <= 1: raise ValueError(name) if not 1 <= self.chemistry.max_cluster_size <= 64: raise ValueError("max_cluster_size must be in [1,64]") if self.model.dim % self.model.heads: raise ValueError("dim must be divisible by heads") if self.model.relation_mode not in {"none", "fixed", "learned", "knn", "set", "softpool"}: raise ValueError("unknown relation mode") if self.model.controller_input not in {"spectrum", "metadata"}: raise ValueError("unknown controller input") if self.train.negative_strategy not in {"random", "static", "dynamic", "feedback", "partition"}: raise ValueError("unknown negative strategy") for n in ("epochs", "negative_budget", "proposal_budget", "probe_size", "teacher_refresh", "threads"): if getattr(self.train, n) < 1: raise ValueError(n + " must be positive") if self.train.proposal_budget < max(4,self.train.negative_budget): raise ValueError("proposal_budget must be at least max(4,negative_budget)") if self.train.temperature <= 0 or self.train.learning_rate <= 0: raise ValueError("temperature and learning_rate must be positive") if self.model.max_peaks < 1 or self.chemistry.neighbors < 1 or self.chemistry.proposal_bucket_cap < 1: raise ValueError("Peak/neighbor/proposal limits must be positive") return self
def to_dict(self): return asdict(self)
@classmethod def load(cls, path=None): if path is None: return cls().validate() d = json.loads(Path(path).read_text()) unknown = set(d) - {"chemistry", "model", "train"} if unknown: raise ValueError(f"Unknown config sections: {unknown}") return cls(ChemistryConfig(**d.get("chemistry", {})), ModelConfig(**d.get("model", {})), TrainConfig(**d.get("train", {}))).validate()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192"""CPU-only, read-only preparation and bounded prefetch for v0.3 training.
Raw official pools and PubChem snapshots are never edited. Truth-guidedsubsampling is TRAINING ONLY and never injects truth into a retrieval pool."""from collections import OrderedDictfrom dataclasses import replaceimport hashlibimport faulthandlerimport jsonimport osfrom pathlib import Pathimport randomimport sqlite3import numpy as npimport torchfrom rdkit import RDLoggerfrom .chemistry import molecule, tanimoto, configure_feature_storefrom .engine import load_modelfrom .forest import Forest, Node, build_forestfrom .multiview_data import unpackedfrom .multiview_pools import FormulaCatalog, training_projection, predicted_formulasfrom .multiview_train import TrainingStreamfrom .retrieval import filter_candidatesfrom .schema import parse_record
def singleton_forest(mols): nodes={f'leaf:{m.identity}':Node(f'leaf:{m.identity}',(i,),(),(0.,1.,1.,0.,float(not m.scaffold_smiles)),i) for i,m in enumerate(mols)} return Forest(nodes,tuple(nodes),tuple(m.identity for m in mols),0,0,False)
def truth_guided_subset(entries, ref, cap, rng): if cap < 1:raise ValueError('Training candidate cap must be positive') if len(entries)<=cap: return entries,False pos=[e for e in entries if molecule(e['smiles']).identity==ref.identity] negatives=[e for e in entries if molecule(e['smiles']).identity!=ref.identity] slots=cap-len(pos) if slots<=0:return pos[:cap],True ordered=sorted(negatives,key=lambda e:(-tanimoto(ref.whole,molecule(e['smiles']).whole),molecule(e['smiles']).identity)) chosen=ordered[:slots//2] used={molecule(e['smiles']).identity for e in chosen} # One representative per scaffold; acyclic entries do not share an empty key. seen_scaffolds=set() for e in ordered: m=molecule(e['smiles']);scaffold=m.scaffold_smiles or m.identity if m.identity not in used and scaffold not in seen_scaffolds: chosen.append(e);used.add(m.identity);seen_scaffolds.add(scaffold) if len(chosen)>=3*slots//4:break left=[e for e in negatives if molecule(e['smiles']).identity not in used] chosen+=rng.sample(left,min(slots-len(chosen),len(left))) return sorted(pos+chosen,key=lambda e:molecule(e['smiles']).identity),True
class ReadyTrainingStream(TrainingStream): def __init__(self, config): self.config=config db=sqlite3.connect(f"file:{config['work_dir']}/data.sqlite?mode=ro",uri=True,timeout=30) db.execute('PRAGMA query_only=ON') super().__init__(db,config['seed']) self.catalog=FormulaCatalog(db) self.ready_formula_signature=None;self.ready_identities=[] self.raw_cache=OrderedDict();self.projected_cache=OrderedDict() self.frozen=None;self.frozen_hash=None self.plan_db=None if config.get('sampling_plan'): self.plan_db=sqlite3.connect(f"file:{config['sampling_plan']}?mode=ro",uri=True)
def sample_ready(self, sequence): self.rng=random.Random(self.config['seed']+sequence*10007) if self.config.get('ready_odata_fraction',0.)==0.: sid,body=super().sample(sequence) return sid,body,False ready=set(r[0] for r in self.db.execute('SELECT formula FROM formula_pools')) signature=tuple(sorted(ready)) if signature!=self.ready_formula_signature: self.ready_identities=[k for k in self.by_source['odata'] if self.structs[k][1] in ready] self.ready_formula_signature=signature if sequence%2==0 and self.ready_identities and self.rng.random()<self.config['ready_odata_fraction']: identity=self.rng.choice(self.ready_identities) rows=list(self.db.execute("SELECT id FROM spectra WHERE source='odata' AND identity=? AND status='eligible'",(identity,))) sid=self.rng.choice(rows)[0] body=self.db.execute('SELECT body FROM spectra WHERE id=?',(sid,)).fetchone()[0] return sid,unpacked(body),True sid,body=super().sample(sequence) return sid,body,False
def entries(self, body, view): if view in {'msg_mass','msg_formula'}: raw=self.db.execute('SELECT body,sha256,count FROM official_pools WHERE view=? AND target=?',(view,body['target_smiles'])).fetchone() return [{'smiles':s,'source_id':None} for s in unpacked(raw[0])],{'status':'ready','view':view,'raw_count':raw[2],'sha256':raw[1],'ppm_filter_applied':False} predictions=[] if view=='odata_predicted_top10': if self.frozen is None: path=Path(self.config['proposal_formula_checkpoint']) self.frozen,_=load_model(path,'cpu') self.frozen_hash=hashlib.sha256(path.read_bytes()).hexdigest() formulas,predictions=predicted_formulas(self.frozen,body,self.catalog) else:formulas=[body['formula']] entries=[];branches=[];pending=[] for f in formulas: row=self.db.execute('SELECT body,sha256,raw_count FROM formula_pools WHERE formula=?',(f,)).fetchone() if row is None:pending.append(f);continue key=(f,row[1]) if key not in self.raw_cache: self.raw_cache[key]=unpacked(row[0])['records'] if len(self.raw_cache)>8:self.raw_cache.popitem(last=False) kept,rejected=filter_candidates(self.raw_cache[key],body['features']['precursor_mz'],body['features']['adduct'],f) entries.extend({'smiles':r['smiles'],'source_id':str(r['cid'])} for r in kept) branches.append({'formula':f,'raw_count':row[2],'filtered_count':len(kept),'rejected_count':len(rejected),'sha256':row[1]}) info={'status':'pending' if pending else 'ready' if entries else 'ready_empty','view':view,'formulas':formulas, 'branches':branches,'pending':pending,'formula_predictions':predictions, 'formula_checkpoint_sha256':self.frozen_hash if view.endswith('top10') else None,'ppm_filter_applied':True} return (None if pending else entries),info
def plan(self, sequence, stage): if self.plan_db is not None: import pickle row=self.plan_db.execute('SELECT spectrum_id,view,stage,rng FROM plan WHERE sequence=?',(sequence,)).fetchone() if row is None or row[2]!=stage:raise RuntimeError('Frozen sample plan missing or stage mismatch') self.rng=random.Random();self.rng.setstate(pickle.loads(row[3])) body=unpacked(self.db.execute('SELECT body FROM spectra WHERE id=?',(row[0],)).fetchone()[0]) return row[0],body,False,row[1] sid,body,ready_selected=self.sample_ready(sequence) if body['source']=='msg_train':view='msg_mass' if (sequence//2)%2==0 else 'msg_formula' else:view='odata_predicted_top10' if stage!='warmup' and self.rng.random()<self.config['predicted_view_fraction'] else 'odata_oracle' return sid,body,ready_selected,view
def prepare(self, sequence, stage, chemistry): sid,body,ready_selected,view=self.plan(sequence,stage) trace_root=Path(self.config['run_dir'])/'worker_diagnostics' trace_root.mkdir(exist_ok=True,parents=True) (trace_root/f'worker_{os.getpid()}_query.json').write_text(json.dumps({'sequence':sequence,'spectrum_id':sid,'stage':stage,'source':body['source']})) entries,view_info=self.entries(body,view) if self.config.get('require_complete_pools') and (entries is None or view_info['status']=='pending'): raise RuntimeError('Offline preparation refused unresolved PubChem pool') ref=molecule(body['reference_smiles']) full,projection=training_projection(entries,self.banned) if entries is not None else ([],{}) subset,sampled=truth_guided_subset(full,ref,self.config['training_candidate_cap'],self.rng) if stage=='warmup':subset=[] record={'sample_id':str(sid),'split':'train','labels':{'reference_smiles':body['reference_smiles']}, 'features':{**body['features'],'candidate_view':view,'candidates':subset}} example=parse_record(record) forest=singleton_forest(example.query.candidates) if stage in {'warmup','direct'} else build_forest(example.query.candidates,chemistry) # Reference-guided nearest ISOMERS come from the complete projected pool, # not the randomly capped list or an absolute Tanimoto cutoff. isomers=[molecule(e['smiles']) for e in full if molecule(e['smiles']).identity!=ref.identity and molecule(e['smiles']).formula==ref.formula] isomers.sort(key=lambda m:(-tanimoto(ref.whole,m.whole),m.identity)) proposed=isomers[:64] if len(isomers)>64:proposed+=self.rng.sample(isomers[64:],min(32,len(isomers)-64)) proposed+=self.global_proposals(body,self.config['global_negative_proposals']) proposed={m.identity:m for m in proposed if m.identity!=ref.identity and m.identity not in self.banned} return {'example':example,'forest':forest,'ref':ref,'proposals':tuple(proposed[k] for k in sorted(proposed)), 'independent_formulas':self.catalog.select(example.query.precursor_mz,example.query.adduct), 'audit':{'sequence':sequence,'spectrum_id':sid,'source':body['source'],'view':view,'pool_status':view_info['status'], 'full_projected_count':len(full),'training_candidate_count':len(subset),'sampled_pool':sampled, 'ready_selected':ready_selected,'ready_odata_identity_count':len(self.ready_identities), 'same_formula_proposals':sum(m.formula==ref.formula for m in proposed.values()), 'molecule_cache':molecule.cache_info()._asdict(), 'negative_proposal_count':len(proposed),'positive_in_original_projected_pool':any(molecule(e['smiles']).identity==ref.identity for e in full), 'candidate_view_provenance':view_info,'projection':projection}}
_STREAM=None_TRACE_FH=None_STORE=None
def initialize_worker(config): global _STREAM,_TRACE_FH,_STORE RDLogger.DisableLog('rdApp.*');torch.set_num_threads(1) trace_root=Path(config['run_dir'])/'worker_diagnostics';trace_root.mkdir(exist_ok=True,parents=True) _TRACE_FH=(trace_root/f'worker_{os.getpid()}_stack.log').open('a') faulthandler.enable(file=_TRACE_FH,all_threads=True) if config.get('feature_cache_dir'): from .feature_store import FeatureStore _STORE=FeatureStore(config['feature_cache_dir']) configure_feature_store(_STORE) _STREAM=ReadyTrainingStream(config)
def prepare_batch(task): batch_index,stage,chemistry=task faulthandler.dump_traceback_later(30,repeat=True,file=_TRACE_FH) try: batch=[_STREAM.prepare(batch_index*_STREAM.config['batch_size']+i,stage,chemistry) for i in range(_STREAM.config['batch_size'])] if _STORE: _STORE.flush() for b in batch:b['audit']['shared_feature_cache']=dict(_STORE.stats) return batch finally:faulthandler.cancel_dump_traceback_later()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257from copy import deepcopyfrom dataclasses import asdictimport hashlibimport jsonfrom pathlib import Pathimport randomimport timeimport numpy as npimport torchfrom .chemistry import ADDUCTS, identity_hash, moleculefrom .config import Configfrom .evaluate import summarizefrom .forest import build_forest, partition_costfrom .losses import contrastive_loss, counterfactual_targets, cut_loss, listwise_loss, positive_indexfrom .model import SpecPartitionfrom .negatives import NegativeBank, DynamicSampler, update_fixed_training_probefrom .schema import assert_train_isolation, input_manifest
def seed_everything(seed, threads=2): random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.set_num_threads(threads) torch.use_deterministic_algorithms(True)
def write_json(path, value): path = Path(path) path.parent.mkdir(parents=True,exist_ok=True) temp = path.with_suffix(path.suffix+".tmp") temp.write_text(json.dumps(value,ensure_ascii=False,indent=2,allow_nan=False)+"\n") temp.replace(path)
def training_signature(examples): """Resume guard covers spectra, labels and pools, not only file names or counts.""" payload = [] for e in examples: payload.append({"sample_id":e.sample_id,"split":e.split,"identity":e.labels.identity if e.labels else None, "peaks":e.query.peaks,"precursor_mz":e.query.precursor_mz,"adduct":e.query.adduct, "collision_energy":e.query.collision_energy,"instrument":e.query.instrument, "formulas":e.query.formula_candidates,"pool":identity_hash(e.query.candidates)}) return hashlib.sha256(json.dumps(payload,sort_keys=True).encode()).hexdigest()
def checkpoint(path, model, optimizer, teacher, sampler, bank, epoch, data_hash): path = Path(path) temp = path.with_suffix(".tmp") state = {"schema_version":1,"epoch_completed":epoch,"config":model.cfg.to_dict(), "model":model.state_dict(),"optimizer":optimizer.state_dict(),"teacher":teacher.state_dict(), "sampler":sampler.state_dict(),"bank_hash":bank.hash,"bank_version":bank.version, "bank_embeddings":torch.tensor(bank.embeddings),"bank_weight_signature":bank.weight_signature, "torch_rng":torch.get_rng_state(),"python_rng":random.getstate(), "cuda_rng":torch.cuda.get_rng_state_all() if torch.cuda.is_available() and model.device.type=="cuda" else [], "training_signature":data_hash} torch.save(state,temp) temp.replace(path)
def load_model(path, device="cpu"): state = torch.load(path,map_location="cpu",weights_only=True) c = state["config"] from .config import ChemistryConfig,ModelConfig,TrainConfig cfg = Config(ChemistryConfig(**c["chemistry"]),ModelConfig(**c["model"]),TrainConfig(**c["train"])).validate() model = SpecPartition(cfg).to(device) model.load_state_dict(state["model"]) model.eval() return model,state
@torch.no_grad()def predict_example(model, example, include_candidates=True): started = time.monotonic() forest = build_forest(example.query.candidates,model.cfg.chemistry) forest_time = time.monotonic()-started output = model(example.query,forest) ids = forest.identities if not torch.isfinite(output.scores).all(): raise RuntimeError("Nonfinite ranking scores; result must not be labelled completed") scores = output.scores.cpu().tolist() order = sorted(range(len(ids)),key=lambda i:(-scores[i],ids[i])) fscore = output.formula_scores.cpu().tolist() formulas = example.query.formula_candidates forder = sorted(range(len(formulas)),key=lambda i:(-fscore[i],formulas[i])) target = example.labels.identity if example.labels else None rank = next((k+1 for k,i in enumerate(order) if ids[i]==target),None) ftarget = example.labels.formula if example.labels else None frank = next((k+1 for k,i in enumerate(forder) if formulas[i]==ftarget),None) formula_evaluable = example.query.dataset_mode == "synthetic" or example.query.formula_universe_source in {"bounded_enumeration", "training_catalog_mass_filtered"} if not formula_evaluable: frank = None cluster = {i:key for key in output.partition for i in forest.nodes[key].members} n = len(ids) row = {"sample_id":example.sample_id,"status":"completed" if n else "completed_empty_pool", "dataset_mode":example.query.dataset_mode,"adduct":example.query.adduct, "candidate_view":example.query.candidate_view,"formula_universe_source":example.query.formula_universe_source, "formula_prediction_evaluable":formula_evaluable, "polarity":"positive" if ADDUCTS[example.query.adduct][1]>0 else "negative", "candidate_regime":"empty" if not n else "small" if n<=256 else "medium" if n<=2000 else "large", "reference_identity":target,"reference_formula":ftarget,"reference_in_original_pool":target in ids if target else False, "connectivity_rank":rank,"formula_rank":frank,"candidate_count":n, "candidate_identity_sha256_before":identity_hash(example.query.candidates), "candidate_identity_sha256_after":hashlib.sha256("\n".join(sorted(ids[i] for i in order)).encode()).hexdigest(), "cluster_count":len(output.partition),"cluster_sizes":[len(forest.nodes[k].members) for k in output.partition], "partition":{k:[ids[i] for i in forest.nodes[k].members] for k in output.partition}, "formula_predictions":[{"rank":k+1,"formula":formulas[i],"score":fscore[i]} for k,i in enumerate(forder)], "chemistry_seconds":forest_time,"total_seconds":time.monotonic()-started, "cost_proxy":partition_cost(forest,output.partition,model.cfg.train.cost_node_overhead), "cost_proxy_is_measured_runtime":False, "forest_audit":{"proposal_pairs":forest.proposal_pairs,"similarity_checks":forest.similarity_checks, "approximate_proposals":forest.approximate_proposals}, "metric_kind":"synthetic_smoke_only" if example.query.dataset_mode=="synthetic" else "experimental_inference"} if include_candidates: row["ranked_candidates"] = [{"rank":k+1,"identity":ids[i],"smiles":example.query.candidates[i].smiles, "formula":example.query.candidates[i].formula,"score":scores[i],"base_score":float(output.encoded.base[i]), "direct_score":float(output.direct_scores[i]),"formula_contribution":float(output.encoded.base[i]-output.direct_scores[i]), "relation_residual":float(output.residual[i]),"cluster":cluster[i],"aliases":example.aliases[ids[i]]} for k,i in enumerate(order)] if row["candidate_identity_sha256_before"] != row["candidate_identity_sha256_after"]: raise RuntimeError("Candidate identity changed during ranking") return row
def train(examples, cfg, run_dir, heldout=(), resume=None, stop_after_epoch=None): cfg.validate() seed_everything(cfg.train.seed,cfg.train.threads) banned = assert_train_isolation(examples,heldout) if not examples or len({e.sample_id for e in examples}) != len(examples): raise ValueError("Training sample IDs must be nonempty and unique") run_dir = Path(run_dir) if run_dir.exists() and any(run_dir.iterdir()) and resume is None: raise FileExistsError("Run directory must be new; use --resume explicitly") run_dir.mkdir(parents=True,exist_ok=True) model = SpecPartition(cfg).to(cfg.train.device) optimizer = torch.optim.AdamW(model.parameters(),lr=cfg.train.learning_rate,weight_decay=cfg.train.weight_decay) teacher = deepcopy(model).eval() for p in teacher.parameters(): p.requires_grad_(False) bank = NegativeBank.from_training(examples,banned) sampler = DynamicSampler(cfg.train) data_hash = training_signature(examples) start_epoch = 0 if resume: state = torch.load(resume,map_location="cpu",weights_only=True) if state["config"] != cfg.to_dict() or state["training_signature"] != data_hash or state["bank_hash"] != bank.hash: raise ValueError("Resume config, training content or bank mismatch") model.load_state_dict(state["model"]) optimizer.load_state_dict(state["optimizer"]) teacher.load_state_dict(state["teacher"]) sampler.load_state_dict(state["sampler"]) bank.embeddings = state["bank_embeddings"].numpy() bank.version,bank.weight_signature = state["bank_version"],state["bank_weight_signature"] torch.set_rng_state(state["torch_rng"]) random.setstate(state["python_rng"]) if state["cuda_rng"] and model.device.type=="cuda": torch.cuda.set_rng_state_all(state["cuda_rng"]) start_epoch = state["epoch_completed"]+1 write_json(run_dir/"config.json",cfg.to_dict()) write_json(run_dir/"input_manifest.json",input_manifest(examples)) write_json(run_dir/"provenance.json",{"project":"SpecPartition-MS","version":"0.1.0","training_signature":data_hash, "bank_identity_sha256":bank.hash,"heldout_registry_targets":len(banned),"torch":torch.__version__, "numpy":np.__version__,"device":str(model.device),"real_data_training":not all(e.query.dataset_mode=="synthetic" for e in examples), "sirius_feature_dependency":False,"resume_boundary":"epoch", "data_isolation_scope":"provided heldout registry only"}) forests = {e.sample_id:build_forest(e.query.candidates,cfg.chemistry) for e in examples} valid_f = sum(e.labels.formula in e.query.formula_candidates for e in examples) valid_r = sum(e.labels.identity in forests[e.sample_id].identities for e in examples) last_summary = None for epoch in range(start_epoch,cfg.train.epochs): started = time.monotonic() warmup = epoch < cfg.train.warmup_epochs if bank.embeddings is None or epoch % cfg.train.teacher_refresh == 0: teacher.load_state_dict(model.state_dict()) teacher.eval() bank.refresh(teacher) probe = update_fixed_training_probe(sampler,teacher,examples,bank) write_json(run_dir/f"probe_epoch_{epoch:03d}.json",probe) targets = {} for e in examples: targets[e.sample_id] = [] if warmup or cfg.model.relation_mode!="learned" else counterfactual_targets( teacher,e.query,forests[e.sample_id],e.labels.identity,cfg.train.cut_nodes,cfg.train.cut_epsilon, cfg.train.cut_cost_tradeoff,cfg.train.cost_node_overhead,offset=epoch*cfg.train.cut_nodes) valid_cut = sum(bool(t) for t in targets.values()) write_json(run_dir/f"counterfactual_epoch_{epoch:03d}.json",{k:[asdict(t) for t in ts] for k,ts in targets.items()}) totals = {k:0. for k in ("formula","contrastive","rank","cut","cost","total")} steps, gradient_norms = [], [] model.train() order = torch.randperm(len(examples)).tolist() for position in order: e = examples[position] forest = forests[e.sample_id] optimizer.zero_grad(set_to_none=True) output = model(e.query,forest) ref = molecule(e.labels.reference_smiles) with torch.no_grad(): tenc = teacher.encode(e.query) partition = teacher.select_partition(tenc,forest) indices,audit = sampler.sample(e.query,ref,bank,tenc.z_query.cpu().numpy(),epoch,forest,partition) _,_,z = model.encode_molecules([ref]+[bank.molecules[i] for i in indices]) lc = contrastive_loss(output.encoded.z_query,z[0],z[1:],cfg.train.temperature) fp = positive_index(e.query.formula_candidates,e.labels.formula) rp = positive_index(forest.identities,e.labels.identity) lf,mf = listwise_loss(output.formula_scores,fp) lr,mr = listwise_loss(output.scores,rp) lcut,ncut = cut_loss(model,output.encoded,forest,targets[e.sample_id]) cost = output.expected_cost if cfg.model.relation_mode=="learned" else output.encoded.q.sum()*0. # Separate valid-example denominators; missing truth is not added to the formal pool. n = len(examples) loss = cfg.train.formula_weight*lf*n/max(1,valid_f)+cfg.train.contrastive_weight*lc if not warmup: loss = loss+cfg.train.rank_weight*lr*n/max(1,valid_r) loss = loss+cfg.train.cut_weight*lcut*n/max(1,valid_cut)+cfg.train.cost_weight*cost if not torch.isfinite(loss): raise RuntimeError(f"Nonfinite loss at {e.sample_id}") loss.backward() grad = torch.nn.utils.clip_grad_norm_(model.parameters(),cfg.train.gradient_clip,error_if_nonfinite=True) optimizer.step() values = {"formula":float(lf.detach()),"contrastive":float(lc.detach()),"rank":float(lr.detach()), "cut":float(lcut.detach()),"cost":float(cost.detach()),"total":float(loss.detach())} for k,v in values.items(): totals[k] += v gradient_norms.append(float(grad)) step = {"epoch":epoch,"sample_id":e.sample_id,"stage":"warmup" if warmup else "joint", "losses":values,"formula_valid":mf,"rank_valid":mr,"cut_targets":ncut, "negative_audit":audit,"partition_sizes":[len(forest.nodes[k].members) for k in output.partition]} steps.append(step) with (run_dir/"progress.jsonl").open("a") as fh: fh.write(json.dumps(step,allow_nan=False)+"\n") last_summary = {"epoch":epoch,"seconds":time.monotonic()-started,"stage":"warmup" if warmup else "joint", "conditional_mean_losses":{k:totals[k]/max(1,denom) for k,denom in (("formula",valid_f),("rank",valid_r),("contrastive",len(examples)),("cut",valid_cut),("cost",len(examples)),("total",len(examples)))}, "valid_examples":{"formula":valid_f,"rank":valid_r,"contrastive":len(examples),"cut":valid_cut}, "max_gradient_norm_before_clip":max(gradient_norms),"bank_version":bank.version, "checkpoint":"last.pt","metric_kind":"training_diagnostics_not_test_performance"} write_json(run_dir/f"epoch_{epoch:03d}.json",last_summary) checkpoint(run_dir/"last.pt",model,optimizer,teacher,sampler,bank,epoch,data_hash) print(json.dumps(last_summary),flush=True) if stop_after_epoch is not None and epoch >= stop_after_epoch: break model.eval() return model,last_summary
def predict_dataset(model, examples, output_dir, bootstrap=0): output_dir = Path(output_dir) output_dir.mkdir(parents=True,exist_ok=True) if (output_dir/"predictions.jsonl").exists(): raise FileExistsError("Prediction output exists; choose a new output directory") rows = [] with (output_dir/"predictions.jsonl").open("w") as fh: for e in examples: row = predict_example(model,e) fh.write(json.dumps(row,allow_nan=False)+"\n") rows.append({k:v for k,v in row.items() if k not in {"ranked_candidates","partition","formula_predictions"}}) metrics = summarize(rows,bootstrap) metrics["metric_kind"] = "synthetic_smoke_only" if rows and all(r["metric_kind"]=="synthetic_smoke_only" for r in rows) else "experimental_inference" write_json(output_dir/"metrics.json",metrics) return metrics123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224"""Full-corpus epochs over immutable features. No RDKit featurizing or forest building."""from collections import defaultdict, Counterfrom concurrent.futures import ThreadPoolExecutorfrom dataclasses import replacefrom functools import lru_cacheimport mathfrom pathlib import Pathimport randomimport threadingimport numpy as npfrom .epoch_features import loadsfrom .prepare_epoch import readonlyfrom .inbatch_data import view_for_batchfrom .schema import Example, Labelsfrom .forest import Forest,Node
def restrict_forest(full, mols): """Induce a subtree from a cached complete-link forest, without reclustering.
Removing members preserves diameter constraints. Recalculate statistics and medoids on retained members from cached fingerprints; no RDKit operations. """ idx={m.identity:i for i,m in enumerate(mols)};nodes={} if mols: x=np.stack([m.whole for m in mols]);intersection=x@x.T;size=x.sum(1) union=size[:,None]+size[None,:]-intersection sims=np.divide(intersection.astype(np.float64),union,out=np.zeros_like(intersection,dtype=np.float64),where=union>0) def visit(key): n=full.nodes[key] members=tuple(idx[full.identities[i]] for i in n.members if full.identities[i] in idx) if not members:return None children=tuple(k for k in (visit(k) for k in n.children) if k is not None) if len(children)==1:return children[0] if len(members)==1: i=members[0];stats=(0.,1.,1.,0.,float(not mols[i].scaffold_smiles));medoid=i else: ws=[sims[x,y] for p,x in enumerate(members) for y in members[p+1:]] stats=(float(np.log1p(len(members))),float(min(ws)),float(np.mean(ws)),float(np.std(ws)),float(np.mean([not mols[i].scaffold_smiles for i in members]))) medoid=min(members,key=lambda x:(-sum(sims[x,y] for y in members if x!=y),mols[x].identity)) nodes[key]=Node(key,members,children,stats,medoid);return key roots=tuple(k for k in (visit(k) for k in full.roots) if k is not None) f=Forest(nodes,roots,tuple(m.identity for m in mols),0,0,full.approximate_proposals) f.validate(roots);return f
def sample_view_ids(pool, identity, get_mol, negatives, rng): pairs=list(zip(pool['molecule_ids'],pool['forest'].identities)) pos=[mid for mid,key in pairs if key==identity] if len(pos)!=1:raise ValueError('Official training pool must contain exactly one true connectivity; no injection allowed') neg=[mid for mid,key in pairs if key!=identity] selected=pos+rng.sample(neg,min(negatives,len(neg))) # Identity order is label-blind; the positive has no reserved model position. keys=dict(pairs) selected.sort(key=keys.__getitem__) mask=np.arange(negatives+1)<len(selected) return selected,mask,len(neg)
def sample_view_with_replacement(pool, identity, negatives, rng): """Draw negative slots with replacement; encode each connectivity once.
Counts are LOSS-ONLY metadata. They are never features of a query or forest. The positive occurs once and can never be drawn as a negative. """ pairs=list(zip(pool['molecule_ids'],pool['forest'].identities)) if len({key for _,key in pairs})!=len(pairs): raise ValueError('Sampling requires unique connectivity in official pool') pos=[mid for mid,key in pairs if key==identity] if len(pos)!=1:raise ValueError('Official training positive must exist exactly once') if negatives<1:raise ValueError('Positive negative draw budget required') neg=[mid for mid,key in pairs if key!=identity] draws=rng.choices(neg,k=negatives) if neg else [] counts=Counter(pos+draws);keys=dict(pairs) selected=sorted(counts,key=keys.__getitem__) multiplicities=tuple(counts[mid] for mid in selected) mask=np.arange(negatives+1)<1+len(draws) return selected,mask,len(neg),multiplicities
class EpochPlan: def __init__(self, ids, c): self.ids = {s:np.asarray(sorted(v),dtype=np.int64) for s,v in ids.items()} self.c=c self.sizes={'odata':c['odata_batch_size'],'msg_train':c['msg_batch_size']} if any(v<1 for v in self.sizes.values()) or c['epochs']<1: raise ValueError('Invalid epoch/batch configuration') self.steps_per_epoch=max(math.ceil(len(v)/self.sizes[s]) for s,v in self.ids.items()) self.batch_counts={s:math.ceil(len(v)/self.sizes[s]) for s,v in self.ids.items()} self.total=self.steps_per_epoch*c['epochs']
@lru_cache(maxsize=2) def order(self, epoch, source): a=self.ids[source].copy() np.random.default_rng(self.c['seed']+epoch*100003+(17 if source=='odata' else 31)).shuffle(a) return a
def batch_ids(self, step, source): epoch, offset=divmod(step,self.steps_per_epoch) n=self.sizes[source] before=offset*self.batch_counts[source]//self.steps_per_epoch after=(offset+1)*self.batch_counts[source]//self.steps_per_epoch if before==after:return [] return self.order(epoch,source)[before*n:after*n].tolist()
def sequence(self, step, source, i): epoch,offset=divmod(step,self.steps_per_epoch) batch=offset*self.batch_counts[source]//self.steps_per_epoch return epoch*len(self.ids[source])+batch*self.sizes[source]+i
class PreparedReader: def __init__(self,c): self.c=c; self.path=Path(c['prepared_dir'])/'prepared.sqlite'; self.local=threading.local() db=self.db self.plan=EpochPlan({s:[r[0] for r in db.execute('SELECT id FROM spectra WHERE source=? ORDER BY id',(s,))] for s in ('odata','msg_train')},c) self.structs={}; self.by_formula=defaultdict(list) for identity,mid,formula in db.execute('SELECT s.identity,m.id,s.formula FROM training_structures s JOIN molecules m USING(smiles) WHERE m.ready=1 AND m.error IS NULL'): self.structs[identity]=mid;self.by_formula[formula].append(identity) self.keys=sorted(self.structs) self.mol=lru_cache(maxsize=c.get('molecule_lru_size',100000))(self._mol) self.pool=lru_cache(maxsize=c.get('pool_lru_size',8192))(self._pool) self.formula_pool=lru_cache(maxsize=c.get('pool_lru_size',8192))(self._formula_pool)
@property def db(self): if not hasattr(self.local,'db'): self.local.db=readonly(self.path) return self.local.db
def _mol(self,mid): r=self.db.execute('SELECT value,error,ready FROM molecules WHERE id=?',(int(mid),)).fetchone() if not r or r[2]!=1 or r[1]: raise RuntimeError('Missing/invalid prepared molecule; no runtime fallback') return loads(r[0])
def _pool(self,view,target): r=self.db.execute('SELECT prepared FROM pools WHERE view=? AND target=?',(view,target)).fetchone() if not r or not r[0]:raise RuntimeError('Missing prepared pool/forest; no runtime fallback') return loads(r[0])
def _formula_pool(self,view,target): """Full prepared training view, independent of the 63 sampled negatives.
The immutable preparation's heldout/support projection still applies; this is not claimed to include unsupported raw official formulas. No runtime RDKit calculation or positive formula insertion. """ ids=self.pool(view,target)['molecule_ids'] forms=set() for a in range(0,len(ids),500): block=tuple(int(x) for x in ids[a:a+500]) placeholders=','.join('?' for _ in block) forms.update(r[0] for r in self.db.execute('SELECT formula FROM molecules WHERE id IN ('+placeholders+')',block)) if None in forms:raise ValueError('Prepared formula metadata missing') return tuple(sorted(forms))
def row(self,sid,source,sequence,view): r=self.db.execute('SELECT identity,ref_smiles,target,body FROM spectra WHERE id=? AND source=?',(sid,source)).fetchone() if not r:raise ValueError('Epoch row missing') identity,ref_smiles,target,blob=r mid=self.db.execute('SELECT id FROM molecules WHERE smiles=?',(ref_smiles,)).fetchone()[0] ref=self.mol(mid);data=loads(blob);q=data['query'] if ref.identity!=identity:raise ValueError('Reference identity mismatch') audit={'sequence':sequence,'spectrum_id':sid,'source':source,'identity':identity,'network_requests':0, 'retrieval_pool_used':False,'view':'odata_inbatch'} if source=='odata': return {'example':Example(str(sid),q,Labels(ref_smiles,identity,ref.formula),{},'train'), 'ref':ref,'independent_formulas':data['independent_formulas'],'audit':audit} pool=self.pool(view,target) view_offset={'msg_mass':53,'msg_formula':97}[view] rng=random.Random(self.c['seed']+sequence*10007+view_offset) if self.c['msg_negative_sampling']=='uniform_with_replacement': selected,mask,available,multiplicities=sample_view_with_replacement(pool,identity,self.c['msg_negative_count'],rng) else: selected,mask,available=sample_view_ids(pool,identity,self.mol,self.c['msg_negative_count'],rng) multiplicities=tuple(1 for _ in selected) mols=tuple(self.mol(i) for i in selected) q=replace(q,candidates=mols,formula_candidates=tuple(sorted({m.formula for m in mols})),candidate_view=view) forest=restrict_forest(pool['forest'],mols) audit.update(view=view,retrieval_pool_used=True,full_projected_count=pool['projected_count'],training_candidate_count=len(mols), positive_in_original_projected_pool=pool['positive_in_original_projected_pool'], candidate_view_provenance={k:pool[k] for k in ('sha256','raw_count','ppm_filter_applied','raw_pool_modified')}, projection=pool['removed'],negative_proposal_count=len(mols)-1, same_formula_proposals=sum(m.formula==ref.formula and m.identity!=identity for m in mols),sampled_pool=len(mols)<pool['projected_count'], available_negative_count=available,selected_negative_count=len(mols)-1, candidate_slot_count=self.c['msg_negative_count']+1,padding_slots=int((~mask).sum()), sampling=self.c['msg_negative_sampling'],positive_injected=False, drawn_negative_slots=sum(multiplicities)-1,unique_negative_count=len(mols)-1, duplicate_negative_slots=sum(multiplicities)-len(mols), candidate_multiplicities=list(multiplicities), empty_negative_pool=available==0) fs=data['independent_formulas'] if self.c.get('formula_v07',{}).get('enabled',False): fs=self.formula_pool(view,target) audit.update(formula_loss_universe='full_prepared_'+view, formula_class_count=len(fs),formula_truth_present=ref.formula in fs, formula_negative_subsampling=False) return {'example':Example(str(sid),q,Labels(ref_smiles,identity,ref.formula),{},'train'), 'ref':ref,'forest':forest,'candidate_mask':mask,'candidate_multiplicities':multiplicities, 'independent_formulas':fs,'audit':audit}
def batch(self,step): views=self.c['msg_views'];ids=self.plan.batch_ids(step,'msg_train') return {'step':step,'view':'both','msg_spectrum_count':len(ids), 'odata':[self.row(sid,'odata',self.plan.sequence(step,'odata',i),None) for i,sid in enumerate(self.plan.batch_ids(step,'odata'))], 'msg':[self.row(sid,'msg_train',self.plan.sequence(step,'msg_train',i),view) for i,sid in enumerate(ids) for view in views]}
class CachedPrefetch: """Threads share a bounded molecular LRU: no graph pickle IPC per batch.""" def __init__(self,reader,first,end): self.reader=reader;self.end=end;self.next=first;self.pending={} self.pool=ThreadPoolExecutor(max_workers=reader.c['workers']) self.fill()
def fill(self): while len(self.pending)<self.reader.c['prefetch_batches'] and self.next<self.end: self.pending[self.next]=self.pool.submit(self.reader.batch,self.next);self.next+=1
def get(self,step): b=self.pending.pop(step).result(timeout=600);self.fill();return b
def close(self): for f in self.pending.values():f.cancel() self.pool.shutdown(wait=True,cancel_futures=True)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465"""Immutable prepared inputs. No labels enter spectrum features or the model.
This cache is internal, locally generated pickle, not an untrusted input format."""from dataclasses import dataclass, fieldimport mathimport pickleimport zlibimport numpy as npimport torchfrom .schema import Queryfrom .model import metadatafrom .model_v03 import BatchedSpectrumEncoder
@dataclass(frozen=True)class PreparedQuery(Query): spectrum_arrays: tuple = field(default=(), repr=False, compare=False)
def dumps(value): return zlib.compress(pickle.dumps(value, protocol=5), 1)
def loads(value): return pickle.loads(zlib.decompress(value))
def spectrum_arrays(query, max_peaks=256): peaks = sorted(query.peaks, key=lambda p: (-p[1], p[0]))[:max_peaks] peaks.sort() p = np.asarray(peaks, dtype=np.float32) if not len(p) or not np.isfinite(p).all() or p[:, 1].max() <= 0: raise ValueError('Invalid prepared spectrum') mz = p[:, 0] / np.float32(1000.) w = np.sqrt(p[:, 1] / max(p[:, 1].max(), 1e-12)).astype(np.float32) delta = (np.float32(query.precursor_mz) - p[:, 0]) / np.float32(1000.) angles = mz[:, None] * (2. ** np.arange(8, dtype=np.float32))[None, :] * np.float32(math.pi) x = np.column_stack((mz, w, delta, np.sin(angles), np.cos(angles))).astype(np.float32) return x, w, np.asarray(metadata(query), dtype=np.float32)
class PreparedSpectrumEncoder(BatchedSpectrumEncoder): """Same weights/semantics; batch CPU collation then three GPU transfers.""" def forward_batch(self, queries): if not queries or not all(isinstance(q, PreparedQuery) and q.spectrum_arrays for q in queries): raise ValueError('v06 training requires fully prepared spectrum features') lengths = [len(q.spectrum_arrays[0]) for q in queries] n = max(lengths) x = np.zeros((len(queries), n, 19), dtype=np.float32) w = np.zeros((len(queries), n), dtype=np.float32) meta = np.stack([q.spectrum_arrays[2] for q in queries]) for i, q in enumerate(queries): x[i, :lengths[i]], w[i, :lengths[i]] = q.spectrum_arrays[:2] dev = self.frequencies.device def transfer(a): t = torch.from_numpy(a) if dev.type == 'cuda': t = t.pin_memory() return t.to(dev, non_blocking=True) x, w, m = transfer(x), transfer(w), self.meta(transfer(meta)) mask = torch.arange(n, device=dev)[None, :] >= torch.tensor(lengths, device=dev)[:, None] tokens = self.encoder(self.peak(x) + m[:, None, :], src_key_padding_mask=mask) pooled = self.output((tokens * w[:, :, None]).sum(1) / w.sum(1).clamp_min(1e-12)[:, None]) return [tokens[i, :n] for i, n in enumerate(lengths)], pooled, m1234567891011121314151617181920212223242526272829303132333435363738394041424344from collections import defaultdictimport numpy as np
TOP_K = (1,3,5,10,20,50,100,200)
def recall_table(rows, key, ks): n = len(rows) return {str(k): {"hits":sum(r.get(key) is not None and r[key] <= k for r in rows),"denominator":n, "recall":sum(r.get(key) is not None and r[key] <= k for r in rows)/n if n else None} for k in ks}
def summarize(rows, bootstrap=0, seed=20260908): labelled = [r for r in rows if r.get("reference_identity")] covered = [r for r in labelled if r["reference_in_original_pool"]] formula_labelled = [r for r in labelled if r.get("formula_prediction_evaluable", True)] bytarget = defaultdict(list) for r in labelled: bytarget[r["reference_identity"]].append(r) result = {"total_queries":len(rows),"labelled_queries":len(labelled), "original_pool_covered":len(covered),"unlabelled_queries":len(rows)-len(labelled), "connectivity_end_to_end":recall_table(labelled,"connectivity_rank",TOP_K), "connectivity_conditional_pool":recall_table(covered,"connectivity_rank",TOP_K), "formula_recall":recall_table(formula_labelled,"formula_rank",range(1,11)), "formula_prediction_evaluable_queries":len(formula_labelled), "formula_universe_coverage":sum(r["formula_rank"] is not None for r in formula_labelled), "target_macro":{str(k):float(np.mean([np.mean([r["connectivity_rank"] is not None and r["connectivity_rank"]<=k for r in group]) for group in bytarget.values()])) if bytarget else None for k in TOP_K}, "distinct_targets":len(bytarget),"strata":{}, "full_inchikey_metric":"Not reported: primary model deduplicates connectivity; use retained aliases in a separate stereochemistry protocol."} for field in ("dataset_mode","adduct","polarity","candidate_regime"): groups = defaultdict(list) for r in labelled: groups[str(r[field])].append(r) result["strata"][field] = {k:recall_table(v,"connectivity_rank",TOP_K) for k,v in sorted(groups.items())} if bootstrap and bytarget: rng = np.random.default_rng(seed) keys = sorted(bytarget) cis = {} for k in TOP_K: vals = np.array([np.mean([r["connectivity_rank"] is not None and r["connectivity_rank"]<=k for r in bytarget[key]]) for key in keys]) boot = [vals[rng.integers(0,len(vals),len(vals))].mean() for _ in range(bootstrap)] cis[str(k)] = [float(x) for x in np.quantile(boot,[.025,.975])] result["target_grouped_bootstrap_95ci_macro"] = cis return result1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677"""Bounded shared derived-feature cache; never writes candidate/source databases.
All workers use the same chemistry/RDKit version namespace. Values and rejectedSMILES are computed by the unchanged molecular featurizer, not PubChem metadata.Only this application's locally generated pickle data is accepted here."""from collections import Counterimport hashlibfrom pathlib import Pathimport pickleimport sqlite3import zlibfrom rdkit import rdBase
class FeatureStore: def __init__(self, root, max_bytes=2 * 1024**3): from . import chemistry digest=hashlib.sha256(Path(chemistry.__file__).read_bytes()).hexdigest() namespace=hashlib.sha256((digest+rdBase.rdkitVersion+'packed-v1').encode()).hexdigest()[:24] root=Path(root);root.mkdir(parents=True,exist_ok=True) self.path=root/f'features_{namespace}.sqlite' self.db=sqlite3.connect(self.path,timeout=10,isolation_level=None) self.db.execute('PRAGMA journal_mode=WAL') self.db.execute('PRAGMA synchronous=NORMAL') self.db.execute('PRAGMA cache_size=-8192') self.db.execute('CREATE TABLE IF NOT EXISTS features (smiles TEXT PRIMARY KEY, value BLOB, error TEXT) WITHOUT ROWID') self.stats=Counter();self.pending={};self.max_bytes=max_bytes;self.writable=True
def get_or_compute(self, smiles, compute): row=self.pending.get(smiles) if row is None: row=self.db.execute('SELECT value,error FROM features WHERE smiles=?',(smiles,)).fetchone() if row is not None: value,error=row if error is not None: self.stats['rejected_hits']+=1 raise ValueError(error) # A corrupt derived cache is an explicit failure, never a silently # altered candidate pool. Source data can regenerate a fresh cache. result=pickle.loads(zlib.decompress(value));self.stats['hits']+=1 return result self.stats['misses']+=1 try: result=compute(smiles) except ValueError as exc: self._put(smiles,(None,str(exc))) raise self._put(smiles,(zlib.compress(pickle.dumps(result,protocol=5),1),None)) return result
def _put(self,key,value): if not self.writable:return self.pending[key]=value if len(self.pending)>=32:self.flush()
def flush(self): if not self.pending:return # Bound this disposable artifact. WAL size is checked too; overshoot is # limited to concurrent small transactions, not a growing corpus cache. size=sum(p.stat().st_size for p in (self.path,Path(str(self.path)+'-wal')) if p.exists()) if size>=self.max_bytes: self.writable=False;self.pending.clear();self.stats['size_guard']+=1;return try: self.db.execute('BEGIN IMMEDIATE') self.db.executemany('INSERT OR IGNORE INTO features VALUES (?,?,?)', [(k,*v) for k,v in self.pending.items()]) self.db.execute('COMMIT') except sqlite3.OperationalError as exc: if self.db.in_transaction:self.db.execute('ROLLBACK') if 'locked' not in str(exc).lower():raise # Cache lock contention must not change a training example. self.stats['write_lock_fallback']+=1 finally:self.pending.clear()
def close(self): self.flush();self.db.close()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154"""Candidate-only, formula-separated complete-link feasible forest.
Large pools use bounded minhash proposals, not an exact minimum clique cover.Every accepted merge is checked against ALL cross-member pairs."""from dataclasses import dataclassfrom collections import defaultdictimport hashlibimport numpy as npfrom .chemistry import scaffold_similarity, tanimoto
@dataclass(frozen=True)class Node: key: str members: tuple[int, ...] children: tuple[str, ...] stats: tuple[float, ...] medoid: int
@dataclassclass Forest: nodes: dict[str, Node] roots: tuple[str, ...] identities: tuple[str, ...] proposal_pairs: int similarity_checks: int approximate_proposals: bool
def leaves(self): return [n for n in self.nodes.values() if not n.children]
def validate(self, partition): ids = [i for k in partition for i in self.nodes[k].members] if sorted(ids) != list(range(len(self.identities))): raise ValueError("Partition must preserve each candidate exactly once")
def to_dict(self): return {"roots": self.roots, "identities": self.identities, "proposal_pairs": self.proposal_pairs, "similarity_checks": self.similarity_checks, "approximate_proposals": self.approximate_proposals, "nodes": {k: {"members": [self.identities[i] for i in n.members], "children": n.children, "stats": n.stats, "medoid": self.identities[n.medoid]} for k,n in self.nodes.items()}}
def proposal_pairs(mols, cfg): groups = defaultdict(list) for i,m in enumerate(mols): groups[m.formula].append(i) pairs = set() approximate = False for indices in groups.values(): indices.sort(key=lambda i: mols[i].identity) if len(indices) <= cfg.exact_pool_limit: pairs.update((a,b) if a < b else (b,a) for p,a in enumerate(indices) for b in indices[p+1:]) continue approximate = True buckets = defaultdict(list) # 16 deterministic minhashes / 8 bands. Candidate order never seeds hashing. for i in indices: bits = np.flatnonzero(mols[i].whole).astype(np.int64) signature = [int(((bits * (1000003+104729*s) + s*s*7919) % 2147483647).min()) if len(bits) else -1 for s in range(16)] for band in range(8): buckets[(band, *signature[2*band:2*band+2])].append(i) for bucket in buckets.values(): bucket.sort(key=lambda i: mols[i].identity) # Sliding windows bound proposal work even for a huge bucket; misses are explicitly audited. for pos, i in enumerate(bucket): for j in bucket[pos+1:pos+1+cfg.proposal_bucket_cap]: pairs.add(tuple(sorted((i,j)))) return pairs, approximate
def build_forest(mols, cfg, vectorized=False): if len({m.identity for m in mols}) != len(mols): raise ValueError("Deduplicate connectivity before building forest") nodes, owner, sims = {}, {}, {} checks = 0 tables = None if vectorized and mols and len(mols) <= 256: def matrix(arrays): x = np.stack(arrays).astype(np.float32) intersection = x @ x.T sizes = x.sum(1) union = sizes[:, None] + sizes[None, :] - intersection return np.divide(intersection.astype(np.float64), union, out=np.zeros_like(intersection, dtype=np.float64), where=union>0) tables = matrix([m.whole for m in mols]), matrix([m.scaffold for m in mols])
def pair(i,j): nonlocal checks k = tuple(sorted((i,j))) if k not in sims: checks += 1 w = float(tables[0][i,j]) if tables is not None else tanimoto(mols[i].whole, mols[j].whole) s = (float(tables[1][i,j]) if mols[i].scaffold_smiles and mols[j].scaffold_smiles else None) if tables is not None else scaffold_similarity(mols[i], mols[j]) sims[k] = w,s return sims[k]
def compatible(i,j): if mols[i].formula != mols[j].formula: return False w,s = pair(i,j) return w >= (cfg.acyclic_threshold if s is None else cfg.whole_threshold) and (s is None or s >= cfg.scaffold_threshold)
for i,m in enumerate(mols): key = "leaf:" + m.identity nodes[key] = Node(key, (i,), (), (0.,1.,1.,0.,float(not m.scaffold_smiles)), i) owner[i] = key pairs, approximate = proposal_pairs(mols, cfg) # Retain a bounded number of best proposed neighbors per candidate before merging. neighbors = defaultdict(list) for i,j in pairs: if compatible(i,j): w,_ = pair(i,j) neighbors[i].append((-w, mols[j].identity, j)) neighbors[j].append((-w, mols[i].identity, i)) retained = {tuple(sorted((i,j))) for i,ns in neighbors.items() for _,__,j in sorted(ns)[:cfg.neighbors]} ordered = sorted(retained, key=lambda ij: (-pair(*ij)[0], *sorted(mols[k].identity for k in ij))) for i,j in ordered: a,b = owner[i],owner[j] if a == b: continue na, nb = nodes[a],nodes[b] if len(na.members)+len(nb.members) > cfg.max_cluster_size: continue if not all(compatible(x,y) for x in na.members for y in nb.members): continue members = tuple(sorted(na.members+nb.members, key=lambda k:mols[k].identity)) key = "node:" + hashlib.sha256("|".join(mols[k].identity for k in members).encode()).hexdigest()[:20] ws = [pair(x,y)[0] for p,x in enumerate(members) for y in members[p+1:]] medoid = min(members, key=lambda x: (-sum(pair(x,y)[0] for y in members if x != y), mols[x].identity)) stats = (np.log1p(len(members)), min(ws), float(np.mean(ws)), float(np.std(ws)), float(np.mean([not mols[k].scaffold_smiles for k in members]))) nodes[key] = Node(key, members, tuple(sorted((a,b))), stats, medoid) for k in members: owner[k] = key result = Forest(nodes, tuple(sorted(set(owner.values()))), tuple(m.identity for m in mols), len(pairs), checks, approximate) result.validate(result.roots) return result
def partition_cost(forest, partition, overhead=16.): # Uncalibrated operation-count proxy, not seconds: per-set overhead plus quadratic attention. return sum(overhead + len(forest.nodes[k].members)**2 for k in partition)
def split_node(forest, partition, key): if key not in partition or not forest.nodes[key].children: raise ValueError("Can split only an active internal node") result = tuple(sorted((set(partition)-{key}) | set(forest.nodes[key].children))) forest.validate(result) return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156"""Opt-in formula evidence head. No labels, candidate positions or SIRIUS inputs.
This module ranks an explicitly supplied formula universe; it does NOT make aclosed training catalogue an open-vocabulary generator. Official pools are nothard-filtered. Physics contributes a soft score, never deletes a candidate."""import mathimport numpy as npimport torchfrom torch import nnfrom torch.nn import functional as Ffrom .chemistry import ELEMENTS, exact_mass, formula_vector, ppm_error
class FormulaEvidenceHead(nn.Module): def __init__(self, dim, config=None): super().__init__() c=config or {};self.settings=c self.formula_encoder=nn.Sequential(nn.Linear(2*len(ELEMENTS)+3,dim),nn.GELU(),nn.LayerNorm(dim),nn.Linear(dim,dim)) self.peak_encoder=nn.Sequential(nn.Linear(3,dim),nn.GELU(),nn.Linear(dim,dim)) self.key=nn.Linear(dim,dim,bias=False);self.value=nn.Linear(dim,dim,bias=False) self.formula_query=nn.Linear(2*dim,dim) self.evidence=nn.Sequential(nn.Linear(5*dim+4,dim),nn.GELU(),nn.Linear(dim,1)) self.elements=nn.Sequential(nn.Linear(dim,dim),nn.GELU(),nn.Linear(dim,2*len(ELEMENTS))) weight=float(c.get('initial_mass_weight',1.)) if weight<=0:raise ValueError('Positive initial mass weight required') self.mass_weight_raw=nn.Parameter(torch.tensor(math.log(math.expm1(weight)))) self.ppm_scale=float(c.get('ppm_scale',1.)) self.residual_bound=float(c.get('residual_bound',4.)) if self.ppm_scale<=0 or self.residual_bound<=0:raise ValueError('Positive scales required') # A new head initially equals the auditable absolute-mass-error baseline. nn.init.zeros_(self.evidence[-1].weight);nn.init.zeros_(self.evidence[-1].bias)
def forward(self,q,query): fs=query.formula_candidates if len(set(fs))!=len(fs):raise ValueError('Formula classes must be unique') with torch.autocast(device_type=q.device.type,enabled=False): q=q.float() if not fs:return q.new_empty(0) counts=q.new_tensor(np.stack([formula_vector(f) for f in fs])) total=counts.sum(-1,keepdim=True).clamp_min(1) carbon=counts[:,ELEMENTS.index('C')];nitrogen=counts[:,ELEMENTS.index('N')] hydrogen=counts[:,ELEMENTS.index('H')] halogens=sum(counts[:,ELEMENTS.index(e)] for e in ('F','Cl','Br','I')) dbe=(2+2*carbon+nitrogen-hydrogen-halogens)/2 mass=q.new_tensor([exact_mass(f) for f in fs]) ef=self.formula_encoder(torch.cat((counts.log1p(),counts/total, torch.stack((mass/1000.,total[:,0].log1p(),dbe/20.),-1)),dim=-1)) # Formula-conditioned attention over raw MS peaks. No assigned peak # formulas, isotopic envelopes or reference-derived inputs assumed. p=sorted(query.peaks,key=lambda x:(-x[1],x[0]))[:256] p=sorted(p);peaks=q.new_tensor(p) if not len(p) or not torch.isfinite(peaks).all() or peaks[:,1].max()<=0: raise ValueError('Valid MS peaks are required') intensity=(peaks[:,1]/peaks[:,1].max()).clamp_min(0).sqrt() hp=self.peak_encoder(torch.stack((peaks[:,0]/1000.,intensity, (query.precursor_mz-peaks[:,0])/1000.),-1)) qq=q.expand(len(fs),-1) attn=(self.formula_query(torch.cat((qq,ef),-1))@self.key(hp).T)/math.sqrt(q.numel()) context=attn.softmax(-1)@self.value(hp) err=q.new_tensor([ppm_error(exact_mass(f),query.precursor_mz,query.adduct) for f in fs]) ae=err.abs()/self.ppm_scale physics=torch.stack((err.sign()*err.abs().log1p(),ae.log1p(),(ae/10.).clamp_max(10), (ae/10.).square().clamp_max(100)),-1) neural=self.evidence(torch.cat((qq,ef,qq*ef,(qq-ef).abs(),context,physics),-1)).squeeze(-1) score=-F.softplus(self.mass_weight_raw)*ae.log1p()+self.residual_bound*neural.tanh() # v07.1: elemental supervision is also connected to formula ranking. # Candidate labels are never consulted here; every formula receives # the same predicted-element compatibility calculation. pw=float(self.settings.get('ranking_presence_weight',0.)) cw=float(self.settings.get('ranking_count_weight',0.)) if pw or cw: presence,pred_counts=self.elements(q).chunk(2) pe=F.binary_cross_entropy_with_logits(presence.expand_as(counts),(counts>0).float(),reduction='none').mean(-1) ce=F.smooth_l1_loss(F.softplus(pred_counts).expand_as(counts),counts.log1p(),reduction='none').mean(-1) score=score-pw*pe-cw*ce if not torch.isfinite(score).all():raise RuntimeError('Nonfinite formula score') return score
def auxiliary(self,q,truth): # Training labels only. These tasks remain active when the formula CE # universe is singleton, empty or misses the supervised training formula. with torch.autocast(device_type=q.device.type,enabled=False): target=q.new_tensor(formula_vector(truth),dtype=torch.float32) presence,counts=self.elements(q.float()).chunk(2) return {'presence':F.binary_cross_entropy_with_logits(presence,(target>0).float()), 'counts':F.smooth_l1_loss(F.softplus(counts),target.log1p())}
def formula_objective(model,qs,queries,universes,truths,total_ce,total_rows,diagnostics=None): """Full-universe CE plus all-row elemental supervision, independently normalized.""" zero=qs.float().sum()*0.;ce=zero;presence=zero;counts=zero;hard=zero from dataclasses import replace for q,query,fs,truth in zip(qs,queries,universes,truths): detail={'classes':len(fs),'truth_present':truth in fs,'ce_valid':len(fs)>1 and truth in fs,'ce':0.,'hard':0.,'rank':None} if len(fs)>1 and truth in fs: score=model.score_formulas(q,replace(query,formula_candidates=tuple(fs))) ce_i=F.cross_entropy(score[None],torch.tensor([fs.index(truth)],device=q.device));ce=ce+ce_i if diagnostics is not None: values=score.detach().float().cpu().tolist() order=sorted(range(len(fs)),key=lambda j:(-values[j],fs[j])) detail.update(ce=float(ce_i.detach()),rank=order.index(fs.index(truth))+1) if model.formula_v07.settings.get('hard_formula_weight',0.): p=fs.index(truth) negative=torch.cat((score[:p],score[p+1:])) top=negative.topk(min(len(negative),int(model.formula_v07.settings.get('hard_formula_count',8)))).values hard_i=F.softplus(top-score[p]+float(model.formula_v07.settings.get('hard_formula_margin',.2))).mean();hard=hard+hard_i if diagnostics is not None:detail['hard']=float(hard_i.detach()) aux=model.formula_v07.auxiliary(q,truth) presence=presence+aux['presence'];counts=counts+aux['counts'] if diagnostics is not None: if len(fs)==1 and truth in fs:detail['rank']=1 detail.update(presence=float(aux['presence'].detach()),counts=float(aux['counts'].detach())) diagnostics.append(detail) c=model.formula_v07.settings return (ce+c.get('hard_formula_weight',0.)*hard)/max(1,total_ce)+c.get('presence_weight',.1)*presence/max(1,total_rows)+c.get('count_weight',.1)*counts/max(1,total_rows)
def warm_start(model,state): """Load v06 base weights; allow ONLY newly introduced head parameters missing.""" incompatible=model.load_state_dict(state,strict=False) if incompatible.unexpected_keys or any(not k.startswith('formula_v07.') for k in incompatible.missing_keys): raise ValueError(f'Unexpected warm-start mismatch: {incompatible}') return list(incompatible.missing_keys)
def validate_frozen_preparation(c, verify_hash=True): """Reuse v06 data only after verifying its frozen producer and feature code.
The only allowed producer-module change is model.score_formulas, which is not used to prepare any input. All other model AST and producer hashes must agree. The original validator still checks data, RDKit, labels and hashes. """ import ast import importlib.util import json from pathlib import Path from .multiview_data import sha root=Path(c['frozen_preparation_source_dir']).resolve() current=Path(__file__).parent manifest=json.loads((Path(c['prepared_dir'])/'manifest.json').read_text()) for name,digest in manifest['preparation_source_hashes'].items(): if sha(root/name)!=digest:raise ValueError('Frozen producer mismatch: '+name) if name!='model.py' and sha(current/name)!=digest: raise ValueError('Current feature producer mismatch: '+name) def without_formula_score(path): tree=ast.parse(path.read_text()) for node in tree.body: if isinstance(node,ast.ClassDef): node.body=[x for x in node.body if not (isinstance(x,ast.FunctionDef) and x.name=='score_formulas')] return ast.dump(tree,include_attributes=False) if without_formula_score(root/'model.py')!=without_formula_score(current/'model.py'): raise ValueError('A non-formula-score model/metadata definition changed') spec=importlib.util.spec_from_file_location('specpartition_ms._frozen_prepare_epoch',root/'prepare_epoch.py') module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module) return module.validate(c,verify_hash)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293"""Network-free training: o_data in-batch labels + random official MSG views.
Only SELECT statements access the shared source index. Neither PubChem tablesnor jobs/requests/cache are used. All preprocessing happens in owned CPU workers."""from dataclasses import replaceimport hashlibimport jsonimport osfrom pathlib import Pathimport randomimport torchfrom rdkit import RDLoggerfrom .data_v03 import ReadyTrainingStreamfrom .multiview_train import TrainingStreamfrom .multiview_data import unpackedfrom .chemistry import moleculefrom .schema import parse_record
def view_for_batch(seed, step): return random.Random(seed + 7919 * step).choice(('msg_mass', 'msg_formula'))
class InbatchStream(ReadyTrainingStream): def __init__(self, config): super().__init__(config) self.msg_view = None self.db.set_authorizer(self.authorize)
@staticmethod def authorize(action, arg1, arg2, database, trigger): import sqlite3 forbidden = {'formula_pools', 'jobs', 'demand'} if action == sqlite3.SQLITE_READ and arg1 in forbidden: return sqlite3.SQLITE_DENY return sqlite3.SQLITE_OK
def entries(self, body, view): if view not in ('msg_mass', 'msg_formula'): raise RuntimeError('PubChem views are forbidden in v05') row = self.db.execute('SELECT body,sha256,count FROM official_pools WHERE view=? AND target=?', (view, body['target_smiles'])).fetchone() if row is None: raise RuntimeError('Official candidate pool missing or hash mismatch') pool = unpacked(row[0]) if hashlib.sha256(json.dumps(pool,separators=(',',':')).encode()).hexdigest() != row[1]: raise RuntimeError('Official candidate pool hash mismatch') if len(pool) != row[2]: raise RuntimeError('Official candidate count mismatch') return [{'smiles':s, 'source_id':None} for s in pool], { 'status':'ready', 'view':view, 'raw_count':len(pool), 'sha256':row[1], 'ppm_filter_applied':False, 'network_requests':0}
def plan(self, sequence, stage): self.rng = random.Random(self.config['seed'] + sequence * 10007) sid, body = TrainingStream.sample(self, 1) return sid, body, False, self.msg_view
def odata(self, sequence): self.rng = random.Random(self.config['seed'] + 999983 + sequence * 10007) sid, body = TrainingStream.sample(self, 0) ref = molecule(body['reference_smiles']) if ref.identity in self.banned: raise RuntimeError('Heldout label reached in-batch data') e = parse_record({'sample_id':str(sid), 'split':'train', 'labels':{'reference_smiles':body['reference_smiles']}, 'features':{**body['features'], 'candidate_view':'warmup', 'candidates':[], 'formula_candidates':[]}}) return {'example':e, 'ref':ref, 'independent_formulas':self.catalog.select(e.query.precursor_mz, e.query.adduct), 'audit':{'sequence':sequence, 'spectrum_id':sid, 'source':'odata', 'view':'odata_inbatch', 'identity':ref.identity, 'retrieval_pool_used':False, 'network_requests':0}}
_STREAM = None
def initialize_worker(config): global _STREAM # Private in-memory features only: no writes to downloader caches or SQLite. RDLogger.DisableLog('rdApp.*') torch.set_num_threads(1) _STREAM = InbatchStream(config)
def prepare_batch(task): step, stage, chemistry = task c = _STREAM.config _STREAM.msg_view = view_for_batch(c['seed'], step) odata = [_STREAM.odata(step*c['odata_batch_size']+i) for i in range(c['odata_batch_size'])] msg = [_STREAM.prepare(step*c['msg_batch_size']+i, stage, chemistry) for i in range(c['msg_batch_size'])] return {'odata':odata, 'msg':msg, 'view':_STREAM.msg_view, 'step':step}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193"""One optimizer update for all tasks; full in-batch o_data denominator.
Gradient replay saves memory, but NEVER freezes the trainable encoders. Itbackpropagates the exact cached feature gradients before the optimizer step."""from collections import Counterfrom dataclasses import replaceimport mathimport torchfrom torch.nn import functional as Ffrom .train_inbatch import identity_columns,inbatch_cefrom .train_v03 import amp_context,microbatch_groupsfrom .formula_v07 import formula_objectivefrom .losses import positive_index,listwise_loss,cut_loss,counterfactual_targets
DEFAULT_WEIGHTS={'formula':1.,'contrastive':1.,'direct_anchor':.25,'rank':1.,'hard':.1,'cut':.1,'cost':.001}
def weights(c):return {**DEFAULT_WEIGHTS,**c.get('joint_loss_weights',{})}
def formula_loss(model,qs,rows,details=None): n=sum(len(r['independent_formulas'])>1 and r['ref'].formula in r['independent_formulas'] for r in rows) return formula_objective(model,qs,[r['example'].query for r in rows], [r['independent_formulas'] for r in rows],[r['ref'].formula for r in rows],n,len(rows),details)
def odata_objective(model,qs,zm,mols,targets,rows,c): w=weights(c);conditional=[];rank=[] # Shared set, label-independent column identities, deduplicated connectivity. forms=tuple(sorted({m.formula for m in mols})) for q,row in zip(qs,rows): query=replace(row['example'].query,formula_candidates=forms) lc,lr,_=model.conditioned(q,query,[m.formula for m in mols],zm) conditional.append(lc);rank.append(lr) target=torch.tensor(targets,device=qs.device) lc=F.cross_entropy(torch.stack(conditional),target) if len(mols)>1 else qs.sum()*0. lr=F.cross_entropy(torch.stack(rank),target) if len(mols)>1 else qs.sum()*0. anchor,_=inbatch_ce(F.normalize(model.query_projection(qs).float(),dim=-1),zm.float(),targets) lf=formula_loss(model,qs,rows) loss=w['formula']*lf+w['contrastive']*lc+w['direct_anchor']*anchor+w['rank']*lr return loss,dict(LF_odata=lf,LC_odata=lc,LR_odata=lr,Lanchor_odata=anchor)
def odata_backward(model,rows,c): if not rows:return dict(odata_loss=0.,LF_odata=0.,LC_odata=0.,LR_odata=0.,Lanchor_odata=0.) mols,targets=identity_columns([r['ref'] for r in rows]);chunk=c['odata_micro_batch_size'] cached=c.get('odata_gradient_cache',True) if cached: with torch.no_grad(),amp_context(c): q0=torch.cat([model.spectrum.forward_batch([r['example'].query for r in rows[a:a+chunk]])[1] for a in range(0,len(rows),chunk)]) m0=torch.cat([model.encode_molecules(mols[a:a+c['graph_chunk']])[2] for a in range(0,len(mols),c['graph_chunk'])]) qs=q0.detach().float().requires_grad_();zm=m0.detach().float().requires_grad_() else: with amp_context(c): qs=model.spectrum.forward_batch([r['example'].query for r in rows])[1] zm=model.encode_molecules(mols)[2] with amp_context(c):loss,components=odata_objective(model,qs,zm,mols,targets,rows,c) if not torch.isfinite(loss):raise RuntimeError('Nonfinite o_data conditional loss') loss.backward() result={k:float(v.detach()) for k,v in components.items()};result['odata_loss']=float(loss.detach()) if cached: dq=qs.grad.detach();dm=zm.grad.detach() if zm.grad is not None else torch.zeros_like(zm) del loss,components,qs,zm,q0,m0 for a in range(0,len(rows),chunk): with amp_context(c):q=model.spectrum.forward_batch([r['example'].query for r in rows[a:a+chunk]])[1] (q.float()*dq[a:a+len(q)]).sum().backward() for a in range(0,len(mols),c['graph_chunk']): with amp_context(c):z=model.encode_molecules(mols[a:a+c['graph_chunk']])[2] (z.float()*dm[a:a+len(z)]).sum().backward() result.update(odata_unique_connectivity=len(mols),odata_negatives_per_query=max(0,len(mols)-1), odata_duplicate_positive_rows=len(rows)-len(mols)) if c.get('scratch_v09'): counts=Counter(m.formula for m in mols) result['odata_same_formula_negative_mean']=sum(counts[r['ref'].formula]-1 for r in rows)/len(rows) result['odata_no_same_formula_negative_fraction']=sum(counts[r['ref'].formula]==1 for r in rows)/len(rows) status=Counter('empty' if not r['independent_formulas'] else 'truth_missing' if r['ref'].formula not in r['independent_formulas'] else 'singleton' if len(r['independent_formulas'])==1 else 'ce_valid' for r in rows) result['odata_formula_supervision']=dict(status) return result
def msg_backward(model,teacher,rows,c,step,diagnostics): if not rows:return dict(msg_loss=0.,samples=[],source_rank_counts={}) # Formula conditioning uses the COMPLETE official view formula universe, # even when structure negatives are sampled. No truth-driven insertion. w=weights(c);targets={};queries=[replace(r['example'].query,formula_candidates=tuple(r['independent_formulas'])) for r in rows] for j in range(min(len(rows),c.get('cut_queries_per_batch',2))): i=(step+j)%len(rows) with torch.autocast(device_type=model.device.type,enabled=False): targets[i]=counterfactual_targets(teacher,queries[i],rows[i]['forest'],rows[i]['ref'].identity, max_nodes=c.get('cut_nodes_per_query',8),epsilon=c.get('cut_epsilon',.005),offset=step*2, multiplicities=rows[i].get('candidate_multiplicities')) nf=sum(len(r['independent_formulas'])>1 and r['ref'].formula in r['independent_formulas'] for r in rows) totals=Counter();audits=[];cut_nodes=0 view_sums={v:Counter() for v in c['msg_views']} groups=microbatch_groups(queries,[[] for _ in rows],c['max_atoms_per_microbatch']) for ids in groups: diagnostics['phase']='joint_msg_forward_backward' with amp_context(c): outs,_=model.forward_batch([queries[i] for i in ids],[rows[i]['forest'] for i in ids]) terms={k:outs[0].scores.sum()*0. for k in ('LC','LR','Lanchor','Lhard','Lcut','Lcost')} for i,out in zip(ids,outs): row=rows[i];p=positive_index(row['forest'].identities,row['ref'].identity) if p is None:raise ValueError('No injected or missing positive allowed in official train pool') mult=row.get('candidate_multiplicities',tuple(1 for _ in queries[i].candidates)) lc=listwise_loss(out.encoded.conditional_logits,p,mult)[0] lr=listwise_loss(out.scores,p,mult)[0] terms['LC']+=lc/len(rows) terms['LR']+=lr/len(rows) direct=(out.encoded.z_molecules.float()@out.encoded.z_query.float())/.1 la=listwise_loss(direct,p,mult)[0];terms['Lanchor']+=la/len(rows) same=[j for j,m in enumerate(queries[i].candidates) if j!=p and m.formula==row['ref'].formula] lh=out.scores.sum()*0. if same: expanded=out.scores[same].repeat_interleave(torch.tensor([mult[j] for j in same],device=out.scores.device)) hard=expanded.topk(min(c.get('same_formula_hard_topk',8),len(expanded))).values lh=F.softplus(hard-out.scores[p]+.2).mean();terms['Lhard']+=lh/len(rows) if i in targets: cl,n=cut_loss(model,out.encoded,row['forest'],targets[i]);cut_nodes+=n terms['Lcut']+=cl/max(1,len(targets)) terms['Lcost']+=out.expected_cost/len(rows) if c.get('scratch_v09'): values=out.scores.detach().float().cpu().tolist() order=sorted(range(len(values)),key=lambda j:(-values[j],row['forest'].identities[j])) rank=order.index(p)+1 raw=[j for j in range(len(values)) if j!=p] unique_lr=listwise_loss(out.scores,p)[0] vs=view_sums[row['audit']['view']] vs.update(queries=1,LC=float(lc.detach()),LR=float(lr.detach()),Lanchor=float(la.detach()), Lhard=float(lh.detach()),LR_unique=float(unique_lr.detach()), positive_probability_multiset=math.exp(-float(lr.detach())), negative_draws=sum(mult)-1,unique_negatives=len(mult)-1, duplicate_draws=sum(mult)-len(mult),same_formula_unique_negatives=len(same), same_formula_draws=sum(mult[j] for j in same),empty_negative_pool=int(not raw), hard_valid_queries=int(bool(same)),cut_valid_queries=int(bool(targets.get(i)))) if raw:vs.update(margin_valid=1,positive_top_negative_margin=values[p]-max(values[j] for j in raw)) for k in (1,3,5,10,20,50,100,200):vs['hit_at_'+str(k)]+=rank<=k audits.append({**row['audit'],'negative':{'count':len(queries[i].candidates)-1, 'draw_count':sum(mult)-1,'duplicates':sum(mult)-len(mult), 'same_formula':len(same),'positive_excluded':sum(m.identity==row['ref'].identity for m in queries[i].candidates)==1 and mult[p]==1}}) formula_details=[] if c.get('scratch_v09') else None terms['LF']=formula_objective(model,torch.stack([o.encoded.q for o in outs]),[queries[i] for i in ids], [rows[i]['independent_formulas'] for i in ids],[rows[i]['ref'].formula for i in ids],nf,len(rows),formula_details) if formula_details is not None: for i,d in zip(ids,formula_details): vs=view_sums[rows[i]['audit']['view']] vs.update(formula_ce_valid=int(d['ce_valid']),formula_CE_sum=d['ce'],formula_hard_sum=d['hard'], formula_presence_sum=d['presence'],formula_counts_sum=d['counts'],formula_classes_sum=d['classes'], formula_truth_present=int(d['truth_present'])) for k in range(1,11):vs['formula_hit_at_'+str(k)]+=d['rank'] is not None and d['rank']<=k loss=sum(w[name]*terms[key] for name,key in [('formula','LF'),('contrastive','LC'),('direct_anchor','Lanchor'), ('rank','LR'),('hard','Lhard'),('cut','Lcut'),('cost','Lcost')]) if not torch.isfinite(loss):raise RuntimeError('Nonfinite MSG conditional joint loss') loss.backward();totals.update({k:float(v.detach()) for k,v in terms.items()});totals['msg_loss']+=float(loss.detach()) del outs,loss,terms views={} if c.get('scratch_v09'): for name,s in view_sums.items(): n=s['queries'] if not n:continue views[name]={'queries':n,'sums':dict(s), 'means':{k:s[k]/n for k in ('LC','LR','Lanchor','Lhard','LR_unique','positive_probability_multiset', 'negative_draws','unique_negatives','duplicate_draws','same_formula_unique_negatives','same_formula_draws')}, 'structure_hit_at':{str(k):s['hit_at_'+str(k)]/n for k in (1,3,5,10,20,50,100,200)}, 'formula_hit_at':{str(k):s['formula_hit_at_'+str(k)]/n for k in range(1,11)}, 'formula_CE_valid_mean':s['formula_CE_sum']/s['formula_ce_valid'] if s['formula_ce_valid'] else None, 'positive_top_negative_margin_mean':s['positive_top_negative_margin']/s['margin_valid'] if s['margin_valid'] else None, 'rank_scope':'unique sampled connectivity; NOT full official pool'} return {**dict(totals),'samples':audits,'source_rank_counts':{'msg_train_rank_valid':len(rows)}, **({'msg_views_metrics':views} if c.get('scratch_v09') else {}), 'cut_valid_nodes':cut_nodes,'microbatches':len(groups)}
def joint_step(model,teacher,optimizer,batch,c,step,stage,diagnostics): if stage!='joint':raise ValueError('v08 requires joint optimization at every update') if any(not p.requires_grad for p in model.parameters()):raise ValueError('Student parameter freezing forbidden') optimizer.zero_grad(set_to_none=True) diagnostics['phase']='joint_odata';o=odata_backward(model,batch['odata'],c) m=msg_backward(model,teacher,batch['msg'],c,step,diagnostics) groups={} for label,prefix in [('spectrum','spectrum.'),('molecule','graph.'),('formula','formula_v07.'),('condition','conditional_'),('cut','cut.')]: grads=[p.grad.detach().float().square().sum() for n,p in model.named_parameters() if n.startswith(prefix) and p.grad is not None] groups[label]=float(torch.stack(grads).sum().sqrt()) if grads else 0. norm=torch.nn.utils.clip_grad_norm_(model.parameters(),5.,error_if_nonfinite=True) optimizer.step() loss=o['odata_loss']+m['msg_loss'] if not math.isfinite(loss):raise RuntimeError('Nonfinite joint loss') return {**o,**m,'loss':loss,'gradient_norm_before_clip':float(norm),'gradient_groups':groups, 'optimizer_updates':1,'view':'both','odata_exposures':len(batch['odata']), 'msg_exposures':batch['msg_spectrum_count'],'msg_view_exposures':len(batch['msg'])}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788"""Soft formula-conditioned retrieval. No reference labels enter this module.
All candidates survive; formula posterior is over DISTINCT candidate formulas,not weighted by the number of candidate molecules belonging to each formula.This is conditional retrieval, not an autoregressive SMILES generator."""from dataclasses import replaceimport numpy as npimport torchfrom torch import nnfrom torch.nn import functional as Ffrom .chemistry import formula_vectorfrom .config import Configfrom .epoch_features import PreparedSpectrumEncoderfrom .formula_v07 import FormulaEvidenceHeadfrom .model_v03 import BatchedSpecPartition
class ConditionalSpecPartition(BatchedSpecPartition): def __init__(self,c): cfg=Config() for k,v in c['model'].items():setattr(cfg.model,k,v) cfg.model.relation_mode='learned';cfg.train.device=c['device'];cfg.validate() super().__init__(cfg,c['graph_chunk'],c['local_chunk'],c.get('gated_graph',True)) self.spectrum=PreparedSpectrumEncoder(cfg.model) self.formula_v07=FormulaEvidenceHead(cfg.model.dim,c['formula_v07']) d=cfg.model.dim self.conditional_query=nn.Sequential(nn.Linear(4*d,d),nn.GELU(),nn.Linear(d,d)) self.conditional_context=nn.Sequential(nn.Linear(2*d,d),nn.GELU(),nn.Linear(d,d)) # Small but nonzero initialization: preserve warm-start scores while # allowing conditioning and formula gradients on the FIRST update. for layer in (self.conditional_query[-1],self.conditional_context[-1]): nn.init.normal_(layer.weight,std=.001);nn.init.zeros_(layer.bias) self.condition_bound=float(c.get('condition_bound',.25))
def conditioned(self,q,query,formulas,zm,formula_scores=None): """Return structural conditional logits and joint formula/structure logits.
formulas is one formula for every molecule in zm (including negatives). The reference molecule/formula is not an argument. For o_data each in-batch molecule is a candidate column for EVERY spectrum. """ fs=tuple(query.formula_candidates) if len(fs)!=len(set(fs)):raise ValueError('Duplicate formula classes') lookup={f:i for i,f in enumerate(fs)} if any(f not in lookup for f in formulas):raise ValueError('Candidate formula missing from inference universe') scores=self.score_formulas(q,query) if formula_scores is None else formula_scores with torch.autocast(device_type=q.device.type,enabled=False): q=q.float();zm=zm.float();scores=scores.float() if not formulas:return scores.new_empty(0),scores.new_empty(0),q features=q.new_tensor(np.stack([formula_vector(f) for f in fs])) ef=self.formula(features.log1p()).float() posterior=scores.softmax(0) context=posterior@ef qf=q.expand_as(ef) delta=self.condition_bound*self.conditional_query(torch.cat((qf,ef,qf*ef,context.expand_as(ef)),-1)).tanh() zf=F.normalize(self.query_projection(qf+delta),dim=-1) idx=torch.tensor([lookup[f] for f in formulas],device=q.device) structural=(zf[idx]*zm).sum(-1)/.1 # A common log-normalizer does not affect within-query ranks. prior=torch.sigmoid(self.formula_gate(q)).squeeze()*scores.log_softmax(0)[idx] relation_q=q+self.condition_bound*self.conditional_context(torch.cat((q,context))).tanh() return structural,structural+prior,relation_q
def encode_batch(self,queries,extras=()): encs,zm=super().encode_batch(queries,extras) for enc in encs: cond,joint,relation_q=self.conditioned(enc.q,enc.query,[m.formula for m in enc.query.candidates],enc.z_molecules,enc.formula_scores) old_cos=self.log_scale.exp().clamp(max=100.)*(enc.z_molecules.float()@enc.z_query.float()) # Keep local peak-atom interactions, replace only global cosine. local=enc.direct-old_cos enc.conditional_logits=cond;enc.conditional_context_q=relation_q enc.direct=cond+local;enc.base=joint+local return encs,zm
def cut_logit(self,enc,node): return super().cut_logit(replace(enc,q=getattr(enc,'conditional_context_q',enc.q)),node)
def score_partition(self,enc,forest,partition): return super().score_partition(replace(enc,q=getattr(enc,'conditional_context_q',enc.q)),forest,partition)
def load_initial(model,state): result=model.load_state_dict(state,strict=False) allowed=('conditional_query.','conditional_context.','formula_v07.') if result.unexpected_keys or any(not k.startswith(allowed) for k in result.missing_keys): raise ValueError('Unexpected initial model mismatch: '+str(result)) return list(result.missing_keys)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110from dataclasses import dataclassimport torchfrom torch.nn import functional as Ffrom .forest import partition_cost, split_node
def positive_index(identities, target): found = [i for i,k in enumerate(identities) if k == target] if len(found) > 1: raise ValueError("Connectivity must be unique before listwise CE") return found[0] if found else None
def listwise_loss(scores, positive, multiplicities=None): if positive is None: return scores.sum()*0., 0 if not 0 <= positive < len(scores): raise ValueError("Invalid positive index") # Exact CE over the supplied pool/multiset, not the full official pool. weighted=scores if multiplicities is not None: counts=torch.as_tensor(multiplicities,device=scores.device,dtype=scores.dtype) if counts.shape!=scores.shape or not bool(torch.isfinite(counts).all()) or bool((counts<1).any()) or bool((counts!=counts.round()).any()): raise ValueError('Positive integer multiplicities must align with unique scores') if float(counts[positive])!=1.:raise ValueError('Positive must occur once; false negatives prohibited') weighted=scores+counts.log() return torch.logsumexp(weighted,0)-scores[positive], 1
def contrastive_loss(z_query, z_positive, z_negatives, temperature=.1): positive = (z_query*z_positive).sum().reshape(1) negative = z_negatives@z_query logits = torch.cat((positive,negative))/temperature return torch.logsumexp(logits,0)-logits[0]
@dataclass(frozen=True)class CutTarget: node_key: str delta: float split: float weight: float stop_rank_loss: float split_rank_loss: float stop_cost: float split_cost: float
@torch.no_grad()def counterfactual_targets(teacher, query, forest, identity, max_nodes=8, epsilon=1e-5, cost_tradeoff=.001, overhead=16., offset=0, multiplicities=None): """Same frozen scorer, same query/pool, one-node intervention at a time.
Rest of the hard partition is held fixed. This does not solve a global optimal tree cut. """ if teacher.training: raise ValueError("Teacher must be in eval mode") positive = positive_index(forest.identities,identity) if positive is None: return [] eligible = sorted((n for n in forest.nodes.values() if n.children),key=lambda n:n.key) if not eligible or max_nodes <= 0: return [] enc = teacher.encode(query) original = teacher.select_partition(enc,forest) if eligible: offset %= len(eligible) eligible = (eligible[offset:]+eligible[:offset])[:max_nodes] targets = [] scale = max(1,len(forest.identities)*(overhead+1)) for node in eligible: members = set(node.members) # Build a partition where this node is active. If an ancestor is active, expand # along the path, keeping all sibling subtrees; other roots remain unchanged. def expose(key): n = forest.nodes[key] if key == node.key: return [key] if members.issubset(set(n.members)) and n.children: return [x for c in n.children for x in expose(c)] return [key] stopped = [] for k in original: if set(forest.nodes[k].members).issubset(members): continue stopped.extend(expose(k)) if node.key not in stopped: stopped.append(node.key) stopped = tuple(sorted(stopped)) forest.validate(stopped) split = split_node(forest,stopped,node.key) rs = float(listwise_loss(teacher.score_partition(enc,forest,stopped)[0],positive,multiplicities)[0]) rr = float(listwise_loss(teacher.score_partition(enc,forest,split)[0],positive,multiplicities)[0]) cs = partition_cost(forest,stopped,overhead)/scale cr = partition_cost(forest,split,overhead)/scale delta = rs-rr+cost_tradeoff*(cs-cr) if abs(delta) > epsilon: targets.append(CutTarget(node.key,delta,float(delta > 0),min(abs(delta),1.),rs,rr,cs,cr)) return targets
def cut_loss(model, encoded, forest, targets): if not targets: return encoded.q.sum()*0., 0 logits = torch.stack([model.cut_logit(encoded,forest.nodes[t.node_key]) for t in targets]) y = logits.new_tensor([t.split for t in targets]) w = logits.new_tensor([t.weight for t in targets]) # Keep absolute teacher confidence: normalising by sum(w) cancelled it for # one-node queries and made near-zero counterfactual differences full labels. return (F.binary_cross_entropy_with_logits(logits,y,reduction="none")*w).mean(),len(targets)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275from dataclasses import dataclassimport mathimport numpy as npimport torchfrom torch import nnfrom torch.nn import functional as Ffrom .chemistry import ADDUCTS, ANCHOR_DIM, ATOM_DIM, BOND_DIM, ELEMENTS, FP_SIZE, formula_vector, exact_mass, ppm_errorfrom .forest import Forest
META_DIM = len(ADDUCTS) + 9
def metadata(query): polarity = 1. if ADDUCTS[query.adduct][1] > 0 else -1. instrument = (query.instrument or "").lower() family = next((i for i,s in enumerate(("orbitrap", "qtof", "iontrap")) if s in instrument), 3 if instrument else 4) return ([float(query.adduct == a) for a in ADDUCTS] + [polarity, (query.collision_energy or 0.)/100., float(query.collision_energy is None), query.precursor_mz/1000.] + [float(i == family) for i in range(5)])
class SpectrumEncoder(nn.Module): def __init__(self, cfg): super().__init__() d = cfg.dim self.max_peaks = cfg.max_peaks self.peak = nn.Sequential(nn.Linear(19, d), nn.GELU(), nn.Linear(d,d)) self.meta = nn.Sequential(nn.Linear(META_DIM,d), nn.GELU(), nn.Linear(d,d)) layer = nn.TransformerEncoderLayer(d, cfg.heads, d*4, dropout=0., activation="gelu", batch_first=True) self.encoder = nn.TransformerEncoder(layer, cfg.spectrum_layers, enable_nested_tensor=False) self.output = nn.LayerNorm(d) self.register_buffer("frequencies", 2.**torch.arange(8))
def forward(self, query): dev = self.frequencies.device peaks = sorted(query.peaks, key=lambda p:(-p[1],p[0]))[:self.max_peaks] peaks.sort() p = torch.tensor(peaks, device=dev, dtype=torch.float32) mz, inten = p[:,0]/1000., torch.sqrt(p[:,1]/p[:,1].max().clamp_min(1e-12)) loss = (query.precursor_mz-p[:,0])/1000. angles = mz[:,None] * self.frequencies[None,:] * math.pi x = torch.cat((mz[:,None], inten[:,None], loss[:,None], angles.sin(), angles.cos()), dim=-1) m = self.meta(torch.tensor(metadata(query), device=dev)) tokens = self.encoder((self.peak(x)+m)[None,:,:])[0] q = self.output((tokens*inten[:,None]).sum(0)/inten.sum().clamp_min(1e-12)) return tokens, q, m
class GraphEncoder(nn.Module): def __init__(self, cfg): super().__init__() d = cfg.dim self.atom = nn.Linear(ATOM_DIM,d) self.edge = nn.Linear(BOND_DIM,d) self.messages = nn.ModuleList(nn.Sequential(nn.Linear(2*d,d),nn.GELU(),nn.Linear(d,d)) for _ in range(cfg.graph_layers)) self.norms = nn.ModuleList(nn.LayerNorm(d) for _ in range(cfg.graph_layers)) self.pool = nn.Linear(2*d,d)
def forward(self, mols, device): if not mols: d = self.atom.out_features return torch.empty((0,d),device=device), [], [] sizes = [len(m.atom_features) for m in mols] offsets = np.cumsum([0]+sizes) atoms = torch.as_tensor(np.concatenate([m.atom_features for m in mols]),device=device) edges = torch.as_tensor(np.concatenate([m.edge_index+o for m,o in zip(mols,offsets)],axis=1),device=device) bonds = torch.as_tensor(np.concatenate([m.bond_features for m in mols]),device=device) h = self.atom(atoms) e = self.edge(bonds) u,v = edges deg = torch.bincount(v,minlength=len(h)).float().clamp_min(1).unsqueeze(-1) for message,norm in zip(self.messages,self.norms): msg = message(torch.cat((h[u],e),dim=-1)) agg = torch.zeros_like(h).index_add(0,v,msg)/deg h = norm(h+agg) split = list(h.split(sizes)) pooled = torch.stack([torch.cat((x.mean(0), x.max(0).values)) for x in split]) return self.pool(pooled), split, sizes
@dataclassclass Encoded: query: object peaks: torch.Tensor q: torch.Tensor meta: torch.Tensor u: torch.Tensor z_query: torch.Tensor z_molecules: torch.Tensor atoms: list whole: torch.Tensor anchors: torch.Tensor formula_scores: torch.Tensor base: torch.Tensor direct: torch.Tensor
@dataclassclass Output: scores: torch.Tensor direct_scores: torch.Tensor formula_scores: torch.Tensor partition: tuple residual: torch.Tensor expected_cost: torch.Tensor encoded: Encoded
class SpecPartition(nn.Module): def __init__(self, cfg): super().__init__() self.cfg = cfg c,d = cfg.model,cfg.model.dim self.spectrum = SpectrumEncoder(c) self.graph = GraphEncoder(c) self.fp = nn.Linear(FP_SIZE,d,bias=False) self.anchor = nn.Linear(ANCHOR_DIM,d,bias=False) self.structure = nn.Sequential(nn.Linear(3*d,d), nn.GELU(), nn.LayerNorm(d)) self.query_projection = nn.Linear(d,d) self.mol_projection = nn.Linear(d,d) self.formula = nn.Sequential(nn.Linear(len(ELEMENTS),d), nn.GELU(),nn.Linear(d,d)) self.formula_energy = nn.Sequential(nn.Linear(2*d+1,d),nn.GELU(),nn.Linear(d,1)) self.formula_gate = nn.Linear(d,1) self.log_scale = nn.Parameter(torch.tensor(math.log(10.))) self.local_q = nn.Linear(d,d,bias=False) self.local_a = nn.Linear(d,d,bias=False) self.local_weight = nn.Parameter(torch.tensor(0.1)) self.cut = nn.Sequential(nn.Linear(3*d+5,d),nn.GELU(),nn.Linear(d,1)) self.attn = nn.MultiheadAttention(d,c.heads,dropout=0.,batch_first=True) self.relative = nn.Sequential(nn.Linear(3*d,d),nn.GELU(),nn.Linear(d,d)) self.member = nn.Sequential(nn.Linear(2*d,d),nn.GELU(),nn.Linear(d,1)) self.group = nn.Sequential(nn.Linear(2*d,d),nn.GELU(),nn.Linear(d,1)) self.relation_gate = nn.Sequential(nn.Linear(2*d+5,d),nn.GELU(),nn.Linear(d,1)) self.soft_assignment = nn.Sequential(nn.Linear(2*d,d),nn.GELU(),nn.Linear(d,8))
@property def device(self): return next(self.parameters()).device
def encode_molecules(self, mols): # Chunk graph construction; graph tensors retain gradients during training. us, atoms = [], [] for off in range(0,len(mols),128): batch = mols[off:off+128] h,a,_ = self.graph(batch,self.device) fp = torch.tensor(np.stack([m.whole for m in batch]),device=self.device) anchors = torch.tensor(np.stack([m.anchors for m in batch]),device=self.device) us.append(self.structure(torch.cat((h,self.fp(fp),self.anchor(anchors)),dim=-1))) atoms.extend(a) u = torch.cat(us) if us else torch.empty((0,self.cfg.model.dim),device=self.device) return u, atoms, F.normalize(self.mol_projection(u),dim=-1)
def score_formulas(self, q, query): if hasattr(self, 'formula_v07'): return self.formula_v07(q, query) fs = query.formula_candidates if not fs: return torch.empty(0,device=self.device) f = torch.tensor(np.stack([formula_vector(s) for s in fs]),device=self.device) err = torch.tensor([ppm_error(exact_mass(s),query.precursor_mz,query.adduct) for s in fs],device=self.device) # Signed log magnitude remains finite for fixed official pools with metadata discrepancies. err = torch.sign(err)*torch.log1p(err.abs())/10. return self.formula_energy(torch.cat((q.expand(len(fs),-1),self.formula(torch.log1p(f)),err[:,None]),-1)).squeeze(-1)
def encode(self, query): peaks,q,meta = self.spectrum(query) u,atoms,zm = self.encode_molecules(query.candidates) zq = F.normalize(self.query_projection(q),dim=-1) direct = self.log_scale.exp().clamp(max=100.) * (zm @ zq) if self.cfg.model.local_match and atoms: qp = F.normalize(self.local_q(peaks),dim=-1) local = [] # Per-candidate late interaction; avoids a P x all-atoms attention matrix. for a in atoms: sim = qp @ F.normalize(self.local_a(a),dim=-1).T local.append(sim.max(-1).values.mean()) direct = direct + self.local_weight*torch.stack(local) fs = self.score_formulas(q,query) base = direct if self.cfg.model.formula_score and query.candidates: lookup = {f:i for i,f in enumerate(query.formula_candidates)} indices = torch.tensor([lookup[m.formula] for m in query.candidates],device=self.device) base = base + torch.sigmoid(self.formula_gate(q))*fs[indices] whole = torch.tensor(np.stack([m.whole for m in query.candidates]),device=self.device) if atoms else torch.empty((0,FP_SIZE),device=self.device) anchors = torch.tensor(np.stack([m.anchors for m in query.candidates]),device=self.device) if atoms else torch.empty((0,ANCHOR_DIM),device=self.device) return Encoded(query,peaks,q,meta,u,zq,zm,atoms,whole,anchors,fs,base,direct)
def cut_logit(self, enc, node): u = enc.u[list(node.members)] q = enc.meta if self.cfg.model.controller_input == "metadata" else enc.q stats = enc.q.new_tensor(node.stats) return self.cut(torch.cat((q,u.mean(0),u.std(0,unbiased=False),stats))).squeeze(-1)
def select_partition(self, enc, forest): result = [] def visit(k): n = forest.nodes[k] if n.children and self.cfg.model.relation_mode == "learned" and self.cut_logit(enc,n).detach().item() > 0: for child in n.children: visit(child) else: result.append(k) for k in forest.roots: visit(k) forest.validate(result) return tuple(result)
def expected_cost(self, enc, forest): overhead = self.cfg.train.cost_node_overhead def cost(k): n = forest.nodes[k] stop = enc.q.new_tensor(overhead+len(n.members)**2) if not n.children: return stop p = torch.sigmoid(self.cut_logit(enc,n)) return (1-p)*stop+p*sum(cost(c) for c in n.children) return sum((cost(k) for k in forest.roots), enc.q.sum()*0.) / max(1,len(forest.identities)*(overhead+1))
def score_partition(self, enc, forest, partition): forest.validate(partition) residual = torch.zeros_like(enc.base) if self.cfg.model.relation_mode == "none": return enc.base, residual if self.cfg.model.relation_mode in {"knn", "set", "softpool"}: # Candidate-set controls. These are explicit adapters, not reproductions of published models. if len(enc.u) < 2: return enc.base,residual if self.cfg.model.relation_mode == "set": # O(Nd) query-attentive set context; no N x N matrix. weights = (enc.u@enc.q/math.sqrt(enc.u.shape[-1])).softmax(0) context = (weights[:,None]*enc.u).sum(0).expand_as(enc.u) elif self.cfg.model.relation_mode == "softpool": assignments = self.soft_assignment(torch.cat((enc.u,enc.q.expand_as(enc.u)),-1)).softmax(-1) prototypes = assignments.T@enc.u/assignments.sum(0).clamp_min(1e-6)[:,None] context = assignments@prototypes else: contexts = [] norm = F.normalize(enc.u,dim=-1) # Exact, blocked kNN in learned space; O(N^2) time but bounded score memory. for start in range(0,len(norm),128): similarities = norm[start:start+128]@norm.T idx = similarities.topk(min(17,len(norm)),dim=-1).indices contexts.append(enc.u[idx].mean(1)) context = torch.cat(contexts) r = self.member(torch.cat((enc.u,context),-1)).squeeze(-1) residual = self.cfg.model.residual_bound*torch.tanh(r) return enc.base+residual,residual for key in partition: node = forest.nodes[key] if len(node.members) == 1: continue ids, med = list(node.members),node.medoid u = enc.u[ids] context,_ = self.attn(enc.q[None,None,:],u[None,:,:],u[None,:,:],need_weights=False) context = context[0,0] if self.cfg.model.relative_difference: # Signed fingerprint and local attachment-environment differences against the medoid. delta = self.relative(torch.cat((u-enc.u[med],self.fp(enc.whole[ids]-enc.whole[med]), self.anchor(enc.anchors[ids]-enc.anchors[med])),dim=-1)) else: delta = u member = self.member(torch.cat((delta,enc.q.expand_as(delta)),-1)).squeeze(-1) member = member-member.mean() group = self.group(torch.cat((enc.q,context))).squeeze(-1) gate = torch.sigmoid(self.relation_gate(torch.cat((enc.q,context,enc.q.new_tensor(node.stats))))).squeeze(-1) r = self.cfg.model.residual_bound*gate*torch.tanh(group+member) residual = residual.index_copy(0,torch.tensor(ids,device=self.device),r) return enc.base+residual,residual
def forward(self, query, forest, partition=None): if tuple(m.identity for m in query.candidates) != forest.identities: raise ValueError("Forest does not match candidate identities/order") enc = self.encode(query) partition = self.select_partition(enc,forest) if partition is None else tuple(partition) scores,residual = self.score_partition(enc,forest,partition) return Output(scores,enc.direct,enc.formula_scores,partition,residual,self.expected_cost(enc,forest),enc)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177"""Capacity and batching upgrade. The v0.2 model/checkpoint format stays untouched.
No candidate pruning is performed by this model. Query-local scores and masksare independent of other queries in the same batch. Canonical structures areencoded once per batch, including contrastive-only training molecules."""from dataclasses import replaceimport mathimport numpy as npimport torchfrom torch import nnfrom torch.nn import functional as Ffrom torch.nn.utils.rnn import pad_sequencefrom .model import SpecPartition, SpectrumEncoder, Encoded, Output, metadatafrom .chemistry import ATOM_DIM, BOND_DIM, FP_SIZE, ANCHOR_DIM
class BatchedSpectrumEncoder(SpectrumEncoder): def forward_batch(self, queries): features, weights, lengths = [], [], [] for query in queries: peaks = sorted(query.peaks, key=lambda p: (-p[1], p[0]))[:self.max_peaks] peaks.sort() p = torch.tensor(peaks, device=self.frequencies.device, dtype=torch.float32) mz = p[:, 0] / 1000. intensity = torch.sqrt(p[:, 1] / p[:, 1].max().clamp_min(1e-12)) delta = (query.precursor_mz - p[:, 0]) / 1000. angles = mz[:, None] * self.frequencies[None, :] * math.pi features.append(torch.cat((mz[:, None], intensity[:, None], delta[:, None], angles.sin(), angles.cos()), -1)) weights.append(intensity) lengths.append(len(p)) x = pad_sequence(features, batch_first=True) w = pad_sequence(weights, batch_first=True) mask = torch.arange(x.shape[1], device=x.device)[None, :] >= torch.tensor(lengths, device=x.device)[:, None] meta = self.meta(torch.tensor([metadata(q) for q in queries], device=x.device)) tokens = self.encoder(self.peak(x) + meta[:, None, :], src_key_padding_mask=mask) pooled = self.output((tokens * w[:, :, None]).sum(1) / w.sum(1).clamp_min(1e-12)[:, None]) return [tokens[i, :n] for i, n in enumerate(lengths)], pooled, meta
def forward(self, query): tokens, q, meta = self.forward_batch([query]) return tokens[0], q[0], meta[0]
class GatedGraphEncoder(nn.Module): """Edge-gated MPNN with source/target context and node feed-forward blocks.""" def __init__(self, cfg): super().__init__() d = cfg.dim self.atom = nn.Linear(ATOM_DIM, d) self.edge = nn.Linear(BOND_DIM, d) self.messages = nn.ModuleList(nn.Sequential(nn.Linear(3*d, 2*d), nn.GELU(), nn.Linear(2*d, d)) for _ in range(cfg.graph_layers)) self.gates = nn.ModuleList(nn.Linear(3*d, d) for _ in range(cfg.graph_layers)) self.norms = nn.ModuleList(nn.LayerNorm(d) for _ in range(cfg.graph_layers)) self.ffns = nn.ModuleList(nn.Sequential(nn.Linear(d, 4*d), nn.GELU(), nn.Linear(4*d, d)) for _ in range(cfg.graph_layers)) self.ffnorms = nn.ModuleList(nn.LayerNorm(d) for _ in range(cfg.graph_layers)) self.pool = nn.Linear(2*d, d)
def forward(self, mols, device): sizes = [len(m.atom_features) for m in mols] offsets = np.cumsum([0] + sizes) atoms = torch.as_tensor(np.concatenate([m.atom_features for m in mols]), device=device) edges = torch.as_tensor(np.concatenate([m.edge_index + o for m, o in zip(mols, offsets)], axis=1), device=device) bonds = torch.as_tensor(np.concatenate([m.bond_features for m in mols]), device=device) h, e = self.atom(atoms), self.edge(bonds) src, dst = edges degree = torch.bincount(dst, minlength=len(h)).clamp_min(1).to(h.dtype)[:, None] for msg, gate, norm, ffn, ffnorm in zip(self.messages, self.gates, self.norms, self.ffns, self.ffnorms): context = torch.cat((h[src], h[dst], e), -1) messages = msg(context) * torch.sigmoid(gate(context)) # LayerNorm may promote h to FP32 under autocast; scatter kernels # require matching dtypes, unlike autocast-aware matrix products. aggregate = torch.zeros_like(h).index_add(0, dst, messages.to(h.dtype)) / degree h = norm(h + aggregate) h = ffnorm(h + ffn(h)) graph_ids = torch.repeat_interleave(torch.arange(len(mols), device=device), torch.tensor(sizes, device=device)) sums = h.new_zeros((len(mols), h.shape[-1])).index_add(0, graph_ids, h) maxima = h.new_full((len(mols), h.shape[-1]), -torch.inf) maxima = maxima.scatter_reduce(0, graph_ids[:, None].expand_as(h), h, reduce='amax', include_self=True) mean = sums / torch.tensor(sizes, device=device, dtype=h.dtype)[:, None] return self.pool(torch.cat((mean, maxima), -1)), list(h.split(sizes)), sizes
class BatchedSpecPartition(SpecPartition): def __init__(self, cfg, graph_chunk=256, local_chunk=64, gated_graph=True): super().__init__(cfg) self.spectrum = BatchedSpectrumEncoder(cfg.model) if gated_graph: self.graph = GatedGraphEncoder(cfg.model) self.graph_chunk, self.local_chunk = graph_chunk, local_chunk
def encode_molecules(self, mols): us, atoms = [], [] for start in range(0, len(mols), self.graph_chunk): batch = mols[start:start+self.graph_chunk] h, a, _ = self.graph(batch, self.device) fp = torch.as_tensor(np.stack([m.whole for m in batch]), device=self.device) anchors = torch.as_tensor(np.stack([m.anchors for m in batch]), device=self.device) us.append(self.structure(torch.cat((h, self.fp(fp), self.anchor(anchors)), -1))) atoms.extend(a) u = torch.cat(us) if us else torch.empty((0, self.cfg.model.dim), device=self.device) return u, atoms, F.normalize(self.mol_projection(u).float(), dim=-1)
def local_scores(self, peaks, atoms): qp = F.normalize(self.local_q(peaks).float(), dim=-1) result = [] for start in range(0, len(atoms), self.local_chunk): block = atoms[start:start+self.local_chunk] padded = pad_sequence(block, batch_first=True) z = F.normalize(self.local_a(padded).float(), dim=-1) valid = torch.arange(padded.shape[1], device=self.device)[None, :] < torch.tensor([len(a) for a in block], device=self.device)[:, None] # Avoid zero-batch-stride broadcast GEMM. On SM120/CUDA 13.2 the # FP32 teacher route triggered a cuBLAS TF32 warp illegal address # under memcheck. A 2D GEMM computes the identical dot products # without materializing B copies of the spectrum or changing loss. scores = (qp @ z.reshape(-1, z.shape[-1]).T).reshape( qp.shape[0], z.shape[0], z.shape[1]).permute(1, 0, 2) result.append(scores.masked_fill(~valid[:, None, :], -torch.inf).max(-1).values.mean(-1)) return torch.cat(result)
def encode_batch(self, queries, extras=()): tokens, qs, metas = self.spectrum.forward_batch(queries) # SMILES as well as connectivity is part of the key: extras/other queries # must never change the representation of an existing candidate alias. key = lambda m: (m.identity, m.smiles) lookup_mols = {key(m):m for q in queries for m in q.candidates} lookup_mols.update({key(m):m for m in extras}) keys = sorted(lookup_mols) positions = {k:i for i,k in enumerate(keys)} u, all_atoms, zm = self.encode_molecules([lookup_mols[k] for k in keys]) zq = F.normalize(self.query_projection(qs).float(), dim=-1) encoded = [] for i, q in enumerate(queries): inds = [positions[key(m)] for m in q.candidates] idx = torch.tensor(inds, device=self.device, dtype=torch.long) ui, zi, ai = u[idx], zm[idx], [all_atoms[k] for k in inds] direct = self.log_scale.exp().clamp(max=100.) * (zi.float() @ zq[i].float()) if self.cfg.model.local_match and ai: direct = direct + self.local_weight * self.local_scores(tokens[i], ai) fs = self.score_formulas(qs[i], q).float() base = direct if self.cfg.model.formula_score and inds: fi = {f:j for j,f in enumerate(q.formula_candidates)} fidx = torch.tensor([fi[m.formula] for m in q.candidates], device=self.device) base = base + torch.sigmoid(self.formula_gate(qs[i])).float() * fs[fidx] whole = torch.as_tensor(np.stack([m.whole for m in q.candidates]), device=self.device) if inds else u.new_empty((0, FP_SIZE)) anchors = torch.as_tensor(np.stack([m.anchors for m in q.candidates]), device=self.device) if inds else u.new_empty((0, ANCHOR_DIM)) encoded.append(Encoded(q,tokens[i].float(),qs[i].float(),metas[i].float(),ui.float(),zq[i],zi, [a.float() for a in ai],whole,anchors,fs,base.float(),direct.float())) return encoded, zm[torch.tensor([positions[key(m)] for m in extras],device=self.device,dtype=torch.long)]
def encode(self, query): return self.encode_batch([query])[0][0]
def forward_batch(self, queries, forests, extras=()): if len(queries) != len(forests): raise ValueError('One forest is required per query') encs, zextra = self.encode_batch(queries, extras) outputs = [] # Keep reductions and the relatively small relation/controller branch FP32. with torch.autocast(device_type=self.device.type, enabled=False): for enc, forest in zip(encs, forests): if tuple(m.identity for m in enc.query.candidates) != forest.identities: raise ValueError('Forest/candidate mismatch') partition = self.select_partition(enc, forest) scores, residual = self.score_partition(enc, forest, partition) cost = self.expected_cost(enc, forest) if self.cfg.model.relation_mode=='learned' else enc.q.sum()*0. outputs.append(Output(scores,enc.direct,enc.formula_scores,partition,residual,cost,enc)) return outputs, zextra
def forward(self, query, forest, partition=None): if partition is None: return self.forward_batch([query],[forest])[0][0] enc = self.encode(query) with torch.autocast(device_type=self.device.type, enabled=False): scores, residual = self.score_partition(enc, forest, partition) return Output(scores,enc.direct,enc.formula_scores,partition,residual,self.expected_cost(enc,forest),enc)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286"""Read-only source adapters and resumable, compressed multi-view training index.
Source row identity is retained: multiple MS for one structure are NOT deduplicated.Official pools are retained verbatim; training-only structural isolation is aseparately labelled projection, never an edit to the official source pools."""import argparseimport csvfrom datetime import datetime, timezonefrom functools import lru_cacheimport hashlibimport jsonimport mathfrom pathlib import Pathimport sqlite3import timeimport zlibfrom rdkit import Chem, RDLoggerfrom rdkit.Chem import Descriptors, rdMolDescriptorsfrom .chemistry import ADDUCTS, canonical_formula, exact_mass
def utc(): return datetime.now(timezone.utc).isoformat()
def sha(path): h = hashlib.sha256() with open(path, "rb") as fh: for part in iter(lambda: fh.read(4*1024*1024), b""): h.update(part) return h.hexdigest()
def packed(value): return zlib.compress(json.dumps(value, ensure_ascii=False, allow_nan=False, separators=(",", ":")).encode())
def unpacked(value): return json.loads(zlib.decompress(value))
def save(path, value): path = Path(path); path.parent.mkdir(parents=True, exist_ok=True) temp = path.with_suffix(path.suffix+".tmp") temp.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False)+"\n") temp.replace(path)
def emit(event, **kw): print(json.dumps({"utc": utc(), "event": event, **kw}, ensure_ascii=False), flush=True)
@lru_cache(maxsize=200000)def structure(smiles): mol = Chem.MolFromSmiles(smiles) if mol is None: raise ValueError("invalid_smiles") key = Chem.MolToInchiKey(mol) if not key: raise ValueError("missing_derived_key") return {"identity": key[:14], "inchikey": key, "formula": rdMolDescriptors.CalcMolFormula(mol), "mass": Descriptors.ExactMolWt(mol), "charge": Chem.GetFormalCharge(mol), "isotope": any(a.GetIsotope() for a in mol.GetAtoms()), "fragments": len(Chem.GetMolFrags(mol))}
def connect(path): db = sqlite3.connect(path, timeout=90) db.execute("PRAGMA journal_mode=WAL") db.execute("PRAGMA busy_timeout=90000") return db
def initialize(path): db = connect(path) db.executescript(''' CREATE TABLE IF NOT EXISTS sources(name TEXT PRIMARY KEY,path TEXT,sha256 TEXT,rows INTEGER DEFAULT 0,done INTEGER DEFAULT 0); CREATE TABLE IF NOT EXISTS heldout(identity TEXT, dataset TEXT, PRIMARY KEY(identity,dataset)); CREATE TABLE IF NOT EXISTS spectra(id INTEGER PRIMARY KEY,source TEXT,source_row INTEGER,sample_id TEXT, identity TEXT,formula TEXT,status TEXT,reason TEXT,body BLOB,UNIQUE(source,source_row)); CREATE INDEX IF NOT EXISTS spectra_source_status ON spectra(source,status,id); CREATE INDEX IF NOT EXISTS spectra_identity ON spectra(identity); CREATE TABLE IF NOT EXISTS structures(identity TEXT PRIMARY KEY,smiles TEXT,formula TEXT,mass REAL); CREATE TABLE IF NOT EXISTS formulas(formula TEXT PRIMARY KEY,mass REAL); CREATE TABLE IF NOT EXISTS official_pools(view TEXT,target TEXT,body BLOB,sha256 TEXT,count INTEGER,PRIMARY KEY(view,target)); CREATE TABLE IF NOT EXISTS jobs(formula TEXT PRIMARY KEY,status TEXT DEFAULT 'pending',attempts INTEGER DEFAULT 0,error TEXT,updated TEXT); CREATE TABLE IF NOT EXISTS demand(formula TEXT PRIMARY KEY,priority INTEGER); CREATE TABLE IF NOT EXISTS formula_pools(formula TEXT PRIMARY KEY,body BLOB,raw_count INTEGER,sha256 TEXT,updated TEXT); CREATE TABLE IF NOT EXISTS meta(key TEXT PRIMARY KEY,value TEXT); ''') db.commit() return db
def meta(db, key, value=None): if value is None: row = db.execute("SELECT value FROM meta WHERE key=?", (key,)).fetchone() return json.loads(row[0]) if row else None db.execute("INSERT OR REPLACE INTO meta VALUES (?,?)", (key, json.dumps(value))); db.commit()
def raw_rows(path): if str(path).endswith(".tsv"): with open(path) as fh: yield from csv.DictReader(fh, delimiter="\t") else: import ijson with open(path, "rb") as fh: yield from ijson.items(fh, "item", use_float=True)
def numeric(value): try: value = float(value) return value if math.isfinite(value) else None except (ValueError, TypeError): return None
def normalized_record(raw, source, row, banned): """Conservative metadata adapter. No mass is calculated from truth for input.""" smiles = raw.get("smiles", raw.get("SMILES")) info = structure(smiles) body = {"source": source, "source_row": row, "reference_smiles": smiles, "identity": info["identity"], "formula": info["formula"], "mass": info["mass"], "target_smiles": smiles, "raw_id": raw.get("identifier", raw.get("record_id", raw.get("id"))), "raw_provenance": raw.get("provenance"), "formula_label_only": True} if info["identity"] in banned: raise ValueError("heldout_connectivity") if info["charge"] or info["isotope"] or info["fragments"] != 1: raise ValueError("unsupported_charged_isotopic_or_multifragment_structure") canonical_formula(info["formula"]) if source == "odata": if str(raw.get("ms_level", "")).upper() not in {"MS2", "2"}: raise ValueError("not_documented_ms2") if raw.get("polarity") == "conflict": raise ValueError("polarity_conflict") if str(raw.get("ion_source", "")).upper() == "EI": raise ValueError("ei_spectrum") peaks = raw.get("ms") mz = numeric(raw.get("precursor_mz")) origin = raw.get("precursor_mz_source_field") if not origin or str(origin).lower() in {"parent_mass", "parent_mz", "exact_mass"}: raise ValueError("unverified_experimental_precursor") body["ms_level_evidence"] = raw.get("ms_level_evidence") instrument = raw.get("instrument") declared = raw.get("charge") else: xs, ys = raw["mzs"].split(","), raw["intensities"].split(",") if len(xs) != len(ys): raise ValueError("peak_length_mismatch") peaks = list(zip(xs, ys)); mz = numeric(raw.get("precursor_mz")) origin = "precursor_mz"; instrument = raw.get("instrument_type"); declared = None adduct = str(raw.get("adduct", "")).strip() # Only unambiguous chemical aliases; ambiguous '[M+FA]-' remains quarantined. adduct = {"[M+HCOOH-H]-": "[M+FA-H]-", "[M+formate]-": "[M+FA-H]-"}.get(adduct, adduct) if adduct not in ADDUCTS: raise ValueError("unsupported_or_ambiguous_adduct") if declared is not None and numeric(declared) != ADDUCTS[adduct][1]: raise ValueError("charge_adduct_conflict") if mz is None or mz <= 0: raise ValueError("invalid_experimental_precursor") peaks = [[float(x),float(y)] for x,y in peaks] if not peaks or any(not math.isfinite(x+y) or x <= 0 or y < 0 for x,y in peaks) or max(y for x,y in peaks) <= 0: raise ValueError("invalid_spectrum") # CE units vary across libraries. Preserve raw CE, mask the numerical feature # until a validated instrument-specific eV/NCE adapter is available. body["collision_energy_raw"] = raw.get("collision_energy") body["precursor_source_field"] = origin body["features"] = {"peaks": peaks, "precursor_mz": mz, "adduct": adduct, "collision_energy": None, "instrument": instrument, "candidates": [], "formula_candidates": [], "dataset_mode": "odata_training" if source == "odata" else "massspecgym_official", "candidate_view": "warmup", "formula_universe_source": "candidate_pool"} return body
def evaluation_record(raw, source, row): """Evaluation only: all original pool entries stay under their official IDs.
CASMI's neutral parent_mz is never accepted. Charge/adduct conflicts receive a terminal unsupported status in the caller, never a forged single charge. """ if source != "casmi2022": b=normalized_record(raw,source,row,set()) b["split"]="validation" if source=="msg_validation" else "test" return b adduct=str(raw["Adduct"]).strip() if adduct not in ADDUCTS:raise ValueError("unsupported_adduct") charge=str(raw["CHARGE"]).strip() signed=int(charge[:-1])*(1 if charge[-1]=="+" else -1) if charge[-1:] in {"+","-"} else int(charge) if signed != ADDUCTS[adduct][1]:raise ValueError("charge_adduct_conflict") proxy={"smiles":raw["SMILES"],"ms":raw["ms"],"ms_level":str(raw["MSLEVEL"]), "precursor_mz":raw["PEPMASS"],"precursor_mz_source_field":"PEPMASS","adduct":adduct, "charge":signed,"record_id":str(raw["CASMI_ID"])} b=normalized_record(proxy,"odata",row,set()) b.update(source="casmi2022",split="test",casmi_id=raw["CASMI_ID"]) b["features"]["dataset_mode"]="casmi_autonomous" return b
def register_source(db, name, path): row = db.execute("SELECT sha256,rows,done,path FROM sources WHERE name=?", (name,)).fetchone() digest = sha(path) if row and (row[0] != digest or row[3] != str(path)): raise ValueError("Source changed: "+name) if not row: db.execute("INSERT INTO sources(name,path,sha256) VALUES (?,?,?)", (name,str(path),digest)); db.commit() return row[1:3] if row else (0,0)
def index_all(config): RDLogger.DisableLog("rdApp.*") root = Path(config["work_dir"]); root.mkdir(parents=True, exist_ok=True) db = initialize(root/"data.sqlite") # Fingerprints of all registered evaluation structures are recomputed, not # inferred from source-declared keys. These references never enter model input. if not meta(db,"registry_complete"): for name,path in config["heldout"].items(): register_source(db,"registry_"+name,path) count = 0 for raw in raw_rows(path): s = raw.get("smiles",raw.get("SMILES")) key = structure(s)["identity"] db.execute("INSERT OR IGNORE INTO heldout VALUES (?,?)",(key,name)); count += 1 db.execute("UPDATE sources SET rows=?,done=1 WHERE name=?",(count,"registry_"+name)) db.commit(); emit("registry",dataset=name,rows=count) meta(db,"registry_complete",True) # Metadata migration for indexes made by the initial v0.2 adapter: registry # keys were complete but source progress rows were not persisted. for name,path in config["heldout"].items(): row=db.execute("SELECT done FROM sources WHERE name=?",("registry_"+name,)).fetchone() if row and not row[0]: register_source(db,"registry_"+name,path) count=sum(1 for _ in raw_rows(path)) db.execute("UPDATE sources SET rows=?,done=1 WHERE name=?",(count,"registry_"+name));db.commit() banned = {r[0] for r in db.execute("SELECT identity FROM heldout")} # Official lists indexed without normalization, filtering, truncation or reordering. import ijson for view,path in config["official_pools"].items(): done_rows, done = register_source(db,view,path) if done: continue with open(path,"rb") as fh: for i,(target,pool) in enumerate(ijson.kvitems(fh,"",use_float=True),1): if i <= done_rows: continue buf = json.dumps(pool,separators=(",",":")).encode() db.execute("INSERT OR REPLACE INTO official_pools VALUES (?,?,?,?,?)", (view,target,packed(pool),hashlib.sha256(buf).hexdigest(),len(pool))) if i % 2000 == 0: db.execute("UPDATE sources SET rows=? WHERE name=?",(i,view)); db.commit() emit("official_pool_index",view=view,pools=i) db.execute("UPDATE sources SET rows=?,done=1 WHERE name=?",(i,view)); db.commit() # MSG first: enables exact fixed-pool checks while the larger o_data scan runs. for source in ("msg_train","odata"): path=config["training"][source] done_rows,done=register_source(db,source,path) if done: continue for i,raw in enumerate(raw_rows(path),1): if i <= done_rows: continue body=None; identity=None; formula=None; status="eligible"; reason=None try: body=normalized_record(raw,source,i,banned) identity,formula=body["identity"],body["formula"] db.execute("INSERT OR IGNORE INTO structures VALUES (?,?,?,?)",(identity,body["reference_smiles"],formula,body["mass"])) db.execute("INSERT OR IGNORE INTO formulas VALUES (?,?)",(formula,exact_mass(formula))) if source == "odata": db.execute("INSERT OR IGNORE INTO jobs(formula) VALUES (?)",(formula,)) except (ValueError,TypeError,KeyError,OverflowError) as exc: status="quarantined"; reason=str(exc)[:250] body={"source":source,"source_row":i,"raw_id":raw.get("identifier",raw.get("record_id")), "reason":reason,"source_kept_unchanged":True} sample=f"{source}:{i}" db.execute("INSERT OR REPLACE INTO spectra(source,source_row,sample_id,identity,formula,status,reason,body) VALUES (?,?,?,?,?,?,?,?)", (source,i,sample,identity,formula,status,reason,packed(body))) if i % 2000 == 0: db.execute("UPDATE sources SET rows=? WHERE name=?",(i,source)); db.commit() emit("spectra_index",source=source,rows=i) db.execute("UPDATE sources SET rows=?,done=1 WHERE name=?",(i,source)); db.commit() emit("source_complete",source=source,rows=i) catalog=[r[0] for r in db.execute("SELECT formula FROM formulas ORDER BY formula")] meta(db,"formula_catalog_sha256",hashlib.sha256("\n".join(catalog).encode()).hexdigest()) meta(db,"index_complete",True) summary={"utc":utc(),"source_counts":list(db.execute("SELECT source,status,COUNT(*) FROM spectra GROUP BY source,status")), "quarantine_reasons":list(db.execute("SELECT source,reason,COUNT(*) FROM spectra WHERE status='quarantined' GROUP BY source,reason")), "structures":db.execute("SELECT COUNT(*) FROM structures").fetchone()[0],"formulas":len(catalog), "heldout_structures":len(banned),"original_records_deduplicated":False, "formula_universe":"mass_filtered_training_catalog; closed vocabulary, not exhaustive elemental enumeration", "source_sha256":list(db.execute("SELECT name,path,sha256,rows,done FROM sources"))} save(root/"index_summary.json",summary); emit("index_complete",**summary) db.close()
def main(): p=argparse.ArgumentParser();p.add_argument("--config",required=True) args=p.parse_args();index_all(json.loads(Path(args.config).read_text()))
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166"""Six independent candidate views with shared formula-level PubChem snapshots."""import argparseimport fcntlfrom dataclasses import replaceimport hashlibimport jsonfrom pathlib import Pathimport shutilimport timefrom datetime import datetime, timezone, timedeltaimport numpy as npimport torchfrom .chemistry import ADDUCTS, exact_mass, molecule, neutral_mass_from_mzfrom .multiview_data import connect, emit, meta, packed, unpacked, save, utcfrom .retrieval import PubChemCache, filter_candidatesfrom .schema import parse_record
class FormulaCatalog: """Truth-independent at query time, but intentionally closed-vocabulary.
Training catalogue coverage and top-K recall must be reported separately; do not call this exhaustive elemental enumeration or an open-vocabulary head. """ def __init__(self, db): rows=list(db.execute("SELECT formula,mass FROM formulas ORDER BY mass,formula")) self.formulas=[r[0] for r in rows]; self.mass=np.array([r[1] for r in rows]) self.sha256=hashlib.sha256("\n".join(sorted(self.formulas)).encode()).hexdigest()
def select(self, mz, adduct, ppm=10.): center=neutral_mass_from_mz(mz,adduct) delta=mz*abs(ADDUCTS[adduct][1])*ppm/1e6 a,b=np.searchsorted(self.mass,[center-delta,center+delta],side="left") b=np.searchsorted(self.mass,center+delta,side="right") return sorted(self.formulas[a:b])
def empty_example(body, view="warmup"): f={**body["features"],"candidate_view":view,"candidates":[],"formula_candidates":[]} return parse_record({"sample_id":f'{body["source"]}:{body["source_row"]}',"split":"train", "features":f,"labels":{"reference_smiles":body["reference_smiles"]}})
@torch.no_grad()def predicted_formulas(model, body, catalog, ppm=10.): example=empty_example(body) fs=catalog.select(example.query.precursor_mz,example.query.adduct,ppm) q=replace(example.query,formula_candidates=tuple(fs),formula_universe_source="training_catalog_mass_filtered") _,vector,_=model.spectrum(q) scores=model.score_formulas(vector,q).cpu().tolist() if not all(np.isfinite(scores)): raise RuntimeError("Nonfinite formula scores") order=sorted(range(len(fs)),key=lambda i:(-scores[i],fs[i])) return [fs[i] for i in order[:10]], [{"formula":fs[i],"score":scores[i],"rank":j+1} for j,i in enumerate(order)]
def candidate_view(db, body, view, catalog=None, frozen_model=None, checkpoint_sha256=None): """Return intact raw pool entries and provenance, or a durable pending status.
The reference is read for ORACLE branches only. Predicted branches receive the MS query and frozen model; no reference injection, forced positive, or CSI/SIRIUS input is permitted. """ if view in {"msg_mass","msg_formula"}: row=db.execute("SELECT body,sha256,count FROM official_pools WHERE view=? AND target=?",(view,body["target_smiles"])).fetchone() if row is None: raise ValueError("missing_official_target_pool") return [{"smiles":s,"source_id":None} for s in unpacked(row[0])], { "status":"ready","view":view,"raw_count":row[2],"filtered_count":row[2], "pool_sha256":row[1],"ppm_filter_applied":False,"official_pool_unchanged":True} if view not in {"odata_oracle","odata_predicted_top10","casmi_oracle","casmi_predicted_top10"}: raise ValueError("Unsupported view") oracle=view.endswith("oracle") if oracle: selected=[body["formula"]]; predictions=[] else: if frozen_model is None or catalog is None or not checkpoint_sha256: raise ValueError("Predicted view requires a frozen checkpoint hash and independent formula universe") selected,predictions=predicted_formulas(frozen_model,body,catalog) pending=[]; branches=[]; candidates=[] for formula in selected: row=db.execute("SELECT body,sha256,raw_count,updated FROM formula_pools WHERE formula=?",(formula,)).fetchone() if row is None: db.execute("INSERT OR IGNORE INTO jobs(formula) VALUES (?)",(formula,)) db.execute("INSERT OR REPLACE INTO demand VALUES (?,10)",(formula,));pending.append(formula);continue artifact=unpacked(row[0]); raw=artifact["records"] kept,rejected=filter_candidates(raw,body["features"]["precursor_mz"],body["features"]["adduct"],formula) candidates.extend({"smiles":r["smiles"],"source_id":str(r["cid"])} for r in kept) counts={} for r in rejected: counts[r["reason"]]=counts.get(r["reason"],0)+1 branches.append({"formula":formula,"raw_count":len(raw),"filtered_count":len(kept), "connectivity_count":len({r["identity"] for r in kept}),"rejections":counts, "snapshot_sha256":row[1],"snapshot_utc":row[3],"kept_cids":[r["cid"] for r in kept]}) db.commit() info={"status":"pending" if pending else "ready" if candidates else "ready_empty", "view":view,"oracle":oracle,"pending_formulas":pending,"selected_formulas":selected, "formula_predictions":predictions,"formula_prediction_checkpoint_sha256":checkpoint_sha256 if not oracle else None, "formula_catalog_sha256":catalog.sha256 if catalog and not oracle else None, "formula_universe_source":"reference_oracle" if oracle else "training_catalog_mass_filtered", "raw_count":sum(b["raw_count"] for b in branches),"filtered_count":len(candidates),"branches":branches, "ppm_filter_applied":True,"ppm":10.,"truth_injected":False,"sirius_used":False} # Never expose a partial union as the complete predicted Top10 view. return (None if pending else candidates),info
def training_projection(entries, banned): """Distinct from raw/official pool: strict holdout & supported-chemistry view.""" retained={}; reasons={}; invalid=[] for entry in entries: try: m=molecule(entry["smiles"]) if m.identity in banned: reason="heldout_connectivity" elif m.charge: reason="unsupported_charged_structure" else: old=retained.get(m.identity) if old is None or entry["smiles"] < old["smiles"]: retained[m.identity]=entry continue except (ValueError,TypeError,OverflowError) as exc: reason="unsupported_structure"; invalid.append({"source_id":entry.get("source_id"),"reason":str(exc)[:100]}) reasons[reason]=reasons.get(reason,0)+1 result=[retained[k] for k in sorted(retained)] return result,{"raw_count":len(entries),"supported_isolated_connectivity_count":len(result), "removed":reasons,"invalid_examples":invalid[:10],"identity_hash":hashlib.sha256("\n".join(sorted(retained)).encode()).hexdigest(), "is_training_only_projection":True,"raw_pool_modified":False}
def pubchem_worker(config): root=Path(config["work_dir"]); root.mkdir(parents=True,exist_ok=True) from .multiview_data import initialize db=initialize(root/"data.sqlite") lock=(root/"pubchem_worker.lock").open("a+") fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB) cache_dir=root/"pubchem";cache_dir.mkdir(exist_ok=True) cache=PubChemCache(cache_dir/"requests.sqlite",online=config["pubchem_online"]) emit("pubchem_worker_started",online=cache.online,requests_per_second_max=2.9412) while True: if shutil.disk_usage(root).free < config["pubchem_min_free_gb"]*1024**3: save(root/"pubchem_status.json",{"status":"paused_low_disk","utc":utc()});time.sleep(30);continue job=db.execute("SELECT j.formula,j.attempts FROM jobs j LEFT JOIN demand d ON j.formula=d.formula WHERE j.status IN ('pending','retry') AND j.attempts < ? AND (j.updated IS NULL OR j.updated < ?) ORDER BY COALESCE(d.priority,0) DESC,j.attempts,LENGTH(j.formula),j.formula LIMIT 1", (config["pubchem_max_attempts"], (datetime.now(timezone.utc)-timedelta(minutes=5)).isoformat())).fetchone() if not job: counts=list(db.execute("SELECT status,COUNT(*) FROM jobs GROUP BY status")) save(root/"pubchem_status.json",{"status":"waiting_for_jobs","counts":counts,"utc":utc()}) time.sleep(10);continue formula,attempts=job emit("formula_retrieval_started",formula=formula,attempt=attempts+1) try: records,provenance=cache.formula_candidates(formula) artifact={"records":records,"provenance":provenance} buf=packed(artifact); digest=hashlib.sha256(buf).hexdigest() db.execute("INSERT OR REPLACE INTO formula_pools VALUES (?,?,?,?,?)",(formula,buf,len(records),digest,utc())) db.execute("UPDATE jobs SET status='completed',attempts=?,updated=?,error=NULL WHERE formula=?",(attempts+1,utc(),formula)); db.commit() emit("formula_retrieval_completed",formula=formula,candidates=len(records),snapshot_sha256=digest) except Exception as exc: status="failed" if attempts+1>=config["pubchem_max_attempts"] else "retry" db.execute("UPDATE jobs SET status=?,attempts=?,error=?,updated=? WHERE formula=?",(status,attempts+1,type(exc).__name__+": "+str(exc)[:250],utc(),formula));db.commit() emit("formula_retrieval_error",formula=formula,status=status,error=type(exc).__name__) save(root/"pubchem_status.json",{"status":"running","utc":utc(),"counts":list(db.execute("SELECT status,COUNT(*) FROM jobs GROUP BY status"))})
def main(): p=argparse.ArgumentParser();p.add_argument("--config",required=True) a=p.parse_args();pubchem_worker(json.loads(Path(a.config).read_text()))
if __name__=="__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265"""Step-resumable real-data curriculum; no eager 2M-example/forest/negative bank.
The first run is a bounded training curriculum, NOT a complete epoch over themulti-million-row corpus and NOT a finished benchmark or convergence claim."""import argparsefrom collections import Counter, defaultdictfrom copy import deepcopyfrom dataclasses import replaceimport fcntlimport hashlibimport jsonimport osfrom pathlib import Pathimport randomimport shutilimport timeimport torchfrom rdkit import RDLoggerfrom .chemistry import molecule, tanimotofrom .config import Configfrom .engine import seed_everything, load_modelfrom .forest import build_forestfrom .losses import positive_index, listwise_loss, contrastive_loss, counterfactual_targets, cut_lossfrom .model import SpecPartitionfrom .multiview_data import connect, meta, packed, unpacked, save, sha, emit, utcfrom .multiview_pools import FormulaCatalog, candidate_view, training_projection, empty_examplefrom .schema import parse_record
class TrainingStream: def __init__(self, db, seed): self.db=db; self.rng=random.Random(seed) self.banned={r[0] for r in db.execute("SELECT identity FROM heldout")} self.by_source={s:[r[0] for r in db.execute("SELECT DISTINCT identity FROM spectra WHERE source=? AND status='eligible'",(s,))] for s in ("odata","msg_train")} if any(not v for v in self.by_source.values()): raise ValueError("Both training sources need eligible records") self.structs={r[0]:(r[1],r[2],r[3]) for r in db.execute("SELECT identity,smiles,formula,mass FROM structures")} if self.banned & set(self.structs): raise ValueError("Heldout label in training structure bank") self.keys=sorted(self.structs) self.by_formula=defaultdict(list) for k,(_,f,_) in self.structs.items(): self.by_formula[f].append(k)
def sample(self, step): # Equal source exposure; uniform structures then a uniform source spectrum. # This changes sampling weights, never deletes repeat spectra from the index. source="odata" if step % 2 == 0 else "msg_train" identity=self.rng.choice(self.by_source[source]) rows=list(self.db.execute("SELECT id FROM spectra WHERE source=? AND identity=? AND status='eligible'",(source,identity))) sid=self.rng.choice(rows)[0] body=unpacked(self.db.execute("SELECT body FROM spectra WHERE id=?",(sid,)).fetchone()[0]) return sid,body
def global_proposals(self, body, n): identity,formula=body["identity"],body["formula"] same=[k for k in self.by_formula[formula] if k != identity] chosen=set(self.rng.sample(same,min(n//2,len(same)))) while len(chosen)<min(n,len(self.keys)-1): k=self.rng.choice(self.keys) if k != identity: chosen.add(k) return [molecule(self.structs[k][0]) for k in sorted(chosen)]
def curriculum(config, step): limits=config["stages"] a=limits["warmup_steps"];b=a+limits["direct_steps"];c=b+limits["fixed_relation_steps"] if step<a: return "warmup","none" if step<b: return "direct","none" if step<c: return "fixed_relation","fixed" return "joint","learned"
def propose_training_pool(entries, identity, cap, rng): # A labelled training proposal may force inclusion of a positive ALREADY in # the formal pool. It never adds a missing truth and is never used in evaluation. if len(entries)<=cap: return entries,False positive=[e for e in entries if molecule(e["smiles"]).identity==identity] rest=[e for e in entries if molecule(e["smiles"]).identity!=identity] selected=positive+rng.sample(rest,cap-len(positive)) return sorted(selected,key=lambda e:molecule(e["smiles"]).identity),True
def save_checkpoint(path, model, optimizer, teacher, stream, step, config, catalog, identity_counts, views): temp=Path(path).with_suffix(".tmp") # Compatible with engine.load_model; both RNGs and optimizer resume at a step boundary. torch.save({"schema_version":2,"step_completed":step,"config":model.cfg.to_dict(), "pipeline_config":config,"model":model.state_dict(),"optimizer":optimizer.state_dict(), "teacher":teacher.state_dict(),"sampling_rng":stream.rng.getstate(),"torch_rng":torch.get_rng_state(), "cuda_rng":torch.cuda.get_rng_state_all() if model.device.type=="cuda" else [], "catalog_sha256":catalog.sha256,"source_signature":meta(stream.db,"source_signature"), "identity_seen":dict(identity_counts),"view_counts":dict(views)},temp) temp.replace(path)
def dynamic_negatives(model, teacher, enc, proposals, pool_mols, identity, budget, rng, forest=None, partition=None): proposal_map={m.identity:m for m in proposals+list(pool_mols) if m.identity!=identity} # Bound teacher work even when the formal PubChem pool is huge. mols=list(proposal_map.values()) if len(mols)>192: mols=rng.sample(mols,192) if not mols: return [],{"negatives":0} with torch.no_grad(): _,_,z=teacher.encode_molecules(mols) hard=(z@enc).detach().cpu().tolist() # Training truth may guide mining. Every branch/root competes; no sibling-only restriction. same_cluster=set();other_cluster=set() if forest and identity in forest.identities: p=forest.identities.index(identity) for key in (partition if partition is not None else forest.roots): ids={forest.identities[i] for i in forest.nodes[key].members} (same_cluster if p in forest.nodes[key].members else other_cluster).update(ids) boosted=[s+(0.25 if m.identity in same_cluster else .10 if m.identity in other_cluster else 0.) for m,s in zip(mols,hard)] order=sorted(range(len(mols)),key=lambda i:(-boosted[i],mols[i].identity)) explore=min(budget//4,len(mols));selected=rng.sample(list(range(len(mols))),explore) selected+= [i for i in order if i not in selected][:max(0,budget-len(selected))] audit={"negatives":len(selected),"proposals":len(mols),"uniform_exploration":explore, "in_truth_microcluster":sum(mols[i].identity in same_cluster for i in selected), "other_roots":sum(mols[i].identity in other_cluster for i in selected), "positive_excluded":all(mols[i].identity!=identity for i in selected), "partition_source":"frozen_teacher_cut" if partition is not None else "feasible_chemical_roots", "objective":"biased hard-negative contrastive, not unbiased full-bank CE"} return [mols[i] for i in selected],audit
def train_pipeline(config, resume=False, max_steps=None): RDLogger.DisableLog("rdApp.*") os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG",":4096:8") root=Path(config["work_dir"]); run=Path(config["run_dir"]); run.mkdir(parents=True,exist_ok=True) lock=(run/"trainer.lock").open("a+") fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB) if (run/"last.pt").exists() and not resume: raise FileExistsError("Use --resume; refusing to overwrite a run") while not (root/"data.sqlite").exists(): save(run/"status.json",{"status":"waiting_for_data_index","utc":utc()});time.sleep(10) db=connect(root/"data.sqlite") db.execute("CREATE TABLE IF NOT EXISTS demand(formula TEXT PRIMARY KEY,priority INTEGER)");db.commit() while not meta(db,"index_complete"): save(run/"status.json",{"status":"waiting_for_complete_index","utc":utc()});time.sleep(10) source_signature=hashlib.sha256(json.dumps(list(db.execute("SELECT name,sha256 FROM sources ORDER BY name"))).encode()).hexdigest() meta(db,"source_signature",source_signature) catalog=FormulaCatalog(db); stream=TrainingStream(db,config["seed"]) db.execute("CREATE TABLE IF NOT EXISTS consumed_views(spectrum_id INTEGER,view TEXT,checkpoint TEXT,body BLOB,PRIMARY KEY(spectrum_id,view,checkpoint))");db.commit() seed_everything(config["seed"],config["threads"]) cfg=Config();cfg.train.device=config["device"];cfg.train.threads=config["threads"] cfg.train.cost_weight=0.;cfg.train.cut_cost_tradeoff=0.;cfg.train.cut_epsilon=config["cut_epsilon"] model=SpecPartition(cfg).to(config["device"]) if model.device.type=="cuda": torch.cuda.set_per_process_memory_fraction(.60,model.device) optimizer=torch.optim.AdamW(model.parameters(),lr=cfg.train.learning_rate,weight_decay=cfg.train.weight_decay) teacher=deepcopy(model).eval() for p in teacher.parameters():p.requires_grad_(False) step0=0; seen=Counter();views=Counter() if resume: state=torch.load(run/"last.pt",map_location="cpu",weights_only=True) if state["pipeline_config"]!=config or state["catalog_sha256"]!=catalog.sha256 or state["source_signature"]!=source_signature: raise ValueError("Checkpoint/config/source/catalog mismatch") model.load_state_dict(state["model"]);optimizer.load_state_dict(state["optimizer"]);teacher.load_state_dict(state["teacher"]) stream.rng.setstate(state["sampling_rng"]);torch.set_rng_state(state["torch_rng"]) if state["cuda_rng"] and model.device.type=="cuda":torch.cuda.set_rng_state_all(state["cuda_rng"]) step0=state["step_completed"]+1; seen.update(state["identity_seen"]);views.update(state["view_counts"]) frozen=None; frozen_hash=None if (run/"formula_selector_frozen.pt").exists(): frozen,_=load_model(run/"formula_selector_frozen.pt",config["device"]);frozen_hash=sha(run/"formula_selector_frozen.pt") save(run/"protocol.json",{"config":config,"source_signature":source_signature,"catalog_sha256":catalog.sha256, "formula_space_size":len(catalog.formulas),"real_data":True,"sirius_features":False, "training_sampling":"equal sources, uniform connectivity, uniform spectrum within connectivity/source", "formula_metrics_warning":"closed training vocabulary; enumerate coverage is not open-world coverage", "official_pool_projection":"strict training-only isolation; official raw pool kept unchanged", "loss_schedule":"LF+LC; then direct LR; then fixed relation LR; then joint LR+Lcut. Cost disabled.", "release_source_hashes":{str(p.relative_to(Path(__file__).parent)):sha(p) for p in Path(__file__).parent.glob('*.py')}, "run_scope":"initial training curriculum, not full corpus sweep or final scientific result"}) emit("training_started",step=step0,device=str(model.device),formula_space=len(catalog.formulas),sources={s:len(v) for s,v in stream.by_source.items()}) total=sum(config["stages"].values());end=min(total,max_steps) if max_steps else total start=time.monotonic() try: for step in range(step0,end): if shutil.disk_usage(root).free < config["train_min_free_gb"]*1024**3: raise RuntimeError("Training low disk guard triggered") stage,relation=curriculum(config,step);model.cfg.model.relation_mode=relation if step % config["teacher_refresh_steps"]==0: teacher.load_state_dict(model.state_dict());teacher.cfg.model.relation_mode=relation if stage != "warmup" and frozen is None: save_checkpoint(run/"formula_selector_frozen.pt",model,optimizer,teacher,stream,step-1,config,catalog,seen,views) frozen,_=load_model(run/"formula_selector_frozen.pt",config["device"]);frozen_hash=sha(run/"formula_selector_frozen.pt") sid,body=stream.sample(step) if body["source"]=="msg_train":view="msg_mass" if (step//2)%2==0 else "msg_formula" else: use_pred=frozen is not None and stream.rng.random() < (.2 if stage=="direct" else .5) view="odata_predicted_top10" if use_pred else "odata_oracle" entries,view_info=candidate_view(db,body,view,catalog,frozen,frozen_hash) projection={}; sample_ce=False; actual_pool=[]; original_count=0 if entries is not None: actual_pool,projection=training_projection(entries,stream.banned);original_count=len(actual_pool) # Warmup uses LC/LF only and need not materialize large-pool activations. if stage=="warmup":actual_pool=[] else:actual_pool,sample_ce=propose_training_pool(actual_pool,body["identity"],config["training_candidate_cap"],stream.rng) record={"sample_id":str(sid),"split":"train","labels":{"reference_smiles":body["reference_smiles"]}, "features":{**body["features"],"candidate_view":view,"candidates":actual_pool}} example=parse_record(record) forest=build_forest(example.query.candidates,cfg.chemistry) model.train();optimizer.zero_grad(set_to_none=True) output=model(example.query,forest) # Independent formula universe, never the oracle/official candidate-formula set. fs=catalog.select(example.query.precursor_mz,example.query.adduct,config["formula_ppm"]) fq=replace(example.query,formula_candidates=tuple(fs)) fscore=model.score_formulas(output.encoded.q,fq) fp=positive_index(fs,body["formula"]) lf,mf=listwise_loss(fscore,fp if len(fs)>1 else None) with torch.no_grad(): teacher_partition=None if stage=="joint" and example.query.candidates: tenc=teacher.encode(example.query) tz=tenc.z_query;teacher_partition=teacher.select_partition(tenc,forest) else: _,tq,_=teacher.spectrum(example.query) tz=torch.nn.functional.normalize(teacher.query_projection(tq),dim=-1) proposals=stream.global_proposals(body,config["negative_proposal_budget"]) negs,negative_audit=dynamic_negatives(model,teacher,tz,proposals,example.query.candidates, body["identity"],config["negative_budget"],stream.rng,forest,teacher_partition) ref=molecule(body["reference_smiles"]) _,_,z=model.encode_molecules([ref]+negs) lc=contrastive_loss(output.encoded.z_query,z[0],z[1:],cfg.train.temperature) rp=positive_index(forest.identities,body["identity"]) lr,mr=listwise_loss(output.scores,rp) lcut=output.encoded.q.sum()*0.;ncut=0 if stage=="joint" and rp is not None: ts=counterfactual_targets(teacher,example.query,forest,body["identity"],max_nodes=4, epsilon=config["cut_epsilon"],cost_tradeoff=0.,offset=step*4) lcut,ncut=cut_loss(model,output.encoded,forest,ts) loss=.3*lf+lc+(lr if stage!="warmup" else 0)+.1*lcut if not torch.isfinite(loss):raise RuntimeError("Nonfinite training loss") loss.backward();grad=torch.nn.utils.clip_grad_norm_(model.parameters(),5.,error_if_nonfinite=True);optimizer.step() seen[body["identity"]]+=1;views[view]+=1 info={"utc":utc(),"step":step,"stage":stage,"spectrum_id":sid,"source":body["source"],"view":view, "loss":float(loss.detach()),"LF":float(lf.detach()),"LC":float(lc.detach()),"LR":float(lr.detach()),"Lcut":float(lcut.detach()), "formula_loss_valid":bool(mf),"formula_truth_covered":fp is not None,"independent_formula_count":len(fs), "ranking_loss_valid":bool(mr) and stage!="warmup","pool_status":view_info["status"], "formal_projected_pool_size":original_count,"training_proposal_size":len(actual_pool), "rank_objective":"sampled_pool_CE_not_full_LR" if sample_ce else "full_projected_pool_CE" if stage!="warmup" else "disabled_warmup", "negative_audit":negative_audit,"gradient_norm_before_clip":float(grad),"cut_targets":ncut, "cuda_peak_mb":torch.cuda.max_memory_allocated()/1024**2 if model.device.type=="cuda" else None} with (run/"progress.jsonl").open("a") as fh:fh.write(json.dumps(info,allow_nan=False)+"\n") db.execute("INSERT OR REPLACE INTO consumed_views VALUES (?,?,?,?)",(sid,view,frozen_hash if view.endswith('top10') else '',packed({"view":view_info,"projection":projection})));db.commit() if step % 10==0: emit("optimizer_step",**info) save(run/"status.json",{"status":"training","utc":utc(),"step_completed":step,"stage":stage,"last":info, "views":dict(views),"unique_training_structures_seen":len(seen),"seconds":time.monotonic()-start}) if (step+1)%config["checkpoint_interval"]==0 or step+1==end or step==0: save_checkpoint(run/"last.pt",model,optimizer,teacher,stream,step,config,catalog,seen,views) save(run/"status.json",{"status":"initial_curriculum_completed" if end==total else "bounded_training_check_completed", "utc":utc(),"step_completed":end-1,"views":dict(views),"unique_training_structures_seen":len(seen), "scientific_evaluation_completed":False}) except BaseException as exc: save(run/"status.json",{"status":"failed","utc":utc(),"error":type(exc).__name__+": "+str(exc)[:300], "last_safe_checkpoint":"last.pt","next_action":"inspect; no automatic destructive restart"}) raise finally: db.close();lock.close()
def main(): p=argparse.ArgumentParser();p.add_argument("--config",required=True);p.add_argument("--resume",action="store_true") p.add_argument("--max-steps",type=int);a=p.parse_args() train_pipeline(json.loads(Path(a.config).read_text()),a.resume,a.max_steps)
if __name__=="__main__":main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185"""Versioned training-only negative bank with fixed-probe EMA and exploration.
All probabilities describe this bounded proposal sampler. No claim of an unbiasedfull-bank softmax estimator or an approximate-nearest-neighbor implementation."""import hashlibimport numpy as npimport torchfrom .chemistry import identity_hash, molecule, ppm_error, tanimoto
class NegativeBank: def __init__(self, molecules, forbidden=()): banned = set(forbidden) unique = {m.identity:m for m in molecules if m.identity not in banned} self.molecules = tuple(unique[k] for k in sorted(unique)) self.identities = tuple(m.identity for m in self.molecules) self.identity_to_index = {k:i for i,k in enumerate(self.identities)} self.hash = identity_hash(self.molecules) self.embeddings = None self.version = 0 self.weight_signature = None
@classmethod def from_training(cls, examples, forbidden=()): if any(e.split != "train" or e.labels is None for e in examples): raise ValueError("Never construct a negative bank from validation/test examples") return cls([m for e in examples for m in (*e.query.candidates,molecule(e.labels.reference_smiles))],forbidden)
@torch.no_grad() def refresh(self, teacher): if teacher.training: raise ValueError("Refresh with frozen eval-mode teacher") chunks = [] for i in range(0,len(self.molecules),128): _,_,z = teacher.encode_molecules(self.molecules[i:i+128]) chunks.append(z.cpu()) self.embeddings = torch.cat(chunks).numpy() if chunks else np.empty((0,teacher.cfg.model.dim),np.float32) h = hashlib.sha256() for k,v in sorted(teacher.state_dict().items()): h.update(k.encode()); h.update(v.detach().cpu().numpy().tobytes()) self.weight_signature = h.hexdigest() self.version += 1
class DynamicSampler: def __init__(self, cfg): self.cfg = cfg self.rng = np.random.default_rng(cfg.seed) self.ema = np.zeros(4,dtype=float) self.probe_updates = 0
def state_dict(self): return {"rng":self.rng.bit_generator.state,"ema":self.ema.tolist(),"probe_updates":self.probe_updates}
def load_state_dict(self,state): self.rng.bit_generator.state = state["rng"] self.ema = np.asarray(state["ema"],float) self.probe_updates = state["probe_updates"]
def groups(self, query, reference, bank): groups = [[],[],[],[]] for i,m in enumerate(bank.molecules): if m.identity == reference.identity: continue if m.formula == reference.formula: g = 3 if tanimoto(m.whole,reference.whole) >= .65 else 2 else: g = 1 if abs(ppm_error(m.mass,query.precursor_mz,query.adduct)) <= 10 else 0 groups[g].append(i) return groups
def quotas(self, groups, epoch): progress = epoch/max(1,self.cfg.epochs-1) prior = np.array([.4,.3,.2,.1] if progress < .34 else ([.2,.25,.3,.25] if progress < .67 else [.15,.2,.3,.35])) if self.cfg.negative_strategy in {"feedback","partition"} and self.probe_updates: exp = np.exp((self.ema-self.ema.max())/.2) prior = .5*prior+.5*exp/exp.sum() prior *= np.array([bool(g) for g in groups]) return prior/prior.sum() if prior.sum() else prior
def update_probe(self, violations): # Caller supplies fixed TRAINING-probe measurements, never validation/test feedback. for g,values in violations.items(): if len(values): v = float(np.mean(values)) self.ema[g] = v if not self.probe_updates else .9*self.ema[g]+.1*v self.probe_updates += 1
def sample(self, query, reference, bank, query_embedding, epoch, forest=None, partition=None): if bank.embeddings is None: raise ValueError("Negative bank requires a versioned teacher refresh") groups = self.groups(query,reference,bank) probabilities = self.quotas(groups,epoch) strategy = self.cfg.negative_strategy all_indices = [i for g in groups for i in g] budget = min(self.cfg.negative_budget,len(all_indices)) if not budget: return [], {"selected":0,"groups":[0]*4,"version":bank.version,"subtypes":{}} # Bounded stratified proposal set, including random exploration in every available stratum. proposals = [] cap = max(1,self.cfg.proposal_budget//4) for g in groups: proposals.append(list(self.rng.choice(g,min(cap,len(g)),replace=False)) if g else []) # Redistribute unused proposal slots so a sparse/empty stratum cannot reduce the fixed negative budget. chosen = {i for group in proposals for i in group} slots = min(self.cfg.proposal_budget,len(all_indices))-len(chosen) remaining = [(g,i) for g,items in enumerate(groups) for i in items if i not in chosen] if slots > 0 and remaining: for index in self.rng.choice(len(remaining),min(slots,len(remaining)),replace=False): g,i = remaining[index] proposals[g].append(i) group_of = {i:g for g,items in enumerate(proposals) for i in items} available = [i for g in proposals for i in g] q = np.asarray(query_embedding,dtype=np.float32) hard = bank.embeddings[available]@q if available else np.array([]) hard_map = dict(zip(available,hard)) reference_pos = bank.identity_to_index.get(reference.identity) pos_score = float(bank.embeddings[reference_pos]@q) if reference_pos is not None else 0. inside, boundary = set(),set() if forest is not None and partition is not None and reference.identity in forest.identities: ip = forest.identities.index(reference.identity) own = next(k for k in partition if ip in forest.nodes[k].members) inside = {forest.identities[i] for i in forest.nodes[own].members}-{reference.identity} # Boundary = members of sibling subtrees along this node's ancestor path. current = own while True: parents = [n for n in forest.nodes.values() if current in n.children] if not parents: break parent = parents[0] for k in parent.children: if k != current: boundary.update(forest.identities[i] for i in forest.nodes[k].members) current = parent.key subtype = {i:("inside" if bank.identities[i] in inside else "boundary" if bank.identities[i] in boundary else "other") for i in available} weights = [] for i in available: g = group_of[i] if strategy == "random": w = 1. elif strategy == "static": w = probabilities[g]*(.2+.8*tanimoto(reference.whole,bank.molecules[i].whole))/len(proposals[g]) else: # Mixture with uniform exploration, clip hardness, fixed total negative budget. logits = np.array([np.clip((hard_map[j]-pos_score)/.1,-8,8) for j in proposals[g]]) exp = np.exp(logits-logits.max()) idx = proposals[g].index(i) local = .2/len(proposals[g])+.8*exp[idx]/exp.sum() w = probabilities[g]*local if strategy == "partition" and g == 3: w *= 2. if subtype[i] in {"inside","boundary"} else 1. weights.append(w) weights = np.asarray(weights,float) weights /= weights.sum() n = min(budget,len(available)) selected = list(self.rng.choice(available,n,replace=False,p=weights)) counts = [sum(group_of[i]==g for i in selected) for g in range(4)] return selected,{"selected":n,"requested":self.cfg.negative_budget,"groups":counts, "group_probabilities":probabilities.tolist(),"version":bank.version, "proposal_count":len(available),"subtypes":{s:sum(subtype[i]==s for i in selected) for s in ("inside","boundary","other")}, "positive_excluded":all(bank.identities[i] != reference.identity for i in selected)}
@torch.no_grad()def update_fixed_training_probe(sampler, teacher, examples, bank): # Stable sample-ID hash subset. Same members and negative probes across refreshes. probes = sorted(examples,key=lambda e:hashlib.sha256(e.sample_id.encode()).hexdigest())[:sampler.cfg.probe_size] violations = {i:[] for i in range(4)} for e in probes: if e.split != "train" or e.labels is None: raise ValueError("Only training examples may update sampling feedback") ref = molecule(e.labels.reference_smiles) _,q,_ = teacher.spectrum(e.query) z = torch.nn.functional.normalize(teacher.query_projection(q),dim=-1).cpu().numpy() p = bank.identity_to_index[ref.identity] positive = float(bank.embeddings[p]@z) groups = sampler.groups(e.query,ref,bank) for g,indices in enumerate(groups): # Identity order gives a stable, model-independent per-group probe, not hardest current items. for i in indices[:32]: violations[g].append(float(bank.embeddings[i]@z + sampler.cfg.probe_margin > positive)) sampler.update_probe(violations) return {"sample_ids":[e.sample_id for e in probes],"counts":{str(g):len(v) for g,v in violations.items()}, "ema":sampler.ema.tolist(),"bank_version":bank.version}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372"""Download -> verified snapshot -> fixed plan -> CPU preprocessing -> GPU.
Only owned, hash-verified pickle batches are read; never load third-party pickle.The corpus index preserves all source rows. The prepacked training curriculumis explicitly bounded, not a full corpus epoch. No live cache is read by GPU training."""import argparsefrom collections import Counterimport fcntlimport hashlibimport jsonfrom pathlib import Pathimport pickleimport shutilimport sqlite3import subprocessimport sysimport timeimport zlibfrom .multiview_data import save, sha, utc, unpacked, packed, meta
def readonly(path): db=sqlite3.connect(f'file:{Path(path).resolve()}?mode=ro',uri=True,timeout=60) db.execute('PRAGMA query_only=ON') return db
def digest(value): return hashlib.sha256(json.dumps(value,sort_keys=True,separators=(',',':'),allow_nan=False).encode()).hexdigest()
def binding(db): return {'sources':list(db.execute('SELECT name,path,sha256,rows,done FROM sources ORDER BY name')), 'formulas':list(db.execute('SELECT formula,mass FROM formulas ORDER BY formula'))}
def audit(path,mass_checks=False): db=readonly(path) queries={ 'source_rows': 'SELECT name,rows,done FROM sources ORDER BY name', 'spectra': 'SELECT source,status,COUNT(*),COUNT(DISTINCT identity),COUNT(DISTINCT formula) FROM spectra GROUP BY source,status', 'quarantine': "SELECT source,reason,COUNT(*) FROM spectra WHERE status='quarantined' GROUP BY source,reason ORDER BY COUNT(*) DESC", 'jobs': 'SELECT status,COUNT(*) FROM jobs GROUP BY status', 'required': 'SELECT COUNT(*) FROM formulas', 'ready': 'SELECT COUNT(*),SUM(p.raw_count) FROM formulas f JOIN formula_pools p USING(formula)', 'odata_ready_spectra': "SELECT COUNT(*) FROM spectra s WHERE source='odata' AND status='eligible' AND EXISTS(SELECT 1 FROM formula_pools p WHERE p.formula=s.formula)", 'holdout_overlap': "SELECT COUNT(*) FROM spectra s WHERE status='eligible' AND EXISTS(SELECT 1 FROM heldout h WHERE h.identity=s.identity)", } # Target keys live in compressed spectrum bodies; do not pretend to join # them with SMILES representatives from structures. Checked during prepacking. result={'utc':utc(),'database':str(Path(path).resolve()),'queries':queries} for key,query in queries.items():result[key]=list(db.execute(query)) result['source_binding_sha256']=digest(binding(db)) result['free_gib']=shutil.disk_usage(Path(path).parent).free/1024**3 if mass_checks: from .chemistry import ppm_error counts=Counter();examples=[] for sid,source,blob in db.execute("SELECT id,source,body FROM spectra WHERE status='eligible'"): b=unpacked(blob);q=b['features'];ppm=ppm_error(b['mass'],q['precursor_mz'],q['adduct']) counts[source+':all']+=1 if abs(ppm)>10: counts[source+':outside_10ppm']+=1 if len(examples)<5:examples.append({'spectrum_id':sid,'source':source,'ppm':ppm,'adduct':q['adduct']}) result['mass_quality']={'counts':dict(counts),'examples':examples,'method':'SMILES-derived reference mass compared with experimental precursor and adduct, no candidate lookup'} db.close();return result
def disk_guard(root, minimum): if shutil.disk_usage(root).free < minimum*1024**3: raise RuntimeError('Disk reserve reached; no deletion or partial-pool training allowed')
def initialize_manifest(c): root=Path(c['pipeline_dir']);root.mkdir(parents=True,exist_ok=True) db=readonly(Path(c['work_dir'])/'data.sqlite') if not meta(db,'index_complete') or not meta(db,'registry_complete'): raise RuntimeError('Complete source index and heldout registry required') b=binding(db) if not b['formulas'] or any(not r[4] for r in b['sources']):raise RuntimeError('Incomplete source registry') overlap=db.execute("SELECT COUNT(*) FROM spectra s WHERE status='eligible' AND EXISTS(SELECT 1 FROM heldout h WHERE h.identity=s.identity)").fetchone()[0] if overlap:raise RuntimeError('Eligible labels overlap heldout connectivity') # Closed training vocabulary contains every possible Top10 output of the # current selector. Retrieve its entire union: no test-derived formula list. value={'version':'offline-v04','source_binding':b,'source_binding_sha256':digest(b), 'required_formulas':[r[0] for r in b['formulas']], 'required_scope':'all closed training-catalog formulas; covers oracle and any selector Top10', 'formula_selector_sha256':sha(c['proposal_formula_checkpoint']), 'pipeline_config_sha256':digest(c),'created_utc':utc(), 'training_batches':sum(c['stages'].values()),'training_exposures':sum(c['stages'].values())*c['batch_size'], 'corpus_epoch':False,'raw_sources_modified':False,'truth_injection':False} path=root/'required_manifest.json' if path.exists(): old=json.loads(path.read_text()) for k in ('source_binding_sha256','formula_selector_sha256','pipeline_config_sha256'): if old[k]!=value[k]:raise RuntimeError('Immutable required manifest changed: '+k) value=old else:save(path,value) db.close();return value
def verify_pool(formula, row): blob,count,digest_expected=row if hashlib.sha256(blob).hexdigest()!=digest_expected:raise RuntimeError('PubChem snapshot hash mismatch: '+formula) a=unpacked(blob);records=a['records'];p=a['provenance'] if p.get('formula')!=formula or p.get('cid_count')!=count or len(records)!=count: raise RuntimeError('PubChem count/provenance mismatch: '+formula) if len({r['CID'] for r in records})!=count:raise RuntimeError('Duplicate PubChem records: '+formula) if not p.get('requests') or any(not all(r.get(k) for k in ('url','fetched_utc','response_sha256')) for r in p['requests']): raise RuntimeError('Missing PubChem request provenance: '+formula)
def screen_quality(db): """Apply the declared o_data 10ppm protocol, never refilter MSG pools.
Outside 10ppm is a protocol conflict, not proof the reference is incorrect. Only the derived snapshot's eligibility changes; every source row survives. """ from .chemistry import ppm_error db.execute('CREATE TABLE offline_quality(spectrum_id INTEGER PRIMARY KEY,source TEXT,truth_ppm REAL,decision TEXT)') counts=Counter();after=0 while True: rows=list(db.execute("SELECT id,source,body FROM spectra WHERE status='eligible' AND id>? ORDER BY id LIMIT 2000",(after,))) if not rows:break for sid,source,blob in rows: b=unpacked(blob);q=b['features'];ppm=ppm_error(b['mass'],q['precursor_mz'],q['adduct']) outside=abs(ppm)>10.;counts[source+':inspected']+=1;counts[source+':outside_10ppm']+=int(outside) decision='excluded_odata_10ppm_protocol' if outside and source=='odata' else 'retained_msg_official' if source=='msg_train' else 'retained_odata' db.execute('INSERT INTO offline_quality VALUES (?,?,?,?)',(sid,source,ppm,decision)) if decision=='excluded_odata_10ppm_protocol': db.execute("UPDATE spectra SET status='quarantined_offline',reason='truth_precursor_outside_declared_10ppm_protocol' WHERE id=?",(sid,)) counts[decision]+=1 after=rows[-1][0];db.commit() return {'utc':utc(),'counts':dict(counts),'raw_rows_deleted':0,'official_pool_modified':False, 'reason':'o_data strict candidate protocol; an outlier is not proof of wrong structural identity', 'remaining_eligible':list(db.execute("SELECT source,COUNT(*),COUNT(DISTINCT identity) FROM spectra WHERE status='eligible' GROUP BY source"))}
def download(c,m): runtime_path=Path(c['pipeline_dir'])/'download_runtime.json' if runtime_path.exists(): runtime=json.loads(runtime_path.read_text()) if runtime.get('formula_workers',1)>1: from .parallel_download import download_parallel return download_parallel(c,m,runtime) from .retrieval import PubChemCache root=Path(c['pipeline_dir']);live=Path(c['work_dir']) db=sqlite3.connect(live/'data.sqlite',timeout=90) guard=(live/'pubchem_worker.lock').open('a+') fcntl.flock(guard,fcntl.LOCK_EX|fcntl.LOCK_NB) if digest(binding(db))!=m['source_binding_sha256']:raise RuntimeError('Source or formula catalog changed') db.executemany('INSERT OR IGNORE INTO jobs(formula) VALUES (?)',[(f,) for f in m['required_formulas']]);db.commit() cache=PubChemCache(live/'pubchem/requests.sqlite',online=True,property_batch_size=c['property_batch_size']) completed=set();verified=[];required=set(m['required_formulas']);failed=[] for f,blob,count,h in db.execute('SELECT formula,body,raw_count,sha256 FROM formula_pools'): if f not in required:continue verify_pool(f,(blob,count,h));completed.add(f);verified.append((f,h,count)) priorities=dict(db.execute("SELECT formula,COUNT(*) FROM spectra WHERE source='odata' AND status='eligible' GROUP BY formula")) todo=sorted(set(m['required_formulas'])-completed,key=lambda f:(-priorities.get(f,0),f)) for f in todo: disk_guard(root,c['download_min_free_gib']) attempts=db.execute('SELECT attempts FROM jobs WHERE formula=?',(f,)).fetchone()[0] status={'utc':utc(),'phase':'downloading','formula':f,'ready':len(completed),'required':len(m['required_formulas']), 'remaining':len(m['required_formulas'])-len(completed),'training_started':False,'requests_per_second_cap':1/.34} save(root/'status.json',status);print(json.dumps(status),flush=True) while attempts<c['pubchem_max_attempts']: attempts+=1 try: records,prov=cache.formula_candidates(f) blob=packed({'records':records,'provenance':prov});h=hashlib.sha256(blob).hexdigest() verify_pool(f,(blob,len(records),h)) disk_guard(root,c['download_min_free_gib']) db.execute('INSERT OR REPLACE INTO formula_pools VALUES (?,?,?,?,?)',(f,blob,len(records),h,utc())) db.execute("UPDATE jobs SET status='completed',attempts=?,error=NULL,updated=? WHERE formula=?",(attempts,utc(),f));db.commit() completed.add(f);verified.append((f,h,len(records))) with (root/'download_events.jsonl').open('a') as out:out.write(json.dumps({'utc':utc(),'formula':f,'records':len(records),'sha256':h,'attempts':attempts})+'\n') break except Exception as exc: db.execute('UPDATE jobs SET status=?,attempts=?,error=?,updated=? WHERE formula=?',('failed' if attempts>=c['pubchem_max_attempts'] else 'retry',attempts,type(exc).__name__+': '+str(exc)[:250],utc(),f));db.commit() if attempts>=c['pubchem_max_attempts']:break time.sleep(min(30,5*attempts)) if f not in completed:failed.append(f) cache.close();db.close();guard.close() result={'utc':utc(),'required':len(m['required_formulas']),'verified':len(completed),'pools':sorted(verified),'failed':failed,'complete':len(completed)==len(m['required_formulas'])} save(root/'download_complete.json',result) if not result['complete']:raise RuntimeError(f'{len(failed)} formula jobs unresolved; see download_complete.json') return result
def freeze(c,m): root=Path(c['pipeline_dir']);dest=root/'snapshot';dest.mkdir(exist_ok=True) receipt=root/'snapshot.json' if receipt.exists(): r=json.loads(receipt.read_text()) if sha(dest/'data.sqlite')!=r['database_sha256'] or sha(dest/'formula_selector.pt')!=m['formula_selector_sha256']: raise RuntimeError('Frozen snapshot changed') return dest disk_guard(root,c['preprocess_min_free_gib']+Path(c['work_dir'],'data.sqlite').stat().st_size/1024**3) src=readonly(Path(c['work_dir'])/'data.sqlite') if digest(binding(src))!=m['source_binding_sha256']:raise RuntimeError('Source binding changed') # Re-hash actual raw sources once before freezing; recorded hashes alone do # not prove source files are unchanged. Streaming sha avoids loading JSON. for name,path,h,rows,done in m['source_binding']['sources']: if sha(path)!=h:raise RuntimeError('Raw input changed: '+name) tmp=dest/'data.sqlite.building' if tmp.exists():tmp.rename(dest/f'data.sqlite.interrupted.{time.time_ns()}') dst=sqlite3.connect(tmp);src.backup(dst,pages=2048);src.close() save(root/'quality_screen.json',screen_quality(dst));dst.close() tmp.replace(dest/'data.sqlite') shutil.copyfile(c['proposal_formula_checkpoint'],dest/'formula_selector.pt') db=readonly(dest/'data.sqlite') if db.execute('PRAGMA integrity_check').fetchone()[0]!='ok':raise RuntimeError('Frozen SQLite integrity failure') for f in m['required_formulas']: row=db.execute('SELECT body,raw_count,sha256 FROM formula_pools WHERE formula=?',(f,)).fetchone() if row is None:raise RuntimeError('Missing frozen formula: '+f) verify_pool(f,row) db.close() save(receipt,{'utc':utc(),'database_sha256':sha(dest/'data.sqlite'),'required_manifest_sha256':sha(root/'required_manifest.json')}) return dest
def training_binding(c): # Extra file hashes are gate outputs; not part of the circular config hash. return digest({k:v for k,v in c.items() if k not in {'offline_manifest','offline_manifest_sha256'}})
def prepare(c,m,dest): from .data_v03 import ReadyTrainingStream from .train_v03 import stage_for from .config import Config from .prefetch import OrderedPrefetch root=Path(c['pipeline_dir']);batchdir=root/'batches';batchdir.mkdir(exist_ok=True) cfg={**c,'work_dir':str(dest),'ready_odata_fraction':0.,'require_complete_pools':True, 'proposal_formula_checkpoint':str(dest/'formula_selector.pt'), 'feature_cache_dir':str(root/'derived_features')} total=sum(c['stages'].values());chem=Config().chemistry code={p.name:sha(p) for p in Path(__file__).parent.glob('*.py')} preparation_binding={'config':digest(cfg),'source_code':code,'snapshot':sha(dest/'data.sqlite'), 'selector':sha(dest/'formula_selector.pt')} binding_path=root/'preparation_binding.json' if binding_path.exists() and json.loads(binding_path.read_text())!=preparation_binding: raise RuntimeError('Existing preprocessing belongs to different code/config/snapshot') if not binding_path.exists():save(binding_path,preparation_binding) plan=root/'sampling_plan.sqlite' if not plan.exists(): temp=root/'sampling_plan.building.sqlite' if temp.exists():temp.rename(root/f'sampling_plan.interrupted.{time.time_ns()}.sqlite') db=sqlite3.connect(temp);db.execute('CREATE TABLE plan(sequence INTEGER PRIMARY KEY,spectrum_id INTEGER,view TEXT,stage TEXT,rng BLOB)') stream=ReadyTrainingStream(cfg) for seq in range(total*c['batch_size']): stage=stage_for(c,seq//c['batch_size']);sid,body,_,view=stream.plan(seq,stage) db.execute('INSERT INTO plan VALUES (?,?,?,?,?)',(seq,sid,view,stage,pickle.dumps(stream.rng.getstate(),protocol=5))) db.commit();db.close();stream.db.close();temp.replace(plan) cfg['sampling_plan']=str(plan) # Persist the exact plan/config before starting preparation workers. save(root/'preparation_config.json',cfg) gate=root/'prepared_manifest.json' if gate.exists(): out=json.loads((root/'training_config.json').read_text());validate_prepared(out,True);return out first=0;files=[];counts=Counter();identities=set() def inspect_batch(batch,index): if len(batch)!=c['batch_size']:raise RuntimeError('Wrong offline batch size') for i,b in enumerate(batch): a=b['audit'];ref=b['ref'] if a['sequence']!=index*c['batch_size']+i or a['pool_status'] not in ('ready','ready_empty'): raise RuntimeError('Unresolved or reordered offline sample') if any(n.identity==ref.identity for n in b['proposals']):raise RuntimeError('False negative') counts[a['source']+':'+a['pool_status']]+=1 counts['positive_present']+=int(a['positive_in_original_projected_pool']) counts['sampled_pool']+=int(a['sampled_pool']) identities.add((a['source'],a['spectrum_id'])) # Resume only complete (batch, receipt) pairs; orphan temp files are ignored. while first<total and (batchdir/f'{first:07d}.json').exists(): rec=json.loads((batchdir/f'{first:07d}.json').read_text()) data=(batchdir/rec['file']).read_bytes() if hashlib.sha256(data).hexdigest()!=rec['sha256']:raise RuntimeError('Prepared batch changed') inspect_batch(pickle.loads(zlib.decompress(data)),first);files.append(rec);first+=1 prefetch=OrderedPrefetch(cfg,first,total,chem,stage_for) try: for index in range(first,total): disk_guard(root,c['preprocess_min_free_gib']) batch=prefetch.get(index);inspect_batch(batch,index) data=zlib.compress(pickle.dumps(batch,protocol=5),level=1) name=f'{index:07d}.pkl.z';tmp=batchdir/(name+'.tmp') with tmp.open('wb') as f:f.write(data) tmp.replace(batchdir/name) rec={'index':index,'file':name,'sha256':hashlib.sha256(data).hexdigest(),'bytes':len(data)} save(batchdir/f'{index:07d}.json',rec);files.append(rec) save(root/'status.json',{'utc':utc(),'phase':'preprocessing','batches':index+1,'total':total,'counts':dict(counts),'training_started':False}) finally:prefetch.close() result={'version':'offline-v04','status':'ready','utc':utc(),'training_config_binding':training_binding(cfg), 'batch_size':c['batch_size'],'batches':files,'batch_directory':str(batchdir), 'sample_exposures':total*c['batch_size'],'unique_source_spectrum_ids':len(identities), 'counts':dict(counts),'pending':0,'sampling_plan_sha256':sha(plan),'database_sha256':sha(dest/'data.sqlite'), 'formula_selector_sha256':sha(dest/'formula_selector.pt'), 'source_hashes':{p.name:sha(p) for p in Path(__file__).parent.glob('*.py')}, 'corpus_epoch':False,'truth_injected':False} save(gate,result) cfg.update(offline_manifest=str(gate),offline_manifest_sha256=sha(gate)) save(root/'training_config.json',cfg);validate_prepared(cfg,True);return cfg
def validate_prepared(c,verify_files=False): path=Path(c['offline_manifest']) if sha(path)!=c['offline_manifest_sha256']:raise RuntimeError('Offline manifest hash mismatch') m=json.loads(path.read_text());n=sum(c['stages'].values()) if m['status']!='ready' or m['pending'] or m['training_config_binding']!=training_binding(c): raise RuntimeError('Offline readiness/config gate failed') if m['sample_exposures']!=n*c['batch_size'] or [r['index'] for r in m['batches']]!=list(range(n)): raise RuntimeError('Offline batch coverage failed') if sha(c['sampling_plan'])!=m['sampling_plan_sha256']:raise RuntimeError('Sample plan hash mismatch') if sha(Path(c['work_dir'])/'data.sqlite')!=m['database_sha256']:raise RuntimeError('Dataset snapshot hash mismatch') if sha(c['proposal_formula_checkpoint'])!=m['formula_selector_sha256']:raise RuntimeError('Formula selector changed') if {p.name:sha(p) for p in Path(__file__).parent.glob('*.py')}!=m['source_hashes']:raise RuntimeError('Preprocessing/training code changed') if verify_files: for r in m['batches']: if Path(r['file']).name!=r['file'] or sha(Path(m['batch_directory'])/r['file'])!=r['sha256']: raise RuntimeError('Prepared batch hash mismatch') return m
class FrozenBatchReader: def __init__(self,c): self.c=c;self.manifest=validate_prepared(c)
def get(self,index): r=self.manifest['batches'][index] data=(Path(self.manifest['batch_directory'])/r['file']).read_bytes() if hashlib.sha256(data).hexdigest()!=r['sha256']:raise RuntimeError('Offline batch mutated') batch=pickle.loads(zlib.decompress(data)) if [b['audit']['sequence'] for b in batch]!=list(range(index*self.c['batch_size'],(index+1)*self.c['batch_size'])): raise RuntimeError('Offline sequence mismatch') return batch
def close(self):pass
def run_pipeline(c): root=Path(c['pipeline_dir']);root.mkdir(parents=True,exist_ok=True) lock=(root/'pipeline.lock').open('a+');fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB) try: m=initialize_manifest(c) save(root/'status.json',{'utc':utc(),'phase':'auditing','training_started':False}) save(root/'initial_audit.json',audit(Path(c['work_dir'])/'data.sqlite',mass_checks=True)) download(c,m) save(root/'status.json',{'utc':utc(),'phase':'freezing','training_started':False}) dest=freeze(c,m) train=prepare(c,m,dest) save(root/'status.json',{'utc':utc(),'phase':'ready_for_training','training_started':False,'pending':0}) if c.get('auto_train_after_validation',False): disk_guard(root,c['preprocess_min_free_gib']) save(root/'status.json',{'utc':utc(),'phase':'training','training_started':True, 'pending':0,'training_status_path':str(Path(train['run_dir'])/'status.json')}) result=subprocess.run([sys.executable,'-u','-m','specpartition_ms.supervise_v03','--config',str(root/'training_config.json')]) if result.returncode:raise RuntimeError('Training supervisor exited '+str(result.returncode)) save(root/'status.json',{'utc':utc(),'phase':'initial_curriculum_verified','training_started':True,'scientific_evaluation_completed':False}) except BaseException as exc: save(root/'status.json',{'utc':utc(),'phase':'blocked','error':type(exc).__name__+': '+str(exc)[:350], 'action':'Inspect error; never bypass readiness or delete data'}) raise finally:lock.close()
def main(): p=argparse.ArgumentParser();p.add_argument('--config',required=True);p.add_argument('--audit-only',action='store_true') a=p.parse_args();c=json.loads(Path(a.config).read_text()) if a.audit_only: result=audit(Path(c['work_dir'])/'data.sqlite');print(json.dumps(result,indent=2));return run_pipeline(c)
if __name__=='__main__':main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266"""Bounded formula concurrency, pooled HTTPS, one writer, global backpressure.
Only scheduling/transport changes: preserve formula IDs, 500-CID propertybatches, full response validation, request keys and the data-before-training gate."""from collections import Counterfrom concurrent.futures import ThreadPoolExecutor, wait, FIRST_COMPLETEDfrom contextlib import contextmanagerfrom datetime import datetime, timezonefrom email.utils import parsedate_to_datetimeimport fcntlimport ioimport jsonfrom pathlib import Pathimport queueimport reimport shutilimport sqlite3import threadingimport timefrom urllib.error import HTTPError, URLErrorfrom .multiview_data import packed, sha, save, utc
class DownloadCancelled(RuntimeError): pass
def retry_after_seconds(value, now=None): if not value:return 0. try:return max(0.,float(value)) except ValueError: try: stamp=parsedate_to_datetime(value) if stamp.tzinfo is None:stamp=stamp.replace(tzinfo=timezone.utc) return max(0.,stamp.timestamp()-(time.time() if now is None else now)) except (ValueError,TypeError,OverflowError):return 0.
def feedback_policy(headers,status,now): h={k.lower():str(v) for k,v in headers.items()} text=h.get('x-throttling-control','') colors=re.findall(r'\b(Green|Yellow|Red|Black)\b',text,re.I) severity=max(({'green':0,'yellow':1,'red':2,'black':3}[x.lower()] for x in colors),default=0) if status in (429,503):severity=max(severity,2) pause=max((0.,0.,15.,60.)[severity],retry_after_seconds(h.get('retry-after'),now)) # A green response from another backend cannot immediately undo a red one. return {'severity':severity,'interval':(0.,.5,1.,2.)[severity], 'pause_until':now+pause,'expires':now+max(60.,pause), 'header':text[:500]}
class RequestController: def __init__(self,cache_dir,runtime,events_path,min_free_gib=20,session_factory=None): self.root=Path(cache_dir);self.root.mkdir(parents=True,exist_ok=True) self.interval=float(runtime.get('min_interval_seconds',.26)) self.connections=int(runtime.get('http_connections',4)) if self.interval<.26 or not 1<=self.connections<=4: raise ValueError('Policy guard: interval >=0.26s and at most 4 outstanding HTTP requests') self.rate=self.root/'pubchem_global_rate.json' self.feedback_path=self.root/'pubchem_feedback.json' self.locks=self.root/'singleflight';self.locks.mkdir(exist_ok=True) self.events_path=Path(events_path) self.stop=threading.Event();self.lock=threading.Lock() self.min_free_gib=min_free_gib;self.inflight=0;self.peak_inflight=0;self.counts=Counter() self.sessions=queue.Queue() if session_factory is None: import requests def session_factory(): session=requests.Session() adapter=requests.adapters.HTTPAdapter(pool_connections=1,pool_maxsize=1,max_retries=0,pool_block=True) session.mount('https://',adapter) return session self.all_sessions=[session_factory() for _ in range(self.connections)] for s in self.all_sessions:self.sessions.put(s)
@contextmanager def key_lock(self,key): # 256 stable lock stripes; only colliding requests queue, no duplicate IO. with (self.locks/(key[:2]+'.lock')).open('a+') as fh: while True: if self.stop.is_set():raise DownloadCancelled('Downloader stopping') try:fcntl.flock(fh,fcntl.LOCK_EX|fcntl.LOCK_NB);break except BlockingIOError:self.stop.wait(.1) try:yield finally:fcntl.flock(fh,fcntl.LOCK_UN)
@contextmanager def feedback_state(self): with self.feedback_path.open('a+') as fh: fcntl.flock(fh,fcntl.LOCK_EX) fh.seek(0) try:state=json.load(fh) except ValueError:state={} try:yield state finally: fh.seek(0);fh.truncate();json.dump(state,fh);fh.flush() fcntl.flock(fh,fcntl.LOCK_UN)
def observe(self,headers,status): now=time.time();p=feedback_policy(headers,status,now) with self.feedback_state() as s: if s.get('expires',0)<now:s.clear() s['severity']=max(s.get('severity',0),p['severity']) s['interval']=max(s.get('interval',0.),p['interval']) s['pause_until']=max(s.get('pause_until',0.),p['pause_until']) if p['severity'] or p['pause_until']>now:s['expires']=max(s.get('expires',0.),p['expires']) s['last_header']=p['header'];s['last_status']=status;s['updated']=utc() return p['header']
def throttle(self): while not self.stop.is_set(): if shutil.disk_usage(self.root).free<self.min_free_gib*1024**3: self.stop.set();raise DownloadCancelled('Disk reserve reached before HTTP request') with self.feedback_state() as s: if s.get('expires',0)<time.time():s.clear() interval=max(self.interval,s.get('interval',0.)) pause=s.get('pause_until',0.) # Reuse the previous downloader's global start lock and timestamp. with self.rate.open('a+') as fh: fcntl.flock(fh,fcntl.LOCK_EX);fh.seek(0) try:last=float(fh.read() or 0) except ValueError:last=0. delay=max(pause-time.time(),interval-(time.time()-last),0.) if delay<=0: stamp=time.time();fh.seek(0);fh.truncate();fh.write(str(stamp));fh.flush() fcntl.flock(fh,fcntl.LOCK_UN);return stamp fcntl.flock(fh,fcntl.LOCK_UN) self.stop.wait(min(delay,.25)) raise DownloadCancelled('Downloader stopping')
def fetch(self,url,payload,key): session=None while session is None: if self.stop.is_set():raise DownloadCancelled('Downloader stopping') try:session=self.sessions.get(timeout=.2) except queue.Empty:pass started=None;status=None;header='';size=0;error=None try: started=self.throttle() with self.lock: self.inflight+=1;self.peak_inflight=max(self.peak_inflight,self.inflight) headers={'User-Agent':'SpecPartition-MS/0.4.1 (research candidate audit)','Accept':'application/json'} if payload:headers['Content-Type']='application/x-www-form-urlencoded' # Session lease is exclusive; cookies cannot become request features. session.cookies.clear() response=session.request('POST' if payload else 'GET',url,data=payload,headers=headers, timeout=(15,65),allow_redirects=False) try: status=response.status_code;body=response.content;size=len(body) header=self.observe(response.headers,status) if status>=300: raise HTTPError(url,status,'PubChem HTTP '+str(status),response.headers,io.BytesIO(body)) return body finally:response.close() except HTTPError as exc:error='HTTP '+str(exc.code);raise except DownloadCancelled:raise except Exception as exc: error=type(exc).__name__ raise URLError(type(exc).__name__+' during PubChem transport') from exc finally: if started is not None: ended=time.time() event={'utc':utc(),'started_epoch':started,'seconds':ended-started,'http_status':status, 'request_sha256':key,'kind':'fastformula' if '/fastformula/' in url else 'properties', 'bytes':size,'error':error,'throttling':header} with self.lock: self.inflight-=1;self.counts[str(status) if status else 'network_error']+=1 with self.events_path.open('a') as out:out.write(json.dumps(event)+'\n') self.sessions.put(session)
def metrics(self): with self.lock:return {'inflight_http':self.inflight,'peak_inflight_http':self.peak_inflight,'http_results':dict(self.counts)}
def close(self): for s in self.all_sessions:s.close()
def download_parallel(c,m,runtime,controller_factory=RequestController,cache_factory=None): from .offline_data import digest,binding,verify_pool,disk_guard from .retrieval import PubChemCache cache_factory=cache_factory or PubChemCache root=Path(c['pipeline_dir']);live=Path(c['work_dir']);cache_dir=live/'pubchem';cache_dir.mkdir(exist_ok=True) workers=int(runtime.get('formula_workers',16)) if not 2<=workers<=32:raise ValueError('formula_workers must be 2..32') guard=(live/'pubchem_worker.lock').open('a+');fcntl.flock(guard,fcntl.LOCK_EX|fcntl.LOCK_NB) db=sqlite3.connect(live/'data.sqlite',timeout=90) controller=None;executor=None;futures={};completed=set();verified=[];failed=[];owned=set() try: if digest(binding(db))!=m['source_binding_sha256']:raise RuntimeError('Source or formula catalog changed') db.executemany('INSERT OR IGNORE INTO jobs(formula) VALUES (?)',[(f,) for f in m['required_formulas']]);db.commit() # Only request cache gets WAL; full formula pools are committed by coordinator. bootstrap=PubChemCache(cache_dir/'requests.sqlite');bootstrap.db.execute('PRAGMA journal_mode=WAL');bootstrap.close() required=set(m['required_formulas']) for f,blob,n,h in db.execute('SELECT formula,body,raw_count,sha256 FROM formula_pools'): if f in required:verify_pool(f,(blob,n,h));completed.add(f);verified.append((f,h,n)) priorities=dict(db.execute("SELECT formula,COUNT(*) FROM spectra WHERE source='odata' AND status='eligible' GROUP BY formula")) todo=iter(sorted(required-completed,key=lambda f:(-priorities.get(f,0),f))) controller=controller_factory(cache_dir,runtime,root/'http_events_parallel.jsonl',c['download_min_free_gib']) started=time.time();run_id=str(time.time_ns()) save(root/f'download_runtime_receipt_{run_id}.json',{'utc':utc(),'runtime':runtime,'runtime_sha256':digest(runtime), 'initial_ready':len(completed),'required':len(required),'source_sha256':sha(__file__),'candidate_protocol_changed':False}) def retrieve(formula,attempts): cache=cache_factory(cache_dir/'requests.sqlite',online=True,property_batch_size=c['property_batch_size'],controller=controller) try: while attempts<c['pubchem_max_attempts'] and not controller.stop.is_set(): attempts+=1 try: records,prov=cache.formula_candidates(formula) blob=packed({'records':records,'provenance':prov});h=__import__('hashlib').sha256(blob).hexdigest() verify_pool(formula,(blob,len(records),h)) return {'blob':blob,'count':len(records),'sha256':h,'attempts':attempts} except DownloadCancelled:raise except Exception as exc: error=type(exc).__name__+': '+str(exc)[:250] if attempts<c['pubchem_max_attempts']:controller.stop.wait(min(30,5*attempts)) return {'error':locals().get('error','prior retry budget exhausted'),'attempts':attempts} finally:cache.close() def publish(): save(root/'status.json',{'utc':utc(),'phase':'downloading','mode':'parallel_pooled_http', 'ready':len(completed),'required':len(required),'remaining':len(required-completed), 'training_started':False,'formula_workers':workers,'active_formulas':sorted(futures.values()), 'http_connections':controller.connections,'requests_per_second_cap':1/controller.interval, 'elapsed_seconds':time.time()-started,'failed_formulas':failed,**controller.metrics()}) executor=ThreadPoolExecutor(max_workers=workers,thread_name_prefix='pubchem-formula') exhausted=False while futures or not exhausted: if controller.stop.is_set():raise DownloadCancelled('Global stop or disk reserve reached') while len(futures)<workers and not exhausted: try:f=next(todo) except StopIteration:exhausted=True;break disk_guard(root,c['download_min_free_gib']) attempts=db.execute('SELECT attempts FROM jobs WHERE formula=?',(f,)).fetchone()[0] db.execute("UPDATE jobs SET status='in_progress',updated=? WHERE formula=?",(utc(),f));db.commit() owned.add(f) futures[executor.submit(retrieve,f,attempts)]=f publish() if not futures:break done,_=wait(futures,timeout=2,return_when=FIRST_COMPLETED) for future in done: f=futures.pop(future);result=future.result() if 'error' in result: failed.append(f) db.execute("UPDATE jobs SET status='failed',attempts=?,error=?,updated=? WHERE formula=?",(result['attempts'],result['error'],utc(),f));db.commit() else: disk_guard(root,c['download_min_free_gib']) db.execute('INSERT INTO formula_pools VALUES (?,?,?,?,?)',(f,result['blob'],result['count'],result['sha256'],utc())) db.execute("UPDATE jobs SET status='completed',attempts=?,error=NULL,updated=? WHERE formula=?",(result['attempts'],utc(),f));db.commit() completed.add(f);verified.append((f,result['sha256'],result['count'])) with (root/'download_events.jsonl').open('a') as out: out.write(json.dumps({'utc':utc(),'formula':f,'records':result['count'],'sha256':result['sha256'],'attempts':result['attempts'],'parallel_run_id':run_id})+'\n') publish() result={'utc':utc(),'required':len(required),'verified':len(completed),'pools':sorted(verified), 'failed':failed,'complete':completed==required,'runtime':runtime,'elapsed_seconds':time.time()-started} save(root/'download_complete.json',result) if not result['complete']:raise RuntimeError(f'{len(failed)} formula jobs unresolved; no training') return result finally: if controller:controller.stop.set() if executor:executor.shutdown(wait=True,cancel_futures=True) # Uncommitted in-flight work becomes pending. Individual HTTP cache entries survive. for f in owned: db.execute("UPDATE jobs SET status='pending',updated=? WHERE formula=? AND status='in_progress'",(utc(),f)) db.commit();db.close() if controller:controller.close() guard.close()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394"""Only the v06 pipeline is owned. Downloader and prior runs are never managed.
wait-prepare attaches read-only to the already started preparation stage.GPU admission waits while another compute process occupies the card. BoundedCUDA recovery is inherited; OOM/unknown failures never trigger retry loops."""import argparseimport fcntlimport jsonimport osfrom pathlib import Pathimport signalimport subprocessimport sysimport timefrom .multiview_data import save,utc,shafrom .supervise_v03 import restart_decision,terminate_owned_group
def run(config_path,wait_prepare=False): path=Path(config_path).resolve();c=json.loads(path.read_text());root=Path(c['run_dir']);root.mkdir(parents=True,exist_ok=True) lock=(root/'pipeline.lock').open('a+');fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB) child=None;stamp=str(time.time_ns()) def record(event,**kw): row={'utc':utc(),'event':event,**kw};save(root/'pipeline_status.json',row) with (root/'pipeline_events.jsonl').open('a') as f:f.write(json.dumps(row)+'\n') print(json.dumps(row),flush=True) def interrupt(s,f):raise KeyboardInterrupt() for s in (signal.SIGINT,signal.SIGTERM):signal.signal(s,interrupt) def command(module,args,logname): nonlocal child with (root/logname).open('a') as log: child=subprocess.Popen([sys.executable,'-u','-m',module,*args],stdout=log,stderr=subprocess.STDOUT,start_new_session=True) record('child_started',module=module,pid=child.pid,log=str(root/logname));code=child.wait() terminate_owned_group(child);child=None return code try: if wait_prepare: record('waiting_for_preparation',prepared_dir=c['prepared_dir']) while not (Path(c['prepared_dir'])/'manifest.json').exists(): failure=Path(c['prepared_dir'])/'failure.json' if failure.exists():raise RuntimeError('Preparation failed; '+str(failure)) # A released preparation lock with no manifest is a real stop. try: with (Path(c['prepared_dir'])/'prepare.lock').open('a+') as guard: fcntl.flock(guard,fcntl.LOCK_EX|fcntl.LOCK_NB) raise RuntimeError('Preparation process stopped before manifest') except BlockingIOError:pass time.sleep(30) else: if command('specpartition_ms.prepare_epoch',['--config',str(path)],'prepare.log'):raise RuntimeError('Preparation failed') from .prepare_epoch import validate _,checks=validate(c,True);record('prepared_verified',checks=checks) # Do not compete with a new, unrelated GPU task that may have appeared # during preparation. Check compute PIDs and available memory. waiting=False while True: gpu=subprocess.check_output(['nvidia-smi','--query-compute-apps=pid','--format=csv,noheader,nounits'],text=True).strip() free=float(subprocess.check_output(['nvidia-smi','--query-gpu=memory.free','--format=csv,noheader,nounits'],text=True).splitlines()[0]) if not gpu and free>29000:break if not waiting:record('waiting_for_gpu_admission',compute_pids=gpu,free_mib=free);waiting=True time.sleep(30) accept=root/'acceptance';accept.mkdir(exist_ok=True) if command('specpartition_ms.benchmark_epoch',['--config',str(path),'--sweep-dir',str(accept)],'batch_sweep.log'): raise RuntimeError('Batch sweep failed; see real-data acceptance log') selected=accept/'selected_config.json';selected_c=json.loads(selected.read_text()) receipt=json.loads((accept/'batch_selection.json').read_text()) if receipt['selected_config_sha256']!=sha(selected):raise ValueError('Accepted configuration hash mismatch') record('training_configuration_accepted',batch=receipt['selected_batch'],epochs=selected_c['epochs'],config=str(selected)) restarts=0;seen=set() while True: args=['--config',str(selected)] if (root/'last.pt').exists():args.append('--resume') code=command('specpartition_ms.train_epoch',args,f'trainer_{stamp}_{restarts}.log') state=json.loads((root/'status.json').read_text()) if (root/'status.json').exists() else {} done=root/'completion_verified.json' if code==0 and state.get('completion_verified') and done.exists() and json.loads(done.read_text()).get('passed'): record('full_epochs_verified',epochs=selected_c['epochs'],checkpoint=str(root/'last.pt'));return 0 allowed,reason=restart_decision(state,restarts,seen,limit=2) record('trainer_exited',returncode=code,recovery_allowed=allowed,reason=reason,status=state) if not allowed:return code or 2 seen.add(state['last_checkpoint_step']);restarts+=1;os.environ['CUDA_LAUNCH_BLOCKING']='1' except KeyboardInterrupt: record('stopped_no_restart');return 130 except BaseException as e: record('pipeline_failed',error=repr(e));raise finally: if child is not None:terminate_owned_group(child) lock.close()
if __name__=='__main__': p=argparse.ArgumentParser();p.add_argument('--config',required=True);p.add_argument('--wait-prepare',action='store_true') a=p.parse_args();raise SystemExit(run(a.config,a.wait_prepare))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566"""Ordered, bounded, restartable CPU preparation. No training step is skipped."""from collections import dequefrom concurrent.futures import ProcessPoolExecutor, TimeoutErrorfrom concurrent.futures.process import BrokenProcessPoolimport jsonimport multiprocessing as mpfrom pathlib import Pathimport timefrom .data_v03 import initialize_worker, prepare_batch
def stop_owned_pool(pool): """Bound shutdown to this executor's own children, never broad pkill.""" processes=list((getattr(pool,'_processes',None) or {}).values()) for p in processes: if p.is_alive():p.terminate() deadline=time.monotonic()+5 for p in processes:p.join(timeout=max(0,deadline-time.monotonic())) for p in processes: if p.is_alive():p.kill();p.join(timeout=1) pool.shutdown(wait=False,cancel_futures=True)
class OrderedPrefetch: def __init__(self,c,first,end,chemistry,stage_for,initializer=initialize_worker,prepare=prepare_batch): self.c=c;self.end=end;self.chemistry=chemistry;self.stage_for=stage_for self.initializer=initializer;self.prepare=prepare;self.next_index=first self.pending=deque();self.restarts=0;self.pool=self._new_pool()
def _new_pool(self): return ProcessPoolExecutor(max_workers=self.c['workers'],mp_context=mp.get_context('spawn'), initializer=self.initializer,initargs=(self.c,))
def get(self,step): attempt=0 while True: try: while len(self.pending)<self.c['prefetch_batches'] and self.next_index<self.end: n=self.next_index task=(n,self.stage_for(self.c,n),self.chemistry) self.pending.append((n,self.pool.submit(self.prepare,task)));self.next_index+=1 index,future=self.pending[0] if index!=step:raise RuntimeError(f'Prefetch order violation: {index} != {step}') result=future.result(timeout=self.c.get('preparation_timeout_seconds',600)) self.pending.popleft() return result except (BrokenProcessPool,TimeoutError) as exc: attempt+=1;self.restarts+=1 processes=list((getattr(self.pool,'_processes',None) or {}).values()) event={'utc_epoch':time.time(),'step':step,'attempt':attempt,'total_restarts':self.restarts, 'error':type(exc).__name__+': '+str(exc), 'workers':[{'pid':p.pid,'exitcode':p.exitcode,'alive':p.is_alive()} for p in processes], 'action':'replay same unconsumed step/sequence; no optimizer update or skipped sample', 'live_pool_readiness_may_change':True} path=Path(self.c['run_dir'])/'worker_recovery.jsonl' with path.open('a') as f:f.write(json.dumps(event)+'\n') stop_owned_pool(self.pool) if attempt>self.c.get('worker_restart_limit',3) or self.restarts>8: raise RuntimeError(f'CPU worker recovery budget exhausted at step {step}; see {path}') from exc self.pending.clear();self.next_index=step;self.pool=self._new_pool()
def close(self): if self.pending: for _,future in self.pending:future.cancel() stop_owned_pool(self.pool) else:self.pool.shutdown(wait=True,cancel_futures=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260"""Offline-only, resumable feature preparation; never accesses PubChem tables.
Copy eligible spectra, materialize required unique molecular inputs, then buildboth official MSG training views/forests. No online fallback is allowed later.All writes target prepared_dir, never work_dir or downloader resources."""import argparsefrom collections import Counterfrom concurrent.futures import ProcessPoolExecutorfrom dataclasses import asdictimport fcntlimport hashlibimport jsonimport multiprocessing as mpfrom pathlib import Pathimport shutilimport sqlite3import timeimport numpy as npfrom rdkit import RDLogger, rdBasefrom .chemistry import _calculate_moleculefrom .config import Configfrom .epoch_features import PreparedQuery, spectrum_arrays, dumps, loadsfrom .forest import build_forestfrom .inbatch_data import InbatchStreamfrom .multiview_data import unpacked, save, utc, shafrom .multiview_pools import FormulaCatalogfrom .train_inbatch import source_binding
def readonly(path): db = sqlite3.connect(f'file:{path}?mode=ro', uri=True, timeout=60) db.execute('PRAGMA query_only=ON') return db
def initialize(path): db = sqlite3.connect(path, timeout=60) db.execute('PRAGMA journal_mode=WAL'); db.execute('PRAGMA synchronous=NORMAL') db.executescript(''' CREATE TABLE IF NOT EXISTS stage(name TEXT PRIMARY KEY, value TEXT); CREATE TABLE IF NOT EXISTS spectra(id INTEGER PRIMARY KEY, source TEXT, identity TEXT, ref_smiles TEXT, target TEXT, body BLOB NOT NULL); CREATE INDEX IF NOT EXISTS spectrum_source ON spectra(source,id); CREATE TABLE IF NOT EXISTS molecules(id INTEGER PRIMARY KEY, smiles TEXT UNIQUE, value BLOB, error TEXT, identity TEXT, formula TEXT, charge INTEGER, ready INTEGER DEFAULT 0); CREATE INDEX IF NOT EXISTS molecule_ready ON molecules(ready,id); CREATE TABLE IF NOT EXISTS targets(target TEXT PRIMARY KEY, ref_smiles TEXT, identity TEXT, formula TEXT); CREATE TABLE IF NOT EXISTS pools(view TEXT, target TEXT, raw BLOB, sha256 TEXT, raw_count INTEGER, prepared BLOB, PRIMARY KEY(view,target)); CREATE TABLE IF NOT EXISTS training_structures(identity TEXT PRIMARY KEY, smiles TEXT, formula TEXT); CREATE TABLE IF NOT EXISTS heldout(identity TEXT PRIMARY KEY); ''') return db
def stage(db, key, value=None): if value is None: r = db.execute('SELECT value FROM stage WHERE name=?', (key,)).fetchone() return json.loads(r[0]) if r else None db.execute('INSERT OR REPLACE INTO stage VALUES (?,?)', (key, json.dumps(value))) db.commit()
def guard(root, c): if shutil.disk_usage(root).free < c['min_free_gb'] * 1024**3: raise RuntimeError('Disk reserve reached; no partial training allowed')
_CAT = None
def worker_init(source_path): global _CAT import torch torch.set_num_threads(1); RDLogger.DisableLog('rdApp.*') db = readonly(source_path); db.set_authorizer(InbatchStream.authorize) _CAT = FormulaCatalog(db); db.close()
def convert_spectra(rows): out = [] for sid, raw in rows: b = unpacked(raw); f = b['features'] q = PreparedQuery(peaks=tuple(tuple(p) for p in f['peaks']), precursor_mz=f['precursor_mz'], adduct=f['adduct'], collision_energy=f.get('collision_energy'), instrument=f.get('instrument'), formula_candidates=(), candidates=(), dataset_mode=f['dataset_mode'], candidate_view='warmup') from dataclasses import replace q = replace(q, spectrum_arrays=spectrum_arrays(q)) fs = tuple(_CAT.select(q.precursor_mz, q.adduct)) out.append((sid, b['source'], b['identity'], b['reference_smiles'], b.get('target_smiles'), dumps({'query':q, 'independent_formulas':fs, 'source_row':b['source_row']}), b['formula'])) return out
def convert_molecules(rows): out = [] for mid, smiles in rows: try: m = _calculate_molecule(smiles) out.append((dumps(m), None, m.identity, m.formula, m.charge, mid)) except (ValueError, TypeError, OverflowError) as e: out.append((None, type(e).__name__ + ': ' + str(e)[:240], None, None, None, mid)) return out
def prepare_pool(task): path, view, target, chemistry = task db = readonly(path) banned = {r[0] for r in db.execute('SELECT identity FROM heldout')} raw, digest, count = db.execute('SELECT raw,sha256,raw_count FROM pools WHERE view=? AND target=?', (view,target)).fetchone() smiles = unpacked(raw) if len(smiles) != count or hashlib.sha256(json.dumps(smiles, separators=(',', ':')).encode()).hexdigest() != digest: raise ValueError('Official candidate pool hash/count mismatch') retained = {}; removed = Counter() for s in smiles: r = db.execute('SELECT id,value,error,ready FROM molecules WHERE smiles=?', (s,)).fetchone() if not r or r[3] != 1: raise ValueError('Molecular preparation incomplete') if r[2]: removed['unsupported_structure'] += 1; continue m = loads(r[1]) if m.identity in banned: removed['heldout_connectivity'] += 1; continue if m.charge: removed['unsupported_charged_structure'] += 1; continue if m.identity not in retained or s < retained[m.identity][0]: retained[m.identity] = (s, r[0], m) values = [retained[k] for k in sorted(retained)] mols = [v[2] for v in values] # Official pools are <=256 here. A future larger source requires an explicit # sampling/forest policy, never silent truncation or reference injection. if len(mols) > 256: raise ValueError('Official training pool >256; explicit protocol update required') cfg = Config().chemistry for k,v in chemistry.items(): setattr(cfg,k,v) forest = build_forest(mols, cfg, vectorized=True) ref_s, identity, formula = db.execute('SELECT ref_smiles,identity,formula FROM targets WHERE target=?', (target,)).fetchone() ref = loads(db.execute('SELECT value FROM molecules WHERE smiles=? AND ready=1 AND error IS NULL', (ref_s,)).fetchone()[0]) isomers = [(v[1], v[2]) for v in values if v[2].identity != identity and v[2].formula == formula] from .chemistry import tanimoto isomers.sort(key=lambda v: (-tanimoto(ref.whole, v[1].whole), v[1].identity)) result = {'molecule_ids':tuple(v[1] for v in values), 'forest':forest, 'same_formula_proposal_ids':tuple(v[0] for v in isomers), 'raw_count':count, 'projected_count':len(mols), 'removed':dict(removed), 'sha256':digest, 'positive_in_original_projected_pool':identity in retained, 'identity_hash':hashlib.sha256('\n'.join(sorted(retained)).encode()).hexdigest(), 'ppm_filter_applied':False, 'raw_pool_modified':False, 'network_requests':0} db.close() return view, target, dumps(result)
def validate(c, verify_hash=False): root = Path(c['prepared_dir']); p = root/'manifest.json' if not p.exists(): raise RuntimeError('No completed preparation manifest') m = json.loads(p.read_text()) if not m.get('complete'): raise RuntimeError('Preparation not complete') if m['source_binding'] != source_binding(c)['sha256']: raise RuntimeError('Source registry changed') if m['chemistry'] != asdict(Config().chemistry): raise RuntimeError('Chemistry configuration changed') if m['rdkit_version'] != rdBase.rdkitVersion: raise RuntimeError('RDKit version changed') for name, digest in m['preparation_source_hashes'].items(): if sha(Path(__file__).parent/name) != digest: raise RuntimeError('Preparation implementation changed: '+name) if verify_hash and sha(root/'prepared.sqlite') != m['sha256']: raise RuntimeError('Prepared artifact hash mismatch') db = readonly(root/'prepared.sqlite') checks = {'spectra':dict(db.execute('SELECT source,COUNT(*) FROM spectra GROUP BY source')) == m['eligible'], 'molecules':db.execute('SELECT COUNT(*) FROM molecules WHERE ready=0').fetchone()[0] == 0, 'pools':db.execute('SELECT COUNT(*) FROM pools WHERE prepared IS NULL').fetchone()[0] == 0, 'all_target_views':db.execute('SELECT COUNT(*) FROM pools').fetchone()[0] == 2*db.execute('SELECT COUNT(*) FROM targets').fetchone()[0], 'heldout_labels':db.execute('SELECT COUNT(*) FROM spectra JOIN heldout USING(identity)').fetchone()[0] == 0, 'reference_features':db.execute('SELECT COUNT(*) FROM (SELECT DISTINCT ref_smiles FROM spectra) s LEFT JOIN molecules m ON s.ref_smiles=m.smiles WHERE m.ready IS NULL OR m.ready!=1 OR m.error IS NOT NULL').fetchone()[0] == 0} db.close() if not all(checks.values()): raise RuntimeError('Preparation checks failed: '+str(checks)) return m, checks
def run(c): root = Path(c['prepared_dir']); root.mkdir(parents=True,exist_ok=True) lock = (root/'prepare.lock').open('a+'); fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB) if (root/'manifest.json').exists(): _, checks = validate(c,True) print(json.dumps({'phase':'complete_reused','utc':utc(),'checks':checks}),flush=True) lock.close() return start = time.monotonic() def status(phase, **kw): guard(root,c); row = {'utc':utc(),'phase':phase,'elapsed_seconds':time.monotonic()-start,**kw} save(root/'status.json',row); print(json.dumps(row),flush=True) binding = source_binding(c) expected = {s:n for s,n,_ in binding['eligible']} source = readonly(Path(c['work_dir'])/'data.sqlite'); source.set_authorizer(InbatchStream.authorize) db = initialize(root/'prepared.sqlite') if stage(db,'binding') not in (None,binding['sha256']): raise ValueError('Preparation source changed') stage(db,'binding',binding['sha256']) chemistry = asdict(Config().chemistry) names = ['prepare_epoch.py','epoch_features.py','chemistry.py','forest.py','schema.py','model.py','multiview_pools.py'] hashes = {name:sha(Path(__file__).parent/name) for name in names} # A changed feature implementation cannot resume an incompatible partial cache. if stage(db,'implementation') not in (None,hashes): raise ValueError('Partial cache implementation changed') stage(db,'implementation',hashes) db.executemany('INSERT OR IGNORE INTO heldout VALUES (?)', source.execute('SELECT identity FROM heldout').fetchall()) structs = source.execute('SELECT identity,smiles,formula FROM structures').fetchall() db.executemany('INSERT OR IGNORE INTO training_structures VALUES (?,?,?)',structs) db.executemany('INSERT OR IGNORE INTO molecules(smiles) VALUES (?)',[(s,) for _,s,_ in structs]); db.commit() with ProcessPoolExecutor(c['prepare_workers'], mp_context=mp.get_context('spawn'), initializer=worker_init, initargs=(str(Path(c['work_dir'])/'data.sqlite'),)) as workers: if not stage(db,'spectra_done'): last = stage(db,'last_spectrum_id') or 0 while True: # Materialize a bounded read then release the shared SQLite read transaction. rows = source.execute("SELECT id,body FROM spectra WHERE id>? AND status='eligible' AND source IN ('odata','msg_train') ORDER BY id LIMIT 4096", (last,)).fetchall() if not rows: break chunks = [rows[i:i+256] for i in range(0,len(rows),256)] for result in workers.map(convert_spectra,chunks): db.executemany('INSERT OR REPLACE INTO spectra VALUES (?,?,?,?,?,?)',[r[:6] for r in result]) db.executemany('INSERT OR IGNORE INTO molecules(smiles) VALUES (?)',[(r[3],) for r in result]) db.executemany('INSERT OR IGNORE INTO targets VALUES (?,?,?,?)',[(r[4],r[3],r[2],r[6]) for r in result if r[1]=='msg_train']) last = rows[-1][0]; stage(db,'last_spectrum_id',last) status('spectra',processed=db.execute('SELECT COUNT(*) FROM spectra').fetchone()[0],expected=sum(expected.values())) if dict(db.execute('SELECT source,COUNT(*) FROM spectra GROUP BY source')) != expected: raise RuntimeError('Spectrum count mismatch') stage(db,'spectra_done',True) if not stage(db,'pools_copied'): targets = [r[0] for r in db.execute('SELECT target FROM targets ORDER BY target')] for i,t in enumerate(targets): for view in ('msg_mass','msg_formula'): raw = source.execute('SELECT body,sha256,count FROM official_pools WHERE view=? AND target=?',(view,t)).fetchone() if not raw: raise ValueError('Missing official training pool') db.execute('INSERT OR IGNORE INTO pools(view,target,raw,sha256,raw_count) VALUES (?,?,?,?,?)',(view,t,*raw)) db.executemany('INSERT OR IGNORE INTO molecules(smiles) VALUES (?)',[(s,) for s in unpacked(raw[0])]) if i%200==0: db.commit(); status('collect_official_inputs',targets=i+1,total=len(targets)) stage(db,'pools_copied',True) while True: rows = db.execute('SELECT id,smiles FROM molecules WHERE ready=0 ORDER BY id LIMIT 4096').fetchall() if not rows: break for result in workers.map(convert_molecules,[rows[i:i+64] for i in range(0,len(rows),64)]): db.executemany('UPDATE molecules SET value=?,error=?,identity=?,formula=?,charge=?,ready=1 WHERE id=?',result) db.commit(); status('molecular_features',counts=dict(db.execute('SELECT ready,COUNT(*) FROM molecules GROUP BY ready'))) while True: rows = db.execute('SELECT view,target FROM pools WHERE prepared IS NULL ORDER BY view,target LIMIT 64').fetchall() if not rows: break # Workers read only this derived artifact; all molecule writes finished. db.commit() for view,target,value in workers.map(prepare_pool,[(str(root/'prepared.sqlite'),v,t,chemistry) for v,t in rows]): db.execute('UPDATE pools SET prepared=? WHERE view=? AND target=?',(value,view,target)) db.commit(); status('candidate_forests',ready=db.execute('SELECT COUNT(*) FROM pools WHERE prepared IS NOT NULL').fetchone()[0],total=db.execute('SELECT COUNT(*) FROM pools').fetchone()[0]) db.execute('PRAGMA wal_checkpoint(TRUNCATE)'); db.close(); source.close() manifest = {'complete':True,'utc':utc(),'eligible':expected,'source_binding':binding['sha256'], 'chemistry':chemistry,'rdkit_version':rdBase.rdkitVersion,'preparation_source_hashes':hashes, 'sha256':sha(root/'prepared.sqlite'),'file':str(root/'prepared.sqlite'), 'network_requests':0,'official_pool_extra_ppm_filter':False,'heldout_label_training':False} save(root/'manifest.json',manifest) _, checks = validate(c,True); save(root/'validation.json',{'passed':all(checks.values()),'checks':checks,'utc':utc()}) status('complete',checks=checks,sha256=manifest['sha256']) lock.close()
if __name__ == '__main__': p=argparse.ArgumentParser(); p.add_argument('--config',required=True) c=json.loads(Path(p.parse_args().config).read_text()) try: run(c) except BaseException as e: save(Path(c['prepared_dir'])/'failure.json',{'utc':utc(),'error':repr(e)}) raise12345678910111213141516171819"""Read-only coordination: yield our GPU before the protected run validates."""import jsonfrom pathlib import Path
def protected_validation_pending(run_dir): if not run_dir:return False root=Path(run_dir) def read(name): p=root/name return json.loads(p.read_text()) if p.exists() else {} pipeline=read('pipeline_status.json') if pipeline.get('status')!='running':return False if pipeline.get('stage')=='validation_mass_formula':return True if pipeline.get('stage')=='joint_training': total=read('protocol.json').get('total_steps') step=read('status.json').get('step',-1) return total is not None and step>=total-21 return False123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164"""Opt-in PubChem adapter. Default is replay-only cache; no SIRIUS dependency.
Live PubChem is not a frozen database release. Save UTC, request, response hash,properties and CIDs to reproduce the exact candidate snapshot."""from dataclasses import replacefrom datetime import datetime, timezoneimport hashlibfrom http.client import IncompleteReadimport jsonimport sqlite3import timefrom urllib.request import Request, urlopenfrom urllib.error import HTTPError, URLErrorfrom urllib.parse import quote, urlencodeimport numpy as npimport torchfrom rdkit import Chemfrom .chemistry import enumerate_formulas, molecule, ppm_errorfrom .schema import parse_record
def utc_now(): return datetime.now(timezone.utc).isoformat()
class PubChemCache: def __init__(self, path, online=False, transport=None, sleep=time.sleep, property_batch_size=100): if not 1 <= property_batch_size <= 500: raise ValueError('property_batch_size must be in 1..500') self.property_batch_size = property_batch_size self.db = sqlite3.connect(path) self.db.execute("CREATE TABLE IF NOT EXISTS requests (key TEXT PRIMARY KEY, url TEXT, fetched_utc TEXT, sha256 TEXT, body TEXT)") self.db.commit() self.online, self.transport, self.sleep = online, transport, sleep
def close(self): self.db.close()
def request(self, path, form=None): url = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/"+path payload = urlencode(form).encode() if form else None key = hashlib.sha256(url.encode()+b"\n"+(payload or b"")).hexdigest() row = self.db.execute("SELECT fetched_utc,sha256,body FROM requests WHERE key=?",(key,)).fetchone() if row: if hashlib.sha256(row[2].encode()).hexdigest()!=row[1]: raise RuntimeError('PubChem cached response hash mismatch') return json.loads(row[2]),{"url":url,"request_sha256":key,"fetched_utc":row[0],"response_sha256":row[1],"replayed":True} if not self.online: raise RuntimeError("PubChem cache miss; explicit --online is required for a network request") error = None for attempt in range(5): try: self.sleep(.3) # conservative <= 3.3 requests/sec; obey rate-limit backoff if self.transport: body = self.transport(url,payload) else: req = Request(url,data=payload,headers={"User-Agent":"SpecPartition-MS/0.1 (research candidate audit)","Accept":"application/json"}) with urlopen(req,timeout=60) as response: body = response.read() value = json.loads(body) # Async or fault responses are not silently treated as complete candidate sets. if "Waiting" in value or "Fault" in value: raise RuntimeError("PubChem did not return a complete result: "+json.dumps(value)[:300]) stamp = utc_now() sha = hashlib.sha256(body).hexdigest() text = body.decode() self.db.execute("INSERT OR REPLACE INTO requests VALUES (?,?,?,?,?)",(key,url,stamp,sha,text)) self.db.commit() return value,{"url":url,"request_sha256":key,"fetched_utc":stamp,"response_sha256":sha,"replayed":False} except HTTPError as exc: if exc.code == 404 and "fastformula/" in path: try: fault = json.loads(exc.read()) except (ValueError,IncompleteRead): raise RuntimeError("Unrecognized HTTP404; not a verified empty PubChem formula result") from exc if fault.get("Fault",{}).get("Code") != "PUGREST.NotFound": raise RuntimeError("HTTP404 is not PubChem's explicit NotFound result") from exc body = b'{"IdentifierList":{"CID":[]}}' stamp,sha = utc_now(),hashlib.sha256(body).hexdigest() self.db.execute("INSERT INTO requests VALUES (?,?,?,?,?)",(key,url,stamp,sha,body.decode())) self.db.commit() return json.loads(body),{"url":url,"request_sha256":key,"fetched_utc":stamp,"response_sha256":sha,"http_status":404} if exc.code not in {429,500,502,503,504}: raise error = exc except (URLError,TimeoutError,ConnectionError,OSError,IncompleteRead,json.JSONDecodeError) as exc: error = exc self.sleep(min(2**attempt,16)) raise RuntimeError("PubChem temporary error retries exhausted") from error
def formula_candidates(self, formula): response,first = self.request("compound/fastformula/"+quote(formula,safe="")+"/cids/JSON") cids = response["IdentifierList"]["CID"] records, requests = [],[first] if len(cids) != len(set(cids)): raise RuntimeError('Duplicate CID in formula response') for start in range(0,len(cids),self.property_batch_size): ids = cids[start:start+self.property_batch_size] props,prov = self.request("compound/cid/property/MolecularFormula,IsomericSMILES,InChIKey,MonoisotopicMass,Charge/JSON",{"cid":",".join(map(str,ids))}) rows = props["PropertyTable"]["Properties"] if len(rows) != len(ids) or {r["CID"] for r in rows} != set(ids): raise RuntimeError("Incomplete PubChem property batch; refusing a silently truncated pool") records.extend(rows); requests.append(prov) return records,{"provider":"PubChem PUG REST FastFormula","database_version":"live service; no immutable release identifier supplied", "formula":formula,"cid_count":len(cids),"requests":requests}
def filter_candidates(records, mz, adduct, formula, ppm=10.): kept, rejected = [],[] for r in records: smiles = r.get("SMILES",r.get("IsomericSMILES",r.get("ConnectivitySMILES",r.get("CanonicalSMILES")))) reason,m,err = None,None,None if r.get("Charge",0) != 0: reason = "nonzero_pubchem_charge" elif not smiles: reason = "missing_smiles" else: try: m = molecule(smiles) err = ppm_error(m.mass,mz,adduct) if m.charge: reason = "nonzero_rdkit_charge" elif m.formula != formula: reason = "formula_mismatch" elif abs(err) > ppm: reason = "precursor_ppm_exceeded" except ValueError as exc: reason = "invalid_or_unsupported_structure: "+str(exc) record = {"cid":r.get("CID"),"smiles":smiles,"raw_pubchem":r,"ppm_error":err, "identity":m.identity if m else None,"reason":reason} (rejected if reason else kept).append(record) return kept,rejected
@torch.no_grad()def prepare_casmi_record(raw, model, cache, bounds, ppm=10., top_formulas=10): if raw["features"]["dataset_mode"] != "casmi_autonomous": raise ValueError("Only casmi_autonomous may enumerate/formula-filter through this adapter") # Discard supplied pools/formula lists: autonomous preparation must derive its formula universe from MS physics. clean = {**raw,"features":{**raw["features"],"candidates":[],"formula_candidates":[]}} example = parse_record(clean) q = example.query formulas,enumeration = enumerate_formulas(q.precursor_mz,q.adduct,bounds,ppm) q = replace(q,formula_candidates=tuple(formulas)) _,z,_ = model.spectrum(q) fs = model.score_formulas(z,q).cpu().tolist() ordered = sorted(range(len(formulas)),key=lambda i:(-fs[i],formulas[i])) selected = [formulas[i] for i in ordered[:top_formulas]] candidates, branches = [],[] for f in selected: records,provenance = cache.formula_candidates(f) kept,rejected = filter_candidates(records,q.precursor_mz,q.adduct,f,ppm) candidates.extend({"smiles":r["smiles"],"source_id":str(r["cid"])} for r in kept) branches.append({"formula":f,"raw_count":len(records),"filtered_count":len(kept), "unique_connectivity":len({r["identity"] for r in kept}),"kept":kept,"rejected":rejected, "provenance":provenance}) final = {**raw,"features":{**raw["features"],"candidates":candidates,"formula_candidates":formulas, "formula_universe_source":"bounded_enumeration","candidate_view":"casmi_predicted_top10"}, "provenance":{"enumeration":enumeration,"selected_top_formulas":selected, "formula_scores":[{"formula":formulas[i],"score":fs[i],"rank":rank+1} for rank,i in enumerate(ordered)], "branches":branches,"sirius_used":False,"ground_truth_used_for_generation":False}} parse_record(final) return final123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127from dataclasses import dataclassimport gzipimport jsonimport mathfrom pathlib import Pathfrom typing import Optionalfrom .chemistry import ADDUCTS, Molecule, canonical_formula, identity_hash, molecule
ALLOWED_FEATURES = {"peaks", "precursor_mz", "adduct", "collision_energy", "instrument", "formula_candidates", "candidates", "dataset_mode", "candidate_view", "formula_universe_source"}MODES = {"casmi_autonomous", "casmi_fixed_pool_control", "massspecgym_official", "synthetic", "odata_training"}VIEWS = {"unspecified", "odata_oracle", "odata_predicted_top10", "msg_mass", "msg_formula", "casmi_predicted_top10", "casmi_oracle", "warmup"}
@dataclass(frozen=True)class Query: peaks: tuple precursor_mz: float adduct: str collision_energy: Optional[float] instrument: Optional[str] formula_candidates: tuple[str, ...] candidates: tuple[Molecule, ...] dataset_mode: str candidate_view: str = "unspecified" formula_universe_source: str = "candidate_pool"
@dataclass(frozen=True)class Labels: reference_smiles: str identity: str formula: str
@dataclass(frozen=True)class Example: sample_id: str query: Query labels: Optional[Labels] aliases: dict split: str
def parse_record(d): if set(d) - {"sample_id", "features", "labels", "split", "provenance"}: raise ValueError("Unknown record fields; annotations must be placed in provenance") f = d["features"] unknown = set(f) - ALLOWED_FEATURES if unknown: raise ValueError(f"Forbidden/unknown model feature fields: {sorted(unknown)}") if f.get("dataset_mode") not in MODES: raise ValueError("Explicit dataset_mode is required") mz, adduct = float(f["precursor_mz"]), f["adduct"] if not math.isfinite(mz) or mz <= 0 or adduct not in ADDUCTS: raise ValueError("Invalid experimental precursor or unsupported adduct") peaks = tuple((float(p[0]), float(p[1])) for p in f["peaks"]) if not peaks or any(not math.isfinite(x+y) or x <= 0 or y < 0 for x,y in peaks) or max(y for x,y in peaks) <= 0: raise ValueError("Spectrum must have finite positive m/z and at least one positive intensity") candidates, aliases = {}, {} for c in f["candidates"]: if not isinstance(c, dict) or set(c) - {"smiles", "source_id"}: raise ValueError("Candidates accept only smiles and opaque source_id, never score or rank") m = molecule(c["smiles"]) if m.identity not in candidates or m.smiles < candidates[m.identity].smiles: candidates[m.identity] = m aliases.setdefault(m.identity, []).append({"smiles": c["smiles"], "source_id": c.get("source_id"), "inchikey": m.inchikey}) # Tie-breaking and batching order depend only on identity, never CID or stored position. candidates = tuple(candidates[k] for k in sorted(candidates)) formulas = tuple(sorted({canonical_formula(x) for x in f.get("formula_candidates", [])})) if not formulas: formulas = tuple(sorted({m.formula for m in candidates})) missing = {m.formula for m in candidates} - set(formulas) if missing: raise ValueError(f"Candidate formulas absent from feature formula universe: {missing}") ce = f.get("collision_energy") ce = float(ce) if ce is not None else None if ce is not None and (not math.isfinite(ce) or ce < 0): raise ValueError("Invalid collision energy") view = f.get("candidate_view", "unspecified") if view not in VIEWS: raise ValueError("Unknown candidate view") labels = None if d.get("labels"): if set(d["labels"]) != {"reference_smiles"}: raise ValueError("labels must contain only reference_smiles") ref = molecule(d["labels"]["reference_smiles"]) labels = Labels(d["labels"]["reference_smiles"], ref.identity, ref.formula) for records in aliases.values(): records.sort(key=lambda r:(r["smiles"],str(r["source_id"]),r["inchikey"])) return Example(str(d["sample_id"]), Query(peaks, mz, adduct, ce, f.get("instrument"), formulas, candidates, f["dataset_mode"], view, f.get("formula_universe_source", "candidate_pool")), labels, aliases, d.get("split", "inference"))
def iter_records(path): """Stream one complete JSON object per line; rejects array exports instead of guessing schemas.""" opener = gzip.open if str(path).endswith(".gz") else open with opener(path, "rt", encoding="utf-8") as fh: for line_number, line in enumerate(fh, 1): if not line.strip(): continue try: yield parse_record(json.loads(line)) except Exception as exc: raise ValueError(f"{path}:{line_number}: {exc}") from exc
def input_manifest(examples): return {e.sample_id: {"candidate_count": len(e.query.candidates), "candidate_identity_sha256": identity_hash(e.query.candidates), "dataset_mode": e.query.dataset_mode} for e in examples}
def assert_train_isolation(train, heldout): if any(e.split != "train" or e.labels is None for e in train): raise ValueError("Training requires explicit split=train and labels") train_keys = {e.labels.identity for e in train} heldout_keys = {e.labels.identity for e in heldout if e.labels} if train_keys & heldout_keys: raise ValueError("Train/heldout connectivity overlap") training_pool_keys = {m.identity for e in train for m in e.query.candidates} if training_pool_keys & heldout_keys: raise ValueError("Training ranking pools contain heldout connectivity; construct training-only pools before training") return heldout_keyscode/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/verify_live_lineage.pyAdded+44
code/snapshot/root/code/r5_evidence_pilot_20261112/confirm.pyAdded+74
code/snapshot/root/code/r5_evidence_pilot_20261112/confirmation_protocol.jsonAdded+12
code/snapshot/root/code/r5_evidence_pilot_20261112/evidence.pyAdded+82
code/snapshot/root/code/r5_evidence_pilot_20261112/guard.pyAdded+80
code/snapshot/root/code/r5_evidence_pilot_20261112/ions.pyAdded+95
code/snapshot/root/code/r5_evidence_pilot_20261112/pilot.pyAdded+89
code/snapshot/root/code/r5_evidence_pilot_20261112/pilot_protocol.jsonAdded+9
code/snapshot/root/code/r5_evidence_pilot_20261112/test_evidence.pyAdded+47
code/snapshot/root/code/r5_evidence_pilot_20261112/test_guard.pyAdded+45
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/configs/capacity_server_v03.jsonAdded+34
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/configs/download_parallel_v041.jsonAdded+7
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/configs/epoch_server_v06.jsonAdded+47
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/configs/inbatch_server_v05.jsonAdded+35
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/configs/joint_server_v08.jsonAdded+23
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/configs/multiview_server_v02.jsonAdded+41
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/configs/offline_server_v04.jsonAdded+42
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/configs/scratch_server_v09.jsonAdded+24
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/configs/validation_suite_v071.jsonAdded+42
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/__init__.pyAdded+2
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/benchmark_epoch.pyAdded+113
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/chemistry.pyAdded+247
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/cli.pyAdded+113
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/config.pyAdded+103
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/data_v03.pyAdded+192
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/engine.pyAdded+257
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/epoch_data.pyAdded+224
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/epoch_features.pyAdded+65
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/evaluate.pyAdded+44
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/feature_store.pyAdded+77
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/forest.pyAdded+154
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/formula_v07.pyAdded+156
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/inbatch_data.pyAdded+93
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/joint_losses_v08.pyAdded+193
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/joint_model_v08.pyAdded+88
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/losses.pyAdded+110
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/model.pyAdded+275
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/model_v03.pyAdded+177
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/multiview_data.pyAdded+286
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/multiview_pools.pyAdded+166
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/multiview_train.pyAdded+265
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/negatives.pyAdded+185
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/offline_data.pyAdded+372
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/parallel_download.pyAdded+266
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/pipeline_epoch.pyAdded+94
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/prefetch.pyAdded+66
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/prepare_epoch.pyAdded+260
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/resource_guard_v09.pyAdded+19
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/retrieval.pyAdded+164
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/schema.pyAdded+127