xiaojie06 commited on
Commit
dbc2c2a
·
verified ·
1 Parent(s): 6ceae6f

Add exact model code and documentation (4/7)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/verify_live_lineage.py +44 -0
  2. code/snapshot/root/code/r5_evidence_pilot_20261112/confirm.py +74 -0
  3. code/snapshot/root/code/r5_evidence_pilot_20261112/confirmation_protocol.json +12 -0
  4. code/snapshot/root/code/r5_evidence_pilot_20261112/evidence.py +82 -0
  5. code/snapshot/root/code/r5_evidence_pilot_20261112/guard.py +80 -0
  6. code/snapshot/root/code/r5_evidence_pilot_20261112/ions.py +95 -0
  7. code/snapshot/root/code/r5_evidence_pilot_20261112/pilot.py +89 -0
  8. code/snapshot/root/code/r5_evidence_pilot_20261112/pilot_protocol.json +9 -0
  9. code/snapshot/root/code/r5_evidence_pilot_20261112/test_evidence.py +47 -0
  10. code/snapshot/root/code/r5_evidence_pilot_20261112/test_guard.py +45 -0
  11. code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/configs/capacity_server_v03.json +34 -0
  12. code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/configs/download_parallel_v041.json +7 -0
  13. code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/configs/epoch_server_v06.json +47 -0
  14. code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/configs/inbatch_server_v05.json +35 -0
  15. code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/configs/joint_server_v08.json +23 -0
  16. code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/configs/multiview_server_v02.json +41 -0
  17. code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/configs/offline_server_v04.json +42 -0
  18. code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/configs/scratch_server_v09.json +24 -0
  19. code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/configs/validation_suite_v071.json +42 -0
  20. code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/__init__.py +2 -0
  21. code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/benchmark_epoch.py +113 -0
  22. code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/chemistry.py +247 -0
  23. code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/cli.py +113 -0
  24. code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/config.py +103 -0
  25. code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/data_v03.py +192 -0
  26. code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/engine.py +257 -0
  27. code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/epoch_data.py +224 -0
  28. code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/epoch_features.py +65 -0
  29. code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/evaluate.py +44 -0
  30. code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/feature_store.py +77 -0
  31. code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/forest.py +154 -0
  32. code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/formula_v07.py +156 -0
  33. code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/inbatch_data.py +93 -0
  34. code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/joint_losses_v08.py +193 -0
  35. code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/joint_model_v08.py +88 -0
  36. code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/losses.py +110 -0
  37. code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/model.py +275 -0
  38. code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/model_v03.py +177 -0
  39. code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/multiview_data.py +286 -0
  40. code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/multiview_pools.py +166 -0
  41. code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/multiview_train.py +265 -0
  42. code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/negatives.py +185 -0
  43. code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/offline_data.py +372 -0
  44. code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/parallel_download.py +266 -0
  45. code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/pipeline_epoch.py +94 -0
  46. code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/prefetch.py +66 -0
  47. code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/prepare_epoch.py +260 -0
  48. code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/resource_guard_v09.py +19 -0
  49. code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/retrieval.py +164 -0
  50. code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/schema.py +127 -0
code/snapshot/root/code/ceir_r5_from_r4d_12000_20261112/verify_live_lineage.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Read-only inspection of the first available *formal* rolling state per arm.
2
+ Pin the inode open across rotation; this never loads a model onto the GPU.
3
+ """
4
+ import sys,time,torch
5
+ from paths5 import *
6
+ def run():
7
+ torch.set_num_threads(1)
8
+ p=Path(C['parent']);assert hashfile(p)==C['parent_sha256']
9
+ par=torch.load(p,map_location='cpu',weights_only=False);po=par['optimizer'];base=par['model']
10
+ assert par['arm']=='D' and par['progress']['update']==9000
11
+ check={}
12
+ for arm in C['arms']:
13
+ folder=ROOT/'arms'/arm/'resume'
14
+ if not (folder/'LAST.json').exists():continue
15
+ for _ in range(3):
16
+ met=read(folder/'LAST.json')
17
+ path=folder/met['file']
18
+ try:f=path.open('rb')
19
+ except FileNotFoundError:continue
20
+ break
21
+ else:raise RuntimeError('could not inspect stable checkpoint')
22
+ with f:
23
+ h=_hash(f);assert h==met['sha256'];f.seek(0);x=torch.load(f,map_location='cpu',weights_only=False)
24
+ assert x['architecture']=='CEIR_R5' and x['arm']==arm and x['binding']['parent']==C['parent_sha256']
25
+ n=x['progress']['r5_updates'];assert 0<n<=3000 and x['progress']['update']==n+9000
26
+ changed=[k for k,v in base.items() if not torch.equal(v,x['model'][k])]
27
+ assert any(k.startswith('r4.') for k in changed) and any(not k.startswith(('r2.','r3.','r4.')) for k in changed)
28
+ moments=x['optimizer'];gs=po['param_groups']
29
+ assert all(moments['param_groups'][j]['params']==g['params'] for j,g in enumerate(gs))
30
+ steps=[int(moments['state'][k]['step'])-int(v['step']) for k,v in po['state'].items() if 'step' in v]
31
+ assert max(steps)==n and min(steps)>=0
32
+ new=[k for k in x['model'] if k not in base]
33
+ assert all(k.startswith('r5.') for k in new) and bool(new)==(arm=='C')
34
+ check[arm]=dict(update=9000+n,actual_new_updates=n,rolling_sha256=h,changed_inherited_state_tensors=len(changed),
35
+ inherited_r4_duel_tensors_changed=sum(k.startswith('r4.') for k in changed),new_state_tensors=len(new),optimizer_groups=len(moments['param_groups']),
36
+ 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'])
37
+ del x
38
+ 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')
39
+ save(SMALL/'LIVE_FORMAL_LINEAGE.json',receipt);print(json.dumps(receipt))
40
+ def _hash(f):
41
+ h=hashlib.sha256()
42
+ for s in iter(lambda:f.read(4*2**20),b''):h.update(s)
43
+ return h.hexdigest()
44
+ if __name__=='__main__':run()
code/snapshot/root/code/r5_evidence_pilot_20261112/confirm.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fit on the first 384 train triples, compare on 192 new disjoint triples."""
2
+ import argparse,gzip,hashlib,json,sys
3
+ from pathlib import Path
4
+ from collections import Counter
5
+ import numpy as np
6
+ import torch
7
+ from torch.nn import functional as F
8
+ from pilot import batch,example,hashed
9
+ from evidence import ForwardEvidence
10
+ from guard import novel_evidence,apply_bounded_bonus
11
+
12
+
13
+ def fit(rows,mode,cfg):
14
+ torch.manual_seed(cfg['seed']);rng=np.random.default_rng(cfg['seed'])
15
+ model=ForwardEvidence(hidden=cfg['hidden']);opt=torch.optim.AdamW(model.parameters(),lr=cfg['learning_rate'])
16
+ for _ in range(cfg['updates_per_fold']):
17
+ rec=[rows[j] for j in rng.choice(len(rows),cfg['batch'],replace=False)]
18
+ inp,y=batch(rec);logit,cos,z=model.prototype_logits(*inp,mode)
19
+ i=torch.arange(len(y));ok=z[i,y,:-1].sum(-1).detach()>1e-9
20
+ loss=F.cross_entropy(logit,y)+cfg['lambda_positive_spectrum']*((1.-cos[i,y])*ok).sum()/ok.sum().clamp_min(1)
21
+ if not torch.isfinite(loss):raise ValueError('nonfinite')
22
+ opt.zero_grad();loss.backward()
23
+ torch.nn.utils.clip_grad_norm_(model.parameters(),5.,error_if_nonfinite=True);opt.step()
24
+ return model.eval()
25
+
26
+
27
+ def main():
28
+ ap=argparse.ArgumentParser()
29
+ for key in ['fit_data','heldout_data','r3_code','output']:ap.add_argument(key,type=Path)
30
+ args=ap.parse_args();sys.path.insert(0,str(args.r3_code.resolve()));import features_r2 as ft
31
+ here=Path(__file__).resolve().parent
32
+ cfg=json.loads((here/'pilot_protocol.json').read_text());p=json.loads((here/'confirmation_protocol.json').read_text())
33
+ a,b=[json.load(gzip.open(path,'rt')) for path in (args.fit_data,args.heldout_data)]
34
+ primary_sha=hashlib.sha256(args.fit_data.read_bytes()).hexdigest()
35
+ assert b['primary_cohort_sha256']==primary_sha
36
+ 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']}
37
+ 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
38
+ 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})
39
+ assert set(Counter(x['stratum'] for x in tb).values())=={p['heldout_per_stratum']}
40
+ torch.set_num_threads(2);torch.use_deterministic_algorithms(True)
41
+ dev={};nets={}
42
+ for kind,mode in [('legacy','absolute'),('diverse','relative')]:
43
+ 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]
44
+ nets[kind]=fit(tr,mode,cfg)
45
+ rows=[]
46
+ with torch.no_grad():
47
+ for j,r in enumerate(tb):
48
+ lh,_=batch([dev['legacy'][j]]);dh,_=batch([dev['diverse'][j]])
49
+ _,cos,z0=nets['legacy'].prototype_logits(*lh,'absolute');other,_,z1=nets['diverse'].prototype_logits(*dh,'relative')
50
+ bonus=novel_evidence(z0[0],z1[0],dh[3][0],[r['formula']]*3,r['keys'],p['saturation'])
51
+ s=cos[0];guard=apply_bounded_bonus(s,bonus,p['max_addition_on_cosine_scale'])
52
+ def rank(x):
53
+ ids=sorted(range(3),key=lambda k:(-float(x[k]),hashed('candidate-id|'+r['keys'][k])))
54
+ return ids[0],ids.index(r['positive'])+1
55
+ j0,base=rank(s);jg,safe=rank(guard);_,alt=rank(other[0])
56
+ rows.append(dict(rid=r['rid'],stratum=r['stratum'],base=base,guard=safe,expanded=alt,winning_identity_changed=j0!=jg,
57
+ any_novel=bool((bonus>0).any()),raw_base=s.tolist(),raw_bonus=bonus.tolist(),positive=r['positive'],keys=r['keys']))
58
+ def stats(rr):
59
+ 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),
60
+ 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),
61
+ any_novel=sum(r['any_novel'] for r in rr),winner_changes=sum(r['winning_identity_changed'] for r in rr))
62
+ rng=np.random.default_rng(cfg['seed']);rep=np.zeros(4000);strata=sorted({r['stratum'] for r in rows})
63
+ for group in strata:
64
+ x=np.array([int(r['guard']==1)-int(r['base']==1) for r in rows if r['stratum']==group])
65
+ rep+=x[rng.integers(len(x),size=(len(rep),len(x)))].sum(1)
66
+ out=dict(protocol=p,all=stats(rows),per_stratum={s:stats([r for r in rows if r['stratum']==s]) for s in strata},
67
+ delta_paired_descriptive_ci95_pp=(100*np.quantile(rep/len(rows),[.025,.975])).tolist(),
68
+ primary_cohort_sha256=primary_sha,confirm_sha256=hashlib.sha256(args.heldout_data.read_bytes()).hexdigest(),
69
+ key14_train_eval_overlap=len(ka&kb),official_keys_overlap=0,rows=rows)
70
+ with args.output.open('x') as f:json.dump(out,f,indent=2,allow_nan=False)
71
+ print(json.dumps(out['all']))
72
+
73
+
74
+ if __name__=='__main__':main()
code/snapshot/root/code/r5_evidence_pilot_20261112/confirmation_protocol.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "scope":"Independent train-source confirmation of a bounded physical-evidence component, not a benchmark or production R4 checkpoint",
3
+ "train_n":384,"heldout_n":192,"heldout_per_stratum":32,
4
+ "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.",
5
+ "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.",
6
+ "comparison":["legacy absolute cosine, fixed","same cosine plus a bounded novel peak bonus","expanded/relative score alone (context only)"],
7
+ "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)",
8
+ "max_addition_on_cosine_scale":0.10,"saturation":0.02,
9
+ "ties":"Stable candidate-key hash; candidate order independent of true identity.",
10
+ "primary_measure":"paired corrected vs damaged top1 count; also report score changes, winner changes, any eligible evidence, uncertainty and missing evidence; all outcomes retained",
11
+ "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."
12
+ }
code/snapshot/root/code/r5_evidence_pilot_20261112/evidence.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Trainable forward-proposal/residual prototype. No CSI/rank/reference inputs.
2
+ One candidate identity per context vote. All official entries keep base scores.
3
+ """
4
+ import torch
5
+ from torch import nn
6
+ from torch.nn import functional as F
7
+
8
+ class ForwardEvidence(nn.Module):
9
+ def __init__(self,feature_dim=24,hidden=48,adducts=6,cap=1.):
10
+ super().__init__();self.cap=cap
11
+ self.adduct=nn.Embedding(adducts,8)
12
+ self.intensity=nn.Sequential(nn.Linear(feature_dim+8,hidden),nn.SiLU(),nn.Linear(hidden,hidden),nn.SiLU(),nn.Linear(hidden,1))
13
+ self.other=nn.Linear(8,1);self.gain=nn.Parameter(torch.zeros(()))
14
+ def ion_prior(self,features,valid,adduct):
15
+ """Predict ion probabilities from molecular features and acquisition mode ONLY.
16
+ features [B,M,H,F]; padding cannot consume probability mass. Last bin is unmodelled.
17
+ """
18
+ cond=self.adduct(adduct)
19
+ ctx=cond[:,None,None,:].expand(*features.shape[:-1],-1)
20
+ logits=self.intensity(torch.cat((features,ctx),-1)).squeeze(-1).float().masked_fill(~valid,-torch.inf)
21
+ other=self.other(cond).float()[:,None,:].expand(-1,features.shape[1],-1)
22
+ return torch.cat((logits,other),-1).softmax(-1)
23
+ @staticmethod
24
+ def matched_distribution(prior,index,peak_count):
25
+ if index.shape!=prior[...,:-1].shape:raise ValueError('ion assignment shape')
26
+ hist=prior.new_zeros((*prior.shape[:-1],peak_count+1)).scatter_add(-1,index,prior[...,:-1])
27
+ return hist+F.pad(prior[...,-1:],(peak_count,0))
28
+ @staticmethod
29
+ def group_readout(hist,observed,groups):
30
+ """One query [M,P+1]. Use global formula sums, not per-compute-chunk sums.
31
+ No MxM comparisons. Singletons get zero new evidence; a common explanation
32
+ cannot distinguish two candidates. Last bin is unmatched probability.
33
+ """
34
+ evidence=hist[:,0]*0
35
+ if not observed.numel() or observed.sum().item()<=0:return evidence
36
+ for g in torch.unique(groups):
37
+ idx=(groups==g).nonzero().flatten();n=len(idx)
38
+ if n<2 or int(g)<0:continue
39
+ z=hist[idx];background=(z.sum(0)-z)/(n-1)
40
+ # Nonlinear peak-specific contrast; not an additive common formula constant.
41
+ contrast=(z[:,:-1]-background[:,:-1])/(.02+z[:,:-1]+background[:,:-1])
42
+ shift=(contrast*observed).sum(-1)+.25*(background[:,-1]-z[:,-1])
43
+ centered=shift.tanh();centered=.5*(centered-centered.mean())
44
+ evidence=evidence.index_copy(0,idx,centered)
45
+ return evidence
46
+ @staticmethod
47
+ def absolute_readout(hist,observed):
48
+ target=F.pad(observed,(0,1))
49
+ return F.cosine_similarity(hist,target.expand_as(hist),dim=-1,eps=1e-8)
50
+ def identity_scores(self,base,distribution,observed,formulas,identities):
51
+ """Reusable single-pool adapter. Aliases retain their original rank positions.
52
+ Consuming code must map the same key14 to the same canonical hypothesis bank.
53
+ """
54
+ if len(base)!=len(identities) or len(formulas)!=len(base) or len(base)!=len(distribution):raise ValueError('pool alignment')
55
+ if not len(base):return base
56
+ reps={};reverse=[];names=sorted(set(identities));pos={x:i for i,x in enumerate(names)}
57
+ for i,key in enumerate(identities):
58
+ if not key:raise ValueError('only scoreable identities in adapter')
59
+ if key in reps:
60
+ j=reps[key]
61
+ if formulas[i]!=formulas[j] or not torch.allclose(distribution[i],distribution[j],atol=1e-6,rtol=0):
62
+ raise ValueError('inconsistent alias asset; canonicalize before scoring')
63
+ else:reps[key]=i
64
+ reverse.append(pos[key])
65
+ idx=[reps[k] for k in names];fs=torch.as_tensor([formulas[i] for i in idx],device=base.device)
66
+ w=observed/observed.sum().clamp_min(1e-12)
67
+ e=self.group_readout(distribution[idx],w,fs)
68
+ return base+self.cap*self.gain.tanh()*e[reverse]
69
+ def prototype_logits(self,features,valid,indices,observed,adduct,mode):
70
+ """Mechanism-only triples (all same formula); not the production R4D score."""
71
+ prior=self.ion_prior(features,valid,adduct)
72
+ z=self.matched_distribution(prior,indices,observed.shape[-1])
73
+ t=F.pad(observed,(0,1));cos=F.cosine_similarity(z,t[:,None,:],dim=-1,eps=1e-8)
74
+ if mode=='absolute':ev=cos
75
+ elif mode=='relative':
76
+ # Vectorized equivalent of group_readout for exactly one formula per triple.
77
+ bg=(z.sum(1,keepdim=True)-z)/(z.shape[1]-1)
78
+ con=(z[:,:,:-1]-bg[:,:,:-1])/(.02+z[:,:,:-1]+bg[:,:,:-1])
79
+ u=((con*observed[:,None,:]).sum(-1)+.25*(bg[:,:,-1]-z[:,:,-1])).tanh()
80
+ ev=.5*(u-u.mean(1,keepdim=True))
81
+ else:raise ValueError(mode)
82
+ return 4*ev,cos,z
code/snapshot/root/code/r5_evidence_pilot_20261112/guard.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Inference-only new-evidence check. No truth, teacher predictions or stored ranks.
2
+
3
+ One row per distinct scoreable identity; include all competitors across compute
4
+ chunks before reducing. Do not silently treat incomplete contexts as complete.
5
+ Unscoreables keep their original status outside this adapter.
6
+ """
7
+ from collections import Counter
8
+ import torch
9
+
10
+
11
+ def novel_evidence(old_hist, new_hist, observed, formulas, ids, strength_scale=.02):
12
+ """Histograms include an unmatched bin last. Return [0,1] per molecule.
13
+
14
+ A peak may contribute only if absent from the molecule's old proposals AND
15
+ absent from EVERY other identity's old and new proposals in its formula.
16
+ """
17
+ if (old_hist.ndim!=2 or old_hist.shape!=new_hist.shape or
18
+ old_hist.shape!=(len(ids),observed.numel()+1) or len(formulas)!=len(ids)):
19
+ raise ValueError("misaligned query, isotope/adduct context or histogram")
20
+ if strength_scale<=0 or not observed.isfinite().all() or (observed<0).any():
21
+ raise ValueError("invalid observed intensities")
22
+ if not all(x is not None and x!='' for x in ids) or len(ids)!=len(set(ids)):
23
+ raise ValueError("give one canonical row per scoreable identity; broadcast aliases afterwards")
24
+ if not torch.isfinite(old_hist).all() or not torch.isfinite(new_hist).all() or (old_hist<0).any() or (new_hist<0).any():
25
+ raise ValueError("invalid evidence distribution")
26
+ w=observed/observed.sum().clamp_min(1e-12)
27
+ a,b=old_hist[:,:-1],new_hist[:,:-1]
28
+ out=b.new_zeros(len(ids))
29
+ grouped={}
30
+ for j,f in enumerate(formulas):
31
+ if f is not None and f!='' and f!=-1:grouped.setdefault(f,[]).append(j)
32
+ for js in grouped.values():
33
+ if len(js)<2:continue
34
+ # Count presence once per identity, not once per ionization channel/CID.
35
+ aj,bj=a[js],b[js]
36
+ union=(aj>0)|(bj>0)
37
+ eligible=(aj==0)&(bj>0)&(union.sum(0)==1)
38
+ out[js]=(w*eligible*(bj/(strength_scale+bj))).sum(-1)
39
+ return out
40
+
41
+
42
+ def apply_bounded_bonus(original, bonus, cap):
43
+ if cap<0 or original.shape!=bonus.shape or not torch.isfinite(bonus).all() or (bonus<0).any() or (bonus>1.00001).any():
44
+ raise ValueError("invalid bounded residual")
45
+ # A gap strictly larger than cap cannot be reversed.
46
+ return original+cap*bonus.clamp(0,1)
47
+
48
+
49
+ @torch.no_grad()
50
+ def stream_novelty(observed,formulas,ids,load,block_size=1024,strength_scale=.02):
51
+ """Exact two-pass inference; load(start,end) returns deterministic old/new
52
+ distributions for the requested slice of *unique scoreable* identities.
53
+ Count the entire formula before evaluating any block. Peak storage O((F+B)*P),
54
+ not O(N^2). The output and identity metadata require O(N).
55
+ """
56
+ n=len(ids);d=observed.numel()
57
+ if block_size<=0 or strength_scale<=0 or observed.ndim!=1 or not observed.isfinite().all() or (observed<0).any():
58
+ raise ValueError('invalid input')
59
+ if len(formulas)!=n or len(set(ids))!=n or any(k is None or k=='' for k in ids):
60
+ raise ValueError('use unique scoreable identities with aligned formulas')
61
+ counts={};sizes=Counter(f for f in formulas if f not in ('',None,-1))
62
+ w=observed/observed.sum().clamp_min(1e-12);result=observed.new_zeros(n)
63
+ for phase in (0,1):
64
+ for start in range(0,n,block_size):
65
+ end=min(start+block_size,n);a,b=load(start,end)
66
+ if (a.shape!=b.shape or a.shape!=(end-start,d+1) or a.device!=observed.device or b.device!=observed.device
67
+ or not a.isfinite().all() or not b.isfinite().all() or (a<0).any() or (b<0).any()):
68
+ raise ValueError('malformed cached hypothesis block')
69
+ a,b=a[:,:-1],b[:,:-1];groups={}
70
+ for j,f in enumerate(formulas[start:end]):
71
+ if sizes.get(f,0)>=2:groups.setdefault(f,[]).append(j)
72
+ for f,ix in groups.items():
73
+ ai,bi=a[ix],b[ix]
74
+ if not phase:
75
+ hits=((ai>0)|(bi>0)).sum(0,dtype=torch.int32)
76
+ counts[f]=(counts[f]+hits).clamp_max_(2) if f in counts else hits.clamp_max_(2)
77
+ else:
78
+ valid=(ai==0)&(bi>0)&(counts[f]==1)
79
+ result[[j+start for j in ix]]=(w*valid*(bi/(strength_scale+bi))).sum(-1)
80
+ return result
code/snapshot/root/code/r5_evidence_pilot_20261112/ions.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Candidate-only ion proposals; spectrum m/z/intensity never enters enumeration.
2
+ Frozen R3 legacy descriptor supplied by caller. Proposed layouts are hypotheses,
3
+ not experimental fragment labels. Supports the six inherited singly charged adducts.
4
+ """
5
+ from collections import defaultdict
6
+ from itertools import combinations
7
+ import numpy as np
8
+ from rdkit import Chem
9
+
10
+ ADDUCTS=('[M+H]+','[M+Na]+','[M+NH4]+','[M-H]-','[M+Cl]-','[M+FA-H]-')
11
+ FEATURE_DIM=24
12
+ def canon(smi):
13
+ m=Chem.MolFromSmiles(smi)
14
+ if m is None or Chem.GetFormalCharge(m) or any(a.GetIsotope() for a in m.GetAtoms()) or len(Chem.GetMolFrags(m))!=1:
15
+ raise ValueError('unsupported structure')
16
+ Chem.RemoveStereochemistry(m);return Chem.MolToSmiles(m,canonical=True,isomericSmiles=False)
17
+ def generate(smi,adduct,variant,ft,budget=32):
18
+ if variant not in ('legacy','diverse'):raise ValueError(variant)
19
+ s=canon(smi);m=Chem.MolFromSmiles(s);n=m.GetNumAtoms()
20
+ empty=lambda:(np.empty(0,np.float32),np.empty((0,FEATURE_DIM),np.float32),0)
21
+ if n<5 or adduct not in ADDUCTS:return empty()
22
+ atoms=list(m.GetAtoms());zs=np.array([a.GetAtomicNum() for a in atoms]);hs=np.array([a.GetTotalNumHs() for a in atoms],int)
23
+ atom_mass=np.array([ft.PT.GetMostCommonIsotopeMass(int(z)) for z in zs])+hs*ft.H
24
+ ar=np.array([a.GetIsAromatic() for a in atoms]);rin=np.array([a.IsInRing() for a in atoms])
25
+ bonds=list(m.GetBonds());edges=[(b.GetBeginAtomIdx(),b.GetEndAtomIdx()) for b in bonds]
26
+ adj=[[] for _ in atoms]
27
+ for j,(a,b) in enumerate(edges):adj[a].append((b,j));adj[b].append((a,j))
28
+ neutral=float(atom_mass.sum())
29
+ parent=ft.build(s);parts={tuple(np.flatnonzero(bits>0)) for bits,valid in zip(parent['members'],parent['valid']) if valid}
30
+ def hetero(j):return sum(zs[u] in (7,8,15,16) for u in edges[j])
31
+ if variant=='diverse':
32
+ 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]
33
+ ring_pairs=set(p for ring in m.GetRingInfo().BondRings() for p in combinations(sorted(ring),2))
34
+ # Paired cuts in the same ring, and internal fragments bounded by two
35
+ # acyclic single bonds. Fixed budgets; no spectral or label-dependent cuts.
36
+ priority=lambda pair:(sum(bonds[j].GetIsAromatic() for j in pair),-sum(hetero(j) for j in pair),pair)
37
+ cuts=[(j,) for j in bridge]+sorted(combinations(bridge,2),key=priority)[:48]+sorted(ring_pairs,key=priority)[:48]
38
+ for cut in cuts:
39
+ for comp in ft.components(n,adj,set(cut)):
40
+ if not 3<=len(comp)<=n-2:continue
41
+ aset=set(comp)
42
+ if all((edges[j][0] in aset)!=(edges[j][1] in aset) for j in cut):parts.add(tuple(comp))
43
+ # Avoid counting identical subformula masses as multiple independent peaks.
44
+ # The representative is chosen deterministically; this small prototype does
45
+ # not learn the alternative cleavage mechanisms giving the same composition.
46
+ uniq={}
47
+ for part in sorted(parts):
48
+ 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]
49
+ mass=float(atom_mass[idx].sum());h=int(hs[idx].sum());size=len(idx)
50
+ if not cut:continue
51
+ ring=sum(bonds[j].IsInRing() for j in cut);het=sum(hetero(j) for j in cut)
52
+ key=tuple(sorted(z.tolist()))+(0,h)
53
+ prio=(len(cut),sum(bonds[j].GetIsAromatic() for j in cut),-het,part)
54
+ if key in uniq and uniq[key][0]<=prio:continue
55
+ vals=[mass/600,mass/neutral,size/n,size/40,h/60,h/max(size,1)/3,
56
+ *[float((z==el).sum())/size for el in (6,7,8,15,16,9,17,35)],
57
+ ar[idx].mean(),rin[idx].mean(),len(cut)/3,ring/2,het/max(1,2*len(cut)),
58
+ float(sum(bonds[j].GetIsAromatic() for j in cut))/len(cut)]
59
+ uniq[key]=(prio, mass, h, vals)
60
+ selected=list(uniq.values())
61
+ if len(selected)>budget:
62
+ buckets=defaultdict(list)
63
+ for item in selected:buckets[min(7,int(8*item[1]/neutral))].append(item)
64
+ for b in buckets.values():b.sort(key=lambda item:item[0])
65
+ selected=[];depth=0
66
+ while len(selected)<budget:
67
+ for k in sorted(buckets):
68
+ if depth<len(buckets[k]):selected.append(buckets[k][depth])
69
+ if len(selected)==budget:break
70
+ depth+=1
71
+ ions={};offsets=[o for o in ft.ion_offsets(adduct) if o is not None]
72
+ for prio,mass,h,features in selected:
73
+ for shift in (-2,-1,0,1,2):
74
+ if h+shift<0:continue
75
+ for channel,offset in enumerate(offsets):
76
+ mz=mass+shift*ft.H+offset
77
+ if mz<=0:continue
78
+ k=round(mz,5);quality=(abs(shift),channel,prio)
79
+ if k not in ions or quality<ions[k][0]:
80
+ ions[k]=(quality,mz,features+[shift/2,float(channel),mz/600,float(adduct.endswith('-'))])
81
+ if not ions:return empty()
82
+ ordered=[ions[k] for k in sorted(ions)]
83
+ features=np.asarray([x[2] for x in ordered],np.float32);assert features.shape[1]==FEATURE_DIM
84
+ return np.array([x[1] for x in ordered],np.float32),features,len(selected)
85
+ def observed(peaks,precursor):
86
+ x=np.array(sorted(sorted(peaks,key=lambda v:(-v[1],v[0]))[:256]),float).reshape(-1,2)
87
+ if np.any(~np.isfinite(x)) or np.any(x[:,1]<0):raise ValueError('invalid spectrum')
88
+ x=x[(x[:,1]>0)&(abs(x[:,0]-precursor)>max(.05,precursor*2e-5))]
89
+ return x[:,0],np.sqrt(x[:,1])/max(1e-12,np.sqrt(x[:,1]).sum())
90
+ def assign(ions,mz):
91
+ # A theoretical ion votes for at most one experimental peak. P means off-spectrum.
92
+ if not len(mz):return np.full(len(ions),0,int)
93
+ k=np.searchsorted(mz,ions);l=np.clip(k-1,0,len(mz)-1);r=np.clip(k,0,len(mz)-1)
94
+ ix=np.where(abs(mz[l]-ions)<=abs(mz[r]-ions),l,r)
95
+ return np.where(abs(mz[ix]-ions)<=np.maximum(.02,2e-5*ions),ix,len(mz))
code/snapshot/root/code/r5_evidence_pilot_20261112/pilot.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse,collections,gzip,hashlib,json,sys,time
2
+ from pathlib import Path
3
+ import numpy as np
4
+ import torch
5
+ from torch.nn import functional as F
6
+ from evidence import ForwardEvidence
7
+ from ions import ADDUCTS,FEATURE_DIM,generate,observed,assign
8
+
9
+ def hashed(v):return hashlib.sha256(v.encode()).hexdigest()
10
+ def example(row,var,ft,K):
11
+ mz,w=observed(row['peaks'],row['precursor']);ff=[];ii=[];nn=[];counts=[]
12
+ for sm in row['smiles']:
13
+ 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))
14
+ matched=np.zeros((3,len(w)),bool)
15
+ for j,idx in enumerate(ii):
16
+ matched[j,idx[idx<len(w)]]=True
17
+ pos=row['positive'];other=matched[[j for j in range(3) if j!=pos]]
18
+ 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'],
19
+ n=nn,ions=counts,truth_any_mass=float(w@matched[pos]),have_differential=bool((other!=matched[pos]).any()),
20
+ truth_exclusive_against_both=float(w@(matched[pos]&~other.any(0))))
21
+ def batch(records,shuffled=False):
22
+ 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))
23
+ 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)
24
+ for b,r in enumerate(records):
25
+ wp=r['w']
26
+ if shuffled:wp=np.random.default_rng(int(hashed('intensity-null|'+r['rid'])[:12],16)).permutation(wp)
27
+ w[b,:len(wp)]=wp
28
+ for j,(x,ind) in enumerate(zip(r['ff'],r['ii'])):
29
+ h=len(ind);ff[b,j,:h]=x;mask[b,j,:h]=True;ii[b,j,:h]=np.where(ind<len(wp),ind,P)
30
+ 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])
31
+ def train_predict(train,dev,mode,fold,cfg):
32
+ torch.manual_seed(cfg['seed']+fold);rng=np.random.default_rng(cfg['seed']+fold)
33
+ model=ForwardEvidence(hidden=cfg['hidden']);opt=torch.optim.AdamW(model.parameters(),lr=cfg['learning_rate'])
34
+ for step in range(cfg['updates_per_fold']):
35
+ rec=[train[j] for j in rng.choice(len(train),cfg['batch'],replace=False)]
36
+ inp,y=batch(rec);logits,cos,z=model.prototype_logits(*inp,mode)
37
+ ids=torch.arange(len(y));eligible=z[ids,y,:-1].sum(-1).detach()>1e-9
38
+ loss=F.cross_entropy(logits,y)+cfg['lambda_positive_spectrum']*((1.-cos[ids,y])*eligible).sum()/eligible.sum().clamp_min(1)
39
+ if not torch.isfinite(loss):raise ValueError('nonfinite loss')
40
+ opt.zero_grad();loss.backward();torch.nn.utils.clip_grad_norm_(model.parameters(),5.,error_if_nonfinite=True);opt.step()
41
+ rows=[]
42
+ with torch.no_grad():
43
+ for start in range(0,len(dev),cfg['batch']):
44
+ rec=dev[start:start+cfg['batch']];inp,y=batch(rec);null,_=batch(rec,True)
45
+ actual,_,_=model.prototype_logits(*inp,mode);shifted,_,_=model.prototype_logits(*null,mode)
46
+ for i,r in enumerate(rec):
47
+ 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])))
48
+ 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,
49
+ 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'])))
50
+ return rows
51
+ def main():
52
+ 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)
53
+ a=ap.parse_args();sys.path.insert(0,str(a.r3_code.resolve()));import features_r2 as ft
54
+ 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']
55
+ 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
56
+ fold={};groups=sorted({r['stratum'] for r in rr})
57
+ for group in groups:
58
+ subset=sorted([r for r in rr if r['stratum']==group],key=lambda r:hashed('r5/folds/v1/'+r['rid']))
59
+ for j,r in enumerate(subset):fold[r['rid']]=j%4
60
+ torch.set_num_threads(2);torch.use_deterministic_algorithms(True);out={};diag={}
61
+ for variant in ['legacy','diverse']:
62
+ examples=[example(r,variant,ft,cfg['proposal_budget']) for r in rr]
63
+ diag[variant]=dict(mean_truth_explained_intensity=float(np.mean([s['truth_any_mass'] for s in examples])),
64
+ 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])),
65
+ 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']])))
66
+ for mode in ['absolute','relative']:
67
+ records=[]
68
+ for f in range(4):
69
+ train=[r for r in examples if fold[r['rid']]!=f];dev=[r for r in examples if fold[r['rid']]==f]
70
+ 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
71
+ records+=train_predict(train,dev,mode,f,cfg)
72
+ assert len(records)==len({v['rid'] for v in records})==384
73
+ method=variant+':'+mode
74
+ out[method]=dict(correct=sum(r['rank']==1 for r in records),intensity_null=sum(r['intensity_null_rank']==1 for r in records),
75
+ 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)
76
+ print(method,out[method]['correct'],out[method]['intensity_null'],flush=True)
77
+ old={r['rid']:r['rank'] for r in out['legacy:absolute']['rows']};pairs={}
78
+ for name,cohort in out.items():
79
+ 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']])
80
+ rng=np.random.default_rng(cfg['seed']);rep=np.zeros(3000)
81
+ for g in groups:
82
+ x=diff[strata==g];rep+=x[rng.integers(0,len(x),size=(len(rep),len(x)))].sum(1)
83
+ pairs[name]=dict(wins=int((diff==1).sum()),losses=int((diff==-1).sum()),difference_pp=100*float(diff.mean()),
84
+ paired_descriptive_ci95_pp=(100*np.quantile(rep/len(diff),[.025,.975])).tolist())
85
+ report=dict(scope=cfg['scope'],protocol=cfg,n=len(rr),cohort_sha256=hashlib.sha256(a.data.read_bytes()).hexdigest(),
86
+ key14_disjoint_across_fit_holdout=True,official_split_used_in_fit=False,budget=cfg['proposal_budget'],diagnostics=diag,
87
+ results=out,paired_vs_matched_legacy_absolute=pairs)
88
+ a.output.write_text(json.dumps(report,allow_nan=False,indent=2)+'\n')
89
+ if __name__=='__main__':main()
code/snapshot/root/code/r5_evidence_pilot_20261112/pilot_protocol.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "scope":"train-source-only CPU mechanism pilot; not an R5 benchmark result",
3
+ "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",
4
+ "split":"4 deterministic folds within each of the 6 equally sized strata; positive and all decoy keys disjoint between fit and holdout",
5
+ "arms":["legacy:absolute","legacy:relative","diverse:absolute","diverse:relative"],
6
+ "proposal_budget":32, "updates_per_fold":48, "batch":8, "seed":20261112, "hidden":32, "learning_rate":0.002, "lambda_positive_spectrum":0.15,
7
+ "ties":"Resolve exact score ties by stable hashed candidate key14 independent of labels; also count ties.",
8
+ "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."
9
+ }
code/snapshot/root/code/r5_evidence_pilot_20261112/test_evidence.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib.util,os,sys,unittest
2
+ from pathlib import Path
3
+ import numpy as np
4
+ import torch
5
+ from evidence import ForwardEvidence
6
+ from ions import generate,FEATURE_DIM,assign
7
+
8
+ class ModelChecks(unittest.TestCase):
9
+ def test_parent_exact_and_gradient(self):
10
+ m=ForwardEvidence();b=torch.tensor([.8,.7]);z=torch.tensor([[.8,.2],[.1,.9]])
11
+ out=m.identity_scores(b,z,torch.ones(1),[1,1],['a','b'])
12
+ torch.testing.assert_close(out,b,atol=0,rtol=0);out[0].backward();self.assertGreater(abs(m.gain.grad.item()),0)
13
+ def test_outside_top32_permutation_and_alias(self):
14
+ m=ForwardEvidence();m.gain.data.fill_(1)
15
+ z=torch.tensor([[.1,.9]]*39+[[.9,.1]]);base=torch.arange(40,0,-1).float()
16
+ ids=['identity-%02d'%j for j in range(40)];f=[1]*40
17
+ s=m.identity_scores(base,z,torch.ones(1),f,ids)
18
+ self.assertGreater(s[-1],base[-1]);order=list(range(39,-1,-1))
19
+ torch.testing.assert_close(m.identity_scores(base[order],z[order],torch.ones(1),f,ids[::-1]),s[order])
20
+ sb=m.identity_scores(torch.cat([base,base[-1:]]),torch.cat([z,z[-1:]]),torch.ones(1),f+[1],ids+[ids[-1]])
21
+ torch.testing.assert_close(sb[:-1],s);torch.testing.assert_close(sb[-1],s[-1])
22
+ def test_neutral_when_no_evidence_or_singleton(self):
23
+ m=ForwardEvidence();m.gain.data.fill_(1.)
24
+ b=torch.randn(3);ids=['a','b','c']
25
+ for z,w,fs in [(torch.tensor([[0.,1.]]*3),torch.ones(1),[1]*3),
26
+ (torch.tensor([[.1,.9],[.4,.6],[.3,.7]]),torch.ones(1),[1,2,-1]),
27
+ (torch.tensor([[.1,.9],[.4,.6],[.3,.7]]),torch.zeros(1),[1]*3)]:
28
+ torch.testing.assert_close(m.identity_scores(b,z,w,fs,ids),b)
29
+ def test_mass_conservation_padding_and_backward(self):
30
+ torch.manual_seed(7);m=ForwardEvidence();x=torch.randn(2,3,7,FEATURE_DIM);v=torch.ones(2,3,7,dtype=torch.bool)
31
+ 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]])
32
+ prob=m.ion_prior(x,v,ad);self.assertTrue((prob[...,:-1][~v]==0).all())
33
+ l,c,z=m.prototype_logits(x,v,idx,obs,ad,'relative')
34
+ torch.testing.assert_close(z.sum(-1),torch.ones(2,3));self.assertEqual(float(z[0,0,-1]),1.)
35
+ independent=m.group_readout(z[1],obs[1],torch.zeros(3,dtype=torch.long));torch.testing.assert_close(4*independent,l[1])
36
+ (-l[1,0]-c[1,1]).backward();self.assertGreater(m.intensity[-1].weight.grad.abs().sum(),0)
37
+ def test_ion_order_and_assignment(self):
38
+ here=Path(__file__).resolve().parent
39
+ code=Path(os.environ.get('R3_FEATURE_SOURCE',str(here.parent/'specpartition-ceir-r3-20261110/features_r2.py')))
40
+ 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)
41
+ a=generate('COc1ccc(CCO)cc1','[M+H]+','diverse',ft);b=generate('OCCc1ccc(OC)cc1','[M+H]+','diverse',ft)
42
+ np.testing.assert_array_equal(a[0],b[0]);np.testing.assert_array_equal(a[1],b[1]);self.assertGreater(len(a[0]),0)
43
+ self.assertEqual(len(a[0]),len(set(np.round(a[0].astype(float),5))));self.assertLessEqual(a[2],32)
44
+ np.testing.assert_array_equal(assign(np.array([100.,101.,103.]),np.array([100.01,100.99])),[0,1,2])
45
+ self.assertEqual(len(generate('CCCCC','unsupported','legacy',ft)[0]),0)
46
+ with self.assertRaises(ValueError):generate('[13CH3]CCCCC','[M+H]+','legacy',ft)
47
+ if __name__=='__main__':unittest.main()
code/snapshot/root/code/r5_evidence_pilot_20261112/test_guard.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+ import torch
3
+ from guard import novel_evidence,apply_bounded_bonus,stream_novelty
4
+
5
+
6
+ class GuardTests(unittest.TestCase):
7
+ def setUp(self):
8
+ self.old=torch.tensor([[.2,0.,0.,.8],[.1,0.,0.,.9],[0.,0.,.4,.6]])
9
+ self.new=torch.tensor([[.1,.2,0.,.7],[0.,0.,.2,.8],[0.,0.,.3,.7]])
10
+ self.obs=torch.tensor([.1,.6,.3]);self.form=['F','F','F'];self.ids=['a','b','c']
11
+ def test_unique_and_permutation(self):
12
+ f=novel_evidence(self.old,self.new,self.obs,self.form,self.ids)
13
+ self.assertAlmostEqual(float(f[0]),.6*.2/.22,places=6)
14
+ self.assertTrue((f[1:]==0).all())
15
+ ix=[2,0,1];g=novel_evidence(self.old[ix],self.new[ix],self.obs,self.form,[self.ids[i] for i in ix])
16
+ torch.testing.assert_close(g,f[ix])
17
+ def test_missing_and_singleton(self):
18
+ for fs,obs in [(['a','b','c'],self.obs),([None]*3,self.obs),(self.form,self.obs*0)]:
19
+ self.assertTrue((novel_evidence(self.old,self.new,obs,fs,self.ids)==0).all())
20
+ with self.assertRaises(ValueError):novel_evidence(self.old,self.new,self.obs,self.form,['a','a','c'])
21
+ def test_guaranteed_margin_and_cap(self):
22
+ s=torch.tensor([.61,.50,.49]);b=torch.tensor([0.,1.,.9])
23
+ self.assertEqual(int(apply_bounded_bonus(s,b,.1).argmax()),0)
24
+ torch.testing.assert_close(apply_bounded_bonus(s,b,0),s)
25
+ with self.assertRaises(ValueError):apply_bounded_bonus(s,torch.tensor([-1.,0.,0.]),.1)
26
+ def test_cross_formula_presence_is_not_a_same_formula_vote(self):
27
+ fs=['F','F','G']
28
+ v=novel_evidence(self.old,self.new,self.obs,fs,self.ids)
29
+ self.assertGreater(float(v[1]),0)
30
+ self.assertEqual(float(v[2]),0)
31
+ def test_stream_same_as_global_even_when_competitors_in_other_blocks(self):
32
+ f=novel_evidence(self.old,self.new,self.obs,self.form,self.ids)
33
+ for k in (1,2,20):
34
+ g=stream_novelty(self.obs,self.form,self.ids,lambda i,j:(self.old[i:j],self.new[i:j]),k)
35
+ torch.testing.assert_close(g,f)
36
+ def test_large_pool_synthetic(self):
37
+ n=33350;form=['F']*n
38
+ def load(i,j):
39
+ a=torch.zeros(j-i,3);b=torch.zeros_like(a);a[:,-1]=1;b[:,0]=.3;b[:,-1]=.7
40
+ if j==n:b[-1]=torch.tensor([.3,.2,.5])
41
+ return a,b
42
+ g=stream_novelty(torch.tensor([.4,.6]),form,list(range(n)),load,256)
43
+ self.assertEqual(int((g>0).sum()),1);self.assertAlmostEqual(float(g[-1]),.6*.2/.22,places=6)
44
+
45
+ if __name__=='__main__':unittest.main()
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/configs/capacity_server_v03.json ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "release_id": "capacity_20260909_v03",
3
+ "work_dir": "/root/autodl-tmp/SpecPartition-MS/data/multiview_20260909_v02",
4
+ "run_dir": "/root/autodl-tmp/SpecPartition-MS/runs/capacity_20260909_v03",
5
+ "proposal_formula_checkpoint": "/root/autodl-tmp/SpecPartition-MS/runs/multiview_20260909_v02/formula_selector_frozen.pt",
6
+ "seed": 20260910,
7
+ "device": "cuda:0",
8
+ "threads": 4,
9
+ "workers": 8,
10
+ "prefetch_batches": 16,
11
+ "feature_cache_dir": "/root/autodl-tmp/SpecPartition-MS/data/derived_features_v03_optimization",
12
+ "worker_restart_limit": 3,
13
+ "preparation_timeout_seconds": 600,
14
+ "batch_size": 16,
15
+ "bf16": true,
16
+ "gpu_memory_fraction": 0.55,
17
+ "min_free_gb": 8,
18
+ "model": {"dim": 256, "heads": 8, "spectrum_layers": 6, "graph_layers": 6, "max_peaks": 256},
19
+ "gated_graph": true,
20
+ "graph_chunk": 128,
21
+ "local_chunk": 64,
22
+ "max_atoms_per_microbatch": 90000,
23
+ "cuda_phase_sync": true,
24
+ "negative_budget": 64,
25
+ "global_negative_proposals": 64,
26
+ "training_candidate_cap": 256,
27
+ "ready_odata_fraction": 0.75,
28
+ "predicted_view_fraction": 0.20,
29
+ "learning_rate": 0.0001,
30
+ "teacher_refresh_steps": 100,
31
+ "checkpoint_interval": 25,
32
+ "min_rank_before_relations": 500,
33
+ "stages": {"warmup": 100, "direct": 1500, "fixed_relation": 200, "joint": 1000}
34
+ }
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/configs/download_parallel_v041.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "formula_workers": 16,
3
+ "http_connections": 4,
4
+ "min_interval_seconds": 0.26,
5
+ "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.",
6
+ "candidate_protocol": "unchanged: all required formulas, all CIDs, 500 IDs/property request, full validation; no candidate truncation"
7
+ }
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/configs/epoch_server_v06.json ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "release_id": "epoch_20260910_v06",
3
+ "work_dir": "/root/autodl-tmp/SpecPartition-MS/data/multiview_20260909_v02",
4
+ "prepared_dir": "/root/autodl-tmp/SpecPartition-MS/data/epoch_20260910_v06",
5
+ "run_dir": "/root/autodl-tmp/SpecPartition-MS/runs/epoch_20260910_v06",
6
+ "initial_checkpoint": "/root/autodl-tmp/SpecPartition-MS/backups/20260910_before_epoch_v06/inbatch_v05_last.pt",
7
+ "seed": 20260913,
8
+ "device": "cuda:0",
9
+ "threads": 4,
10
+ "prepare_workers": 6,
11
+ "workers": 2,
12
+ "prefetch_batches": 3,
13
+ "epochs": 5,
14
+ "odata_base_batch_size": 128,
15
+ "odata_batch_multiplier": 2,
16
+ "odata_batch_size": 256,
17
+ "odata_micro_batch_size": 128,
18
+ "odata_gradient_cache": false,
19
+ "msg_batch_size": 8,
20
+ "msg_views": ["msg_mass", "msg_formula"],
21
+ "msg_negative_count": 63,
22
+ "msg_negative_sampling": "uniform_without_replacement",
23
+ "small_pool_policy": "all_unique_masked_padding",
24
+ "epoch_schedule": "full_sources_interleaved_no_replacement",
25
+ "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}],
26
+ "bf16": true,
27
+ "gpu_memory_fraction": 0.85,
28
+ "min_free_gb": 32,
29
+ "model": {"dim":256,"heads":8,"spectrum_layers":6,"graph_layers":6,"max_peaks":256},
30
+ "gated_graph": true,
31
+ "graph_chunk": 128,
32
+ "local_chunk": 64,
33
+ "max_atoms_per_microbatch": 120000,
34
+ "cuda_phase_sync": false,
35
+ "negative_budget": 63,
36
+ "global_negative_proposals": 0,
37
+ "training_candidate_cap": 64,
38
+ "learning_rate": 0.0001,
39
+ "minimum_learning_rate": 0.00001,
40
+ "warmup_steps": 100,
41
+ "teacher_refresh_steps": 100,
42
+ "checkpoint_interval": 100,
43
+ "molecule_lru_size": 100000,
44
+ "pool_lru_size": 8192,
45
+ "network_disabled": true,
46
+ "epoch_stages": ["direct","fixed_relation","joint","joint","joint"]
47
+ }
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/configs/inbatch_server_v05.json ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "release_id": "inbatch_20260909_v05",
3
+ "work_dir": "/root/autodl-tmp/SpecPartition-MS/data/multiview_20260909_v02",
4
+ "run_dir": "/root/autodl-tmp/SpecPartition-MS/runs/inbatch_20260909_v05",
5
+ "initial_checkpoint": "/root/autodl-tmp/SpecPartition-MS/runs/capacity_20260909_v03/last.pt",
6
+ "seed": 20260913,
7
+ "device": "cuda:0",
8
+ "threads": 4,
9
+ "workers": 3,
10
+ "prefetch_batches": 4,
11
+ "worker_restart_limit": 2,
12
+ "preparation_timeout_seconds": 900,
13
+ "odata_batch_size": 128,
14
+ "msg_batch_size": 8,
15
+ "bf16": true,
16
+ "gpu_memory_fraction": 0.65,
17
+ "min_free_gb": 32,
18
+ "model": {"dim": 256, "heads": 8, "spectrum_layers": 6, "graph_layers": 6, "max_peaks": 256},
19
+ "gated_graph": true,
20
+ "graph_chunk": 128,
21
+ "local_chunk": 64,
22
+ "max_atoms_per_microbatch": 70000,
23
+ "cuda_phase_sync": true,
24
+ "negative_budget": 64,
25
+ "global_negative_proposals": 64,
26
+ "training_candidate_cap": 256,
27
+ "ready_odata_fraction": 0.0,
28
+ "learning_rate": 0.0001,
29
+ "teacher_refresh_steps": 100,
30
+ "checkpoint_interval": 25,
31
+ "min_msg_rank_before_relations": 500,
32
+ "stages": {"warmup": 100, "direct": 1500, "fixed_relation": 200, "joint": 1000},
33
+ "network_disabled": true,
34
+ "scope": "2800 joint optimizer updates; 358400 o_data and 22400 MSG exposures; initial continuation curriculum, not full-corpus epoch or convergence claim"
35
+ }
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/configs/joint_server_v08.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "release_id":"joint_20260911_v08","joint_v08":true,
3
+ "work_dir":"/root/autodl-tmp/SpecPartition-MS/data/multiview_20260909_v02",
4
+ "prepared_dir":"/root/autodl-tmp/SpecPartition-MS/data/epoch_20260910_v06",
5
+ "frozen_preparation_source_dir":"/root/autodl-tmp/SpecPartition-MS/releases/epoch_20260910_v06/src/specpartition_ms",
6
+ "run_dir":"/root/autodl-tmp/SpecPartition-MS/runs/joint_20260911_v08",
7
+ "initial_checkpoint":"/root/autodl-tmp/SpecPartition-MS/runs/validation_20260911_v071/formula_head/last.pt",
8
+ "initial_checkpoint_sha256":"1c51858644d965317126eff85cae66c02994a9a60a5caba9be712ce4090f7c0c",
9
+ "seed":20260913,"device":"cuda:0","threads":4,"prepare_workers":6,"workers":2,"prefetch_batches":3,
10
+ "epochs":3,"epoch_stages":["joint","joint","joint"],
11
+ "odata_base_batch_size":128,"odata_batch_multiplier":2,"odata_batch_size":256,"odata_micro_batch_size":64,"odata_gradient_cache":true,
12
+ "msg_batch_size":32,"msg_views":["msg_mass","msg_formula"],"msg_negative_count":63,
13
+ "msg_negative_sampling":"uniform_without_replacement","small_pool_policy":"all_unique_masked_padding",
14
+ "epoch_schedule":"full_sources_interleaved_no_replacement","bf16":true,"gpu_memory_fraction":0.85,"min_free_gb":32,
15
+ "model":{"dim":256,"heads":8,"spectrum_layers":6,"graph_layers":6,"max_peaks":256},
16
+ "gated_graph":true,"graph_chunk":128,"local_chunk":128,"max_atoms_per_microbatch":40000,
17
+ "negative_budget":63,"global_negative_proposals":0,"training_candidate_cap":64,"network_disabled":true,
18
+ "learning_rate":0.00003,"minimum_learning_rate":0.000003,"warmup_steps":200,"teacher_refresh_steps":100,"checkpoint_interval":100,
19
+ "molecule_lru_size":100000,"pool_lru_size":8192,"condition_bound":0.25,
20
+ "cut_queries_per_batch":2,"cut_nodes_per_query":8,"cut_epsilon":0.005,"same_formula_hard_topk":8,
21
+ "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},
22
+ "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}
23
+ }
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/configs/multiview_server_v02.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "release_id": "multiview_20260909_v02",
3
+ "work_dir": "/root/autodl-tmp/SpecPartition-MS/data/multiview_20260909_v02",
4
+ "run_dir": "/root/autodl-tmp/SpecPartition-MS/runs/multiview_20260909_v02",
5
+ "training": {
6
+ "odata": "/root/autodl-tmp/o_data_training_multispectra_20260909/release_v1/train.json",
7
+ "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"
8
+ },
9
+ "heldout": {
10
+ "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",
11
+ "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",
12
+ "casmi2022": "/root/autodl-tmp/dataset_distribution_overview_20260909/verified/casmi2022_full_metadata_reference.json"
13
+ },
14
+ "official_pools": {
15
+ "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",
16
+ "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"
17
+ },
18
+ "seed": 20260909,
19
+ "device": "cuda:0",
20
+ "threads": 4,
21
+ "stages": {"warmup_steps": 2000, "direct_steps": 10000, "fixed_relation_steps": 2000, "joint_steps": 10000},
22
+ "checkpoint_interval": 100,
23
+ "teacher_refresh_steps": 500,
24
+ "predicted_pool_refresh": "frozen post-warmup checkpoint; not test selected",
25
+ "negative_budget": 32,
26
+ "negative_proposal_budget": 128,
27
+ "training_candidate_cap": 512,
28
+ "candidate_cap_scope": "training proposals only; full stored and evaluation pools never truncated",
29
+ "pubchem_online": true,
30
+ "pubchem_max_attempts": 5,
31
+ "pubchem_min_free_gb": 12,
32
+ "train_min_free_gb": 5,
33
+ "minimum_indexed_train_rows": 1000,
34
+ "formula_policy": "training_catalog_mass_filtered",
35
+ "formula_ppm": 10.0,
36
+ "cost_weight": 0.0,
37
+ "cut_cost_tradeoff": 0.0,
38
+ "cut_epsilon": 0.005,
39
+ "training_isolation": "exclude evaluation connectivity from labels and training negative projection; official raw pools preserved",
40
+ "casmi_use": "final evaluation and oracle control only; never training or checkpoint selection"
41
+ }
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/configs/offline_server_v04.json ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "release_id": "offline_20260909_v04",
3
+ "pipeline_dir": "/root/autodl-tmp/SpecPartition-MS/data/offline_20260909_v04",
4
+ "work_dir": "/root/autodl-tmp/SpecPartition-MS/data/multiview_20260909_v02",
5
+ "run_dir": "/root/autodl-tmp/SpecPartition-MS/runs/offline_20260909_v04",
6
+ "proposal_formula_checkpoint": "/root/autodl-tmp/SpecPartition-MS/runs/multiview_20260909_v02/formula_selector_frozen.pt",
7
+ "auto_train_after_validation": true,
8
+ "property_batch_size": 500,
9
+ "pubchem_max_attempts": 5,
10
+ "download_min_free_gib": 20,
11
+ "preprocess_min_free_gib": 16,
12
+ "seed": 20260911,
13
+ "device": "cuda:0",
14
+ "threads": 4,
15
+ "workers": 4,
16
+ "prefetch_batches": 8,
17
+ "worker_restart_limit": 2,
18
+ "preparation_timeout_seconds": 1200,
19
+ "batch_size": 16,
20
+ "bf16": true,
21
+ "gpu_memory_fraction": 0.55,
22
+ "min_free_gb": 12,
23
+ "model": {"dim": 256, "heads": 8, "spectrum_layers": 6, "graph_layers": 6, "max_peaks": 256},
24
+ "gated_graph": true,
25
+ "graph_chunk": 128,
26
+ "local_chunk": 64,
27
+ "max_atoms_per_microbatch": 90000,
28
+ "cuda_phase_sync": true,
29
+ "negative_budget": 64,
30
+ "global_negative_proposals": 64,
31
+ "training_candidate_cap": 256,
32
+ "ready_odata_fraction": 0.0,
33
+ "predicted_view_fraction": 0.20,
34
+ "learning_rate": 0.0001,
35
+ "teacher_refresh_steps": 100,
36
+ "checkpoint_interval": 25,
37
+ "min_rank_before_relations": 500,
38
+ "stages": {"warmup": 100, "direct": 1500, "fixed_relation": 200, "joint": 1000},
39
+ "scope": "all eligible-source formulas downloaded; next 44800 exposures prepacked before a new initial curriculum, not a full corpus epoch",
40
+ "empty_pool_policy": "retain and audit; no invented positive, no LR or cut target without true candidate; valid LC/LF remain",
41
+ "initialization": "new independent model seed; old v03 checkpoint preserved, no silent optimizer resume"
42
+ }
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/configs/scratch_server_v09.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "release_id":"scratch_wr_20260912_v09","joint_v08":true,"scratch_v09":true,
3
+ "work_dir":"/root/autodl-tmp/SpecPartition-MS/data/multiview_20260909_v02",
4
+ "prepared_dir":"/root/autodl-tmp/SpecPartition-MS/data/epoch_20260910_v06",
5
+ "frozen_preparation_source_dir":"/root/autodl-tmp/SpecPartition-MS/releases/epoch_20260910_v06/src/specpartition_ms",
6
+ "run_dir":"/root/autodl-tmp/SpecPartition-MS/runs/scratch_wr_20260912_v09",
7
+ "initial_checkpoint":null,"initial_checkpoint_sha256":null,
8
+ "seed":20260913,"device":"cuda:0","threads":4,"prepare_workers":6,"workers":2,"prefetch_batches":3,
9
+ "epochs":3,"epoch_stages":["joint","joint","joint"],
10
+ "odata_base_batch_size":128,"odata_batch_multiplier":2,"odata_batch_size":256,"odata_micro_batch_size":64,"odata_gradient_cache":true,
11
+ "msg_batch_size":32,"msg_views":["msg_mass","msg_formula"],"msg_negative_count":63,
12
+ "msg_negative_sampling":"uniform_with_replacement","small_pool_policy":"replacement_counts_no_positive_resampling",
13
+ "epoch_schedule":"full_sources_interleaved_no_replacement","bf16":true,"gpu_memory_fraction":0.32,"min_free_gb":32,
14
+ "model":{"dim":256,"heads":8,"spectrum_layers":6,"graph_layers":6,"max_peaks":256},
15
+ "gated_graph":true,"graph_chunk":64,"local_chunk":64,"max_atoms_per_microbatch":24000,
16
+ "negative_budget":63,"global_negative_proposals":0,"training_candidate_cap":64,"network_disabled":true,
17
+ "learning_rate":0.00003,"minimum_learning_rate":0.000003,"warmup_steps":200,"teacher_refresh_steps":100,"checkpoint_interval":100,
18
+ "molecule_lru_size":100000,"pool_lru_size":8192,"condition_bound":0.25,
19
+ "cut_queries_per_batch":2,"cut_nodes_per_query":8,"cut_epsilon":0.005,"same_formula_hard_topk":8,
20
+ "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},
21
+ "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},
22
+ "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,
23
+ "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}
24
+ }
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/configs/validation_suite_v071.json ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "base_config": "formula_server_v07.json",
3
+ "release_id": "validation_20260911_v071",
4
+ "root": "/root/autodl-tmp/SpecPartition-MS",
5
+ "evaluation_root": "/root/autodl-tmp/SpecPartition-MS/evaluations/msg_val_v071_20260911",
6
+ "run_root": "/root/autodl-tmp/SpecPartition-MS/runs/validation_20260911_v071",
7
+ "seed": 20260913,
8
+ "formula_steps": 2000,
9
+ "rank_steps_per_arm": 800,
10
+ "formula_learning_rate": 0.0002,
11
+ "rank_learning_rate": 0.00001,
12
+ "evaluation_batch_views": 4,
13
+ "mces_workers": 4,
14
+ "formula_v07": {
15
+ "enabled": true, "loss_weight": 1.0,
16
+ "presence_weight": 0.2, "count_weight": 0.2,
17
+ "initial_mass_weight": 1.0, "ppm_scale": 1.0, "residual_bound": 4.0,
18
+ "ranking_presence_weight": 0.2, "ranking_count_weight": 0.2,
19
+ "hard_formula_weight": 0.2, "hard_formula_count": 8, "hard_formula_margin": 0.2
20
+ },
21
+ "matched_teacher_probe": true,
22
+ "cut_queries_per_batch": 2,
23
+ "cut_nodes_per_query": 8,
24
+ "cut_epsilon": 0.005,
25
+ "chemical_risk_weight": 0.1,
26
+ "arms": [
27
+ {"name": "direct_uniform", "phase": "direct", "strategy": "uniform", "mode": "none"},
28
+ {"name": "direct_hard", "phase": "direct", "strategy": "mixed", "mode": "none"},
29
+ {"name": "fixed_hard", "phase": "fixed_relation", "strategy": "mixed", "mode": "fixed"},
30
+ {"name": "cut_hard", "phase": "joint", "strategy": "mixed", "mode": "learned"}
31
+ ],
32
+ "selection": {
33
+ "split": "val", "primary": "mass.formula.10.micro", "tie_break": "mass.formula.1.micro",
34
+ "require_formula_top10_above_old": true,
35
+ "require_formula_top10_above_mass_prior_for_promotion": true,
36
+ "report_gain_over_abs_ppm_separately": true,
37
+ "structure_guardrail": "Both views: Top1, Top5 and Top20 >= frozen v06, MCES evaluated mean <= frozen v06; identical no-prediction denominator required",
38
+ "promotion": "Only report eligible checkpoints; never overwrite the v06/v07 checkpoints or automatically rerun Test"
39
+ },
40
+ "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.",
41
+ "scope": "Finite development pilot, not a full-corpus epoch or proven final improvement. Official Validation only; Test and CASMI forbidden. PubChem downloader untouched."
42
+ }
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ """Original research implementation. No experimental performance claims."""
2
+ __version__ = "0.1.0"
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/benchmark_epoch.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fresh-process GPU batch sweep over cached real inputs, with audited acceptance.
2
+
3
+ OOM is a failed batch trial, not authorization to omit candidates or samples.
4
+ Unknown numerical/CUDA errors stop the sweep. Benchmark weights never become
5
+ the production checkpoint; every trial loads the same preserved v05 weights.
6
+ """
7
+ import argparse
8
+ from copy import deepcopy
9
+ import json
10
+ import math
11
+ from pathlib import Path
12
+ import statistics
13
+ import subprocess
14
+ import sys
15
+ import time
16
+ import torch
17
+ from .epoch_data import PreparedReader, CachedPrefetch
18
+ from .train_epoch import make_model, joint_step, validate_training_config
19
+ from .prepare_epoch import validate
20
+ from .multiview_data import save, utc, sha
21
+
22
+
23
+ def trial(c,output):
24
+ validate_training_config(c)
25
+ validate(c,False)
26
+ torch.set_num_threads(c['threads']);torch.manual_seed(c['seed']);torch.set_float32_matmul_precision('high')
27
+ torch.cuda.set_device(c['device']);torch.cuda.set_per_process_memory_fraction(c['gpu_memory_fraction'])
28
+ model=make_model(c).to(c['device'])
29
+ state=torch.load(c['initial_checkpoint'],map_location='cpu',weights_only=True)
30
+ model.load_state_dict(state['model']);del state
31
+ teacher=deepcopy(model).eval()
32
+ for p in teacher.parameters():p.requires_grad_(False)
33
+ opt=torch.optim.AdamW(model.parameters(),lr=c['learning_rate'],weight_decay=.01,fused=True)
34
+ reader=PreparedReader(c);records=[]
35
+ # Cold + prefetch overlap + relation stages; both official views guaranteed.
36
+ steps=list(range(8))
37
+ loader=CachedPrefetch(reader,0,8)
38
+ try:
39
+ for step in steps:
40
+ tick=time.monotonic();batch=loader.get(step);wait=time.monotonic()-tick
41
+ stage=['direct','direct','direct','fixed_relation','fixed_relation','joint','joint','joint'][step]
42
+ mode={'direct':'none','fixed_relation':'fixed','joint':'learned'}[stage]
43
+ model.cfg.model.relation_mode=teacher.cfg.model.relation_mode=mode
44
+ model.train();torch.cuda.synchronize();torch.cuda.reset_peak_memory_stats();tick=time.monotonic()
45
+ diagnostics={}
46
+ result=joint_step(model,teacher,opt,batch,c,step,stage,diagnostics)
47
+ torch.cuda.synchronize();seconds=time.monotonic()-tick
48
+ samples=result.pop('samples')
49
+ record={'step':step,'stage':stage,'data_wait_seconds':wait,'compute_seconds':seconds,
50
+ 'peak_allocated_mib':torch.cuda.max_memory_allocated()/1024**2,
51
+ 'peak_reserved_mib':torch.cuda.max_memory_reserved()/1024**2,
52
+ 'false_negatives':sum(not s['negative']['positive_excluded'] for s in samples),
53
+ '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}),
54
+ 'negative_budget_valid':all(s['selected_negative_count']==min(c['msg_negative_count'],s['available_negative_count']) for s in samples),
55
+ 'padding_slots':sum(s['padding_slots'] for s in samples),
56
+ 'max_spectrum_peaks':max(len(b['example'].query.spectrum_arrays[0]) for b in batch['odata']+batch['msg']),
57
+ 'max_candidate_count':max(len(b['example'].query.candidates) for b in batch['msg']),**result}
58
+ records.append(record);print(json.dumps(record),flush=True)
59
+ checks={'finite_loss_grad':all(math.isfinite(r['loss']) and math.isfinite(r['gradient_norm_before_clip']) for r in records),
60
+ 'no_false_negatives':all(r['false_negatives']==0 for r in records),
61
+ 'both_views':all(r['both_views_in_every_spectrum'] for r in records),
62
+ 'negative_budget':all(r['negative_budget_valid'] for r in records),
63
+ 'all_stages':{r['stage'] for r in records}=={'direct','fixed_relation','joint'},
64
+ '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),
65
+ 'finite_parameters':all(torch.isfinite(p).all().item() for p in model.parameters())}
66
+ selected=records[1:]
67
+ result={'utc':utc(),'passed':all(checks.values()),'checks':checks,'config':c,'records':records,
68
+ '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),
69
+ 'peak_allocated_mib':max(r['peak_allocated_mib'] for r in records),
70
+ 'mean_data_wait_seconds':statistics.mean(r['data_wait_seconds'] for r in selected),
71
+ 'mean_compute_seconds':statistics.mean(r['compute_seconds'] for r in selected)}
72
+ save(output,result)
73
+ if not result['passed']:raise RuntimeError('Real-data acceptance checks failed')
74
+ finally:loader.close()
75
+
76
+
77
+ def sweep(c,root):
78
+ root=Path(root);root.mkdir(parents=True,exist_ok=True);validate(c,True)
79
+ results=[]
80
+ for i,runtime in enumerate(c['runtime_sweep']):
81
+ 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')
82
+ trial_config={**c,**runtime}
83
+ path=root/f'runtime_{i}.json';output=root/f'runtime_{i}_result.json'
84
+ save(path,trial_config)
85
+ with (root/f'runtime_{i}.log').open('w') as log:
86
+ proc=subprocess.run([sys.executable,'-u','-m','specpartition_ms.benchmark_epoch','--config',str(path),'--trial-output',str(output)],stdout=log,stderr=subprocess.STDOUT)
87
+ r=json.loads(output.read_text()) if output.exists() else {'passed':False,'error':'trial did not produce receipt'}
88
+ r.update(returncode=proc.returncode,runtime=runtime)
89
+ results.append(r);save(root/'batch_sweep_progress.json',{'utc':utc(),'results':results})
90
+ if not r.get('passed') and not r.get('oom'):
91
+ raise RuntimeError('Non-OOM batch acceptance failure; no automatic production launch')
92
+ candidates=[r for r in results if r.get('passed')]
93
+ if not candidates:raise RuntimeError('All larger batches failed; no automatic training launch')
94
+ best=max(candidates,key=lambda r:r['samples_per_second'])
95
+ selected={**c,**best['runtime']}
96
+ save(root/'selected_config.json',selected)
97
+ save(root/'batch_selection.json',{'utc':utc(),'reason':'highest measured real-data samples/s; user batch256/8 and both64-candidate views are never changed',
98
+ 'results':results,'selected_batch':[selected['odata_batch_size'],selected['msg_batch_size']],
99
+ 'selected_config_sha256':sha(root/'selected_config.json'),'test_set_used':False,
100
+ 'source_hashes':{p.name:sha(p) for p in Path(__file__).parent.glob('*.py')}})
101
+ return root/'selected_config.json'
102
+
103
+
104
+ if __name__=='__main__':
105
+ p=argparse.ArgumentParser();p.add_argument('--config',required=True);p.add_argument('--trial-output');p.add_argument('--sweep-dir')
106
+ a=p.parse_args();c=json.loads(Path(a.config).read_text())
107
+ if a.trial_output:
108
+ try:trial(c,a.trial_output)
109
+ except BaseException as e:
110
+ oom=isinstance(e,torch.OutOfMemoryError) or 'out of memory' in str(e).lower()
111
+ save(a.trial_output,{'utc':utc(),'passed':False,'error':repr(e),'oom':oom})
112
+ raise
113
+ else:sweep(c,a.sweep_dir)
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/chemistry.py ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Chemical identities and physics; no reference-dependent features or SIRIUS calls."""
2
+ from dataclasses import dataclass
3
+ from functools import lru_cache
4
+ import hashlib
5
+ import os
6
+ import re
7
+ import time
8
+ import numpy as np
9
+ from rdkit import Chem, DataStructs
10
+ from rdkit.Chem import Descriptors, rdFingerprintGenerator, rdMolDescriptors
11
+ from rdkit.Chem.Scaffolds import MurckoScaffold
12
+
13
+ ELEMENTS = ("C", "H", "N", "O", "P", "S", "F", "Cl", "Br", "I", "B", "Si")
14
+ MASSES = {e: Chem.GetPeriodicTable().GetMostCommonIsotopeMass(e) for e in ELEMENTS}
15
+ ELECTRON_MASS = 0.000548579909065
16
+ FP_SIZE = 2048
17
+ GENERATOR = rdFingerprintGenerator.GetMorganGenerator(radius=2, fpSize=FP_SIZE, includeChirality=False)
18
+ # Mass added to a neutral molecule, divided by absolute charge afterwards.
19
+ ADDUCTS = {
20
+ "[M+H]+": (MASSES["H"] - ELECTRON_MASS, 1),
21
+ "[M-H]-": (-MASSES["H"] + ELECTRON_MASS, -1),
22
+ "[M+Na]+": (22.989769282 - ELECTRON_MASS, 1),
23
+ "[M+NH4]+": (MASSES["N"] + 4 * MASSES["H"] - ELECTRON_MASS, 1),
24
+ "[M+Cl]-": (MASSES["Cl"] + ELECTRON_MASS, -1),
25
+ "[M+FA-H]-": (MASSES["C"] + MASSES["H"] + 2 * MASSES["O"] + ELECTRON_MASS, -1),
26
+ "[M+2H]2+": (2 * (MASSES["H"] - ELECTRON_MASS), 2),
27
+ "[M-2H]2-": (-2 * (MASSES["H"] - ELECTRON_MASS), -2),
28
+ }
29
+
30
+
31
+ def formula_counts(formula):
32
+ tokens = re.findall(r"([A-Z][a-z]?)(\d*)", formula)
33
+ if not tokens or "".join(a+b for a, b in tokens) != formula:
34
+ raise ValueError(f"Unsupported neutral formula: {formula!r}")
35
+ result = {}
36
+ for e, n in tokens:
37
+ if e not in MASSES or e in result or (n and int(n) < 1):
38
+ raise ValueError(f"Unsupported/repeated element or count: {formula}")
39
+ result[e] = int(n or 1)
40
+ return result
41
+
42
+
43
+ def canonical_formula(formula):
44
+ d = formula_counts(formula) if isinstance(formula, str) else formula
45
+ order = (["C", "H"] + sorted(set(d) - {"C", "H"})) if "C" in d else sorted(d)
46
+ return "".join(e + (str(d[e]) if d[e] != 1 else "") for e in order if d.get(e, 0))
47
+
48
+
49
+ def formula_vector(formula):
50
+ d = formula_counts(formula)
51
+ return np.array([d.get(e, 0) for e in ELEMENTS], dtype=np.float32)
52
+
53
+
54
+ def exact_mass(formula):
55
+ return sum(MASSES[e] * n for e, n in formula_counts(formula).items())
56
+
57
+
58
+ def precursor_mz(neutral_mass, adduct):
59
+ delta, charge = ADDUCTS[adduct]
60
+ return (neutral_mass + delta) / abs(charge)
61
+
62
+
63
+ def neutral_mass_from_mz(mz, adduct):
64
+ delta, charge = ADDUCTS[adduct]
65
+ return mz * abs(charge) - delta
66
+
67
+
68
+ def ppm_error(neutral_mass, mz, adduct):
69
+ if not np.isfinite(mz) or mz <= 0:
70
+ raise ValueError("experimental precursor_mz must be positive and finite")
71
+ return (precursor_mz(neutral_mass, adduct) - mz) / mz * 1e6
72
+
73
+
74
+ def bit_array(fp):
75
+ a = np.zeros(FP_SIZE, dtype=np.float32)
76
+ DataStructs.ConvertToNumpyArray(fp, a)
77
+ return a
78
+
79
+
80
+ def tanimoto(a, b):
81
+ inter = float(np.dot(a, b))
82
+ union = float(a.sum() + b.sum() - inter)
83
+ return inter / union if union else 0.0 # empties are not identical scaffolds
84
+
85
+
86
+ @dataclass(frozen=True)
87
+ class Molecule:
88
+ smiles: str
89
+ identity: str
90
+ inchikey: str
91
+ formula: str
92
+ mass: float
93
+ charge: int
94
+ mol: object
95
+ whole: np.ndarray
96
+ scaffold: np.ndarray
97
+ scaffold_smiles: str
98
+ atom_features: np.ndarray
99
+ edge_index: np.ndarray
100
+ bond_features: np.ndarray
101
+ anchors: np.ndarray
102
+
103
+ def __reduce__(self):
104
+ # Lossless wire/cache format: binary fingerprints need 256 bytes, not
105
+ # 8192 bytes each. Keep float32 in memory (uint8 dot products overflow).
106
+ return (_restore_molecule, (self.smiles, self.identity, self.inchikey,
107
+ self.formula, self.mass, self.charge, self.mol.ToBinary(),
108
+ np.packbits(self.whole.astype(np.uint8)),
109
+ np.packbits(self.scaffold.astype(np.uint8)), self.scaffold_smiles,
110
+ self.atom_features, self.edge_index, self.bond_features, self.anchors))
111
+
112
+
113
+ def _restore_molecule(smiles, identity, inchikey, formula, mass, charge, binary,
114
+ whole, scaffold, scaffold_smiles, atoms, edges, bonds, anchors):
115
+ return Molecule(smiles, identity, inchikey, formula, mass, charge, Chem.Mol(binary),
116
+ np.unpackbits(whole)[:FP_SIZE].astype(np.float32),
117
+ np.unpackbits(scaffold)[:FP_SIZE].astype(np.float32),
118
+ scaffold_smiles, atoms, edges, bonds, anchors)
119
+
120
+
121
+ ATOM_TYPES = (6, 7, 8, 9, 15, 16, 17, 35, 53, 5, 14)
122
+ ATOM_DIM = len(ATOM_TYPES) + 1 + 9
123
+ BOND_DIM = 6
124
+ ANCHOR_DIM = 128
125
+
126
+
127
+ def murcko_with_core(m):
128
+ """Track surviving atoms through scaffold extraction, without NP-hard matching.
129
+
130
+ RDKit preserves atom properties on scaffold atoms. The returned mask is the
131
+ actual extraction provenance, not an arbitrary isomorphic embedding.
132
+ """
133
+ marked=Chem.Mol(m)
134
+ prop='_specpartition_original_atom_index'
135
+ for atom in marked.GetAtoms():atom.SetIntProp(prop,atom.GetIdx())
136
+ scaffold=MurckoScaffold.GetScaffoldForMol(marked)
137
+ core=set()
138
+ for atom in scaffold.GetAtoms():
139
+ if not atom.HasProp(prop):raise ValueError('Scaffold atom provenance was not preserved')
140
+ core.add(atom.GetIntProp(prop));atom.ClearProp(prop)
141
+ return scaffold,core
142
+
143
+
144
+ _FEATURE_STORE = None
145
+
146
+
147
+ def configure_feature_store(store):
148
+ """Opt-in worker-local handle to a shared, versioned derived cache."""
149
+ global _FEATURE_STORE
150
+ _FEATURE_STORE = store
151
+
152
+
153
+ @lru_cache(maxsize=int(os.environ.get('SPECPARTITION_MOLECULE_CACHE_SIZE','8192')))
154
+ def molecule(smiles):
155
+ if _FEATURE_STORE is None:
156
+ return _calculate_molecule(smiles)
157
+ return _FEATURE_STORE.get_or_compute(smiles, _calculate_molecule)
158
+
159
+
160
+ def _calculate_molecule(smiles):
161
+ m = Chem.MolFromSmiles(smiles)
162
+ if m is None or m.GetNumAtoms() == 0:
163
+ raise ValueError(f"Invalid SMILES: {smiles!r}")
164
+ if any(a.GetIsotope() for a in m.GetAtoms()):
165
+ raise ValueError("Isotope-labelled candidates require an explicit isotope-aware adapter")
166
+ key = Chem.MolToInchiKey(m)
167
+ if not key:
168
+ raise ValueError("Cannot obtain candidate identity")
169
+ formula = canonical_formula(rdMolDescriptors.CalcMolFormula(m))
170
+ # Connectivity task: canonicalize without stereochemistry. Preserve full key separately.
171
+ Chem.RemoveStereochemistry(m)
172
+ smi = Chem.MolToSmiles(m, canonical=True, isomericSmiles=False)
173
+ m = Chem.MolFromSmiles(smi)
174
+ scaffold,core = murcko_with_core(m)
175
+ ss = Chem.MolToSmiles(scaffold)
176
+ sfp = bit_array(GENERATOR.GetFingerprint(scaffold)) if scaffold.GetNumAtoms() else np.zeros(FP_SIZE, np.float32)
177
+ # The extraction-derived core is invariant under atom renumbering and does
178
+ # not enumerate potentially explosive subgraph automorphisms.
179
+ atoms, anchors = [], np.zeros(ANCHOR_DIM, np.float32)
180
+ for a in m.GetAtoms():
181
+ onehot = [float(a.GetAtomicNum() == x) for x in ATOM_TYPES] + [float(a.GetAtomicNum() not in ATOM_TYPES)]
182
+ iscore = a.GetIdx() in core
183
+ attach = iscore and any(n.GetIdx() not in core for n in a.GetNeighbors())
184
+ atoms.append(onehot + [a.GetDegree()/4, a.GetFormalCharge()/2, float(a.GetIsAromatic()),
185
+ float(a.IsInRing()), a.GetTotalNumHs()/4, float(iscore), float(attach),
186
+ float(a.GetHybridization() == Chem.HybridizationType.SP2), a.GetMass()/100])
187
+ if attach or (not core and a.GetDegree() > 1):
188
+ env = Chem.FindAtomEnvironmentOfRadiusN(m, 2, a.GetIdx())
189
+ sub = Chem.PathToSubmol(m, env)
190
+ label = Chem.MolToSmiles(sub, canonical=True, isomericSmiles=False)
191
+ pos = int(hashlib.sha256(label.encode()).hexdigest()[:16], 16) % ANCHOR_DIM
192
+ anchors[pos] += 1
193
+ edges, bonds = [], []
194
+ for b in m.GetBonds():
195
+ f = [float(b.GetBondTypeAsDouble() == x) for x in (1, 2, 3, 1.5)]
196
+ f += [float(b.GetIsConjugated()), float(b.IsInRing())]
197
+ for u, v in ((b.GetBeginAtomIdx(), b.GetEndAtomIdx()), (b.GetEndAtomIdx(), b.GetBeginAtomIdx())):
198
+ edges.append((u, v)); bonds.append(f)
199
+ return Molecule(smi, key.split("-")[0], key, formula, Descriptors.ExactMolWt(m), Chem.GetFormalCharge(m),
200
+ m, bit_array(GENERATOR.GetFingerprint(m)), sfp, ss, np.asarray(atoms, np.float32),
201
+ np.asarray(edges, np.int64).reshape(-1, 2).T,
202
+ np.asarray(bonds, np.float32).reshape(-1, BOND_DIM), np.log1p(anchors))
203
+
204
+
205
+ def scaffold_similarity(a, b):
206
+ if not a.scaffold_smiles or not b.scaffold_smiles:
207
+ return None
208
+ return tanimoto(a.scaffold, b.scaffold)
209
+
210
+
211
+ def identity_hash(mols):
212
+ return hashlib.sha256("\n".join(sorted(m.identity for m in mols)).encode()).hexdigest()
213
+
214
+
215
+ def enumerate_formulas(mz, adduct, bounds, ppm=10.0, max_nodes=2_000_000, timeout=30.0):
216
+ """Bounded exhaustive mass enumeration. Raises on exhaustion, never silently returns a partial Top10.
217
+
218
+ Bounds are trained/validation-selected element maxima, not derived from a query's truth.
219
+ No valence heuristic is silently used. More selective chemistry can be added as an audited adapter.
220
+ """
221
+ 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()):
222
+ raise ValueError("Invalid enumeration bounds")
223
+ center = neutral_mass_from_mz(mz, adduct)
224
+ tol = mz * abs(ADDUCTS[adduct][1]) * ppm / 1e6
225
+ order = sorted(bounds, key=lambda e: -MASSES[e])
226
+ remaining = [sum(bounds[e] * MASSES[e] for e in order[i:]) for i in range(len(order)+1)]
227
+ result, visited, started = [], 0, time.monotonic()
228
+
229
+ def visit(i, mass, counts):
230
+ nonlocal visited
231
+ visited += 1
232
+ if visited > max_nodes or (visited % 1024 == 0 and time.monotonic()-started > timeout):
233
+ raise RuntimeError("Formula enumeration budget exhausted; increase bounds budget or use a faster enumerator")
234
+ if mass > center+tol or mass+remaining[i] < center-tol:
235
+ return
236
+ if i == len(order):
237
+ if counts and abs(mass-center) <= tol:
238
+ result.append(canonical_formula(counts))
239
+ return
240
+ e = order[i]
241
+ lo = max(0, int(np.ceil((center-tol-mass-remaining[i+1])/MASSES[e])))
242
+ hi = min(bounds[e], int(np.floor((center+tol-mass)/MASSES[e])))
243
+ for n in range(lo, hi+1):
244
+ visit(i+1, mass+n*MASSES[e], {**counts, **({e:n} if n else {})})
245
+ visit(0, 0.0, {})
246
+ return sorted(set(result)), {"visited_nodes": visited, "complete_within_bounds": True,
247
+ "seconds": time.monotonic()-started, "bounds": bounds}
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/cli.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ from copy import deepcopy
3
+ import json
4
+ from pathlib import Path
5
+ import sys
6
+ from .config import Config
7
+ from .engine import load_model,predict_dataset,seed_everything,train,write_json
8
+ from .forest import build_forest
9
+ from .schema import iter_records,parse_record
10
+
11
+
12
+ def main(argv=None):
13
+ p = argparse.ArgumentParser(description="SpecPartition-MS v0.1: data-independent reference implementation")
14
+ sub = p.add_subparsers(dest="command",required=True)
15
+ s = sub.add_parser("smoke",help="Generate artificial fixtures and run real CPU optimizer steps")
16
+ s.add_argument("--out",required=True); s.add_argument("--epochs",type=int,default=3)
17
+ t = sub.add_parser("train")
18
+ t.add_argument("--input",required=True);t.add_argument("--config");t.add_argument("--out",required=True)
19
+ t.add_argument("--heldout",action="append",default=[]);t.add_argument("--resume")
20
+ t.add_argument("--allow-unregistered-holdouts",action="store_true")
21
+ r = sub.add_parser("predict")
22
+ r.add_argument("--input",required=True);r.add_argument("--checkpoint",required=True);r.add_argument("--out",required=True)
23
+ r.add_argument("--device",default="cpu");r.add_argument("--bootstrap",type=int,default=1000)
24
+ a = sub.add_parser("audit-input")
25
+ a.add_argument("--input",required=True);a.add_argument("--out",required=True);a.add_argument("--config")
26
+ c = sub.add_parser("config")
27
+ c.add_argument("--out",required=True)
28
+ ab = sub.add_parser("ablation-configs")
29
+ ab.add_argument("--out",required=True);ab.add_argument("--config")
30
+ prep = sub.add_parser("prepare-casmi")
31
+ prep.add_argument("--input",required=True);prep.add_argument("--checkpoint",required=True)
32
+ prep.add_argument("--out",required=True);prep.add_argument("--cache",required=True)
33
+ prep.add_argument("--bounds",required=True,help='JSON element maxima, e.g. {"C":40,"H":80,"N":8,"O":12}')
34
+ prep.add_argument("--online",action="store_true");prep.add_argument("--ppm",type=float,default=10.)
35
+ args = p.parse_args(argv)
36
+ if args.command=="config":
37
+ write_json(args.out,Config().to_dict()); return
38
+ if args.command=="smoke":
39
+ from .synthetic import records
40
+ root = Path(args.out)
41
+ if root.exists() and any(root.iterdir()):
42
+ raise FileExistsError("Smoke output must be a new directory")
43
+ root.mkdir(parents=True,exist_ok=True)
44
+ raw = records()
45
+ with (root/"synthetic.jsonl").open("w") as fh:
46
+ for d in raw:
47
+ fh.write(json.dumps(d)+"\n")
48
+ cfg = Config()
49
+ cfg.model.dim=32;cfg.model.spectrum_layers=1;cfg.model.graph_layers=2
50
+ cfg.chemistry.whole_threshold=.30;cfg.chemistry.acyclic_threshold=.30
51
+ cfg.train.epochs=args.epochs;cfg.train.negative_budget=8;cfg.train.cut_nodes=6
52
+ examples = [parse_record(d) for d in raw]
53
+ model,diagnostics = train(examples,cfg,root/"train")
54
+ metrics = predict_dataset(model,examples,root/"inference",bootstrap=50)
55
+ write_json(root/"SMOKE_RESULT.json",{"status":"software_smoke_completed","real_benchmark":False,
56
+ "last_epoch":diagnostics,"queries":metrics["total_queries"],"checkpoint":"train/last.pt",
57
+ "warning":"Artificial peaks, training-set predictions; recall is NOT scientific evidence"})
58
+ print(json.dumps({"status":"software_smoke_completed","out":str(root)}));return
59
+ if args.command=="train":
60
+ examples = list(iter_records(args.input))
61
+ heldout = [e for path in args.heldout for e in iter_records(path)]
62
+ if not heldout and not args.allow_unregistered_holdouts and any(e.query.dataset_mode!="synthetic" for e in examples):
63
+ raise ValueError("Real training requires --heldout registry, or explicit --allow-unregistered-holdouts acknowledgement")
64
+ train(examples,Config.load(args.config),args.out,heldout,args.resume);return
65
+ if args.command=="predict":
66
+ model,_ = load_model(args.checkpoint,args.device)
67
+ seed_everything(model.cfg.train.seed,model.cfg.train.threads)
68
+ metrics = predict_dataset(model,iter_records(args.input),args.out,args.bootstrap)
69
+ print(json.dumps(metrics,indent=2));return
70
+ if args.command=="audit-input":
71
+ cfg = Config.load(args.config)
72
+ rows = []
73
+ for e in iter_records(args.input):
74
+ f = build_forest(e.query.candidates,cfg.chemistry)
75
+ rows.append({"sample_id":e.sample_id,"forest":f.to_dict(),"source_records":sum(len(x) for x in e.aliases.values())})
76
+ write_json(args.out,{"samples":rows,"count":len(rows)});return
77
+ if args.command=="ablation-configs":
78
+ cfg = Config.load(args.config)
79
+ root = Path(args.out)
80
+ if root.exists() and any(root.iterdir()):
81
+ raise FileExistsError("Ablation config output must be new")
82
+ controls = []
83
+ for mode in ("none","fixed","learned","knn","set","softpool"):
84
+ for negatives in ("static","partition"):
85
+ c = deepcopy(cfg);c.model.relation_mode=mode;c.train.negative_strategy=negatives
86
+ name = mode+"__"+negatives
87
+ write_json(root/(name+".json"),c.to_dict());controls.append(name)
88
+ for key,value in (("local_match",False),("relative_difference",False),("formula_score",False),("controller_input","metadata")):
89
+ c = deepcopy(cfg);setattr(c.model,key,value)
90
+ name = "control_"+key;write_json(root/(name+".json"),c.to_dict());controls.append(name)
91
+ write_json(root/"manifest.json",{"configs":controls,"executed":False,
92
+ "note":"knn/set/softpool are original adaptation controls, not claimed reproductions of DiffPool/MinCut/SetTransformer papers"});return
93
+ if args.command=="prepare-casmi":
94
+ from .retrieval import PubChemCache,prepare_casmi_record
95
+ model,_ = load_model(args.checkpoint)
96
+ seed_everything(model.cfg.train.seed,model.cfg.train.threads)
97
+ out = Path(args.out)
98
+ if out.exists():
99
+ raise FileExistsError(out)
100
+ out.parent.mkdir(parents=True,exist_ok=True)
101
+ cache = PubChemCache(args.cache,args.online)
102
+ try:
103
+ with open(args.input) as source,out.open("w") as dest:
104
+ for line in source:
105
+ if line.strip():
106
+ result = prepare_casmi_record(json.loads(line),model,cache,json.loads(args.bounds),args.ppm)
107
+ dest.write(json.dumps(result,allow_nan=False)+"\n");dest.flush()
108
+ finally:
109
+ cache.close()
110
+
111
+
112
+ if __name__=="__main__":
113
+ main()
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/config.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import asdict, dataclass, field
2
+ import json
3
+ from pathlib import Path
4
+
5
+
6
+ @dataclass
7
+ class ChemistryConfig:
8
+ whole_threshold: float = 0.55
9
+ scaffold_threshold: float = 0.65
10
+ acyclic_threshold: float = 0.60
11
+ max_cluster_size: int = 32
12
+ neighbors: int = 16
13
+ exact_pool_limit: int = 1024
14
+ proposal_bucket_cap: int = 128
15
+
16
+
17
+ @dataclass
18
+ class ModelConfig:
19
+ dim: int = 64
20
+ heads: int = 4
21
+ spectrum_layers: int = 2
22
+ graph_layers: int = 3
23
+ max_peaks: int = 128
24
+ local_match: bool = True
25
+ formula_score: bool = True
26
+ relative_difference: bool = True
27
+ relation_mode: str = "learned" # none/fixed/learned/knn/set/softpool
28
+ controller_input: str = "spectrum" # spectrum/metadata
29
+ residual_bound: float = 2.0
30
+
31
+
32
+ @dataclass
33
+ class TrainConfig:
34
+ seed: int = 20260908
35
+ epochs: int = 4
36
+ warmup_epochs: int = 1
37
+ learning_rate: float = 0.0003
38
+ weight_decay: float = 0.0001
39
+ negative_budget: int = 16
40
+ negative_strategy: str = "partition" # random/static/dynamic/feedback/partition
41
+ proposal_budget: int = 256
42
+ probe_size: int = 32
43
+ probe_margin: float = 0.10
44
+ teacher_refresh: int = 1
45
+ cut_nodes: int = 8
46
+ cut_epsilon: float = 0.00001
47
+ cut_cost_tradeoff: float = 0.001
48
+ cost_node_overhead: float = 16.0
49
+ temperature: float = 0.10
50
+ formula_weight: float = 0.3
51
+ contrastive_weight: float = 1.0
52
+ rank_weight: float = 1.0
53
+ cut_weight: float = 0.1
54
+ cost_weight: float = 0.001
55
+ gradient_clip: float = 5.0
56
+ threads: int = 2
57
+ device: str = "cpu"
58
+
59
+
60
+ @dataclass
61
+ class Config:
62
+ chemistry: ChemistryConfig = field(default_factory=ChemistryConfig)
63
+ model: ModelConfig = field(default_factory=ModelConfig)
64
+ train: TrainConfig = field(default_factory=TrainConfig)
65
+
66
+ def validate(self):
67
+ for name in ("whole_threshold", "scaffold_threshold", "acyclic_threshold"):
68
+ if not 0 <= getattr(self.chemistry, name) <= 1:
69
+ raise ValueError(name)
70
+ if not 1 <= self.chemistry.max_cluster_size <= 64:
71
+ raise ValueError("max_cluster_size must be in [1,64]")
72
+ if self.model.dim % self.model.heads:
73
+ raise ValueError("dim must be divisible by heads")
74
+ if self.model.relation_mode not in {"none", "fixed", "learned", "knn", "set", "softpool"}:
75
+ raise ValueError("unknown relation mode")
76
+ if self.model.controller_input not in {"spectrum", "metadata"}:
77
+ raise ValueError("unknown controller input")
78
+ if self.train.negative_strategy not in {"random", "static", "dynamic", "feedback", "partition"}:
79
+ raise ValueError("unknown negative strategy")
80
+ for n in ("epochs", "negative_budget", "proposal_budget", "probe_size", "teacher_refresh", "threads"):
81
+ if getattr(self.train, n) < 1:
82
+ raise ValueError(n + " must be positive")
83
+ if self.train.proposal_budget < max(4,self.train.negative_budget):
84
+ raise ValueError("proposal_budget must be at least max(4,negative_budget)")
85
+ if self.train.temperature <= 0 or self.train.learning_rate <= 0:
86
+ raise ValueError("temperature and learning_rate must be positive")
87
+ if self.model.max_peaks < 1 or self.chemistry.neighbors < 1 or self.chemistry.proposal_bucket_cap < 1:
88
+ raise ValueError("Peak/neighbor/proposal limits must be positive")
89
+ return self
90
+
91
+ def to_dict(self):
92
+ return asdict(self)
93
+
94
+ @classmethod
95
+ def load(cls, path=None):
96
+ if path is None:
97
+ return cls().validate()
98
+ d = json.loads(Path(path).read_text())
99
+ unknown = set(d) - {"chemistry", "model", "train"}
100
+ if unknown:
101
+ raise ValueError(f"Unknown config sections: {unknown}")
102
+ return cls(ChemistryConfig(**d.get("chemistry", {})), ModelConfig(**d.get("model", {})),
103
+ TrainConfig(**d.get("train", {}))).validate()
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/data_v03.py ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CPU-only, read-only preparation and bounded prefetch for v0.3 training.
2
+
3
+ Raw official pools and PubChem snapshots are never edited. Truth-guided
4
+ subsampling is TRAINING ONLY and never injects truth into a retrieval pool.
5
+ """
6
+ from collections import OrderedDict
7
+ from dataclasses import replace
8
+ import hashlib
9
+ import faulthandler
10
+ import json
11
+ import os
12
+ from pathlib import Path
13
+ import random
14
+ import sqlite3
15
+ import numpy as np
16
+ import torch
17
+ from rdkit import RDLogger
18
+ from .chemistry import molecule, tanimoto, configure_feature_store
19
+ from .engine import load_model
20
+ from .forest import Forest, Node, build_forest
21
+ from .multiview_data import unpacked
22
+ from .multiview_pools import FormulaCatalog, training_projection, predicted_formulas
23
+ from .multiview_train import TrainingStream
24
+ from .retrieval import filter_candidates
25
+ from .schema import parse_record
26
+
27
+
28
+ def singleton_forest(mols):
29
+ 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)}
30
+ return Forest(nodes,tuple(nodes),tuple(m.identity for m in mols),0,0,False)
31
+
32
+
33
+ def truth_guided_subset(entries, ref, cap, rng):
34
+ if cap < 1:raise ValueError('Training candidate cap must be positive')
35
+ if len(entries)<=cap:
36
+ return entries,False
37
+ pos=[e for e in entries if molecule(e['smiles']).identity==ref.identity]
38
+ negatives=[e for e in entries if molecule(e['smiles']).identity!=ref.identity]
39
+ slots=cap-len(pos)
40
+ if slots<=0:return pos[:cap],True
41
+ ordered=sorted(negatives,key=lambda e:(-tanimoto(ref.whole,molecule(e['smiles']).whole),molecule(e['smiles']).identity))
42
+ chosen=ordered[:slots//2]
43
+ used={molecule(e['smiles']).identity for e in chosen}
44
+ # One representative per scaffold; acyclic entries do not share an empty key.
45
+ seen_scaffolds=set()
46
+ for e in ordered:
47
+ m=molecule(e['smiles']);scaffold=m.scaffold_smiles or m.identity
48
+ if m.identity not in used and scaffold not in seen_scaffolds:
49
+ chosen.append(e);used.add(m.identity);seen_scaffolds.add(scaffold)
50
+ if len(chosen)>=3*slots//4:break
51
+ left=[e for e in negatives if molecule(e['smiles']).identity not in used]
52
+ chosen+=rng.sample(left,min(slots-len(chosen),len(left)))
53
+ return sorted(pos+chosen,key=lambda e:molecule(e['smiles']).identity),True
54
+
55
+
56
+ class ReadyTrainingStream(TrainingStream):
57
+ def __init__(self, config):
58
+ self.config=config
59
+ db=sqlite3.connect(f"file:{config['work_dir']}/data.sqlite?mode=ro",uri=True,timeout=30)
60
+ db.execute('PRAGMA query_only=ON')
61
+ super().__init__(db,config['seed'])
62
+ self.catalog=FormulaCatalog(db)
63
+ self.ready_formula_signature=None;self.ready_identities=[]
64
+ self.raw_cache=OrderedDict();self.projected_cache=OrderedDict()
65
+ self.frozen=None;self.frozen_hash=None
66
+ self.plan_db=None
67
+ if config.get('sampling_plan'):
68
+ self.plan_db=sqlite3.connect(f"file:{config['sampling_plan']}?mode=ro",uri=True)
69
+
70
+ def sample_ready(self, sequence):
71
+ self.rng=random.Random(self.config['seed']+sequence*10007)
72
+ if self.config.get('ready_odata_fraction',0.)==0.:
73
+ sid,body=super().sample(sequence)
74
+ return sid,body,False
75
+ ready=set(r[0] for r in self.db.execute('SELECT formula FROM formula_pools'))
76
+ signature=tuple(sorted(ready))
77
+ if signature!=self.ready_formula_signature:
78
+ self.ready_identities=[k for k in self.by_source['odata'] if self.structs[k][1] in ready]
79
+ self.ready_formula_signature=signature
80
+ if sequence%2==0 and self.ready_identities and self.rng.random()<self.config['ready_odata_fraction']:
81
+ identity=self.rng.choice(self.ready_identities)
82
+ rows=list(self.db.execute("SELECT id FROM spectra WHERE source='odata' AND identity=? AND status='eligible'",(identity,)))
83
+ sid=self.rng.choice(rows)[0]
84
+ body=self.db.execute('SELECT body FROM spectra WHERE id=?',(sid,)).fetchone()[0]
85
+ return sid,unpacked(body),True
86
+ sid,body=super().sample(sequence)
87
+ return sid,body,False
88
+
89
+ def entries(self, body, view):
90
+ if view in {'msg_mass','msg_formula'}:
91
+ raw=self.db.execute('SELECT body,sha256,count FROM official_pools WHERE view=? AND target=?',(view,body['target_smiles'])).fetchone()
92
+ 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}
93
+ predictions=[]
94
+ if view=='odata_predicted_top10':
95
+ if self.frozen is None:
96
+ path=Path(self.config['proposal_formula_checkpoint'])
97
+ self.frozen,_=load_model(path,'cpu')
98
+ self.frozen_hash=hashlib.sha256(path.read_bytes()).hexdigest()
99
+ formulas,predictions=predicted_formulas(self.frozen,body,self.catalog)
100
+ else:formulas=[body['formula']]
101
+ entries=[];branches=[];pending=[]
102
+ for f in formulas:
103
+ row=self.db.execute('SELECT body,sha256,raw_count FROM formula_pools WHERE formula=?',(f,)).fetchone()
104
+ if row is None:pending.append(f);continue
105
+ key=(f,row[1])
106
+ if key not in self.raw_cache:
107
+ self.raw_cache[key]=unpacked(row[0])['records']
108
+ if len(self.raw_cache)>8:self.raw_cache.popitem(last=False)
109
+ kept,rejected=filter_candidates(self.raw_cache[key],body['features']['precursor_mz'],body['features']['adduct'],f)
110
+ entries.extend({'smiles':r['smiles'],'source_id':str(r['cid'])} for r in kept)
111
+ branches.append({'formula':f,'raw_count':row[2],'filtered_count':len(kept),'rejected_count':len(rejected),'sha256':row[1]})
112
+ info={'status':'pending' if pending else 'ready' if entries else 'ready_empty','view':view,'formulas':formulas,
113
+ 'branches':branches,'pending':pending,'formula_predictions':predictions,
114
+ 'formula_checkpoint_sha256':self.frozen_hash if view.endswith('top10') else None,'ppm_filter_applied':True}
115
+ return (None if pending else entries),info
116
+
117
+ def plan(self, sequence, stage):
118
+ if self.plan_db is not None:
119
+ import pickle
120
+ row=self.plan_db.execute('SELECT spectrum_id,view,stage,rng FROM plan WHERE sequence=?',(sequence,)).fetchone()
121
+ if row is None or row[2]!=stage:raise RuntimeError('Frozen sample plan missing or stage mismatch')
122
+ self.rng=random.Random();self.rng.setstate(pickle.loads(row[3]))
123
+ body=unpacked(self.db.execute('SELECT body FROM spectra WHERE id=?',(row[0],)).fetchone()[0])
124
+ return row[0],body,False,row[1]
125
+ sid,body,ready_selected=self.sample_ready(sequence)
126
+ if body['source']=='msg_train':view='msg_mass' if (sequence//2)%2==0 else 'msg_formula'
127
+ else:view='odata_predicted_top10' if stage!='warmup' and self.rng.random()<self.config['predicted_view_fraction'] else 'odata_oracle'
128
+ return sid,body,ready_selected,view
129
+
130
+ def prepare(self, sequence, stage, chemistry):
131
+ sid,body,ready_selected,view=self.plan(sequence,stage)
132
+ trace_root=Path(self.config['run_dir'])/'worker_diagnostics'
133
+ trace_root.mkdir(exist_ok=True,parents=True)
134
+ (trace_root/f'worker_{os.getpid()}_query.json').write_text(json.dumps({'sequence':sequence,'spectrum_id':sid,'stage':stage,'source':body['source']}))
135
+ entries,view_info=self.entries(body,view)
136
+ if self.config.get('require_complete_pools') and (entries is None or view_info['status']=='pending'):
137
+ raise RuntimeError('Offline preparation refused unresolved PubChem pool')
138
+ ref=molecule(body['reference_smiles'])
139
+ full,projection=training_projection(entries,self.banned) if entries is not None else ([],{})
140
+ subset,sampled=truth_guided_subset(full,ref,self.config['training_candidate_cap'],self.rng)
141
+ if stage=='warmup':subset=[]
142
+ record={'sample_id':str(sid),'split':'train','labels':{'reference_smiles':body['reference_smiles']},
143
+ 'features':{**body['features'],'candidate_view':view,'candidates':subset}}
144
+ example=parse_record(record)
145
+ forest=singleton_forest(example.query.candidates) if stage in {'warmup','direct'} else build_forest(example.query.candidates,chemistry)
146
+ # Reference-guided nearest ISOMERS come from the complete projected pool,
147
+ # not the randomly capped list or an absolute Tanimoto cutoff.
148
+ isomers=[molecule(e['smiles']) for e in full if molecule(e['smiles']).identity!=ref.identity and molecule(e['smiles']).formula==ref.formula]
149
+ isomers.sort(key=lambda m:(-tanimoto(ref.whole,m.whole),m.identity))
150
+ proposed=isomers[:64]
151
+ if len(isomers)>64:proposed+=self.rng.sample(isomers[64:],min(32,len(isomers)-64))
152
+ proposed+=self.global_proposals(body,self.config['global_negative_proposals'])
153
+ proposed={m.identity:m for m in proposed if m.identity!=ref.identity and m.identity not in self.banned}
154
+ return {'example':example,'forest':forest,'ref':ref,'proposals':tuple(proposed[k] for k in sorted(proposed)),
155
+ 'independent_formulas':self.catalog.select(example.query.precursor_mz,example.query.adduct),
156
+ 'audit':{'sequence':sequence,'spectrum_id':sid,'source':body['source'],'view':view,'pool_status':view_info['status'],
157
+ 'full_projected_count':len(full),'training_candidate_count':len(subset),'sampled_pool':sampled,
158
+ 'ready_selected':ready_selected,'ready_odata_identity_count':len(self.ready_identities),
159
+ 'same_formula_proposals':sum(m.formula==ref.formula for m in proposed.values()),
160
+ 'molecule_cache':molecule.cache_info()._asdict(),
161
+ 'negative_proposal_count':len(proposed),'positive_in_original_projected_pool':any(molecule(e['smiles']).identity==ref.identity for e in full),
162
+ 'candidate_view_provenance':view_info,'projection':projection}}
163
+
164
+
165
+ _STREAM=None
166
+ _TRACE_FH=None
167
+ _STORE=None
168
+
169
+
170
+ def initialize_worker(config):
171
+ global _STREAM,_TRACE_FH,_STORE
172
+ RDLogger.DisableLog('rdApp.*');torch.set_num_threads(1)
173
+ trace_root=Path(config['run_dir'])/'worker_diagnostics';trace_root.mkdir(exist_ok=True,parents=True)
174
+ _TRACE_FH=(trace_root/f'worker_{os.getpid()}_stack.log').open('a')
175
+ faulthandler.enable(file=_TRACE_FH,all_threads=True)
176
+ if config.get('feature_cache_dir'):
177
+ from .feature_store import FeatureStore
178
+ _STORE=FeatureStore(config['feature_cache_dir'])
179
+ configure_feature_store(_STORE)
180
+ _STREAM=ReadyTrainingStream(config)
181
+
182
+
183
+ def prepare_batch(task):
184
+ batch_index,stage,chemistry=task
185
+ faulthandler.dump_traceback_later(30,repeat=True,file=_TRACE_FH)
186
+ try:
187
+ batch=[_STREAM.prepare(batch_index*_STREAM.config['batch_size']+i,stage,chemistry) for i in range(_STREAM.config['batch_size'])]
188
+ if _STORE:
189
+ _STORE.flush()
190
+ for b in batch:b['audit']['shared_feature_cache']=dict(_STORE.stats)
191
+ return batch
192
+ finally:faulthandler.cancel_dump_traceback_later()
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/engine.py ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from copy import deepcopy
2
+ from dataclasses import asdict
3
+ import hashlib
4
+ import json
5
+ from pathlib import Path
6
+ import random
7
+ import time
8
+ import numpy as np
9
+ import torch
10
+ from .chemistry import ADDUCTS, identity_hash, molecule
11
+ from .config import Config
12
+ from .evaluate import summarize
13
+ from .forest import build_forest, partition_cost
14
+ from .losses import contrastive_loss, counterfactual_targets, cut_loss, listwise_loss, positive_index
15
+ from .model import SpecPartition
16
+ from .negatives import NegativeBank, DynamicSampler, update_fixed_training_probe
17
+ from .schema import assert_train_isolation, input_manifest
18
+
19
+
20
+ def seed_everything(seed, threads=2):
21
+ random.seed(seed)
22
+ np.random.seed(seed)
23
+ torch.manual_seed(seed)
24
+ torch.set_num_threads(threads)
25
+ torch.use_deterministic_algorithms(True)
26
+
27
+
28
+ def write_json(path, value):
29
+ path = Path(path)
30
+ path.parent.mkdir(parents=True,exist_ok=True)
31
+ temp = path.with_suffix(path.suffix+".tmp")
32
+ temp.write_text(json.dumps(value,ensure_ascii=False,indent=2,allow_nan=False)+"\n")
33
+ temp.replace(path)
34
+
35
+
36
+ def training_signature(examples):
37
+ """Resume guard covers spectra, labels and pools, not only file names or counts."""
38
+ payload = []
39
+ for e in examples:
40
+ payload.append({"sample_id":e.sample_id,"split":e.split,"identity":e.labels.identity if e.labels else None,
41
+ "peaks":e.query.peaks,"precursor_mz":e.query.precursor_mz,"adduct":e.query.adduct,
42
+ "collision_energy":e.query.collision_energy,"instrument":e.query.instrument,
43
+ "formulas":e.query.formula_candidates,"pool":identity_hash(e.query.candidates)})
44
+ return hashlib.sha256(json.dumps(payload,sort_keys=True).encode()).hexdigest()
45
+
46
+
47
+ def checkpoint(path, model, optimizer, teacher, sampler, bank, epoch, data_hash):
48
+ path = Path(path)
49
+ temp = path.with_suffix(".tmp")
50
+ state = {"schema_version":1,"epoch_completed":epoch,"config":model.cfg.to_dict(),
51
+ "model":model.state_dict(),"optimizer":optimizer.state_dict(),"teacher":teacher.state_dict(),
52
+ "sampler":sampler.state_dict(),"bank_hash":bank.hash,"bank_version":bank.version,
53
+ "bank_embeddings":torch.tensor(bank.embeddings),"bank_weight_signature":bank.weight_signature,
54
+ "torch_rng":torch.get_rng_state(),"python_rng":random.getstate(),
55
+ "cuda_rng":torch.cuda.get_rng_state_all() if torch.cuda.is_available() and model.device.type=="cuda" else [],
56
+ "training_signature":data_hash}
57
+ torch.save(state,temp)
58
+ temp.replace(path)
59
+
60
+
61
+ def load_model(path, device="cpu"):
62
+ state = torch.load(path,map_location="cpu",weights_only=True)
63
+ c = state["config"]
64
+ from .config import ChemistryConfig,ModelConfig,TrainConfig
65
+ cfg = Config(ChemistryConfig(**c["chemistry"]),ModelConfig(**c["model"]),TrainConfig(**c["train"])).validate()
66
+ model = SpecPartition(cfg).to(device)
67
+ model.load_state_dict(state["model"])
68
+ model.eval()
69
+ return model,state
70
+
71
+
72
+ @torch.no_grad()
73
+ def predict_example(model, example, include_candidates=True):
74
+ started = time.monotonic()
75
+ forest = build_forest(example.query.candidates,model.cfg.chemistry)
76
+ forest_time = time.monotonic()-started
77
+ output = model(example.query,forest)
78
+ ids = forest.identities
79
+ if not torch.isfinite(output.scores).all():
80
+ raise RuntimeError("Nonfinite ranking scores; result must not be labelled completed")
81
+ scores = output.scores.cpu().tolist()
82
+ order = sorted(range(len(ids)),key=lambda i:(-scores[i],ids[i]))
83
+ fscore = output.formula_scores.cpu().tolist()
84
+ formulas = example.query.formula_candidates
85
+ forder = sorted(range(len(formulas)),key=lambda i:(-fscore[i],formulas[i]))
86
+ target = example.labels.identity if example.labels else None
87
+ rank = next((k+1 for k,i in enumerate(order) if ids[i]==target),None)
88
+ ftarget = example.labels.formula if example.labels else None
89
+ frank = next((k+1 for k,i in enumerate(forder) if formulas[i]==ftarget),None)
90
+ formula_evaluable = example.query.dataset_mode == "synthetic" or example.query.formula_universe_source in {"bounded_enumeration", "training_catalog_mass_filtered"}
91
+ if not formula_evaluable:
92
+ frank = None
93
+ cluster = {i:key for key in output.partition for i in forest.nodes[key].members}
94
+ n = len(ids)
95
+ row = {"sample_id":example.sample_id,"status":"completed" if n else "completed_empty_pool",
96
+ "dataset_mode":example.query.dataset_mode,"adduct":example.query.adduct,
97
+ "candidate_view":example.query.candidate_view,"formula_universe_source":example.query.formula_universe_source,
98
+ "formula_prediction_evaluable":formula_evaluable,
99
+ "polarity":"positive" if ADDUCTS[example.query.adduct][1]>0 else "negative",
100
+ "candidate_regime":"empty" if not n else "small" if n<=256 else "medium" if n<=2000 else "large",
101
+ "reference_identity":target,"reference_formula":ftarget,"reference_in_original_pool":target in ids if target else False,
102
+ "connectivity_rank":rank,"formula_rank":frank,"candidate_count":n,
103
+ "candidate_identity_sha256_before":identity_hash(example.query.candidates),
104
+ "candidate_identity_sha256_after":hashlib.sha256("\n".join(sorted(ids[i] for i in order)).encode()).hexdigest(),
105
+ "cluster_count":len(output.partition),"cluster_sizes":[len(forest.nodes[k].members) for k in output.partition],
106
+ "partition":{k:[ids[i] for i in forest.nodes[k].members] for k in output.partition},
107
+ "formula_predictions":[{"rank":k+1,"formula":formulas[i],"score":fscore[i]} for k,i in enumerate(forder)],
108
+ "chemistry_seconds":forest_time,"total_seconds":time.monotonic()-started,
109
+ "cost_proxy":partition_cost(forest,output.partition,model.cfg.train.cost_node_overhead),
110
+ "cost_proxy_is_measured_runtime":False,
111
+ "forest_audit":{"proposal_pairs":forest.proposal_pairs,"similarity_checks":forest.similarity_checks,
112
+ "approximate_proposals":forest.approximate_proposals},
113
+ "metric_kind":"synthetic_smoke_only" if example.query.dataset_mode=="synthetic" else "experimental_inference"}
114
+ if include_candidates:
115
+ row["ranked_candidates"] = [{"rank":k+1,"identity":ids[i],"smiles":example.query.candidates[i].smiles,
116
+ "formula":example.query.candidates[i].formula,"score":scores[i],"base_score":float(output.encoded.base[i]),
117
+ "direct_score":float(output.direct_scores[i]),"formula_contribution":float(output.encoded.base[i]-output.direct_scores[i]),
118
+ "relation_residual":float(output.residual[i]),"cluster":cluster[i],"aliases":example.aliases[ids[i]]} for k,i in enumerate(order)]
119
+ if row["candidate_identity_sha256_before"] != row["candidate_identity_sha256_after"]:
120
+ raise RuntimeError("Candidate identity changed during ranking")
121
+ return row
122
+
123
+
124
+ def train(examples, cfg, run_dir, heldout=(), resume=None, stop_after_epoch=None):
125
+ cfg.validate()
126
+ seed_everything(cfg.train.seed,cfg.train.threads)
127
+ banned = assert_train_isolation(examples,heldout)
128
+ if not examples or len({e.sample_id for e in examples}) != len(examples):
129
+ raise ValueError("Training sample IDs must be nonempty and unique")
130
+ run_dir = Path(run_dir)
131
+ if run_dir.exists() and any(run_dir.iterdir()) and resume is None:
132
+ raise FileExistsError("Run directory must be new; use --resume explicitly")
133
+ run_dir.mkdir(parents=True,exist_ok=True)
134
+ model = SpecPartition(cfg).to(cfg.train.device)
135
+ optimizer = torch.optim.AdamW(model.parameters(),lr=cfg.train.learning_rate,weight_decay=cfg.train.weight_decay)
136
+ teacher = deepcopy(model).eval()
137
+ for p in teacher.parameters():
138
+ p.requires_grad_(False)
139
+ bank = NegativeBank.from_training(examples,banned)
140
+ sampler = DynamicSampler(cfg.train)
141
+ data_hash = training_signature(examples)
142
+ start_epoch = 0
143
+ if resume:
144
+ state = torch.load(resume,map_location="cpu",weights_only=True)
145
+ if state["config"] != cfg.to_dict() or state["training_signature"] != data_hash or state["bank_hash"] != bank.hash:
146
+ raise ValueError("Resume config, training content or bank mismatch")
147
+ model.load_state_dict(state["model"])
148
+ optimizer.load_state_dict(state["optimizer"])
149
+ teacher.load_state_dict(state["teacher"])
150
+ sampler.load_state_dict(state["sampler"])
151
+ bank.embeddings = state["bank_embeddings"].numpy()
152
+ bank.version,bank.weight_signature = state["bank_version"],state["bank_weight_signature"]
153
+ torch.set_rng_state(state["torch_rng"])
154
+ random.setstate(state["python_rng"])
155
+ if state["cuda_rng"] and model.device.type=="cuda":
156
+ torch.cuda.set_rng_state_all(state["cuda_rng"])
157
+ start_epoch = state["epoch_completed"]+1
158
+ write_json(run_dir/"config.json",cfg.to_dict())
159
+ write_json(run_dir/"input_manifest.json",input_manifest(examples))
160
+ write_json(run_dir/"provenance.json",{"project":"SpecPartition-MS","version":"0.1.0","training_signature":data_hash,
161
+ "bank_identity_sha256":bank.hash,"heldout_registry_targets":len(banned),"torch":torch.__version__,
162
+ "numpy":np.__version__,"device":str(model.device),"real_data_training":not all(e.query.dataset_mode=="synthetic" for e in examples),
163
+ "sirius_feature_dependency":False,"resume_boundary":"epoch", "data_isolation_scope":"provided heldout registry only"})
164
+ forests = {e.sample_id:build_forest(e.query.candidates,cfg.chemistry) for e in examples}
165
+ valid_f = sum(e.labels.formula in e.query.formula_candidates for e in examples)
166
+ valid_r = sum(e.labels.identity in forests[e.sample_id].identities for e in examples)
167
+ last_summary = None
168
+ for epoch in range(start_epoch,cfg.train.epochs):
169
+ started = time.monotonic()
170
+ warmup = epoch < cfg.train.warmup_epochs
171
+ if bank.embeddings is None or epoch % cfg.train.teacher_refresh == 0:
172
+ teacher.load_state_dict(model.state_dict())
173
+ teacher.eval()
174
+ bank.refresh(teacher)
175
+ probe = update_fixed_training_probe(sampler,teacher,examples,bank)
176
+ write_json(run_dir/f"probe_epoch_{epoch:03d}.json",probe)
177
+ targets = {}
178
+ for e in examples:
179
+ targets[e.sample_id] = [] if warmup or cfg.model.relation_mode!="learned" else counterfactual_targets(
180
+ teacher,e.query,forests[e.sample_id],e.labels.identity,cfg.train.cut_nodes,cfg.train.cut_epsilon,
181
+ cfg.train.cut_cost_tradeoff,cfg.train.cost_node_overhead,offset=epoch*cfg.train.cut_nodes)
182
+ valid_cut = sum(bool(t) for t in targets.values())
183
+ write_json(run_dir/f"counterfactual_epoch_{epoch:03d}.json",{k:[asdict(t) for t in ts] for k,ts in targets.items()})
184
+ totals = {k:0. for k in ("formula","contrastive","rank","cut","cost","total")}
185
+ steps, gradient_norms = [], []
186
+ model.train()
187
+ order = torch.randperm(len(examples)).tolist()
188
+ for position in order:
189
+ e = examples[position]
190
+ forest = forests[e.sample_id]
191
+ optimizer.zero_grad(set_to_none=True)
192
+ output = model(e.query,forest)
193
+ ref = molecule(e.labels.reference_smiles)
194
+ with torch.no_grad():
195
+ tenc = teacher.encode(e.query)
196
+ partition = teacher.select_partition(tenc,forest)
197
+ indices,audit = sampler.sample(e.query,ref,bank,tenc.z_query.cpu().numpy(),epoch,forest,partition)
198
+ _,_,z = model.encode_molecules([ref]+[bank.molecules[i] for i in indices])
199
+ lc = contrastive_loss(output.encoded.z_query,z[0],z[1:],cfg.train.temperature)
200
+ fp = positive_index(e.query.formula_candidates,e.labels.formula)
201
+ rp = positive_index(forest.identities,e.labels.identity)
202
+ lf,mf = listwise_loss(output.formula_scores,fp)
203
+ lr,mr = listwise_loss(output.scores,rp)
204
+ lcut,ncut = cut_loss(model,output.encoded,forest,targets[e.sample_id])
205
+ cost = output.expected_cost if cfg.model.relation_mode=="learned" else output.encoded.q.sum()*0.
206
+ # Separate valid-example denominators; missing truth is not added to the formal pool.
207
+ n = len(examples)
208
+ loss = cfg.train.formula_weight*lf*n/max(1,valid_f)+cfg.train.contrastive_weight*lc
209
+ if not warmup:
210
+ loss = loss+cfg.train.rank_weight*lr*n/max(1,valid_r)
211
+ loss = loss+cfg.train.cut_weight*lcut*n/max(1,valid_cut)+cfg.train.cost_weight*cost
212
+ if not torch.isfinite(loss):
213
+ raise RuntimeError(f"Nonfinite loss at {e.sample_id}")
214
+ loss.backward()
215
+ grad = torch.nn.utils.clip_grad_norm_(model.parameters(),cfg.train.gradient_clip,error_if_nonfinite=True)
216
+ optimizer.step()
217
+ values = {"formula":float(lf.detach()),"contrastive":float(lc.detach()),"rank":float(lr.detach()),
218
+ "cut":float(lcut.detach()),"cost":float(cost.detach()),"total":float(loss.detach())}
219
+ for k,v in values.items():
220
+ totals[k] += v
221
+ gradient_norms.append(float(grad))
222
+ step = {"epoch":epoch,"sample_id":e.sample_id,"stage":"warmup" if warmup else "joint",
223
+ "losses":values,"formula_valid":mf,"rank_valid":mr,"cut_targets":ncut,
224
+ "negative_audit":audit,"partition_sizes":[len(forest.nodes[k].members) for k in output.partition]}
225
+ steps.append(step)
226
+ with (run_dir/"progress.jsonl").open("a") as fh:
227
+ fh.write(json.dumps(step,allow_nan=False)+"\n")
228
+ last_summary = {"epoch":epoch,"seconds":time.monotonic()-started,"stage":"warmup" if warmup else "joint",
229
+ "conditional_mean_losses":{k:totals[k]/max(1,denom) for k,denom in
230
+ (("formula",valid_f),("rank",valid_r),("contrastive",len(examples)),("cut",valid_cut),("cost",len(examples)),("total",len(examples)))},
231
+ "valid_examples":{"formula":valid_f,"rank":valid_r,"contrastive":len(examples),"cut":valid_cut},
232
+ "max_gradient_norm_before_clip":max(gradient_norms),"bank_version":bank.version,
233
+ "checkpoint":"last.pt","metric_kind":"training_diagnostics_not_test_performance"}
234
+ write_json(run_dir/f"epoch_{epoch:03d}.json",last_summary)
235
+ checkpoint(run_dir/"last.pt",model,optimizer,teacher,sampler,bank,epoch,data_hash)
236
+ print(json.dumps(last_summary),flush=True)
237
+ if stop_after_epoch is not None and epoch >= stop_after_epoch:
238
+ break
239
+ model.eval()
240
+ return model,last_summary
241
+
242
+
243
+ def predict_dataset(model, examples, output_dir, bootstrap=0):
244
+ output_dir = Path(output_dir)
245
+ output_dir.mkdir(parents=True,exist_ok=True)
246
+ if (output_dir/"predictions.jsonl").exists():
247
+ raise FileExistsError("Prediction output exists; choose a new output directory")
248
+ rows = []
249
+ with (output_dir/"predictions.jsonl").open("w") as fh:
250
+ for e in examples:
251
+ row = predict_example(model,e)
252
+ fh.write(json.dumps(row,allow_nan=False)+"\n")
253
+ rows.append({k:v for k,v in row.items() if k not in {"ranked_candidates","partition","formula_predictions"}})
254
+ metrics = summarize(rows,bootstrap)
255
+ metrics["metric_kind"] = "synthetic_smoke_only" if rows and all(r["metric_kind"]=="synthetic_smoke_only" for r in rows) else "experimental_inference"
256
+ write_json(output_dir/"metrics.json",metrics)
257
+ return metrics
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/epoch_data.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Full-corpus epochs over immutable features. No RDKit featurizing or forest building."""
2
+ from collections import defaultdict, Counter
3
+ from concurrent.futures import ThreadPoolExecutor
4
+ from dataclasses import replace
5
+ from functools import lru_cache
6
+ import math
7
+ from pathlib import Path
8
+ import random
9
+ import threading
10
+ import numpy as np
11
+ from .epoch_features import loads
12
+ from .prepare_epoch import readonly
13
+ from .inbatch_data import view_for_batch
14
+ from .schema import Example, Labels
15
+ from .forest import Forest,Node
16
+
17
+
18
+ def restrict_forest(full, mols):
19
+ """Induce a subtree from a cached complete-link forest, without reclustering.
20
+
21
+ Removing members preserves diameter constraints. Recalculate statistics and
22
+ medoids on retained members from cached fingerprints; no RDKit operations.
23
+ """
24
+ idx={m.identity:i for i,m in enumerate(mols)};nodes={}
25
+ if mols:
26
+ x=np.stack([m.whole for m in mols]);intersection=x@x.T;size=x.sum(1)
27
+ union=size[:,None]+size[None,:]-intersection
28
+ sims=np.divide(intersection.astype(np.float64),union,out=np.zeros_like(intersection,dtype=np.float64),where=union>0)
29
+ def visit(key):
30
+ n=full.nodes[key]
31
+ members=tuple(idx[full.identities[i]] for i in n.members if full.identities[i] in idx)
32
+ if not members:return None
33
+ children=tuple(k for k in (visit(k) for k in n.children) if k is not None)
34
+ if len(children)==1:return children[0]
35
+ if len(members)==1:
36
+ i=members[0];stats=(0.,1.,1.,0.,float(not mols[i].scaffold_smiles));medoid=i
37
+ else:
38
+ ws=[sims[x,y] for p,x in enumerate(members) for y in members[p+1:]]
39
+ 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])))
40
+ medoid=min(members,key=lambda x:(-sum(sims[x,y] for y in members if x!=y),mols[x].identity))
41
+ nodes[key]=Node(key,members,children,stats,medoid);return key
42
+ roots=tuple(k for k in (visit(k) for k in full.roots) if k is not None)
43
+ f=Forest(nodes,roots,tuple(m.identity for m in mols),0,0,full.approximate_proposals)
44
+ f.validate(roots);return f
45
+
46
+
47
+ def sample_view_ids(pool, identity, get_mol, negatives, rng):
48
+ pairs=list(zip(pool['molecule_ids'],pool['forest'].identities))
49
+ pos=[mid for mid,key in pairs if key==identity]
50
+ if len(pos)!=1:raise ValueError('Official training pool must contain exactly one true connectivity; no injection allowed')
51
+ neg=[mid for mid,key in pairs if key!=identity]
52
+ selected=pos+rng.sample(neg,min(negatives,len(neg)))
53
+ # Identity order is label-blind; the positive has no reserved model position.
54
+ keys=dict(pairs)
55
+ selected.sort(key=keys.__getitem__)
56
+ mask=np.arange(negatives+1)<len(selected)
57
+ return selected,mask,len(neg)
58
+
59
+
60
+ def sample_view_with_replacement(pool, identity, negatives, rng):
61
+ """Draw negative slots with replacement; encode each connectivity once.
62
+
63
+ Counts are LOSS-ONLY metadata. They are never features of a query or forest.
64
+ The positive occurs once and can never be drawn as a negative.
65
+ """
66
+ pairs=list(zip(pool['molecule_ids'],pool['forest'].identities))
67
+ if len({key for _,key in pairs})!=len(pairs):
68
+ raise ValueError('Sampling requires unique connectivity in official pool')
69
+ pos=[mid for mid,key in pairs if key==identity]
70
+ if len(pos)!=1:raise ValueError('Official training positive must exist exactly once')
71
+ if negatives<1:raise ValueError('Positive negative draw budget required')
72
+ neg=[mid for mid,key in pairs if key!=identity]
73
+ draws=rng.choices(neg,k=negatives) if neg else []
74
+ counts=Counter(pos+draws);keys=dict(pairs)
75
+ selected=sorted(counts,key=keys.__getitem__)
76
+ multiplicities=tuple(counts[mid] for mid in selected)
77
+ mask=np.arange(negatives+1)<1+len(draws)
78
+ return selected,mask,len(neg),multiplicities
79
+
80
+
81
+ class EpochPlan:
82
+ def __init__(self, ids, c):
83
+ self.ids = {s:np.asarray(sorted(v),dtype=np.int64) for s,v in ids.items()}
84
+ self.c=c
85
+ self.sizes={'odata':c['odata_batch_size'],'msg_train':c['msg_batch_size']}
86
+ if any(v<1 for v in self.sizes.values()) or c['epochs']<1: raise ValueError('Invalid epoch/batch configuration')
87
+ self.steps_per_epoch=max(math.ceil(len(v)/self.sizes[s]) for s,v in self.ids.items())
88
+ self.batch_counts={s:math.ceil(len(v)/self.sizes[s]) for s,v in self.ids.items()}
89
+ self.total=self.steps_per_epoch*c['epochs']
90
+
91
+ @lru_cache(maxsize=2)
92
+ def order(self, epoch, source):
93
+ a=self.ids[source].copy()
94
+ np.random.default_rng(self.c['seed']+epoch*100003+(17 if source=='odata' else 31)).shuffle(a)
95
+ return a
96
+
97
+ def batch_ids(self, step, source):
98
+ epoch, offset=divmod(step,self.steps_per_epoch)
99
+ n=self.sizes[source]
100
+ before=offset*self.batch_counts[source]//self.steps_per_epoch
101
+ after=(offset+1)*self.batch_counts[source]//self.steps_per_epoch
102
+ if before==after:return []
103
+ return self.order(epoch,source)[before*n:after*n].tolist()
104
+
105
+ def sequence(self, step, source, i):
106
+ epoch,offset=divmod(step,self.steps_per_epoch)
107
+ batch=offset*self.batch_counts[source]//self.steps_per_epoch
108
+ return epoch*len(self.ids[source])+batch*self.sizes[source]+i
109
+
110
+
111
+ class PreparedReader:
112
+ def __init__(self,c):
113
+ self.c=c; self.path=Path(c['prepared_dir'])/'prepared.sqlite'; self.local=threading.local()
114
+ db=self.db
115
+ self.plan=EpochPlan({s:[r[0] for r in db.execute('SELECT id FROM spectra WHERE source=? ORDER BY id',(s,))]
116
+ for s in ('odata','msg_train')},c)
117
+ self.structs={}; self.by_formula=defaultdict(list)
118
+ 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'):
119
+ self.structs[identity]=mid;self.by_formula[formula].append(identity)
120
+ self.keys=sorted(self.structs)
121
+ self.mol=lru_cache(maxsize=c.get('molecule_lru_size',100000))(self._mol)
122
+ self.pool=lru_cache(maxsize=c.get('pool_lru_size',8192))(self._pool)
123
+ self.formula_pool=lru_cache(maxsize=c.get('pool_lru_size',8192))(self._formula_pool)
124
+
125
+ @property
126
+ def db(self):
127
+ if not hasattr(self.local,'db'): self.local.db=readonly(self.path)
128
+ return self.local.db
129
+
130
+ def _mol(self,mid):
131
+ r=self.db.execute('SELECT value,error,ready FROM molecules WHERE id=?',(int(mid),)).fetchone()
132
+ if not r or r[2]!=1 or r[1]: raise RuntimeError('Missing/invalid prepared molecule; no runtime fallback')
133
+ return loads(r[0])
134
+
135
+ def _pool(self,view,target):
136
+ r=self.db.execute('SELECT prepared FROM pools WHERE view=? AND target=?',(view,target)).fetchone()
137
+ if not r or not r[0]:raise RuntimeError('Missing prepared pool/forest; no runtime fallback')
138
+ return loads(r[0])
139
+
140
+ def _formula_pool(self,view,target):
141
+ """Full prepared training view, independent of the 63 sampled negatives.
142
+
143
+ The immutable preparation's heldout/support projection still applies;
144
+ this is not claimed to include unsupported raw official formulas.
145
+ No runtime RDKit calculation or positive formula insertion.
146
+ """
147
+ ids=self.pool(view,target)['molecule_ids']
148
+ forms=set()
149
+ for a in range(0,len(ids),500):
150
+ block=tuple(int(x) for x in ids[a:a+500])
151
+ placeholders=','.join('?' for _ in block)
152
+ forms.update(r[0] for r in self.db.execute('SELECT formula FROM molecules WHERE id IN ('+placeholders+')',block))
153
+ if None in forms:raise ValueError('Prepared formula metadata missing')
154
+ return tuple(sorted(forms))
155
+
156
+ def row(self,sid,source,sequence,view):
157
+ r=self.db.execute('SELECT identity,ref_smiles,target,body FROM spectra WHERE id=? AND source=?',(sid,source)).fetchone()
158
+ if not r:raise ValueError('Epoch row missing')
159
+ identity,ref_smiles,target,blob=r
160
+ mid=self.db.execute('SELECT id FROM molecules WHERE smiles=?',(ref_smiles,)).fetchone()[0]
161
+ ref=self.mol(mid);data=loads(blob);q=data['query']
162
+ if ref.identity!=identity:raise ValueError('Reference identity mismatch')
163
+ audit={'sequence':sequence,'spectrum_id':sid,'source':source,'identity':identity,'network_requests':0,
164
+ 'retrieval_pool_used':False,'view':'odata_inbatch'}
165
+ if source=='odata':
166
+ return {'example':Example(str(sid),q,Labels(ref_smiles,identity,ref.formula),{},'train'),
167
+ 'ref':ref,'independent_formulas':data['independent_formulas'],'audit':audit}
168
+ pool=self.pool(view,target)
169
+ view_offset={'msg_mass':53,'msg_formula':97}[view]
170
+ rng=random.Random(self.c['seed']+sequence*10007+view_offset)
171
+ if self.c['msg_negative_sampling']=='uniform_with_replacement':
172
+ selected,mask,available,multiplicities=sample_view_with_replacement(pool,identity,self.c['msg_negative_count'],rng)
173
+ else:
174
+ selected,mask,available=sample_view_ids(pool,identity,self.mol,self.c['msg_negative_count'],rng)
175
+ multiplicities=tuple(1 for _ in selected)
176
+ mols=tuple(self.mol(i) for i in selected)
177
+ q=replace(q,candidates=mols,formula_candidates=tuple(sorted({m.formula for m in mols})),candidate_view=view)
178
+ forest=restrict_forest(pool['forest'],mols)
179
+ audit.update(view=view,retrieval_pool_used=True,full_projected_count=pool['projected_count'],training_candidate_count=len(mols),
180
+ positive_in_original_projected_pool=pool['positive_in_original_projected_pool'],
181
+ candidate_view_provenance={k:pool[k] for k in ('sha256','raw_count','ppm_filter_applied','raw_pool_modified')},
182
+ projection=pool['removed'],negative_proposal_count=len(mols)-1,
183
+ same_formula_proposals=sum(m.formula==ref.formula and m.identity!=identity for m in mols),sampled_pool=len(mols)<pool['projected_count'],
184
+ available_negative_count=available,selected_negative_count=len(mols)-1,
185
+ candidate_slot_count=self.c['msg_negative_count']+1,padding_slots=int((~mask).sum()),
186
+ sampling=self.c['msg_negative_sampling'],positive_injected=False,
187
+ drawn_negative_slots=sum(multiplicities)-1,unique_negative_count=len(mols)-1,
188
+ duplicate_negative_slots=sum(multiplicities)-len(mols),
189
+ candidate_multiplicities=list(multiplicities),
190
+ empty_negative_pool=available==0)
191
+ fs=data['independent_formulas']
192
+ if self.c.get('formula_v07',{}).get('enabled',False):
193
+ fs=self.formula_pool(view,target)
194
+ audit.update(formula_loss_universe='full_prepared_'+view,
195
+ formula_class_count=len(fs),formula_truth_present=ref.formula in fs,
196
+ formula_negative_subsampling=False)
197
+ return {'example':Example(str(sid),q,Labels(ref_smiles,identity,ref.formula),{},'train'),
198
+ 'ref':ref,'forest':forest,'candidate_mask':mask,'candidate_multiplicities':multiplicities,
199
+ 'independent_formulas':fs,'audit':audit}
200
+
201
+ def batch(self,step):
202
+ views=self.c['msg_views'];ids=self.plan.batch_ids(step,'msg_train')
203
+ return {'step':step,'view':'both','msg_spectrum_count':len(ids),
204
+ 'odata':[self.row(sid,'odata',self.plan.sequence(step,'odata',i),None) for i,sid in enumerate(self.plan.batch_ids(step,'odata'))],
205
+ 'msg':[self.row(sid,'msg_train',self.plan.sequence(step,'msg_train',i),view) for i,sid in enumerate(ids) for view in views]}
206
+
207
+
208
+ class CachedPrefetch:
209
+ """Threads share a bounded molecular LRU: no graph pickle IPC per batch."""
210
+ def __init__(self,reader,first,end):
211
+ self.reader=reader;self.end=end;self.next=first;self.pending={}
212
+ self.pool=ThreadPoolExecutor(max_workers=reader.c['workers'])
213
+ self.fill()
214
+
215
+ def fill(self):
216
+ while len(self.pending)<self.reader.c['prefetch_batches'] and self.next<self.end:
217
+ self.pending[self.next]=self.pool.submit(self.reader.batch,self.next);self.next+=1
218
+
219
+ def get(self,step):
220
+ b=self.pending.pop(step).result(timeout=600);self.fill();return b
221
+
222
+ def close(self):
223
+ for f in self.pending.values():f.cancel()
224
+ self.pool.shutdown(wait=True,cancel_futures=True)
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/epoch_features.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Immutable prepared inputs. No labels enter spectrum features or the model.
2
+
3
+ This cache is internal, locally generated pickle, not an untrusted input format.
4
+ """
5
+ from dataclasses import dataclass, field
6
+ import math
7
+ import pickle
8
+ import zlib
9
+ import numpy as np
10
+ import torch
11
+ from .schema import Query
12
+ from .model import metadata
13
+ from .model_v03 import BatchedSpectrumEncoder
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class PreparedQuery(Query):
18
+ spectrum_arrays: tuple = field(default=(), repr=False, compare=False)
19
+
20
+
21
+ def dumps(value):
22
+ return zlib.compress(pickle.dumps(value, protocol=5), 1)
23
+
24
+
25
+ def loads(value):
26
+ return pickle.loads(zlib.decompress(value))
27
+
28
+
29
+ def spectrum_arrays(query, max_peaks=256):
30
+ peaks = sorted(query.peaks, key=lambda p: (-p[1], p[0]))[:max_peaks]
31
+ peaks.sort()
32
+ p = np.asarray(peaks, dtype=np.float32)
33
+ if not len(p) or not np.isfinite(p).all() or p[:, 1].max() <= 0:
34
+ raise ValueError('Invalid prepared spectrum')
35
+ mz = p[:, 0] / np.float32(1000.)
36
+ w = np.sqrt(p[:, 1] / max(p[:, 1].max(), 1e-12)).astype(np.float32)
37
+ delta = (np.float32(query.precursor_mz) - p[:, 0]) / np.float32(1000.)
38
+ angles = mz[:, None] * (2. ** np.arange(8, dtype=np.float32))[None, :] * np.float32(math.pi)
39
+ x = np.column_stack((mz, w, delta, np.sin(angles), np.cos(angles))).astype(np.float32)
40
+ return x, w, np.asarray(metadata(query), dtype=np.float32)
41
+
42
+
43
+ class PreparedSpectrumEncoder(BatchedSpectrumEncoder):
44
+ """Same weights/semantics; batch CPU collation then three GPU transfers."""
45
+ def forward_batch(self, queries):
46
+ if not queries or not all(isinstance(q, PreparedQuery) and q.spectrum_arrays for q in queries):
47
+ raise ValueError('v06 training requires fully prepared spectrum features')
48
+ lengths = [len(q.spectrum_arrays[0]) for q in queries]
49
+ n = max(lengths)
50
+ x = np.zeros((len(queries), n, 19), dtype=np.float32)
51
+ w = np.zeros((len(queries), n), dtype=np.float32)
52
+ meta = np.stack([q.spectrum_arrays[2] for q in queries])
53
+ for i, q in enumerate(queries):
54
+ x[i, :lengths[i]], w[i, :lengths[i]] = q.spectrum_arrays[:2]
55
+ dev = self.frequencies.device
56
+ def transfer(a):
57
+ t = torch.from_numpy(a)
58
+ if dev.type == 'cuda':
59
+ t = t.pin_memory()
60
+ return t.to(dev, non_blocking=True)
61
+ x, w, m = transfer(x), transfer(w), self.meta(transfer(meta))
62
+ mask = torch.arange(n, device=dev)[None, :] >= torch.tensor(lengths, device=dev)[:, None]
63
+ tokens = self.encoder(self.peak(x) + m[:, None, :], src_key_padding_mask=mask)
64
+ pooled = self.output((tokens * w[:, :, None]).sum(1) / w.sum(1).clamp_min(1e-12)[:, None])
65
+ return [tokens[i, :n] for i, n in enumerate(lengths)], pooled, m
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/evaluate.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import defaultdict
2
+ import numpy as np
3
+
4
+ TOP_K = (1,3,5,10,20,50,100,200)
5
+
6
+
7
+ def recall_table(rows, key, ks):
8
+ n = len(rows)
9
+ return {str(k): {"hits":sum(r.get(key) is not None and r[key] <= k for r in rows),"denominator":n,
10
+ "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}
11
+
12
+
13
+ def summarize(rows, bootstrap=0, seed=20260908):
14
+ labelled = [r for r in rows if r.get("reference_identity")]
15
+ covered = [r for r in labelled if r["reference_in_original_pool"]]
16
+ formula_labelled = [r for r in labelled if r.get("formula_prediction_evaluable", True)]
17
+ bytarget = defaultdict(list)
18
+ for r in labelled:
19
+ bytarget[r["reference_identity"]].append(r)
20
+ result = {"total_queries":len(rows),"labelled_queries":len(labelled),
21
+ "original_pool_covered":len(covered),"unlabelled_queries":len(rows)-len(labelled),
22
+ "connectivity_end_to_end":recall_table(labelled,"connectivity_rank",TOP_K),
23
+ "connectivity_conditional_pool":recall_table(covered,"connectivity_rank",TOP_K),
24
+ "formula_recall":recall_table(formula_labelled,"formula_rank",range(1,11)),
25
+ "formula_prediction_evaluable_queries":len(formula_labelled),
26
+ "formula_universe_coverage":sum(r["formula_rank"] is not None for r in formula_labelled),
27
+ "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},
28
+ "distinct_targets":len(bytarget),"strata":{},
29
+ "full_inchikey_metric":"Not reported: primary model deduplicates connectivity; use retained aliases in a separate stereochemistry protocol."}
30
+ for field in ("dataset_mode","adduct","polarity","candidate_regime"):
31
+ groups = defaultdict(list)
32
+ for r in labelled:
33
+ groups[str(r[field])].append(r)
34
+ result["strata"][field] = {k:recall_table(v,"connectivity_rank",TOP_K) for k,v in sorted(groups.items())}
35
+ if bootstrap and bytarget:
36
+ rng = np.random.default_rng(seed)
37
+ keys = sorted(bytarget)
38
+ cis = {}
39
+ for k in TOP_K:
40
+ 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])
41
+ boot = [vals[rng.integers(0,len(vals),len(vals))].mean() for _ in range(bootstrap)]
42
+ cis[str(k)] = [float(x) for x in np.quantile(boot,[.025,.975])]
43
+ result["target_grouped_bootstrap_95ci_macro"] = cis
44
+ return result
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/feature_store.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Bounded shared derived-feature cache; never writes candidate/source databases.
2
+
3
+ All workers use the same chemistry/RDKit version namespace. Values and rejected
4
+ SMILES are computed by the unchanged molecular featurizer, not PubChem metadata.
5
+ Only this application's locally generated pickle data is accepted here.
6
+ """
7
+ from collections import Counter
8
+ import hashlib
9
+ from pathlib import Path
10
+ import pickle
11
+ import sqlite3
12
+ import zlib
13
+ from rdkit import rdBase
14
+
15
+
16
+ class FeatureStore:
17
+ def __init__(self, root, max_bytes=2 * 1024**3):
18
+ from . import chemistry
19
+ digest=hashlib.sha256(Path(chemistry.__file__).read_bytes()).hexdigest()
20
+ namespace=hashlib.sha256((digest+rdBase.rdkitVersion+'packed-v1').encode()).hexdigest()[:24]
21
+ root=Path(root);root.mkdir(parents=True,exist_ok=True)
22
+ self.path=root/f'features_{namespace}.sqlite'
23
+ self.db=sqlite3.connect(self.path,timeout=10,isolation_level=None)
24
+ self.db.execute('PRAGMA journal_mode=WAL')
25
+ self.db.execute('PRAGMA synchronous=NORMAL')
26
+ self.db.execute('PRAGMA cache_size=-8192')
27
+ self.db.execute('CREATE TABLE IF NOT EXISTS features (smiles TEXT PRIMARY KEY, value BLOB, error TEXT) WITHOUT ROWID')
28
+ self.stats=Counter();self.pending={};self.max_bytes=max_bytes;self.writable=True
29
+
30
+ def get_or_compute(self, smiles, compute):
31
+ row=self.pending.get(smiles)
32
+ if row is None:
33
+ row=self.db.execute('SELECT value,error FROM features WHERE smiles=?',(smiles,)).fetchone()
34
+ if row is not None:
35
+ value,error=row
36
+ if error is not None:
37
+ self.stats['rejected_hits']+=1
38
+ raise ValueError(error)
39
+ # A corrupt derived cache is an explicit failure, never a silently
40
+ # altered candidate pool. Source data can regenerate a fresh cache.
41
+ result=pickle.loads(zlib.decompress(value));self.stats['hits']+=1
42
+ return result
43
+ self.stats['misses']+=1
44
+ try:
45
+ result=compute(smiles)
46
+ except ValueError as exc:
47
+ self._put(smiles,(None,str(exc)))
48
+ raise
49
+ self._put(smiles,(zlib.compress(pickle.dumps(result,protocol=5),1),None))
50
+ return result
51
+
52
+ def _put(self,key,value):
53
+ if not self.writable:return
54
+ self.pending[key]=value
55
+ if len(self.pending)>=32:self.flush()
56
+
57
+ def flush(self):
58
+ if not self.pending:return
59
+ # Bound this disposable artifact. WAL size is checked too; overshoot is
60
+ # limited to concurrent small transactions, not a growing corpus cache.
61
+ size=sum(p.stat().st_size for p in (self.path,Path(str(self.path)+'-wal')) if p.exists())
62
+ if size>=self.max_bytes:
63
+ self.writable=False;self.pending.clear();self.stats['size_guard']+=1;return
64
+ try:
65
+ self.db.execute('BEGIN IMMEDIATE')
66
+ self.db.executemany('INSERT OR IGNORE INTO features VALUES (?,?,?)',
67
+ [(k,*v) for k,v in self.pending.items()])
68
+ self.db.execute('COMMIT')
69
+ except sqlite3.OperationalError as exc:
70
+ if self.db.in_transaction:self.db.execute('ROLLBACK')
71
+ if 'locked' not in str(exc).lower():raise
72
+ # Cache lock contention must not change a training example.
73
+ self.stats['write_lock_fallback']+=1
74
+ finally:self.pending.clear()
75
+
76
+ def close(self):
77
+ self.flush();self.db.close()
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/forest.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Candidate-only, formula-separated complete-link feasible forest.
2
+
3
+ Large pools use bounded minhash proposals, not an exact minimum clique cover.
4
+ Every accepted merge is checked against ALL cross-member pairs.
5
+ """
6
+ from dataclasses import dataclass
7
+ from collections import defaultdict
8
+ import hashlib
9
+ import numpy as np
10
+ from .chemistry import scaffold_similarity, tanimoto
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class Node:
15
+ key: str
16
+ members: tuple[int, ...]
17
+ children: tuple[str, ...]
18
+ stats: tuple[float, ...]
19
+ medoid: int
20
+
21
+
22
+ @dataclass
23
+ class Forest:
24
+ nodes: dict[str, Node]
25
+ roots: tuple[str, ...]
26
+ identities: tuple[str, ...]
27
+ proposal_pairs: int
28
+ similarity_checks: int
29
+ approximate_proposals: bool
30
+
31
+ def leaves(self):
32
+ return [n for n in self.nodes.values() if not n.children]
33
+
34
+ def validate(self, partition):
35
+ ids = [i for k in partition for i in self.nodes[k].members]
36
+ if sorted(ids) != list(range(len(self.identities))):
37
+ raise ValueError("Partition must preserve each candidate exactly once")
38
+
39
+ def to_dict(self):
40
+ return {"roots": self.roots, "identities": self.identities,
41
+ "proposal_pairs": self.proposal_pairs, "similarity_checks": self.similarity_checks,
42
+ "approximate_proposals": self.approximate_proposals,
43
+ "nodes": {k: {"members": [self.identities[i] for i in n.members], "children": n.children,
44
+ "stats": n.stats, "medoid": self.identities[n.medoid]} for k,n in self.nodes.items()}}
45
+
46
+
47
+ def proposal_pairs(mols, cfg):
48
+ groups = defaultdict(list)
49
+ for i,m in enumerate(mols):
50
+ groups[m.formula].append(i)
51
+ pairs = set()
52
+ approximate = False
53
+ for indices in groups.values():
54
+ indices.sort(key=lambda i: mols[i].identity)
55
+ if len(indices) <= cfg.exact_pool_limit:
56
+ pairs.update((a,b) if a < b else (b,a) for p,a in enumerate(indices) for b in indices[p+1:])
57
+ continue
58
+ approximate = True
59
+ buckets = defaultdict(list)
60
+ # 16 deterministic minhashes / 8 bands. Candidate order never seeds hashing.
61
+ for i in indices:
62
+ bits = np.flatnonzero(mols[i].whole).astype(np.int64)
63
+ signature = [int(((bits * (1000003+104729*s) + s*s*7919) % 2147483647).min()) if len(bits) else -1
64
+ for s in range(16)]
65
+ for band in range(8):
66
+ buckets[(band, *signature[2*band:2*band+2])].append(i)
67
+ for bucket in buckets.values():
68
+ bucket.sort(key=lambda i: mols[i].identity)
69
+ # Sliding windows bound proposal work even for a huge bucket; misses are explicitly audited.
70
+ for pos, i in enumerate(bucket):
71
+ for j in bucket[pos+1:pos+1+cfg.proposal_bucket_cap]:
72
+ pairs.add(tuple(sorted((i,j))))
73
+ return pairs, approximate
74
+
75
+
76
+ def build_forest(mols, cfg, vectorized=False):
77
+ if len({m.identity for m in mols}) != len(mols):
78
+ raise ValueError("Deduplicate connectivity before building forest")
79
+ nodes, owner, sims = {}, {}, {}
80
+ checks = 0
81
+ tables = None
82
+ if vectorized and mols and len(mols) <= 256:
83
+ def matrix(arrays):
84
+ x = np.stack(arrays).astype(np.float32)
85
+ intersection = x @ x.T
86
+ sizes = x.sum(1)
87
+ union = sizes[:, None] + sizes[None, :] - intersection
88
+ return np.divide(intersection.astype(np.float64), union, out=np.zeros_like(intersection, dtype=np.float64), where=union>0)
89
+ tables = matrix([m.whole for m in mols]), matrix([m.scaffold for m in mols])
90
+
91
+ def pair(i,j):
92
+ nonlocal checks
93
+ k = tuple(sorted((i,j)))
94
+ if k not in sims:
95
+ checks += 1
96
+ w = float(tables[0][i,j]) if tables is not None else tanimoto(mols[i].whole, mols[j].whole)
97
+ 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])
98
+ sims[k] = w,s
99
+ return sims[k]
100
+
101
+ def compatible(i,j):
102
+ if mols[i].formula != mols[j].formula:
103
+ return False
104
+ w,s = pair(i,j)
105
+ return w >= (cfg.acyclic_threshold if s is None else cfg.whole_threshold) and (s is None or s >= cfg.scaffold_threshold)
106
+
107
+ for i,m in enumerate(mols):
108
+ key = "leaf:" + m.identity
109
+ nodes[key] = Node(key, (i,), (), (0.,1.,1.,0.,float(not m.scaffold_smiles)), i)
110
+ owner[i] = key
111
+ pairs, approximate = proposal_pairs(mols, cfg)
112
+ # Retain a bounded number of best proposed neighbors per candidate before merging.
113
+ neighbors = defaultdict(list)
114
+ for i,j in pairs:
115
+ if compatible(i,j):
116
+ w,_ = pair(i,j)
117
+ neighbors[i].append((-w, mols[j].identity, j))
118
+ neighbors[j].append((-w, mols[i].identity, i))
119
+ retained = {tuple(sorted((i,j))) for i,ns in neighbors.items() for _,__,j in sorted(ns)[:cfg.neighbors]}
120
+ ordered = sorted(retained, key=lambda ij: (-pair(*ij)[0], *sorted(mols[k].identity for k in ij)))
121
+ for i,j in ordered:
122
+ a,b = owner[i],owner[j]
123
+ if a == b:
124
+ continue
125
+ na, nb = nodes[a],nodes[b]
126
+ if len(na.members)+len(nb.members) > cfg.max_cluster_size:
127
+ continue
128
+ if not all(compatible(x,y) for x in na.members for y in nb.members):
129
+ continue
130
+ members = tuple(sorted(na.members+nb.members, key=lambda k:mols[k].identity))
131
+ key = "node:" + hashlib.sha256("|".join(mols[k].identity for k in members).encode()).hexdigest()[:20]
132
+ ws = [pair(x,y)[0] for p,x in enumerate(members) for y in members[p+1:]]
133
+ medoid = min(members, key=lambda x: (-sum(pair(x,y)[0] for y in members if x != y), mols[x].identity))
134
+ stats = (np.log1p(len(members)), min(ws), float(np.mean(ws)), float(np.std(ws)),
135
+ float(np.mean([not mols[k].scaffold_smiles for k in members])))
136
+ nodes[key] = Node(key, members, tuple(sorted((a,b))), stats, medoid)
137
+ for k in members:
138
+ owner[k] = key
139
+ result = Forest(nodes, tuple(sorted(set(owner.values()))), tuple(m.identity for m in mols), len(pairs), checks, approximate)
140
+ result.validate(result.roots)
141
+ return result
142
+
143
+
144
+ def partition_cost(forest, partition, overhead=16.):
145
+ # Uncalibrated operation-count proxy, not seconds: per-set overhead plus quadratic attention.
146
+ return sum(overhead + len(forest.nodes[k].members)**2 for k in partition)
147
+
148
+
149
+ def split_node(forest, partition, key):
150
+ if key not in partition or not forest.nodes[key].children:
151
+ raise ValueError("Can split only an active internal node")
152
+ result = tuple(sorted((set(partition)-{key}) | set(forest.nodes[key].children)))
153
+ forest.validate(result)
154
+ return result
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/formula_v07.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Opt-in formula evidence head. No labels, candidate positions or SIRIUS inputs.
2
+
3
+ This module ranks an explicitly supplied formula universe; it does NOT make a
4
+ closed training catalogue an open-vocabulary generator. Official pools are not
5
+ hard-filtered. Physics contributes a soft score, never deletes a candidate.
6
+ """
7
+ import math
8
+ import numpy as np
9
+ import torch
10
+ from torch import nn
11
+ from torch.nn import functional as F
12
+ from .chemistry import ELEMENTS, exact_mass, formula_vector, ppm_error
13
+
14
+
15
+ class FormulaEvidenceHead(nn.Module):
16
+ def __init__(self, dim, config=None):
17
+ super().__init__()
18
+ c=config or {};self.settings=c
19
+ self.formula_encoder=nn.Sequential(nn.Linear(2*len(ELEMENTS)+3,dim),nn.GELU(),nn.LayerNorm(dim),nn.Linear(dim,dim))
20
+ self.peak_encoder=nn.Sequential(nn.Linear(3,dim),nn.GELU(),nn.Linear(dim,dim))
21
+ self.key=nn.Linear(dim,dim,bias=False);self.value=nn.Linear(dim,dim,bias=False)
22
+ self.formula_query=nn.Linear(2*dim,dim)
23
+ self.evidence=nn.Sequential(nn.Linear(5*dim+4,dim),nn.GELU(),nn.Linear(dim,1))
24
+ self.elements=nn.Sequential(nn.Linear(dim,dim),nn.GELU(),nn.Linear(dim,2*len(ELEMENTS)))
25
+ weight=float(c.get('initial_mass_weight',1.))
26
+ if weight<=0:raise ValueError('Positive initial mass weight required')
27
+ self.mass_weight_raw=nn.Parameter(torch.tensor(math.log(math.expm1(weight))))
28
+ self.ppm_scale=float(c.get('ppm_scale',1.))
29
+ self.residual_bound=float(c.get('residual_bound',4.))
30
+ if self.ppm_scale<=0 or self.residual_bound<=0:raise ValueError('Positive scales required')
31
+ # A new head initially equals the auditable absolute-mass-error baseline.
32
+ nn.init.zeros_(self.evidence[-1].weight);nn.init.zeros_(self.evidence[-1].bias)
33
+
34
+ def forward(self,q,query):
35
+ fs=query.formula_candidates
36
+ if len(set(fs))!=len(fs):raise ValueError('Formula classes must be unique')
37
+ with torch.autocast(device_type=q.device.type,enabled=False):
38
+ q=q.float()
39
+ if not fs:return q.new_empty(0)
40
+ counts=q.new_tensor(np.stack([formula_vector(f) for f in fs]))
41
+ total=counts.sum(-1,keepdim=True).clamp_min(1)
42
+ carbon=counts[:,ELEMENTS.index('C')];nitrogen=counts[:,ELEMENTS.index('N')]
43
+ hydrogen=counts[:,ELEMENTS.index('H')]
44
+ halogens=sum(counts[:,ELEMENTS.index(e)] for e in ('F','Cl','Br','I'))
45
+ dbe=(2+2*carbon+nitrogen-hydrogen-halogens)/2
46
+ mass=q.new_tensor([exact_mass(f) for f in fs])
47
+ ef=self.formula_encoder(torch.cat((counts.log1p(),counts/total,
48
+ torch.stack((mass/1000.,total[:,0].log1p(),dbe/20.),-1)),dim=-1))
49
+ # Formula-conditioned attention over raw MS peaks. No assigned peak
50
+ # formulas, isotopic envelopes or reference-derived inputs assumed.
51
+ p=sorted(query.peaks,key=lambda x:(-x[1],x[0]))[:256]
52
+ p=sorted(p);peaks=q.new_tensor(p)
53
+ if not len(p) or not torch.isfinite(peaks).all() or peaks[:,1].max()<=0:
54
+ raise ValueError('Valid MS peaks are required')
55
+ intensity=(peaks[:,1]/peaks[:,1].max()).clamp_min(0).sqrt()
56
+ hp=self.peak_encoder(torch.stack((peaks[:,0]/1000.,intensity,
57
+ (query.precursor_mz-peaks[:,0])/1000.),-1))
58
+ qq=q.expand(len(fs),-1)
59
+ attn=(self.formula_query(torch.cat((qq,ef),-1))@self.key(hp).T)/math.sqrt(q.numel())
60
+ context=attn.softmax(-1)@self.value(hp)
61
+ err=q.new_tensor([ppm_error(exact_mass(f),query.precursor_mz,query.adduct) for f in fs])
62
+ ae=err.abs()/self.ppm_scale
63
+ physics=torch.stack((err.sign()*err.abs().log1p(),ae.log1p(),(ae/10.).clamp_max(10),
64
+ (ae/10.).square().clamp_max(100)),-1)
65
+ neural=self.evidence(torch.cat((qq,ef,qq*ef,(qq-ef).abs(),context,physics),-1)).squeeze(-1)
66
+ score=-F.softplus(self.mass_weight_raw)*ae.log1p()+self.residual_bound*neural.tanh()
67
+ # v07.1: elemental supervision is also connected to formula ranking.
68
+ # Candidate labels are never consulted here; every formula receives
69
+ # the same predicted-element compatibility calculation.
70
+ pw=float(self.settings.get('ranking_presence_weight',0.))
71
+ cw=float(self.settings.get('ranking_count_weight',0.))
72
+ if pw or cw:
73
+ presence,pred_counts=self.elements(q).chunk(2)
74
+ pe=F.binary_cross_entropy_with_logits(presence.expand_as(counts),(counts>0).float(),reduction='none').mean(-1)
75
+ ce=F.smooth_l1_loss(F.softplus(pred_counts).expand_as(counts),counts.log1p(),reduction='none').mean(-1)
76
+ score=score-pw*pe-cw*ce
77
+ if not torch.isfinite(score).all():raise RuntimeError('Nonfinite formula score')
78
+ return score
79
+
80
+ def auxiliary(self,q,truth):
81
+ # Training labels only. These tasks remain active when the formula CE
82
+ # universe is singleton, empty or misses the supervised training formula.
83
+ with torch.autocast(device_type=q.device.type,enabled=False):
84
+ target=q.new_tensor(formula_vector(truth),dtype=torch.float32)
85
+ presence,counts=self.elements(q.float()).chunk(2)
86
+ return {'presence':F.binary_cross_entropy_with_logits(presence,(target>0).float()),
87
+ 'counts':F.smooth_l1_loss(F.softplus(counts),target.log1p())}
88
+
89
+
90
+ def formula_objective(model,qs,queries,universes,truths,total_ce,total_rows,diagnostics=None):
91
+ """Full-universe CE plus all-row elemental supervision, independently normalized."""
92
+ zero=qs.float().sum()*0.;ce=zero;presence=zero;counts=zero;hard=zero
93
+ from dataclasses import replace
94
+ for q,query,fs,truth in zip(qs,queries,universes,truths):
95
+ detail={'classes':len(fs),'truth_present':truth in fs,'ce_valid':len(fs)>1 and truth in fs,'ce':0.,'hard':0.,'rank':None}
96
+ if len(fs)>1 and truth in fs:
97
+ score=model.score_formulas(q,replace(query,formula_candidates=tuple(fs)))
98
+ ce_i=F.cross_entropy(score[None],torch.tensor([fs.index(truth)],device=q.device));ce=ce+ce_i
99
+ if diagnostics is not None:
100
+ values=score.detach().float().cpu().tolist()
101
+ order=sorted(range(len(fs)),key=lambda j:(-values[j],fs[j]))
102
+ detail.update(ce=float(ce_i.detach()),rank=order.index(fs.index(truth))+1)
103
+ if model.formula_v07.settings.get('hard_formula_weight',0.):
104
+ p=fs.index(truth)
105
+ negative=torch.cat((score[:p],score[p+1:]))
106
+ top=negative.topk(min(len(negative),int(model.formula_v07.settings.get('hard_formula_count',8)))).values
107
+ hard_i=F.softplus(top-score[p]+float(model.formula_v07.settings.get('hard_formula_margin',.2))).mean();hard=hard+hard_i
108
+ if diagnostics is not None:detail['hard']=float(hard_i.detach())
109
+ aux=model.formula_v07.auxiliary(q,truth)
110
+ presence=presence+aux['presence'];counts=counts+aux['counts']
111
+ if diagnostics is not None:
112
+ if len(fs)==1 and truth in fs:detail['rank']=1
113
+ detail.update(presence=float(aux['presence'].detach()),counts=float(aux['counts'].detach()))
114
+ diagnostics.append(detail)
115
+ c=model.formula_v07.settings
116
+ 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)
117
+
118
+
119
+ def warm_start(model,state):
120
+ """Load v06 base weights; allow ONLY newly introduced head parameters missing."""
121
+ incompatible=model.load_state_dict(state,strict=False)
122
+ if incompatible.unexpected_keys or any(not k.startswith('formula_v07.') for k in incompatible.missing_keys):
123
+ raise ValueError(f'Unexpected warm-start mismatch: {incompatible}')
124
+ return list(incompatible.missing_keys)
125
+
126
+
127
+ def validate_frozen_preparation(c, verify_hash=True):
128
+ """Reuse v06 data only after verifying its frozen producer and feature code.
129
+
130
+ The only allowed producer-module change is model.score_formulas, which is
131
+ not used to prepare any input. All other model AST and producer hashes must
132
+ agree. The original validator still checks data, RDKit, labels and hashes.
133
+ """
134
+ import ast
135
+ import importlib.util
136
+ import json
137
+ from pathlib import Path
138
+ from .multiview_data import sha
139
+ root=Path(c['frozen_preparation_source_dir']).resolve()
140
+ current=Path(__file__).parent
141
+ manifest=json.loads((Path(c['prepared_dir'])/'manifest.json').read_text())
142
+ for name,digest in manifest['preparation_source_hashes'].items():
143
+ if sha(root/name)!=digest:raise ValueError('Frozen producer mismatch: '+name)
144
+ if name!='model.py' and sha(current/name)!=digest:
145
+ raise ValueError('Current feature producer mismatch: '+name)
146
+ def without_formula_score(path):
147
+ tree=ast.parse(path.read_text())
148
+ for node in tree.body:
149
+ if isinstance(node,ast.ClassDef):
150
+ node.body=[x for x in node.body if not (isinstance(x,ast.FunctionDef) and x.name=='score_formulas')]
151
+ return ast.dump(tree,include_attributes=False)
152
+ if without_formula_score(root/'model.py')!=without_formula_score(current/'model.py'):
153
+ raise ValueError('A non-formula-score model/metadata definition changed')
154
+ spec=importlib.util.spec_from_file_location('specpartition_ms._frozen_prepare_epoch',root/'prepare_epoch.py')
155
+ module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module)
156
+ return module.validate(c,verify_hash)
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/inbatch_data.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Network-free training: o_data in-batch labels + random official MSG views.
2
+
3
+ Only SELECT statements access the shared source index. Neither PubChem tables
4
+ nor jobs/requests/cache are used. All preprocessing happens in owned CPU workers.
5
+ """
6
+ from dataclasses import replace
7
+ import hashlib
8
+ import json
9
+ import os
10
+ from pathlib import Path
11
+ import random
12
+ import torch
13
+ from rdkit import RDLogger
14
+ from .data_v03 import ReadyTrainingStream
15
+ from .multiview_train import TrainingStream
16
+ from .multiview_data import unpacked
17
+ from .chemistry import molecule
18
+ from .schema import parse_record
19
+
20
+
21
+ def view_for_batch(seed, step):
22
+ return random.Random(seed + 7919 * step).choice(('msg_mass', 'msg_formula'))
23
+
24
+
25
+ class InbatchStream(ReadyTrainingStream):
26
+ def __init__(self, config):
27
+ super().__init__(config)
28
+ self.msg_view = None
29
+ self.db.set_authorizer(self.authorize)
30
+
31
+ @staticmethod
32
+ def authorize(action, arg1, arg2, database, trigger):
33
+ import sqlite3
34
+ forbidden = {'formula_pools', 'jobs', 'demand'}
35
+ if action == sqlite3.SQLITE_READ and arg1 in forbidden:
36
+ return sqlite3.SQLITE_DENY
37
+ return sqlite3.SQLITE_OK
38
+
39
+ def entries(self, body, view):
40
+ if view not in ('msg_mass', 'msg_formula'):
41
+ raise RuntimeError('PubChem views are forbidden in v05')
42
+ row = self.db.execute('SELECT body,sha256,count FROM official_pools WHERE view=? AND target=?',
43
+ (view, body['target_smiles'])).fetchone()
44
+ if row is None:
45
+ raise RuntimeError('Official candidate pool missing or hash mismatch')
46
+ pool = unpacked(row[0])
47
+ if hashlib.sha256(json.dumps(pool,separators=(',',':')).encode()).hexdigest() != row[1]:
48
+ raise RuntimeError('Official candidate pool hash mismatch')
49
+ if len(pool) != row[2]:
50
+ raise RuntimeError('Official candidate count mismatch')
51
+ return [{'smiles':s, 'source_id':None} for s in pool], {
52
+ 'status':'ready', 'view':view, 'raw_count':len(pool), 'sha256':row[1],
53
+ 'ppm_filter_applied':False, 'network_requests':0}
54
+
55
+ def plan(self, sequence, stage):
56
+ self.rng = random.Random(self.config['seed'] + sequence * 10007)
57
+ sid, body = TrainingStream.sample(self, 1)
58
+ return sid, body, False, self.msg_view
59
+
60
+ def odata(self, sequence):
61
+ self.rng = random.Random(self.config['seed'] + 999983 + sequence * 10007)
62
+ sid, body = TrainingStream.sample(self, 0)
63
+ ref = molecule(body['reference_smiles'])
64
+ if ref.identity in self.banned:
65
+ raise RuntimeError('Heldout label reached in-batch data')
66
+ e = parse_record({'sample_id':str(sid), 'split':'train',
67
+ 'labels':{'reference_smiles':body['reference_smiles']},
68
+ 'features':{**body['features'], 'candidate_view':'warmup', 'candidates':[], 'formula_candidates':[]}})
69
+ return {'example':e, 'ref':ref,
70
+ 'independent_formulas':self.catalog.select(e.query.precursor_mz, e.query.adduct),
71
+ 'audit':{'sequence':sequence, 'spectrum_id':sid, 'source':'odata',
72
+ 'view':'odata_inbatch', 'identity':ref.identity,
73
+ 'retrieval_pool_used':False, 'network_requests':0}}
74
+
75
+
76
+ _STREAM = None
77
+
78
+
79
+ def initialize_worker(config):
80
+ global _STREAM
81
+ # Private in-memory features only: no writes to downloader caches or SQLite.
82
+ RDLogger.DisableLog('rdApp.*')
83
+ torch.set_num_threads(1)
84
+ _STREAM = InbatchStream(config)
85
+
86
+
87
+ def prepare_batch(task):
88
+ step, stage, chemistry = task
89
+ c = _STREAM.config
90
+ _STREAM.msg_view = view_for_batch(c['seed'], step)
91
+ odata = [_STREAM.odata(step*c['odata_batch_size']+i) for i in range(c['odata_batch_size'])]
92
+ msg = [_STREAM.prepare(step*c['msg_batch_size']+i, stage, chemistry) for i in range(c['msg_batch_size'])]
93
+ return {'odata':odata, 'msg':msg, 'view':_STREAM.msg_view, 'step':step}
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/joint_losses_v08.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """One optimizer update for all tasks; full in-batch o_data denominator.
2
+
3
+ Gradient replay saves memory, but NEVER freezes the trainable encoders. It
4
+ backpropagates the exact cached feature gradients before the optimizer step.
5
+ """
6
+ from collections import Counter
7
+ from dataclasses import replace
8
+ import math
9
+ import torch
10
+ from torch.nn import functional as F
11
+ from .train_inbatch import identity_columns,inbatch_ce
12
+ from .train_v03 import amp_context,microbatch_groups
13
+ from .formula_v07 import formula_objective
14
+ from .losses import positive_index,listwise_loss,cut_loss,counterfactual_targets
15
+
16
+
17
+ DEFAULT_WEIGHTS={'formula':1.,'contrastive':1.,'direct_anchor':.25,'rank':1.,'hard':.1,'cut':.1,'cost':.001}
18
+
19
+
20
+ def weights(c):return {**DEFAULT_WEIGHTS,**c.get('joint_loss_weights',{})}
21
+
22
+
23
+ def formula_loss(model,qs,rows,details=None):
24
+ n=sum(len(r['independent_formulas'])>1 and r['ref'].formula in r['independent_formulas'] for r in rows)
25
+ return formula_objective(model,qs,[r['example'].query for r in rows],
26
+ [r['independent_formulas'] for r in rows],[r['ref'].formula for r in rows],n,len(rows),details)
27
+
28
+
29
+ def odata_objective(model,qs,zm,mols,targets,rows,c):
30
+ w=weights(c);conditional=[];rank=[]
31
+ # Shared set, label-independent column identities, deduplicated connectivity.
32
+ forms=tuple(sorted({m.formula for m in mols}))
33
+ for q,row in zip(qs,rows):
34
+ query=replace(row['example'].query,formula_candidates=forms)
35
+ lc,lr,_=model.conditioned(q,query,[m.formula for m in mols],zm)
36
+ conditional.append(lc);rank.append(lr)
37
+ target=torch.tensor(targets,device=qs.device)
38
+ lc=F.cross_entropy(torch.stack(conditional),target) if len(mols)>1 else qs.sum()*0.
39
+ lr=F.cross_entropy(torch.stack(rank),target) if len(mols)>1 else qs.sum()*0.
40
+ anchor,_=inbatch_ce(F.normalize(model.query_projection(qs).float(),dim=-1),zm.float(),targets)
41
+ lf=formula_loss(model,qs,rows)
42
+ loss=w['formula']*lf+w['contrastive']*lc+w['direct_anchor']*anchor+w['rank']*lr
43
+ return loss,dict(LF_odata=lf,LC_odata=lc,LR_odata=lr,Lanchor_odata=anchor)
44
+
45
+
46
+ def odata_backward(model,rows,c):
47
+ if not rows:return dict(odata_loss=0.,LF_odata=0.,LC_odata=0.,LR_odata=0.,Lanchor_odata=0.)
48
+ mols,targets=identity_columns([r['ref'] for r in rows]);chunk=c['odata_micro_batch_size']
49
+ cached=c.get('odata_gradient_cache',True)
50
+ if cached:
51
+ with torch.no_grad(),amp_context(c):
52
+ 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)])
53
+ m0=torch.cat([model.encode_molecules(mols[a:a+c['graph_chunk']])[2] for a in range(0,len(mols),c['graph_chunk'])])
54
+ qs=q0.detach().float().requires_grad_();zm=m0.detach().float().requires_grad_()
55
+ else:
56
+ with amp_context(c):
57
+ qs=model.spectrum.forward_batch([r['example'].query for r in rows])[1]
58
+ zm=model.encode_molecules(mols)[2]
59
+ with amp_context(c):loss,components=odata_objective(model,qs,zm,mols,targets,rows,c)
60
+ if not torch.isfinite(loss):raise RuntimeError('Nonfinite o_data conditional loss')
61
+ loss.backward()
62
+ result={k:float(v.detach()) for k,v in components.items()};result['odata_loss']=float(loss.detach())
63
+ if cached:
64
+ dq=qs.grad.detach();dm=zm.grad.detach() if zm.grad is not None else torch.zeros_like(zm)
65
+ del loss,components,qs,zm,q0,m0
66
+ for a in range(0,len(rows),chunk):
67
+ with amp_context(c):q=model.spectrum.forward_batch([r['example'].query for r in rows[a:a+chunk]])[1]
68
+ (q.float()*dq[a:a+len(q)]).sum().backward()
69
+ for a in range(0,len(mols),c['graph_chunk']):
70
+ with amp_context(c):z=model.encode_molecules(mols[a:a+c['graph_chunk']])[2]
71
+ (z.float()*dm[a:a+len(z)]).sum().backward()
72
+ result.update(odata_unique_connectivity=len(mols),odata_negatives_per_query=max(0,len(mols)-1),
73
+ odata_duplicate_positive_rows=len(rows)-len(mols))
74
+ if c.get('scratch_v09'):
75
+ counts=Counter(m.formula for m in mols)
76
+ result['odata_same_formula_negative_mean']=sum(counts[r['ref'].formula]-1 for r in rows)/len(rows)
77
+ result['odata_no_same_formula_negative_fraction']=sum(counts[r['ref'].formula]==1 for r in rows)/len(rows)
78
+ status=Counter('empty' if not r['independent_formulas'] else
79
+ 'truth_missing' if r['ref'].formula not in r['independent_formulas'] else
80
+ 'singleton' if len(r['independent_formulas'])==1 else 'ce_valid' for r in rows)
81
+ result['odata_formula_supervision']=dict(status)
82
+ return result
83
+
84
+
85
+ def msg_backward(model,teacher,rows,c,step,diagnostics):
86
+ if not rows:return dict(msg_loss=0.,samples=[],source_rank_counts={})
87
+ # Formula conditioning uses the COMPLETE official view formula universe,
88
+ # even when structure negatives are sampled. No truth-driven insertion.
89
+ w=weights(c);targets={};queries=[replace(r['example'].query,formula_candidates=tuple(r['independent_formulas'])) for r in rows]
90
+ for j in range(min(len(rows),c.get('cut_queries_per_batch',2))):
91
+ i=(step+j)%len(rows)
92
+ with torch.autocast(device_type=model.device.type,enabled=False):
93
+ targets[i]=counterfactual_targets(teacher,queries[i],rows[i]['forest'],rows[i]['ref'].identity,
94
+ max_nodes=c.get('cut_nodes_per_query',8),epsilon=c.get('cut_epsilon',.005),offset=step*2,
95
+ multiplicities=rows[i].get('candidate_multiplicities'))
96
+ nf=sum(len(r['independent_formulas'])>1 and r['ref'].formula in r['independent_formulas'] for r in rows)
97
+ totals=Counter();audits=[];cut_nodes=0
98
+ view_sums={v:Counter() for v in c['msg_views']}
99
+ groups=microbatch_groups(queries,[[] for _ in rows],c['max_atoms_per_microbatch'])
100
+ for ids in groups:
101
+ diagnostics['phase']='joint_msg_forward_backward'
102
+ with amp_context(c):
103
+ outs,_=model.forward_batch([queries[i] for i in ids],[rows[i]['forest'] for i in ids])
104
+ terms={k:outs[0].scores.sum()*0. for k in ('LC','LR','Lanchor','Lhard','Lcut','Lcost')}
105
+ for i,out in zip(ids,outs):
106
+ row=rows[i];p=positive_index(row['forest'].identities,row['ref'].identity)
107
+ if p is None:raise ValueError('No injected or missing positive allowed in official train pool')
108
+ mult=row.get('candidate_multiplicities',tuple(1 for _ in queries[i].candidates))
109
+ lc=listwise_loss(out.encoded.conditional_logits,p,mult)[0]
110
+ lr=listwise_loss(out.scores,p,mult)[0]
111
+ terms['LC']+=lc/len(rows)
112
+ terms['LR']+=lr/len(rows)
113
+ direct=(out.encoded.z_molecules.float()@out.encoded.z_query.float())/.1
114
+ la=listwise_loss(direct,p,mult)[0];terms['Lanchor']+=la/len(rows)
115
+ same=[j for j,m in enumerate(queries[i].candidates) if j!=p and m.formula==row['ref'].formula]
116
+ lh=out.scores.sum()*0.
117
+ if same:
118
+ expanded=out.scores[same].repeat_interleave(torch.tensor([mult[j] for j in same],device=out.scores.device))
119
+ hard=expanded.topk(min(c.get('same_formula_hard_topk',8),len(expanded))).values
120
+ lh=F.softplus(hard-out.scores[p]+.2).mean();terms['Lhard']+=lh/len(rows)
121
+ if i in targets:
122
+ cl,n=cut_loss(model,out.encoded,row['forest'],targets[i]);cut_nodes+=n
123
+ terms['Lcut']+=cl/max(1,len(targets))
124
+ terms['Lcost']+=out.expected_cost/len(rows)
125
+ if c.get('scratch_v09'):
126
+ values=out.scores.detach().float().cpu().tolist()
127
+ order=sorted(range(len(values)),key=lambda j:(-values[j],row['forest'].identities[j]))
128
+ rank=order.index(p)+1
129
+ raw=[j for j in range(len(values)) if j!=p]
130
+ unique_lr=listwise_loss(out.scores,p)[0]
131
+ vs=view_sums[row['audit']['view']]
132
+ vs.update(queries=1,LC=float(lc.detach()),LR=float(lr.detach()),Lanchor=float(la.detach()),
133
+ Lhard=float(lh.detach()),LR_unique=float(unique_lr.detach()),
134
+ positive_probability_multiset=math.exp(-float(lr.detach())),
135
+ negative_draws=sum(mult)-1,unique_negatives=len(mult)-1,
136
+ duplicate_draws=sum(mult)-len(mult),same_formula_unique_negatives=len(same),
137
+ same_formula_draws=sum(mult[j] for j in same),empty_negative_pool=int(not raw),
138
+ hard_valid_queries=int(bool(same)),cut_valid_queries=int(bool(targets.get(i))))
139
+ if raw:vs.update(margin_valid=1,positive_top_negative_margin=values[p]-max(values[j] for j in raw))
140
+ for k in (1,3,5,10,20,50,100,200):vs['hit_at_'+str(k)]+=rank<=k
141
+ audits.append({**row['audit'],'negative':{'count':len(queries[i].candidates)-1,
142
+ 'draw_count':sum(mult)-1,'duplicates':sum(mult)-len(mult),
143
+ 'same_formula':len(same),'positive_excluded':sum(m.identity==row['ref'].identity for m in queries[i].candidates)==1 and mult[p]==1}})
144
+ formula_details=[] if c.get('scratch_v09') else None
145
+ terms['LF']=formula_objective(model,torch.stack([o.encoded.q for o in outs]),[queries[i] for i in ids],
146
+ [rows[i]['independent_formulas'] for i in ids],[rows[i]['ref'].formula for i in ids],nf,len(rows),formula_details)
147
+ if formula_details is not None:
148
+ for i,d in zip(ids,formula_details):
149
+ vs=view_sums[rows[i]['audit']['view']]
150
+ vs.update(formula_ce_valid=int(d['ce_valid']),formula_CE_sum=d['ce'],formula_hard_sum=d['hard'],
151
+ formula_presence_sum=d['presence'],formula_counts_sum=d['counts'],formula_classes_sum=d['classes'],
152
+ formula_truth_present=int(d['truth_present']))
153
+ for k in range(1,11):vs['formula_hit_at_'+str(k)]+=d['rank'] is not None and d['rank']<=k
154
+ loss=sum(w[name]*terms[key] for name,key in [('formula','LF'),('contrastive','LC'),('direct_anchor','Lanchor'),
155
+ ('rank','LR'),('hard','Lhard'),('cut','Lcut'),('cost','Lcost')])
156
+ if not torch.isfinite(loss):raise RuntimeError('Nonfinite MSG conditional joint loss')
157
+ loss.backward();totals.update({k:float(v.detach()) for k,v in terms.items()});totals['msg_loss']+=float(loss.detach())
158
+ del outs,loss,terms
159
+ views={}
160
+ if c.get('scratch_v09'):
161
+ for name,s in view_sums.items():
162
+ n=s['queries']
163
+ if not n:continue
164
+ views[name]={'queries':n,'sums':dict(s),
165
+ 'means':{k:s[k]/n for k in ('LC','LR','Lanchor','Lhard','LR_unique','positive_probability_multiset',
166
+ 'negative_draws','unique_negatives','duplicate_draws','same_formula_unique_negatives','same_formula_draws')},
167
+ 'structure_hit_at':{str(k):s['hit_at_'+str(k)]/n for k in (1,3,5,10,20,50,100,200)},
168
+ 'formula_hit_at':{str(k):s['formula_hit_at_'+str(k)]/n for k in range(1,11)},
169
+ 'formula_CE_valid_mean':s['formula_CE_sum']/s['formula_ce_valid'] if s['formula_ce_valid'] else None,
170
+ 'positive_top_negative_margin_mean':s['positive_top_negative_margin']/s['margin_valid'] if s['margin_valid'] else None,
171
+ 'rank_scope':'unique sampled connectivity; NOT full official pool'}
172
+ return {**dict(totals),'samples':audits,'source_rank_counts':{'msg_train_rank_valid':len(rows)},
173
+ **({'msg_views_metrics':views} if c.get('scratch_v09') else {}),
174
+ 'cut_valid_nodes':cut_nodes,'microbatches':len(groups)}
175
+
176
+
177
+ def joint_step(model,teacher,optimizer,batch,c,step,stage,diagnostics):
178
+ if stage!='joint':raise ValueError('v08 requires joint optimization at every update')
179
+ if any(not p.requires_grad for p in model.parameters()):raise ValueError('Student parameter freezing forbidden')
180
+ optimizer.zero_grad(set_to_none=True)
181
+ diagnostics['phase']='joint_odata';o=odata_backward(model,batch['odata'],c)
182
+ m=msg_backward(model,teacher,batch['msg'],c,step,diagnostics)
183
+ groups={}
184
+ for label,prefix in [('spectrum','spectrum.'),('molecule','graph.'),('formula','formula_v07.'),('condition','conditional_'),('cut','cut.')]:
185
+ grads=[p.grad.detach().float().square().sum() for n,p in model.named_parameters() if n.startswith(prefix) and p.grad is not None]
186
+ groups[label]=float(torch.stack(grads).sum().sqrt()) if grads else 0.
187
+ norm=torch.nn.utils.clip_grad_norm_(model.parameters(),5.,error_if_nonfinite=True)
188
+ optimizer.step()
189
+ loss=o['odata_loss']+m['msg_loss']
190
+ if not math.isfinite(loss):raise RuntimeError('Nonfinite joint loss')
191
+ return {**o,**m,'loss':loss,'gradient_norm_before_clip':float(norm),'gradient_groups':groups,
192
+ 'optimizer_updates':1,'view':'both','odata_exposures':len(batch['odata']),
193
+ 'msg_exposures':batch['msg_spectrum_count'],'msg_view_exposures':len(batch['msg'])}
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/joint_model_v08.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Soft formula-conditioned retrieval. No reference labels enter this module.
2
+
3
+ All candidates survive; formula posterior is over DISTINCT candidate formulas,
4
+ not weighted by the number of candidate molecules belonging to each formula.
5
+ This is conditional retrieval, not an autoregressive SMILES generator.
6
+ """
7
+ from dataclasses import replace
8
+ import numpy as np
9
+ import torch
10
+ from torch import nn
11
+ from torch.nn import functional as F
12
+ from .chemistry import formula_vector
13
+ from .config import Config
14
+ from .epoch_features import PreparedSpectrumEncoder
15
+ from .formula_v07 import FormulaEvidenceHead
16
+ from .model_v03 import BatchedSpecPartition
17
+
18
+
19
+ class ConditionalSpecPartition(BatchedSpecPartition):
20
+ def __init__(self,c):
21
+ cfg=Config()
22
+ for k,v in c['model'].items():setattr(cfg.model,k,v)
23
+ cfg.model.relation_mode='learned';cfg.train.device=c['device'];cfg.validate()
24
+ super().__init__(cfg,c['graph_chunk'],c['local_chunk'],c.get('gated_graph',True))
25
+ self.spectrum=PreparedSpectrumEncoder(cfg.model)
26
+ self.formula_v07=FormulaEvidenceHead(cfg.model.dim,c['formula_v07'])
27
+ d=cfg.model.dim
28
+ self.conditional_query=nn.Sequential(nn.Linear(4*d,d),nn.GELU(),nn.Linear(d,d))
29
+ self.conditional_context=nn.Sequential(nn.Linear(2*d,d),nn.GELU(),nn.Linear(d,d))
30
+ # Small but nonzero initialization: preserve warm-start scores while
31
+ # allowing conditioning and formula gradients on the FIRST update.
32
+ for layer in (self.conditional_query[-1],self.conditional_context[-1]):
33
+ nn.init.normal_(layer.weight,std=.001);nn.init.zeros_(layer.bias)
34
+ self.condition_bound=float(c.get('condition_bound',.25))
35
+
36
+ def conditioned(self,q,query,formulas,zm,formula_scores=None):
37
+ """Return structural conditional logits and joint formula/structure logits.
38
+
39
+ formulas is one formula for every molecule in zm (including negatives).
40
+ The reference molecule/formula is not an argument. For o_data each
41
+ in-batch molecule is a candidate column for EVERY spectrum.
42
+ """
43
+ fs=tuple(query.formula_candidates)
44
+ if len(fs)!=len(set(fs)):raise ValueError('Duplicate formula classes')
45
+ lookup={f:i for i,f in enumerate(fs)}
46
+ if any(f not in lookup for f in formulas):raise ValueError('Candidate formula missing from inference universe')
47
+ scores=self.score_formulas(q,query) if formula_scores is None else formula_scores
48
+ with torch.autocast(device_type=q.device.type,enabled=False):
49
+ q=q.float();zm=zm.float();scores=scores.float()
50
+ if not formulas:return scores.new_empty(0),scores.new_empty(0),q
51
+ features=q.new_tensor(np.stack([formula_vector(f) for f in fs]))
52
+ ef=self.formula(features.log1p()).float()
53
+ posterior=scores.softmax(0)
54
+ context=posterior@ef
55
+ qf=q.expand_as(ef)
56
+ delta=self.condition_bound*self.conditional_query(torch.cat((qf,ef,qf*ef,context.expand_as(ef)),-1)).tanh()
57
+ zf=F.normalize(self.query_projection(qf+delta),dim=-1)
58
+ idx=torch.tensor([lookup[f] for f in formulas],device=q.device)
59
+ structural=(zf[idx]*zm).sum(-1)/.1
60
+ # A common log-normalizer does not affect within-query ranks.
61
+ prior=torch.sigmoid(self.formula_gate(q)).squeeze()*scores.log_softmax(0)[idx]
62
+ relation_q=q+self.condition_bound*self.conditional_context(torch.cat((q,context))).tanh()
63
+ return structural,structural+prior,relation_q
64
+
65
+ def encode_batch(self,queries,extras=()):
66
+ encs,zm=super().encode_batch(queries,extras)
67
+ for enc in encs:
68
+ cond,joint,relation_q=self.conditioned(enc.q,enc.query,[m.formula for m in enc.query.candidates],enc.z_molecules,enc.formula_scores)
69
+ old_cos=self.log_scale.exp().clamp(max=100.)*(enc.z_molecules.float()@enc.z_query.float())
70
+ # Keep local peak-atom interactions, replace only global cosine.
71
+ local=enc.direct-old_cos
72
+ enc.conditional_logits=cond;enc.conditional_context_q=relation_q
73
+ enc.direct=cond+local;enc.base=joint+local
74
+ return encs,zm
75
+
76
+ def cut_logit(self,enc,node):
77
+ return super().cut_logit(replace(enc,q=getattr(enc,'conditional_context_q',enc.q)),node)
78
+
79
+ def score_partition(self,enc,forest,partition):
80
+ return super().score_partition(replace(enc,q=getattr(enc,'conditional_context_q',enc.q)),forest,partition)
81
+
82
+
83
+ def load_initial(model,state):
84
+ result=model.load_state_dict(state,strict=False)
85
+ allowed=('conditional_query.','conditional_context.','formula_v07.')
86
+ if result.unexpected_keys or any(not k.startswith(allowed) for k in result.missing_keys):
87
+ raise ValueError('Unexpected initial model mismatch: '+str(result))
88
+ return list(result.missing_keys)
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/losses.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ import torch
3
+ from torch.nn import functional as F
4
+ from .forest import partition_cost, split_node
5
+
6
+
7
+ def positive_index(identities, target):
8
+ found = [i for i,k in enumerate(identities) if k == target]
9
+ if len(found) > 1:
10
+ raise ValueError("Connectivity must be unique before listwise CE")
11
+ return found[0] if found else None
12
+
13
+
14
+ def listwise_loss(scores, positive, multiplicities=None):
15
+ if positive is None:
16
+ return scores.sum()*0., 0
17
+ if not 0 <= positive < len(scores):
18
+ raise ValueError("Invalid positive index")
19
+ # Exact CE over the supplied pool/multiset, not the full official pool.
20
+ weighted=scores
21
+ if multiplicities is not None:
22
+ counts=torch.as_tensor(multiplicities,device=scores.device,dtype=scores.dtype)
23
+ if counts.shape!=scores.shape or not bool(torch.isfinite(counts).all()) or bool((counts<1).any()) or bool((counts!=counts.round()).any()):
24
+ raise ValueError('Positive integer multiplicities must align with unique scores')
25
+ if float(counts[positive])!=1.:raise ValueError('Positive must occur once; false negatives prohibited')
26
+ weighted=scores+counts.log()
27
+ return torch.logsumexp(weighted,0)-scores[positive], 1
28
+
29
+
30
+ def contrastive_loss(z_query, z_positive, z_negatives, temperature=.1):
31
+ positive = (z_query*z_positive).sum().reshape(1)
32
+ negative = z_negatives@z_query
33
+ logits = torch.cat((positive,negative))/temperature
34
+ return torch.logsumexp(logits,0)-logits[0]
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class CutTarget:
39
+ node_key: str
40
+ delta: float
41
+ split: float
42
+ weight: float
43
+ stop_rank_loss: float
44
+ split_rank_loss: float
45
+ stop_cost: float
46
+ split_cost: float
47
+
48
+
49
+ @torch.no_grad()
50
+ def counterfactual_targets(teacher, query, forest, identity, max_nodes=8, epsilon=1e-5,
51
+ cost_tradeoff=.001, overhead=16., offset=0, multiplicities=None):
52
+ """Same frozen scorer, same query/pool, one-node intervention at a time.
53
+
54
+ Rest of the hard partition is held fixed. This does not solve a global optimal tree cut.
55
+ """
56
+ if teacher.training:
57
+ raise ValueError("Teacher must be in eval mode")
58
+ positive = positive_index(forest.identities,identity)
59
+ if positive is None:
60
+ return []
61
+ eligible = sorted((n for n in forest.nodes.values() if n.children),key=lambda n:n.key)
62
+ if not eligible or max_nodes <= 0:
63
+ return []
64
+ enc = teacher.encode(query)
65
+ original = teacher.select_partition(enc,forest)
66
+ if eligible:
67
+ offset %= len(eligible)
68
+ eligible = (eligible[offset:]+eligible[:offset])[:max_nodes]
69
+ targets = []
70
+ scale = max(1,len(forest.identities)*(overhead+1))
71
+ for node in eligible:
72
+ members = set(node.members)
73
+ # Build a partition where this node is active. If an ancestor is active, expand
74
+ # along the path, keeping all sibling subtrees; other roots remain unchanged.
75
+ def expose(key):
76
+ n = forest.nodes[key]
77
+ if key == node.key:
78
+ return [key]
79
+ if members.issubset(set(n.members)) and n.children:
80
+ return [x for c in n.children for x in expose(c)]
81
+ return [key]
82
+ stopped = []
83
+ for k in original:
84
+ if set(forest.nodes[k].members).issubset(members):
85
+ continue
86
+ stopped.extend(expose(k))
87
+ if node.key not in stopped:
88
+ stopped.append(node.key)
89
+ stopped = tuple(sorted(stopped))
90
+ forest.validate(stopped)
91
+ split = split_node(forest,stopped,node.key)
92
+ rs = float(listwise_loss(teacher.score_partition(enc,forest,stopped)[0],positive,multiplicities)[0])
93
+ rr = float(listwise_loss(teacher.score_partition(enc,forest,split)[0],positive,multiplicities)[0])
94
+ cs = partition_cost(forest,stopped,overhead)/scale
95
+ cr = partition_cost(forest,split,overhead)/scale
96
+ delta = rs-rr+cost_tradeoff*(cs-cr)
97
+ if abs(delta) > epsilon:
98
+ targets.append(CutTarget(node.key,delta,float(delta > 0),min(abs(delta),1.),rs,rr,cs,cr))
99
+ return targets
100
+
101
+
102
+ def cut_loss(model, encoded, forest, targets):
103
+ if not targets:
104
+ return encoded.q.sum()*0., 0
105
+ logits = torch.stack([model.cut_logit(encoded,forest.nodes[t.node_key]) for t in targets])
106
+ y = logits.new_tensor([t.split for t in targets])
107
+ w = logits.new_tensor([t.weight for t in targets])
108
+ # Keep absolute teacher confidence: normalising by sum(w) cancelled it for
109
+ # one-node queries and made near-zero counterfactual differences full labels.
110
+ return (F.binary_cross_entropy_with_logits(logits,y,reduction="none")*w).mean(),len(targets)
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/model.py ADDED
@@ -0,0 +1,275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ import math
3
+ import numpy as np
4
+ import torch
5
+ from torch import nn
6
+ from torch.nn import functional as F
7
+ from .chemistry import ADDUCTS, ANCHOR_DIM, ATOM_DIM, BOND_DIM, ELEMENTS, FP_SIZE, formula_vector, exact_mass, ppm_error
8
+ from .forest import Forest
9
+
10
+ META_DIM = len(ADDUCTS) + 9
11
+
12
+
13
+ def metadata(query):
14
+ polarity = 1. if ADDUCTS[query.adduct][1] > 0 else -1.
15
+ instrument = (query.instrument or "").lower()
16
+ family = next((i for i,s in enumerate(("orbitrap", "qtof", "iontrap")) if s in instrument), 3 if instrument else 4)
17
+ return ([float(query.adduct == a) for a in ADDUCTS] + [polarity, (query.collision_energy or 0.)/100.,
18
+ float(query.collision_energy is None), query.precursor_mz/1000.] + [float(i == family) for i in range(5)])
19
+
20
+
21
+ class SpectrumEncoder(nn.Module):
22
+ def __init__(self, cfg):
23
+ super().__init__()
24
+ d = cfg.dim
25
+ self.max_peaks = cfg.max_peaks
26
+ self.peak = nn.Sequential(nn.Linear(19, d), nn.GELU(), nn.Linear(d,d))
27
+ self.meta = nn.Sequential(nn.Linear(META_DIM,d), nn.GELU(), nn.Linear(d,d))
28
+ layer = nn.TransformerEncoderLayer(d, cfg.heads, d*4, dropout=0., activation="gelu", batch_first=True)
29
+ self.encoder = nn.TransformerEncoder(layer, cfg.spectrum_layers, enable_nested_tensor=False)
30
+ self.output = nn.LayerNorm(d)
31
+ self.register_buffer("frequencies", 2.**torch.arange(8))
32
+
33
+ def forward(self, query):
34
+ dev = self.frequencies.device
35
+ peaks = sorted(query.peaks, key=lambda p:(-p[1],p[0]))[:self.max_peaks]
36
+ peaks.sort()
37
+ p = torch.tensor(peaks, device=dev, dtype=torch.float32)
38
+ mz, inten = p[:,0]/1000., torch.sqrt(p[:,1]/p[:,1].max().clamp_min(1e-12))
39
+ loss = (query.precursor_mz-p[:,0])/1000.
40
+ angles = mz[:,None] * self.frequencies[None,:] * math.pi
41
+ x = torch.cat((mz[:,None], inten[:,None], loss[:,None], angles.sin(), angles.cos()), dim=-1)
42
+ m = self.meta(torch.tensor(metadata(query), device=dev))
43
+ tokens = self.encoder((self.peak(x)+m)[None,:,:])[0]
44
+ q = self.output((tokens*inten[:,None]).sum(0)/inten.sum().clamp_min(1e-12))
45
+ return tokens, q, m
46
+
47
+
48
+ class GraphEncoder(nn.Module):
49
+ def __init__(self, cfg):
50
+ super().__init__()
51
+ d = cfg.dim
52
+ self.atom = nn.Linear(ATOM_DIM,d)
53
+ self.edge = nn.Linear(BOND_DIM,d)
54
+ self.messages = nn.ModuleList(nn.Sequential(nn.Linear(2*d,d),nn.GELU(),nn.Linear(d,d)) for _ in range(cfg.graph_layers))
55
+ self.norms = nn.ModuleList(nn.LayerNorm(d) for _ in range(cfg.graph_layers))
56
+ self.pool = nn.Linear(2*d,d)
57
+
58
+ def forward(self, mols, device):
59
+ if not mols:
60
+ d = self.atom.out_features
61
+ return torch.empty((0,d),device=device), [], []
62
+ sizes = [len(m.atom_features) for m in mols]
63
+ offsets = np.cumsum([0]+sizes)
64
+ atoms = torch.as_tensor(np.concatenate([m.atom_features for m in mols]),device=device)
65
+ edges = torch.as_tensor(np.concatenate([m.edge_index+o for m,o in zip(mols,offsets)],axis=1),device=device)
66
+ bonds = torch.as_tensor(np.concatenate([m.bond_features for m in mols]),device=device)
67
+ h = self.atom(atoms)
68
+ e = self.edge(bonds)
69
+ u,v = edges
70
+ deg = torch.bincount(v,minlength=len(h)).float().clamp_min(1).unsqueeze(-1)
71
+ for message,norm in zip(self.messages,self.norms):
72
+ msg = message(torch.cat((h[u],e),dim=-1))
73
+ agg = torch.zeros_like(h).index_add(0,v,msg)/deg
74
+ h = norm(h+agg)
75
+ split = list(h.split(sizes))
76
+ pooled = torch.stack([torch.cat((x.mean(0), x.max(0).values)) for x in split])
77
+ return self.pool(pooled), split, sizes
78
+
79
+
80
+ @dataclass
81
+ class Encoded:
82
+ query: object
83
+ peaks: torch.Tensor
84
+ q: torch.Tensor
85
+ meta: torch.Tensor
86
+ u: torch.Tensor
87
+ z_query: torch.Tensor
88
+ z_molecules: torch.Tensor
89
+ atoms: list
90
+ whole: torch.Tensor
91
+ anchors: torch.Tensor
92
+ formula_scores: torch.Tensor
93
+ base: torch.Tensor
94
+ direct: torch.Tensor
95
+
96
+
97
+ @dataclass
98
+ class Output:
99
+ scores: torch.Tensor
100
+ direct_scores: torch.Tensor
101
+ formula_scores: torch.Tensor
102
+ partition: tuple
103
+ residual: torch.Tensor
104
+ expected_cost: torch.Tensor
105
+ encoded: Encoded
106
+
107
+
108
+ class SpecPartition(nn.Module):
109
+ def __init__(self, cfg):
110
+ super().__init__()
111
+ self.cfg = cfg
112
+ c,d = cfg.model,cfg.model.dim
113
+ self.spectrum = SpectrumEncoder(c)
114
+ self.graph = GraphEncoder(c)
115
+ self.fp = nn.Linear(FP_SIZE,d,bias=False)
116
+ self.anchor = nn.Linear(ANCHOR_DIM,d,bias=False)
117
+ self.structure = nn.Sequential(nn.Linear(3*d,d), nn.GELU(), nn.LayerNorm(d))
118
+ self.query_projection = nn.Linear(d,d)
119
+ self.mol_projection = nn.Linear(d,d)
120
+ self.formula = nn.Sequential(nn.Linear(len(ELEMENTS),d), nn.GELU(),nn.Linear(d,d))
121
+ self.formula_energy = nn.Sequential(nn.Linear(2*d+1,d),nn.GELU(),nn.Linear(d,1))
122
+ self.formula_gate = nn.Linear(d,1)
123
+ self.log_scale = nn.Parameter(torch.tensor(math.log(10.)))
124
+ self.local_q = nn.Linear(d,d,bias=False)
125
+ self.local_a = nn.Linear(d,d,bias=False)
126
+ self.local_weight = nn.Parameter(torch.tensor(0.1))
127
+ self.cut = nn.Sequential(nn.Linear(3*d+5,d),nn.GELU(),nn.Linear(d,1))
128
+ self.attn = nn.MultiheadAttention(d,c.heads,dropout=0.,batch_first=True)
129
+ self.relative = nn.Sequential(nn.Linear(3*d,d),nn.GELU(),nn.Linear(d,d))
130
+ self.member = nn.Sequential(nn.Linear(2*d,d),nn.GELU(),nn.Linear(d,1))
131
+ self.group = nn.Sequential(nn.Linear(2*d,d),nn.GELU(),nn.Linear(d,1))
132
+ self.relation_gate = nn.Sequential(nn.Linear(2*d+5,d),nn.GELU(),nn.Linear(d,1))
133
+ self.soft_assignment = nn.Sequential(nn.Linear(2*d,d),nn.GELU(),nn.Linear(d,8))
134
+
135
+ @property
136
+ def device(self):
137
+ return next(self.parameters()).device
138
+
139
+ def encode_molecules(self, mols):
140
+ # Chunk graph construction; graph tensors retain gradients during training.
141
+ us, atoms = [], []
142
+ for off in range(0,len(mols),128):
143
+ batch = mols[off:off+128]
144
+ h,a,_ = self.graph(batch,self.device)
145
+ fp = torch.tensor(np.stack([m.whole for m in batch]),device=self.device)
146
+ anchors = torch.tensor(np.stack([m.anchors for m in batch]),device=self.device)
147
+ us.append(self.structure(torch.cat((h,self.fp(fp),self.anchor(anchors)),dim=-1)))
148
+ atoms.extend(a)
149
+ u = torch.cat(us) if us else torch.empty((0,self.cfg.model.dim),device=self.device)
150
+ return u, atoms, F.normalize(self.mol_projection(u),dim=-1)
151
+
152
+ def score_formulas(self, q, query):
153
+ if hasattr(self, 'formula_v07'):
154
+ return self.formula_v07(q, query)
155
+ fs = query.formula_candidates
156
+ if not fs:
157
+ return torch.empty(0,device=self.device)
158
+ f = torch.tensor(np.stack([formula_vector(s) for s in fs]),device=self.device)
159
+ err = torch.tensor([ppm_error(exact_mass(s),query.precursor_mz,query.adduct) for s in fs],device=self.device)
160
+ # Signed log magnitude remains finite for fixed official pools with metadata discrepancies.
161
+ err = torch.sign(err)*torch.log1p(err.abs())/10.
162
+ return self.formula_energy(torch.cat((q.expand(len(fs),-1),self.formula(torch.log1p(f)),err[:,None]),-1)).squeeze(-1)
163
+
164
+ def encode(self, query):
165
+ peaks,q,meta = self.spectrum(query)
166
+ u,atoms,zm = self.encode_molecules(query.candidates)
167
+ zq = F.normalize(self.query_projection(q),dim=-1)
168
+ direct = self.log_scale.exp().clamp(max=100.) * (zm @ zq)
169
+ if self.cfg.model.local_match and atoms:
170
+ qp = F.normalize(self.local_q(peaks),dim=-1)
171
+ local = []
172
+ # Per-candidate late interaction; avoids a P x all-atoms attention matrix.
173
+ for a in atoms:
174
+ sim = qp @ F.normalize(self.local_a(a),dim=-1).T
175
+ local.append(sim.max(-1).values.mean())
176
+ direct = direct + self.local_weight*torch.stack(local)
177
+ fs = self.score_formulas(q,query)
178
+ base = direct
179
+ if self.cfg.model.formula_score and query.candidates:
180
+ lookup = {f:i for i,f in enumerate(query.formula_candidates)}
181
+ indices = torch.tensor([lookup[m.formula] for m in query.candidates],device=self.device)
182
+ base = base + torch.sigmoid(self.formula_gate(q))*fs[indices]
183
+ 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)
184
+ 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)
185
+ return Encoded(query,peaks,q,meta,u,zq,zm,atoms,whole,anchors,fs,base,direct)
186
+
187
+ def cut_logit(self, enc, node):
188
+ u = enc.u[list(node.members)]
189
+ q = enc.meta if self.cfg.model.controller_input == "metadata" else enc.q
190
+ stats = enc.q.new_tensor(node.stats)
191
+ return self.cut(torch.cat((q,u.mean(0),u.std(0,unbiased=False),stats))).squeeze(-1)
192
+
193
+ def select_partition(self, enc, forest):
194
+ result = []
195
+ def visit(k):
196
+ n = forest.nodes[k]
197
+ if n.children and self.cfg.model.relation_mode == "learned" and self.cut_logit(enc,n).detach().item() > 0:
198
+ for child in n.children:
199
+ visit(child)
200
+ else:
201
+ result.append(k)
202
+ for k in forest.roots:
203
+ visit(k)
204
+ forest.validate(result)
205
+ return tuple(result)
206
+
207
+ def expected_cost(self, enc, forest):
208
+ overhead = self.cfg.train.cost_node_overhead
209
+ def cost(k):
210
+ n = forest.nodes[k]
211
+ stop = enc.q.new_tensor(overhead+len(n.members)**2)
212
+ if not n.children:
213
+ return stop
214
+ p = torch.sigmoid(self.cut_logit(enc,n))
215
+ return (1-p)*stop+p*sum(cost(c) for c in n.children)
216
+ return sum((cost(k) for k in forest.roots), enc.q.sum()*0.) / max(1,len(forest.identities)*(overhead+1))
217
+
218
+ def score_partition(self, enc, forest, partition):
219
+ forest.validate(partition)
220
+ residual = torch.zeros_like(enc.base)
221
+ if self.cfg.model.relation_mode == "none":
222
+ return enc.base, residual
223
+ if self.cfg.model.relation_mode in {"knn", "set", "softpool"}:
224
+ # Candidate-set controls. These are explicit adapters, not reproductions of published models.
225
+ if len(enc.u) < 2:
226
+ return enc.base,residual
227
+ if self.cfg.model.relation_mode == "set":
228
+ # O(Nd) query-attentive set context; no N x N matrix.
229
+ weights = (enc.u@enc.q/math.sqrt(enc.u.shape[-1])).softmax(0)
230
+ context = (weights[:,None]*enc.u).sum(0).expand_as(enc.u)
231
+ elif self.cfg.model.relation_mode == "softpool":
232
+ assignments = self.soft_assignment(torch.cat((enc.u,enc.q.expand_as(enc.u)),-1)).softmax(-1)
233
+ prototypes = assignments.T@enc.u/assignments.sum(0).clamp_min(1e-6)[:,None]
234
+ context = assignments@prototypes
235
+ else:
236
+ contexts = []
237
+ norm = F.normalize(enc.u,dim=-1)
238
+ # Exact, blocked kNN in learned space; O(N^2) time but bounded score memory.
239
+ for start in range(0,len(norm),128):
240
+ similarities = norm[start:start+128]@norm.T
241
+ idx = similarities.topk(min(17,len(norm)),dim=-1).indices
242
+ contexts.append(enc.u[idx].mean(1))
243
+ context = torch.cat(contexts)
244
+ r = self.member(torch.cat((enc.u,context),-1)).squeeze(-1)
245
+ residual = self.cfg.model.residual_bound*torch.tanh(r)
246
+ return enc.base+residual,residual
247
+ for key in partition:
248
+ node = forest.nodes[key]
249
+ if len(node.members) == 1:
250
+ continue
251
+ ids, med = list(node.members),node.medoid
252
+ u = enc.u[ids]
253
+ context,_ = self.attn(enc.q[None,None,:],u[None,:,:],u[None,:,:],need_weights=False)
254
+ context = context[0,0]
255
+ if self.cfg.model.relative_difference:
256
+ # Signed fingerprint and local attachment-environment differences against the medoid.
257
+ delta = self.relative(torch.cat((u-enc.u[med],self.fp(enc.whole[ids]-enc.whole[med]),
258
+ self.anchor(enc.anchors[ids]-enc.anchors[med])),dim=-1))
259
+ else:
260
+ delta = u
261
+ member = self.member(torch.cat((delta,enc.q.expand_as(delta)),-1)).squeeze(-1)
262
+ member = member-member.mean()
263
+ group = self.group(torch.cat((enc.q,context))).squeeze(-1)
264
+ gate = torch.sigmoid(self.relation_gate(torch.cat((enc.q,context,enc.q.new_tensor(node.stats))))).squeeze(-1)
265
+ r = self.cfg.model.residual_bound*gate*torch.tanh(group+member)
266
+ residual = residual.index_copy(0,torch.tensor(ids,device=self.device),r)
267
+ return enc.base+residual,residual
268
+
269
+ def forward(self, query, forest, partition=None):
270
+ if tuple(m.identity for m in query.candidates) != forest.identities:
271
+ raise ValueError("Forest does not match candidate identities/order")
272
+ enc = self.encode(query)
273
+ partition = self.select_partition(enc,forest) if partition is None else tuple(partition)
274
+ scores,residual = self.score_partition(enc,forest,partition)
275
+ return Output(scores,enc.direct,enc.formula_scores,partition,residual,self.expected_cost(enc,forest),enc)
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/model_v03.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Capacity and batching upgrade. The v0.2 model/checkpoint format stays untouched.
2
+
3
+ No candidate pruning is performed by this model. Query-local scores and masks
4
+ are independent of other queries in the same batch. Canonical structures are
5
+ encoded once per batch, including contrastive-only training molecules.
6
+ """
7
+ from dataclasses import replace
8
+ import math
9
+ import numpy as np
10
+ import torch
11
+ from torch import nn
12
+ from torch.nn import functional as F
13
+ from torch.nn.utils.rnn import pad_sequence
14
+ from .model import SpecPartition, SpectrumEncoder, Encoded, Output, metadata
15
+ from .chemistry import ATOM_DIM, BOND_DIM, FP_SIZE, ANCHOR_DIM
16
+
17
+
18
+ class BatchedSpectrumEncoder(SpectrumEncoder):
19
+ def forward_batch(self, queries):
20
+ features, weights, lengths = [], [], []
21
+ for query in queries:
22
+ peaks = sorted(query.peaks, key=lambda p: (-p[1], p[0]))[:self.max_peaks]
23
+ peaks.sort()
24
+ p = torch.tensor(peaks, device=self.frequencies.device, dtype=torch.float32)
25
+ mz = p[:, 0] / 1000.
26
+ intensity = torch.sqrt(p[:, 1] / p[:, 1].max().clamp_min(1e-12))
27
+ delta = (query.precursor_mz - p[:, 0]) / 1000.
28
+ angles = mz[:, None] * self.frequencies[None, :] * math.pi
29
+ features.append(torch.cat((mz[:, None], intensity[:, None], delta[:, None], angles.sin(), angles.cos()), -1))
30
+ weights.append(intensity)
31
+ lengths.append(len(p))
32
+ x = pad_sequence(features, batch_first=True)
33
+ w = pad_sequence(weights, batch_first=True)
34
+ mask = torch.arange(x.shape[1], device=x.device)[None, :] >= torch.tensor(lengths, device=x.device)[:, None]
35
+ meta = self.meta(torch.tensor([metadata(q) for q in queries], device=x.device))
36
+ tokens = self.encoder(self.peak(x) + meta[:, None, :], src_key_padding_mask=mask)
37
+ pooled = self.output((tokens * w[:, :, None]).sum(1) / w.sum(1).clamp_min(1e-12)[:, None])
38
+ return [tokens[i, :n] for i, n in enumerate(lengths)], pooled, meta
39
+
40
+ def forward(self, query):
41
+ tokens, q, meta = self.forward_batch([query])
42
+ return tokens[0], q[0], meta[0]
43
+
44
+
45
+ class GatedGraphEncoder(nn.Module):
46
+ """Edge-gated MPNN with source/target context and node feed-forward blocks."""
47
+ def __init__(self, cfg):
48
+ super().__init__()
49
+ d = cfg.dim
50
+ self.atom = nn.Linear(ATOM_DIM, d)
51
+ self.edge = nn.Linear(BOND_DIM, d)
52
+ 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))
53
+ self.gates = nn.ModuleList(nn.Linear(3*d, d) for _ in range(cfg.graph_layers))
54
+ self.norms = nn.ModuleList(nn.LayerNorm(d) for _ in range(cfg.graph_layers))
55
+ self.ffns = nn.ModuleList(nn.Sequential(nn.Linear(d, 4*d), nn.GELU(), nn.Linear(4*d, d)) for _ in range(cfg.graph_layers))
56
+ self.ffnorms = nn.ModuleList(nn.LayerNorm(d) for _ in range(cfg.graph_layers))
57
+ self.pool = nn.Linear(2*d, d)
58
+
59
+ def forward(self, mols, device):
60
+ sizes = [len(m.atom_features) for m in mols]
61
+ offsets = np.cumsum([0] + sizes)
62
+ atoms = torch.as_tensor(np.concatenate([m.atom_features for m in mols]), device=device)
63
+ edges = torch.as_tensor(np.concatenate([m.edge_index + o for m, o in zip(mols, offsets)], axis=1), device=device)
64
+ bonds = torch.as_tensor(np.concatenate([m.bond_features for m in mols]), device=device)
65
+ h, e = self.atom(atoms), self.edge(bonds)
66
+ src, dst = edges
67
+ degree = torch.bincount(dst, minlength=len(h)).clamp_min(1).to(h.dtype)[:, None]
68
+ for msg, gate, norm, ffn, ffnorm in zip(self.messages, self.gates, self.norms, self.ffns, self.ffnorms):
69
+ context = torch.cat((h[src], h[dst], e), -1)
70
+ messages = msg(context) * torch.sigmoid(gate(context))
71
+ # LayerNorm may promote h to FP32 under autocast; scatter kernels
72
+ # require matching dtypes, unlike autocast-aware matrix products.
73
+ aggregate = torch.zeros_like(h).index_add(0, dst, messages.to(h.dtype)) / degree
74
+ h = norm(h + aggregate)
75
+ h = ffnorm(h + ffn(h))
76
+ graph_ids = torch.repeat_interleave(torch.arange(len(mols), device=device), torch.tensor(sizes, device=device))
77
+ sums = h.new_zeros((len(mols), h.shape[-1])).index_add(0, graph_ids, h)
78
+ maxima = h.new_full((len(mols), h.shape[-1]), -torch.inf)
79
+ maxima = maxima.scatter_reduce(0, graph_ids[:, None].expand_as(h), h, reduce='amax', include_self=True)
80
+ mean = sums / torch.tensor(sizes, device=device, dtype=h.dtype)[:, None]
81
+ return self.pool(torch.cat((mean, maxima), -1)), list(h.split(sizes)), sizes
82
+
83
+
84
+ class BatchedSpecPartition(SpecPartition):
85
+ def __init__(self, cfg, graph_chunk=256, local_chunk=64, gated_graph=True):
86
+ super().__init__(cfg)
87
+ self.spectrum = BatchedSpectrumEncoder(cfg.model)
88
+ if gated_graph:
89
+ self.graph = GatedGraphEncoder(cfg.model)
90
+ self.graph_chunk, self.local_chunk = graph_chunk, local_chunk
91
+
92
+ def encode_molecules(self, mols):
93
+ us, atoms = [], []
94
+ for start in range(0, len(mols), self.graph_chunk):
95
+ batch = mols[start:start+self.graph_chunk]
96
+ h, a, _ = self.graph(batch, self.device)
97
+ fp = torch.as_tensor(np.stack([m.whole for m in batch]), device=self.device)
98
+ anchors = torch.as_tensor(np.stack([m.anchors for m in batch]), device=self.device)
99
+ us.append(self.structure(torch.cat((h, self.fp(fp), self.anchor(anchors)), -1)))
100
+ atoms.extend(a)
101
+ u = torch.cat(us) if us else torch.empty((0, self.cfg.model.dim), device=self.device)
102
+ return u, atoms, F.normalize(self.mol_projection(u).float(), dim=-1)
103
+
104
+ def local_scores(self, peaks, atoms):
105
+ qp = F.normalize(self.local_q(peaks).float(), dim=-1)
106
+ result = []
107
+ for start in range(0, len(atoms), self.local_chunk):
108
+ block = atoms[start:start+self.local_chunk]
109
+ padded = pad_sequence(block, batch_first=True)
110
+ z = F.normalize(self.local_a(padded).float(), dim=-1)
111
+ valid = torch.arange(padded.shape[1], device=self.device)[None, :] < torch.tensor([len(a) for a in block], device=self.device)[:, None]
112
+ # Avoid zero-batch-stride broadcast GEMM. On SM120/CUDA 13.2 the
113
+ # FP32 teacher route triggered a cuBLAS TF32 warp illegal address
114
+ # under memcheck. A 2D GEMM computes the identical dot products
115
+ # without materializing B copies of the spectrum or changing loss.
116
+ scores = (qp @ z.reshape(-1, z.shape[-1]).T).reshape(
117
+ qp.shape[0], z.shape[0], z.shape[1]).permute(1, 0, 2)
118
+ result.append(scores.masked_fill(~valid[:, None, :], -torch.inf).max(-1).values.mean(-1))
119
+ return torch.cat(result)
120
+
121
+ def encode_batch(self, queries, extras=()):
122
+ tokens, qs, metas = self.spectrum.forward_batch(queries)
123
+ # SMILES as well as connectivity is part of the key: extras/other queries
124
+ # must never change the representation of an existing candidate alias.
125
+ key = lambda m: (m.identity, m.smiles)
126
+ lookup_mols = {key(m):m for q in queries for m in q.candidates}
127
+ lookup_mols.update({key(m):m for m in extras})
128
+ keys = sorted(lookup_mols)
129
+ positions = {k:i for i,k in enumerate(keys)}
130
+ u, all_atoms, zm = self.encode_molecules([lookup_mols[k] for k in keys])
131
+ zq = F.normalize(self.query_projection(qs).float(), dim=-1)
132
+ encoded = []
133
+ for i, q in enumerate(queries):
134
+ inds = [positions[key(m)] for m in q.candidates]
135
+ idx = torch.tensor(inds, device=self.device, dtype=torch.long)
136
+ ui, zi, ai = u[idx], zm[idx], [all_atoms[k] for k in inds]
137
+ direct = self.log_scale.exp().clamp(max=100.) * (zi.float() @ zq[i].float())
138
+ if self.cfg.model.local_match and ai:
139
+ direct = direct + self.local_weight * self.local_scores(tokens[i], ai)
140
+ fs = self.score_formulas(qs[i], q).float()
141
+ base = direct
142
+ if self.cfg.model.formula_score and inds:
143
+ fi = {f:j for j,f in enumerate(q.formula_candidates)}
144
+ fidx = torch.tensor([fi[m.formula] for m in q.candidates], device=self.device)
145
+ base = base + torch.sigmoid(self.formula_gate(qs[i])).float() * fs[fidx]
146
+ 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))
147
+ 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))
148
+ encoded.append(Encoded(q,tokens[i].float(),qs[i].float(),metas[i].float(),ui.float(),zq[i],zi,
149
+ [a.float() for a in ai],whole,anchors,fs,base.float(),direct.float()))
150
+ return encoded, zm[torch.tensor([positions[key(m)] for m in extras],device=self.device,dtype=torch.long)]
151
+
152
+ def encode(self, query):
153
+ return self.encode_batch([query])[0][0]
154
+
155
+ def forward_batch(self, queries, forests, extras=()):
156
+ if len(queries) != len(forests):
157
+ raise ValueError('One forest is required per query')
158
+ encs, zextra = self.encode_batch(queries, extras)
159
+ outputs = []
160
+ # Keep reductions and the relatively small relation/controller branch FP32.
161
+ with torch.autocast(device_type=self.device.type, enabled=False):
162
+ for enc, forest in zip(encs, forests):
163
+ if tuple(m.identity for m in enc.query.candidates) != forest.identities:
164
+ raise ValueError('Forest/candidate mismatch')
165
+ partition = self.select_partition(enc, forest)
166
+ scores, residual = self.score_partition(enc, forest, partition)
167
+ cost = self.expected_cost(enc, forest) if self.cfg.model.relation_mode=='learned' else enc.q.sum()*0.
168
+ outputs.append(Output(scores,enc.direct,enc.formula_scores,partition,residual,cost,enc))
169
+ return outputs, zextra
170
+
171
+ def forward(self, query, forest, partition=None):
172
+ if partition is None:
173
+ return self.forward_batch([query],[forest])[0][0]
174
+ enc = self.encode(query)
175
+ with torch.autocast(device_type=self.device.type, enabled=False):
176
+ scores, residual = self.score_partition(enc, forest, partition)
177
+ return Output(scores,enc.direct,enc.formula_scores,partition,residual,self.expected_cost(enc,forest),enc)
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/multiview_data.py ADDED
@@ -0,0 +1,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Read-only source adapters and resumable, compressed multi-view training index.
2
+
3
+ Source row identity is retained: multiple MS for one structure are NOT deduplicated.
4
+ Official pools are retained verbatim; training-only structural isolation is a
5
+ separately labelled projection, never an edit to the official source pools.
6
+ """
7
+ import argparse
8
+ import csv
9
+ from datetime import datetime, timezone
10
+ from functools import lru_cache
11
+ import hashlib
12
+ import json
13
+ import math
14
+ from pathlib import Path
15
+ import sqlite3
16
+ import time
17
+ import zlib
18
+ from rdkit import Chem, RDLogger
19
+ from rdkit.Chem import Descriptors, rdMolDescriptors
20
+ from .chemistry import ADDUCTS, canonical_formula, exact_mass
21
+
22
+
23
+ def utc():
24
+ return datetime.now(timezone.utc).isoformat()
25
+
26
+
27
+ def sha(path):
28
+ h = hashlib.sha256()
29
+ with open(path, "rb") as fh:
30
+ for part in iter(lambda: fh.read(4*1024*1024), b""): h.update(part)
31
+ return h.hexdigest()
32
+
33
+
34
+ def packed(value):
35
+ return zlib.compress(json.dumps(value, ensure_ascii=False, allow_nan=False, separators=(",", ":")).encode())
36
+
37
+
38
+ def unpacked(value):
39
+ return json.loads(zlib.decompress(value))
40
+
41
+
42
+ def save(path, value):
43
+ path = Path(path); path.parent.mkdir(parents=True, exist_ok=True)
44
+ temp = path.with_suffix(path.suffix+".tmp")
45
+ temp.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False)+"\n")
46
+ temp.replace(path)
47
+
48
+
49
+ def emit(event, **kw):
50
+ print(json.dumps({"utc": utc(), "event": event, **kw}, ensure_ascii=False), flush=True)
51
+
52
+
53
+ @lru_cache(maxsize=200000)
54
+ def structure(smiles):
55
+ mol = Chem.MolFromSmiles(smiles)
56
+ if mol is None: raise ValueError("invalid_smiles")
57
+ key = Chem.MolToInchiKey(mol)
58
+ if not key: raise ValueError("missing_derived_key")
59
+ return {"identity": key[:14], "inchikey": key, "formula": rdMolDescriptors.CalcMolFormula(mol),
60
+ "mass": Descriptors.ExactMolWt(mol), "charge": Chem.GetFormalCharge(mol),
61
+ "isotope": any(a.GetIsotope() for a in mol.GetAtoms()),
62
+ "fragments": len(Chem.GetMolFrags(mol))}
63
+
64
+
65
+ def connect(path):
66
+ db = sqlite3.connect(path, timeout=90)
67
+ db.execute("PRAGMA journal_mode=WAL")
68
+ db.execute("PRAGMA busy_timeout=90000")
69
+ return db
70
+
71
+
72
+ def initialize(path):
73
+ db = connect(path)
74
+ db.executescript('''
75
+ CREATE TABLE IF NOT EXISTS sources(name TEXT PRIMARY KEY,path TEXT,sha256 TEXT,rows INTEGER DEFAULT 0,done INTEGER DEFAULT 0);
76
+ CREATE TABLE IF NOT EXISTS heldout(identity TEXT, dataset TEXT, PRIMARY KEY(identity,dataset));
77
+ CREATE TABLE IF NOT EXISTS spectra(id INTEGER PRIMARY KEY,source TEXT,source_row INTEGER,sample_id TEXT,
78
+ identity TEXT,formula TEXT,status TEXT,reason TEXT,body BLOB,UNIQUE(source,source_row));
79
+ CREATE INDEX IF NOT EXISTS spectra_source_status ON spectra(source,status,id);
80
+ CREATE INDEX IF NOT EXISTS spectra_identity ON spectra(identity);
81
+ CREATE TABLE IF NOT EXISTS structures(identity TEXT PRIMARY KEY,smiles TEXT,formula TEXT,mass REAL);
82
+ CREATE TABLE IF NOT EXISTS formulas(formula TEXT PRIMARY KEY,mass REAL);
83
+ CREATE TABLE IF NOT EXISTS official_pools(view TEXT,target TEXT,body BLOB,sha256 TEXT,count INTEGER,PRIMARY KEY(view,target));
84
+ CREATE TABLE IF NOT EXISTS jobs(formula TEXT PRIMARY KEY,status TEXT DEFAULT 'pending',attempts INTEGER DEFAULT 0,error TEXT,updated TEXT);
85
+ CREATE TABLE IF NOT EXISTS demand(formula TEXT PRIMARY KEY,priority INTEGER);
86
+ CREATE TABLE IF NOT EXISTS formula_pools(formula TEXT PRIMARY KEY,body BLOB,raw_count INTEGER,sha256 TEXT,updated TEXT);
87
+ CREATE TABLE IF NOT EXISTS meta(key TEXT PRIMARY KEY,value TEXT);
88
+ ''')
89
+ db.commit()
90
+ return db
91
+
92
+
93
+ def meta(db, key, value=None):
94
+ if value is None:
95
+ row = db.execute("SELECT value FROM meta WHERE key=?", (key,)).fetchone()
96
+ return json.loads(row[0]) if row else None
97
+ db.execute("INSERT OR REPLACE INTO meta VALUES (?,?)", (key, json.dumps(value))); db.commit()
98
+
99
+
100
+ def raw_rows(path):
101
+ if str(path).endswith(".tsv"):
102
+ with open(path) as fh:
103
+ yield from csv.DictReader(fh, delimiter="\t")
104
+ else:
105
+ import ijson
106
+ with open(path, "rb") as fh:
107
+ yield from ijson.items(fh, "item", use_float=True)
108
+
109
+
110
+ def numeric(value):
111
+ try:
112
+ value = float(value)
113
+ return value if math.isfinite(value) else None
114
+ except (ValueError, TypeError): return None
115
+
116
+
117
+ def normalized_record(raw, source, row, banned):
118
+ """Conservative metadata adapter. No mass is calculated from truth for input."""
119
+ smiles = raw.get("smiles", raw.get("SMILES"))
120
+ info = structure(smiles)
121
+ body = {"source": source, "source_row": row, "reference_smiles": smiles,
122
+ "identity": info["identity"], "formula": info["formula"], "mass": info["mass"],
123
+ "target_smiles": smiles, "raw_id": raw.get("identifier", raw.get("record_id", raw.get("id"))),
124
+ "raw_provenance": raw.get("provenance"), "formula_label_only": True}
125
+ if info["identity"] in banned: raise ValueError("heldout_connectivity")
126
+ if info["charge"] or info["isotope"] or info["fragments"] != 1:
127
+ raise ValueError("unsupported_charged_isotopic_or_multifragment_structure")
128
+ canonical_formula(info["formula"])
129
+ if source == "odata":
130
+ if str(raw.get("ms_level", "")).upper() not in {"MS2", "2"}:
131
+ raise ValueError("not_documented_ms2")
132
+ if raw.get("polarity") == "conflict": raise ValueError("polarity_conflict")
133
+ if str(raw.get("ion_source", "")).upper() == "EI": raise ValueError("ei_spectrum")
134
+ peaks = raw.get("ms")
135
+ mz = numeric(raw.get("precursor_mz"))
136
+ origin = raw.get("precursor_mz_source_field")
137
+ if not origin or str(origin).lower() in {"parent_mass", "parent_mz", "exact_mass"}:
138
+ raise ValueError("unverified_experimental_precursor")
139
+ body["ms_level_evidence"] = raw.get("ms_level_evidence")
140
+ instrument = raw.get("instrument")
141
+ declared = raw.get("charge")
142
+ else:
143
+ xs, ys = raw["mzs"].split(","), raw["intensities"].split(",")
144
+ if len(xs) != len(ys): raise ValueError("peak_length_mismatch")
145
+ peaks = list(zip(xs, ys)); mz = numeric(raw.get("precursor_mz"))
146
+ origin = "precursor_mz"; instrument = raw.get("instrument_type"); declared = None
147
+ adduct = str(raw.get("adduct", "")).strip()
148
+ # Only unambiguous chemical aliases; ambiguous '[M+FA]-' remains quarantined.
149
+ adduct = {"[M+HCOOH-H]-": "[M+FA-H]-", "[M+formate]-": "[M+FA-H]-"}.get(adduct, adduct)
150
+ if adduct not in ADDUCTS: raise ValueError("unsupported_or_ambiguous_adduct")
151
+ if declared is not None and numeric(declared) != ADDUCTS[adduct][1]: raise ValueError("charge_adduct_conflict")
152
+ if mz is None or mz <= 0: raise ValueError("invalid_experimental_precursor")
153
+ peaks = [[float(x),float(y)] for x,y in peaks]
154
+ 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:
155
+ raise ValueError("invalid_spectrum")
156
+ # CE units vary across libraries. Preserve raw CE, mask the numerical feature
157
+ # until a validated instrument-specific eV/NCE adapter is available.
158
+ body["collision_energy_raw"] = raw.get("collision_energy")
159
+ body["precursor_source_field"] = origin
160
+ body["features"] = {"peaks": peaks, "precursor_mz": mz, "adduct": adduct,
161
+ "collision_energy": None, "instrument": instrument, "candidates": [], "formula_candidates": [],
162
+ "dataset_mode": "odata_training" if source == "odata" else "massspecgym_official",
163
+ "candidate_view": "warmup", "formula_universe_source": "candidate_pool"}
164
+ return body
165
+
166
+
167
+ def evaluation_record(raw, source, row):
168
+ """Evaluation only: all original pool entries stay under their official IDs.
169
+
170
+ CASMI's neutral parent_mz is never accepted. Charge/adduct conflicts receive
171
+ a terminal unsupported status in the caller, never a forged single charge.
172
+ """
173
+ if source != "casmi2022":
174
+ b=normalized_record(raw,source,row,set())
175
+ b["split"]="validation" if source=="msg_validation" else "test"
176
+ return b
177
+ adduct=str(raw["Adduct"]).strip()
178
+ if adduct not in ADDUCTS:raise ValueError("unsupported_adduct")
179
+ charge=str(raw["CHARGE"]).strip()
180
+ signed=int(charge[:-1])*(1 if charge[-1]=="+" else -1) if charge[-1:] in {"+","-"} else int(charge)
181
+ if signed != ADDUCTS[adduct][1]:raise ValueError("charge_adduct_conflict")
182
+ proxy={"smiles":raw["SMILES"],"ms":raw["ms"],"ms_level":str(raw["MSLEVEL"]),
183
+ "precursor_mz":raw["PEPMASS"],"precursor_mz_source_field":"PEPMASS","adduct":adduct,
184
+ "charge":signed,"record_id":str(raw["CASMI_ID"])}
185
+ b=normalized_record(proxy,"odata",row,set())
186
+ b.update(source="casmi2022",split="test",casmi_id=raw["CASMI_ID"])
187
+ b["features"]["dataset_mode"]="casmi_autonomous"
188
+ return b
189
+
190
+
191
+ def register_source(db, name, path):
192
+ row = db.execute("SELECT sha256,rows,done,path FROM sources WHERE name=?", (name,)).fetchone()
193
+ digest = sha(path)
194
+ if row and (row[0] != digest or row[3] != str(path)): raise ValueError("Source changed: "+name)
195
+ if not row:
196
+ db.execute("INSERT INTO sources(name,path,sha256) VALUES (?,?,?)", (name,str(path),digest)); db.commit()
197
+ return row[1:3] if row else (0,0)
198
+
199
+
200
+ def index_all(config):
201
+ RDLogger.DisableLog("rdApp.*")
202
+ root = Path(config["work_dir"]); root.mkdir(parents=True, exist_ok=True)
203
+ db = initialize(root/"data.sqlite")
204
+ # Fingerprints of all registered evaluation structures are recomputed, not
205
+ # inferred from source-declared keys. These references never enter model input.
206
+ if not meta(db,"registry_complete"):
207
+ for name,path in config["heldout"].items():
208
+ register_source(db,"registry_"+name,path)
209
+ count = 0
210
+ for raw in raw_rows(path):
211
+ s = raw.get("smiles",raw.get("SMILES"))
212
+ key = structure(s)["identity"]
213
+ db.execute("INSERT OR IGNORE INTO heldout VALUES (?,?)",(key,name)); count += 1
214
+ db.execute("UPDATE sources SET rows=?,done=1 WHERE name=?",(count,"registry_"+name))
215
+ db.commit(); emit("registry",dataset=name,rows=count)
216
+ meta(db,"registry_complete",True)
217
+ # Metadata migration for indexes made by the initial v0.2 adapter: registry
218
+ # keys were complete but source progress rows were not persisted.
219
+ for name,path in config["heldout"].items():
220
+ row=db.execute("SELECT done FROM sources WHERE name=?",("registry_"+name,)).fetchone()
221
+ if row and not row[0]:
222
+ register_source(db,"registry_"+name,path)
223
+ count=sum(1 for _ in raw_rows(path))
224
+ db.execute("UPDATE sources SET rows=?,done=1 WHERE name=?",(count,"registry_"+name));db.commit()
225
+ banned = {r[0] for r in db.execute("SELECT identity FROM heldout")}
226
+ # Official lists indexed without normalization, filtering, truncation or reordering.
227
+ import ijson
228
+ for view,path in config["official_pools"].items():
229
+ done_rows, done = register_source(db,view,path)
230
+ if done: continue
231
+ with open(path,"rb") as fh:
232
+ for i,(target,pool) in enumerate(ijson.kvitems(fh,"",use_float=True),1):
233
+ if i <= done_rows: continue
234
+ buf = json.dumps(pool,separators=(",",":")).encode()
235
+ db.execute("INSERT OR REPLACE INTO official_pools VALUES (?,?,?,?,?)",
236
+ (view,target,packed(pool),hashlib.sha256(buf).hexdigest(),len(pool)))
237
+ if i % 2000 == 0:
238
+ db.execute("UPDATE sources SET rows=? WHERE name=?",(i,view)); db.commit()
239
+ emit("official_pool_index",view=view,pools=i)
240
+ db.execute("UPDATE sources SET rows=?,done=1 WHERE name=?",(i,view)); db.commit()
241
+ # MSG first: enables exact fixed-pool checks while the larger o_data scan runs.
242
+ for source in ("msg_train","odata"):
243
+ path=config["training"][source]
244
+ done_rows,done=register_source(db,source,path)
245
+ if done: continue
246
+ for i,raw in enumerate(raw_rows(path),1):
247
+ if i <= done_rows: continue
248
+ body=None; identity=None; formula=None; status="eligible"; reason=None
249
+ try:
250
+ body=normalized_record(raw,source,i,banned)
251
+ identity,formula=body["identity"],body["formula"]
252
+ db.execute("INSERT OR IGNORE INTO structures VALUES (?,?,?,?)",(identity,body["reference_smiles"],formula,body["mass"]))
253
+ db.execute("INSERT OR IGNORE INTO formulas VALUES (?,?)",(formula,exact_mass(formula)))
254
+ if source == "odata":
255
+ db.execute("INSERT OR IGNORE INTO jobs(formula) VALUES (?)",(formula,))
256
+ except (ValueError,TypeError,KeyError,OverflowError) as exc:
257
+ status="quarantined"; reason=str(exc)[:250]
258
+ body={"source":source,"source_row":i,"raw_id":raw.get("identifier",raw.get("record_id")),
259
+ "reason":reason,"source_kept_unchanged":True}
260
+ sample=f"{source}:{i}"
261
+ db.execute("INSERT OR REPLACE INTO spectra(source,source_row,sample_id,identity,formula,status,reason,body) VALUES (?,?,?,?,?,?,?,?)",
262
+ (source,i,sample,identity,formula,status,reason,packed(body)))
263
+ if i % 2000 == 0:
264
+ db.execute("UPDATE sources SET rows=? WHERE name=?",(i,source)); db.commit()
265
+ emit("spectra_index",source=source,rows=i)
266
+ db.execute("UPDATE sources SET rows=?,done=1 WHERE name=?",(i,source)); db.commit()
267
+ emit("source_complete",source=source,rows=i)
268
+ catalog=[r[0] for r in db.execute("SELECT formula FROM formulas ORDER BY formula")]
269
+ meta(db,"formula_catalog_sha256",hashlib.sha256("\n".join(catalog).encode()).hexdigest())
270
+ meta(db,"index_complete",True)
271
+ summary={"utc":utc(),"source_counts":list(db.execute("SELECT source,status,COUNT(*) FROM spectra GROUP BY source,status")),
272
+ "quarantine_reasons":list(db.execute("SELECT source,reason,COUNT(*) FROM spectra WHERE status='quarantined' GROUP BY source,reason")),
273
+ "structures":db.execute("SELECT COUNT(*) FROM structures").fetchone()[0],"formulas":len(catalog),
274
+ "heldout_structures":len(banned),"original_records_deduplicated":False,
275
+ "formula_universe":"mass_filtered_training_catalog; closed vocabulary, not exhaustive elemental enumeration",
276
+ "source_sha256":list(db.execute("SELECT name,path,sha256,rows,done FROM sources"))}
277
+ save(root/"index_summary.json",summary); emit("index_complete",**summary)
278
+ db.close()
279
+
280
+
281
+ def main():
282
+ p=argparse.ArgumentParser();p.add_argument("--config",required=True)
283
+ args=p.parse_args();index_all(json.loads(Path(args.config).read_text()))
284
+
285
+
286
+ if __name__ == "__main__": main()
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/multiview_pools.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Six independent candidate views with shared formula-level PubChem snapshots."""
2
+ import argparse
3
+ import fcntl
4
+ from dataclasses import replace
5
+ import hashlib
6
+ import json
7
+ from pathlib import Path
8
+ import shutil
9
+ import time
10
+ from datetime import datetime, timezone, timedelta
11
+ import numpy as np
12
+ import torch
13
+ from .chemistry import ADDUCTS, exact_mass, molecule, neutral_mass_from_mz
14
+ from .multiview_data import connect, emit, meta, packed, unpacked, save, utc
15
+ from .retrieval import PubChemCache, filter_candidates
16
+ from .schema import parse_record
17
+
18
+
19
+ class FormulaCatalog:
20
+ """Truth-independent at query time, but intentionally closed-vocabulary.
21
+
22
+ Training catalogue coverage and top-K recall must be reported separately;
23
+ do not call this exhaustive elemental enumeration or an open-vocabulary head.
24
+ """
25
+ def __init__(self, db):
26
+ rows=list(db.execute("SELECT formula,mass FROM formulas ORDER BY mass,formula"))
27
+ self.formulas=[r[0] for r in rows]; self.mass=np.array([r[1] for r in rows])
28
+ self.sha256=hashlib.sha256("\n".join(sorted(self.formulas)).encode()).hexdigest()
29
+
30
+ def select(self, mz, adduct, ppm=10.):
31
+ center=neutral_mass_from_mz(mz,adduct)
32
+ delta=mz*abs(ADDUCTS[adduct][1])*ppm/1e6
33
+ a,b=np.searchsorted(self.mass,[center-delta,center+delta],side="left")
34
+ b=np.searchsorted(self.mass,center+delta,side="right")
35
+ return sorted(self.formulas[a:b])
36
+
37
+
38
+ def empty_example(body, view="warmup"):
39
+ f={**body["features"],"candidate_view":view,"candidates":[],"formula_candidates":[]}
40
+ return parse_record({"sample_id":f'{body["source"]}:{body["source_row"]}',"split":"train",
41
+ "features":f,"labels":{"reference_smiles":body["reference_smiles"]}})
42
+
43
+
44
+ @torch.no_grad()
45
+ def predicted_formulas(model, body, catalog, ppm=10.):
46
+ example=empty_example(body)
47
+ fs=catalog.select(example.query.precursor_mz,example.query.adduct,ppm)
48
+ q=replace(example.query,formula_candidates=tuple(fs),formula_universe_source="training_catalog_mass_filtered")
49
+ _,vector,_=model.spectrum(q)
50
+ scores=model.score_formulas(vector,q).cpu().tolist()
51
+ if not all(np.isfinite(scores)): raise RuntimeError("Nonfinite formula scores")
52
+ order=sorted(range(len(fs)),key=lambda i:(-scores[i],fs[i]))
53
+ return [fs[i] for i in order[:10]], [{"formula":fs[i],"score":scores[i],"rank":j+1} for j,i in enumerate(order)]
54
+
55
+
56
+ def candidate_view(db, body, view, catalog=None, frozen_model=None, checkpoint_sha256=None):
57
+ """Return intact raw pool entries and provenance, or a durable pending status.
58
+
59
+ The reference is read for ORACLE branches only. Predicted branches receive
60
+ the MS query and frozen model; no reference injection, forced positive, or
61
+ CSI/SIRIUS input is permitted.
62
+ """
63
+ if view in {"msg_mass","msg_formula"}:
64
+ row=db.execute("SELECT body,sha256,count FROM official_pools WHERE view=? AND target=?",(view,body["target_smiles"])).fetchone()
65
+ if row is None: raise ValueError("missing_official_target_pool")
66
+ return [{"smiles":s,"source_id":None} for s in unpacked(row[0])], {
67
+ "status":"ready","view":view,"raw_count":row[2],"filtered_count":row[2],
68
+ "pool_sha256":row[1],"ppm_filter_applied":False,"official_pool_unchanged":True}
69
+ if view not in {"odata_oracle","odata_predicted_top10","casmi_oracle","casmi_predicted_top10"}:
70
+ raise ValueError("Unsupported view")
71
+ oracle=view.endswith("oracle")
72
+ if oracle:
73
+ selected=[body["formula"]]; predictions=[]
74
+ else:
75
+ if frozen_model is None or catalog is None or not checkpoint_sha256:
76
+ raise ValueError("Predicted view requires a frozen checkpoint hash and independent formula universe")
77
+ selected,predictions=predicted_formulas(frozen_model,body,catalog)
78
+ pending=[]; branches=[]; candidates=[]
79
+ for formula in selected:
80
+ row=db.execute("SELECT body,sha256,raw_count,updated FROM formula_pools WHERE formula=?",(formula,)).fetchone()
81
+ if row is None:
82
+ db.execute("INSERT OR IGNORE INTO jobs(formula) VALUES (?)",(formula,))
83
+ db.execute("INSERT OR REPLACE INTO demand VALUES (?,10)",(formula,));pending.append(formula);continue
84
+ artifact=unpacked(row[0]); raw=artifact["records"]
85
+ kept,rejected=filter_candidates(raw,body["features"]["precursor_mz"],body["features"]["adduct"],formula)
86
+ candidates.extend({"smiles":r["smiles"],"source_id":str(r["cid"])} for r in kept)
87
+ counts={}
88
+ for r in rejected: counts[r["reason"]]=counts.get(r["reason"],0)+1
89
+ branches.append({"formula":formula,"raw_count":len(raw),"filtered_count":len(kept),
90
+ "connectivity_count":len({r["identity"] for r in kept}),"rejections":counts,
91
+ "snapshot_sha256":row[1],"snapshot_utc":row[3],"kept_cids":[r["cid"] for r in kept]})
92
+ db.commit()
93
+ info={"status":"pending" if pending else "ready" if candidates else "ready_empty",
94
+ "view":view,"oracle":oracle,"pending_formulas":pending,"selected_formulas":selected,
95
+ "formula_predictions":predictions,"formula_prediction_checkpoint_sha256":checkpoint_sha256 if not oracle else None,
96
+ "formula_catalog_sha256":catalog.sha256 if catalog and not oracle else None,
97
+ "formula_universe_source":"reference_oracle" if oracle else "training_catalog_mass_filtered",
98
+ "raw_count":sum(b["raw_count"] for b in branches),"filtered_count":len(candidates),"branches":branches,
99
+ "ppm_filter_applied":True,"ppm":10.,"truth_injected":False,"sirius_used":False}
100
+ # Never expose a partial union as the complete predicted Top10 view.
101
+ return (None if pending else candidates),info
102
+
103
+
104
+ def training_projection(entries, banned):
105
+ """Distinct from raw/official pool: strict holdout & supported-chemistry view."""
106
+ retained={}; reasons={}; invalid=[]
107
+ for entry in entries:
108
+ try:
109
+ m=molecule(entry["smiles"])
110
+ if m.identity in banned:
111
+ reason="heldout_connectivity"
112
+ elif m.charge:
113
+ reason="unsupported_charged_structure"
114
+ else:
115
+ old=retained.get(m.identity)
116
+ if old is None or entry["smiles"] < old["smiles"]: retained[m.identity]=entry
117
+ continue
118
+ except (ValueError,TypeError,OverflowError) as exc:
119
+ reason="unsupported_structure"; invalid.append({"source_id":entry.get("source_id"),"reason":str(exc)[:100]})
120
+ reasons[reason]=reasons.get(reason,0)+1
121
+ result=[retained[k] for k in sorted(retained)]
122
+ return result,{"raw_count":len(entries),"supported_isolated_connectivity_count":len(result),
123
+ "removed":reasons,"invalid_examples":invalid[:10],"identity_hash":hashlib.sha256("\n".join(sorted(retained)).encode()).hexdigest(),
124
+ "is_training_only_projection":True,"raw_pool_modified":False}
125
+
126
+
127
+ def pubchem_worker(config):
128
+ root=Path(config["work_dir"]); root.mkdir(parents=True,exist_ok=True)
129
+ from .multiview_data import initialize
130
+ db=initialize(root/"data.sqlite")
131
+ lock=(root/"pubchem_worker.lock").open("a+")
132
+ fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
133
+ cache_dir=root/"pubchem";cache_dir.mkdir(exist_ok=True)
134
+ cache=PubChemCache(cache_dir/"requests.sqlite",online=config["pubchem_online"])
135
+ emit("pubchem_worker_started",online=cache.online,requests_per_second_max=2.9412)
136
+ while True:
137
+ if shutil.disk_usage(root).free < config["pubchem_min_free_gb"]*1024**3:
138
+ save(root/"pubchem_status.json",{"status":"paused_low_disk","utc":utc()});time.sleep(30);continue
139
+ 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",
140
+ (config["pubchem_max_attempts"], (datetime.now(timezone.utc)-timedelta(minutes=5)).isoformat())).fetchone()
141
+ if not job:
142
+ counts=list(db.execute("SELECT status,COUNT(*) FROM jobs GROUP BY status"))
143
+ save(root/"pubchem_status.json",{"status":"waiting_for_jobs","counts":counts,"utc":utc()})
144
+ time.sleep(10);continue
145
+ formula,attempts=job
146
+ emit("formula_retrieval_started",formula=formula,attempt=attempts+1)
147
+ try:
148
+ records,provenance=cache.formula_candidates(formula)
149
+ artifact={"records":records,"provenance":provenance}
150
+ buf=packed(artifact); digest=hashlib.sha256(buf).hexdigest()
151
+ db.execute("INSERT OR REPLACE INTO formula_pools VALUES (?,?,?,?,?)",(formula,buf,len(records),digest,utc()))
152
+ db.execute("UPDATE jobs SET status='completed',attempts=?,updated=?,error=NULL WHERE formula=?",(attempts+1,utc(),formula)); db.commit()
153
+ emit("formula_retrieval_completed",formula=formula,candidates=len(records),snapshot_sha256=digest)
154
+ except Exception as exc:
155
+ status="failed" if attempts+1>=config["pubchem_max_attempts"] else "retry"
156
+ db.execute("UPDATE jobs SET status=?,attempts=?,error=?,updated=? WHERE formula=?",(status,attempts+1,type(exc).__name__+": "+str(exc)[:250],utc(),formula));db.commit()
157
+ emit("formula_retrieval_error",formula=formula,status=status,error=type(exc).__name__)
158
+ save(root/"pubchem_status.json",{"status":"running","utc":utc(),"counts":list(db.execute("SELECT status,COUNT(*) FROM jobs GROUP BY status"))})
159
+
160
+
161
+ def main():
162
+ p=argparse.ArgumentParser();p.add_argument("--config",required=True)
163
+ a=p.parse_args();pubchem_worker(json.loads(Path(a.config).read_text()))
164
+
165
+
166
+ if __name__=="__main__": main()
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/multiview_train.py ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Step-resumable real-data curriculum; no eager 2M-example/forest/negative bank.
2
+
3
+ The first run is a bounded training curriculum, NOT a complete epoch over the
4
+ multi-million-row corpus and NOT a finished benchmark or convergence claim.
5
+ """
6
+ import argparse
7
+ from collections import Counter, defaultdict
8
+ from copy import deepcopy
9
+ from dataclasses import replace
10
+ import fcntl
11
+ import hashlib
12
+ import json
13
+ import os
14
+ from pathlib import Path
15
+ import random
16
+ import shutil
17
+ import time
18
+ import torch
19
+ from rdkit import RDLogger
20
+ from .chemistry import molecule, tanimoto
21
+ from .config import Config
22
+ from .engine import seed_everything, load_model
23
+ from .forest import build_forest
24
+ from .losses import positive_index, listwise_loss, contrastive_loss, counterfactual_targets, cut_loss
25
+ from .model import SpecPartition
26
+ from .multiview_data import connect, meta, packed, unpacked, save, sha, emit, utc
27
+ from .multiview_pools import FormulaCatalog, candidate_view, training_projection, empty_example
28
+ from .schema import parse_record
29
+
30
+
31
+ class TrainingStream:
32
+ def __init__(self, db, seed):
33
+ self.db=db; self.rng=random.Random(seed)
34
+ self.banned={r[0] for r in db.execute("SELECT identity FROM heldout")}
35
+ self.by_source={s:[r[0] for r in db.execute("SELECT DISTINCT identity FROM spectra WHERE source=? AND status='eligible'",(s,))]
36
+ for s in ("odata","msg_train")}
37
+ if any(not v for v in self.by_source.values()): raise ValueError("Both training sources need eligible records")
38
+ self.structs={r[0]:(r[1],r[2],r[3]) for r in db.execute("SELECT identity,smiles,formula,mass FROM structures")}
39
+ if self.banned & set(self.structs): raise ValueError("Heldout label in training structure bank")
40
+ self.keys=sorted(self.structs)
41
+ self.by_formula=defaultdict(list)
42
+ for k,(_,f,_) in self.structs.items(): self.by_formula[f].append(k)
43
+
44
+ def sample(self, step):
45
+ # Equal source exposure; uniform structures then a uniform source spectrum.
46
+ # This changes sampling weights, never deletes repeat spectra from the index.
47
+ source="odata" if step % 2 == 0 else "msg_train"
48
+ identity=self.rng.choice(self.by_source[source])
49
+ rows=list(self.db.execute("SELECT id FROM spectra WHERE source=? AND identity=? AND status='eligible'",(source,identity)))
50
+ sid=self.rng.choice(rows)[0]
51
+ body=unpacked(self.db.execute("SELECT body FROM spectra WHERE id=?",(sid,)).fetchone()[0])
52
+ return sid,body
53
+
54
+ def global_proposals(self, body, n):
55
+ identity,formula=body["identity"],body["formula"]
56
+ same=[k for k in self.by_formula[formula] if k != identity]
57
+ chosen=set(self.rng.sample(same,min(n//2,len(same))))
58
+ while len(chosen)<min(n,len(self.keys)-1):
59
+ k=self.rng.choice(self.keys)
60
+ if k != identity: chosen.add(k)
61
+ return [molecule(self.structs[k][0]) for k in sorted(chosen)]
62
+
63
+
64
+ def curriculum(config, step):
65
+ limits=config["stages"]
66
+ a=limits["warmup_steps"];b=a+limits["direct_steps"];c=b+limits["fixed_relation_steps"]
67
+ if step<a: return "warmup","none"
68
+ if step<b: return "direct","none"
69
+ if step<c: return "fixed_relation","fixed"
70
+ return "joint","learned"
71
+
72
+
73
+ def propose_training_pool(entries, identity, cap, rng):
74
+ # A labelled training proposal may force inclusion of a positive ALREADY in
75
+ # the formal pool. It never adds a missing truth and is never used in evaluation.
76
+ if len(entries)<=cap: return entries,False
77
+ positive=[e for e in entries if molecule(e["smiles"]).identity==identity]
78
+ rest=[e for e in entries if molecule(e["smiles"]).identity!=identity]
79
+ selected=positive+rng.sample(rest,cap-len(positive))
80
+ return sorted(selected,key=lambda e:molecule(e["smiles"]).identity),True
81
+
82
+
83
+ def save_checkpoint(path, model, optimizer, teacher, stream, step, config, catalog, identity_counts, views):
84
+ temp=Path(path).with_suffix(".tmp")
85
+ # Compatible with engine.load_model; both RNGs and optimizer resume at a step boundary.
86
+ torch.save({"schema_version":2,"step_completed":step,"config":model.cfg.to_dict(),
87
+ "pipeline_config":config,"model":model.state_dict(),"optimizer":optimizer.state_dict(),
88
+ "teacher":teacher.state_dict(),"sampling_rng":stream.rng.getstate(),"torch_rng":torch.get_rng_state(),
89
+ "cuda_rng":torch.cuda.get_rng_state_all() if model.device.type=="cuda" else [],
90
+ "catalog_sha256":catalog.sha256,"source_signature":meta(stream.db,"source_signature"),
91
+ "identity_seen":dict(identity_counts),"view_counts":dict(views)},temp)
92
+ temp.replace(path)
93
+
94
+
95
+ def dynamic_negatives(model, teacher, enc, proposals, pool_mols, identity, budget, rng, forest=None, partition=None):
96
+ proposal_map={m.identity:m for m in proposals+list(pool_mols) if m.identity!=identity}
97
+ # Bound teacher work even when the formal PubChem pool is huge.
98
+ mols=list(proposal_map.values())
99
+ if len(mols)>192: mols=rng.sample(mols,192)
100
+ if not mols: return [],{"negatives":0}
101
+ with torch.no_grad():
102
+ _,_,z=teacher.encode_molecules(mols)
103
+ hard=(z@enc).detach().cpu().tolist()
104
+ # Training truth may guide mining. Every branch/root competes; no sibling-only restriction.
105
+ same_cluster=set();other_cluster=set()
106
+ if forest and identity in forest.identities:
107
+ p=forest.identities.index(identity)
108
+ for key in (partition if partition is not None else forest.roots):
109
+ ids={forest.identities[i] for i in forest.nodes[key].members}
110
+ (same_cluster if p in forest.nodes[key].members else other_cluster).update(ids)
111
+ 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)]
112
+ order=sorted(range(len(mols)),key=lambda i:(-boosted[i],mols[i].identity))
113
+ explore=min(budget//4,len(mols));selected=rng.sample(list(range(len(mols))),explore)
114
+ selected+= [i for i in order if i not in selected][:max(0,budget-len(selected))]
115
+ audit={"negatives":len(selected),"proposals":len(mols),"uniform_exploration":explore,
116
+ "in_truth_microcluster":sum(mols[i].identity in same_cluster for i in selected),
117
+ "other_roots":sum(mols[i].identity in other_cluster for i in selected),
118
+ "positive_excluded":all(mols[i].identity!=identity for i in selected),
119
+ "partition_source":"frozen_teacher_cut" if partition is not None else "feasible_chemical_roots",
120
+ "objective":"biased hard-negative contrastive, not unbiased full-bank CE"}
121
+ return [mols[i] for i in selected],audit
122
+
123
+
124
+ def train_pipeline(config, resume=False, max_steps=None):
125
+ RDLogger.DisableLog("rdApp.*")
126
+ os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG",":4096:8")
127
+ root=Path(config["work_dir"]); run=Path(config["run_dir"]); run.mkdir(parents=True,exist_ok=True)
128
+ lock=(run/"trainer.lock").open("a+")
129
+ fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
130
+ if (run/"last.pt").exists() and not resume: raise FileExistsError("Use --resume; refusing to overwrite a run")
131
+ while not (root/"data.sqlite").exists():
132
+ save(run/"status.json",{"status":"waiting_for_data_index","utc":utc()});time.sleep(10)
133
+ db=connect(root/"data.sqlite")
134
+ db.execute("CREATE TABLE IF NOT EXISTS demand(formula TEXT PRIMARY KEY,priority INTEGER)");db.commit()
135
+ while not meta(db,"index_complete"):
136
+ save(run/"status.json",{"status":"waiting_for_complete_index","utc":utc()});time.sleep(10)
137
+ source_signature=hashlib.sha256(json.dumps(list(db.execute("SELECT name,sha256 FROM sources ORDER BY name"))).encode()).hexdigest()
138
+ meta(db,"source_signature",source_signature)
139
+ catalog=FormulaCatalog(db); stream=TrainingStream(db,config["seed"])
140
+ 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()
141
+ seed_everything(config["seed"],config["threads"])
142
+ cfg=Config();cfg.train.device=config["device"];cfg.train.threads=config["threads"]
143
+ cfg.train.cost_weight=0.;cfg.train.cut_cost_tradeoff=0.;cfg.train.cut_epsilon=config["cut_epsilon"]
144
+ model=SpecPartition(cfg).to(config["device"])
145
+ if model.device.type=="cuda":
146
+ torch.cuda.set_per_process_memory_fraction(.60,model.device)
147
+ optimizer=torch.optim.AdamW(model.parameters(),lr=cfg.train.learning_rate,weight_decay=cfg.train.weight_decay)
148
+ teacher=deepcopy(model).eval()
149
+ for p in teacher.parameters():p.requires_grad_(False)
150
+ step0=0; seen=Counter();views=Counter()
151
+ if resume:
152
+ state=torch.load(run/"last.pt",map_location="cpu",weights_only=True)
153
+ if state["pipeline_config"]!=config or state["catalog_sha256"]!=catalog.sha256 or state["source_signature"]!=source_signature:
154
+ raise ValueError("Checkpoint/config/source/catalog mismatch")
155
+ model.load_state_dict(state["model"]);optimizer.load_state_dict(state["optimizer"]);teacher.load_state_dict(state["teacher"])
156
+ stream.rng.setstate(state["sampling_rng"]);torch.set_rng_state(state["torch_rng"])
157
+ if state["cuda_rng"] and model.device.type=="cuda":torch.cuda.set_rng_state_all(state["cuda_rng"])
158
+ step0=state["step_completed"]+1; seen.update(state["identity_seen"]);views.update(state["view_counts"])
159
+ frozen=None; frozen_hash=None
160
+ if (run/"formula_selector_frozen.pt").exists():
161
+ frozen,_=load_model(run/"formula_selector_frozen.pt",config["device"]);frozen_hash=sha(run/"formula_selector_frozen.pt")
162
+ save(run/"protocol.json",{"config":config,"source_signature":source_signature,"catalog_sha256":catalog.sha256,
163
+ "formula_space_size":len(catalog.formulas),"real_data":True,"sirius_features":False,
164
+ "training_sampling":"equal sources, uniform connectivity, uniform spectrum within connectivity/source",
165
+ "formula_metrics_warning":"closed training vocabulary; enumerate coverage is not open-world coverage",
166
+ "official_pool_projection":"strict training-only isolation; official raw pool kept unchanged",
167
+ "loss_schedule":"LF+LC; then direct LR; then fixed relation LR; then joint LR+Lcut. Cost disabled.",
168
+ "release_source_hashes":{str(p.relative_to(Path(__file__).parent)):sha(p) for p in Path(__file__).parent.glob('*.py')},
169
+ "run_scope":"initial training curriculum, not full corpus sweep or final scientific result"})
170
+ 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()})
171
+ total=sum(config["stages"].values());end=min(total,max_steps) if max_steps else total
172
+ start=time.monotonic()
173
+ try:
174
+ for step in range(step0,end):
175
+ if shutil.disk_usage(root).free < config["train_min_free_gb"]*1024**3:
176
+ raise RuntimeError("Training low disk guard triggered")
177
+ stage,relation=curriculum(config,step);model.cfg.model.relation_mode=relation
178
+ if step % config["teacher_refresh_steps"]==0:
179
+ teacher.load_state_dict(model.state_dict());teacher.cfg.model.relation_mode=relation
180
+ if stage != "warmup" and frozen is None:
181
+ save_checkpoint(run/"formula_selector_frozen.pt",model,optimizer,teacher,stream,step-1,config,catalog,seen,views)
182
+ frozen,_=load_model(run/"formula_selector_frozen.pt",config["device"]);frozen_hash=sha(run/"formula_selector_frozen.pt")
183
+ sid,body=stream.sample(step)
184
+ if body["source"]=="msg_train":view="msg_mass" if (step//2)%2==0 else "msg_formula"
185
+ else:
186
+ use_pred=frozen is not None and stream.rng.random() < (.2 if stage=="direct" else .5)
187
+ view="odata_predicted_top10" if use_pred else "odata_oracle"
188
+ entries,view_info=candidate_view(db,body,view,catalog,frozen,frozen_hash)
189
+ projection={}; sample_ce=False; actual_pool=[]; original_count=0
190
+ if entries is not None:
191
+ actual_pool,projection=training_projection(entries,stream.banned);original_count=len(actual_pool)
192
+ # Warmup uses LC/LF only and need not materialize large-pool activations.
193
+ if stage=="warmup":actual_pool=[]
194
+ else:actual_pool,sample_ce=propose_training_pool(actual_pool,body["identity"],config["training_candidate_cap"],stream.rng)
195
+ record={"sample_id":str(sid),"split":"train","labels":{"reference_smiles":body["reference_smiles"]},
196
+ "features":{**body["features"],"candidate_view":view,"candidates":actual_pool}}
197
+ example=parse_record(record)
198
+ forest=build_forest(example.query.candidates,cfg.chemistry)
199
+ model.train();optimizer.zero_grad(set_to_none=True)
200
+ output=model(example.query,forest)
201
+ # Independent formula universe, never the oracle/official candidate-formula set.
202
+ fs=catalog.select(example.query.precursor_mz,example.query.adduct,config["formula_ppm"])
203
+ fq=replace(example.query,formula_candidates=tuple(fs))
204
+ fscore=model.score_formulas(output.encoded.q,fq)
205
+ fp=positive_index(fs,body["formula"])
206
+ lf,mf=listwise_loss(fscore,fp if len(fs)>1 else None)
207
+ with torch.no_grad():
208
+ teacher_partition=None
209
+ if stage=="joint" and example.query.candidates:
210
+ tenc=teacher.encode(example.query)
211
+ tz=tenc.z_query;teacher_partition=teacher.select_partition(tenc,forest)
212
+ else:
213
+ _,tq,_=teacher.spectrum(example.query)
214
+ tz=torch.nn.functional.normalize(teacher.query_projection(tq),dim=-1)
215
+ proposals=stream.global_proposals(body,config["negative_proposal_budget"])
216
+ negs,negative_audit=dynamic_negatives(model,teacher,tz,proposals,example.query.candidates,
217
+ body["identity"],config["negative_budget"],stream.rng,forest,teacher_partition)
218
+ ref=molecule(body["reference_smiles"])
219
+ _,_,z=model.encode_molecules([ref]+negs)
220
+ lc=contrastive_loss(output.encoded.z_query,z[0],z[1:],cfg.train.temperature)
221
+ rp=positive_index(forest.identities,body["identity"])
222
+ lr,mr=listwise_loss(output.scores,rp)
223
+ lcut=output.encoded.q.sum()*0.;ncut=0
224
+ if stage=="joint" and rp is not None:
225
+ ts=counterfactual_targets(teacher,example.query,forest,body["identity"],max_nodes=4,
226
+ epsilon=config["cut_epsilon"],cost_tradeoff=0.,offset=step*4)
227
+ lcut,ncut=cut_loss(model,output.encoded,forest,ts)
228
+ loss=.3*lf+lc+(lr if stage!="warmup" else 0)+.1*lcut
229
+ if not torch.isfinite(loss):raise RuntimeError("Nonfinite training loss")
230
+ loss.backward();grad=torch.nn.utils.clip_grad_norm_(model.parameters(),5.,error_if_nonfinite=True);optimizer.step()
231
+ seen[body["identity"]]+=1;views[view]+=1
232
+ info={"utc":utc(),"step":step,"stage":stage,"spectrum_id":sid,"source":body["source"],"view":view,
233
+ "loss":float(loss.detach()),"LF":float(lf.detach()),"LC":float(lc.detach()),"LR":float(lr.detach()),"Lcut":float(lcut.detach()),
234
+ "formula_loss_valid":bool(mf),"formula_truth_covered":fp is not None,"independent_formula_count":len(fs),
235
+ "ranking_loss_valid":bool(mr) and stage!="warmup","pool_status":view_info["status"],
236
+ "formal_projected_pool_size":original_count,"training_proposal_size":len(actual_pool),
237
+ "rank_objective":"sampled_pool_CE_not_full_LR" if sample_ce else "full_projected_pool_CE" if stage!="warmup" else "disabled_warmup",
238
+ "negative_audit":negative_audit,"gradient_norm_before_clip":float(grad),"cut_targets":ncut,
239
+ "cuda_peak_mb":torch.cuda.max_memory_allocated()/1024**2 if model.device.type=="cuda" else None}
240
+ with (run/"progress.jsonl").open("a") as fh:fh.write(json.dumps(info,allow_nan=False)+"\n")
241
+ 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()
242
+ if step % 10==0:
243
+ emit("optimizer_step",**info)
244
+ save(run/"status.json",{"status":"training","utc":utc(),"step_completed":step,"stage":stage,"last":info,
245
+ "views":dict(views),"unique_training_structures_seen":len(seen),"seconds":time.monotonic()-start})
246
+ if (step+1)%config["checkpoint_interval"]==0 or step+1==end or step==0:
247
+ save_checkpoint(run/"last.pt",model,optimizer,teacher,stream,step,config,catalog,seen,views)
248
+ save(run/"status.json",{"status":"initial_curriculum_completed" if end==total else "bounded_training_check_completed",
249
+ "utc":utc(),"step_completed":end-1,"views":dict(views),"unique_training_structures_seen":len(seen),
250
+ "scientific_evaluation_completed":False})
251
+ except BaseException as exc:
252
+ save(run/"status.json",{"status":"failed","utc":utc(),"error":type(exc).__name__+": "+str(exc)[:300],
253
+ "last_safe_checkpoint":"last.pt","next_action":"inspect; no automatic destructive restart"})
254
+ raise
255
+ finally:
256
+ db.close();lock.close()
257
+
258
+
259
+ def main():
260
+ p=argparse.ArgumentParser();p.add_argument("--config",required=True);p.add_argument("--resume",action="store_true")
261
+ p.add_argument("--max-steps",type=int);a=p.parse_args()
262
+ train_pipeline(json.loads(Path(a.config).read_text()),a.resume,a.max_steps)
263
+
264
+
265
+ if __name__=="__main__":main()
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/negatives.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Versioned training-only negative bank with fixed-probe EMA and exploration.
2
+
3
+ All probabilities describe this bounded proposal sampler. No claim of an unbiased
4
+ full-bank softmax estimator or an approximate-nearest-neighbor implementation.
5
+ """
6
+ import hashlib
7
+ import numpy as np
8
+ import torch
9
+ from .chemistry import identity_hash, molecule, ppm_error, tanimoto
10
+
11
+
12
+ class NegativeBank:
13
+ def __init__(self, molecules, forbidden=()):
14
+ banned = set(forbidden)
15
+ unique = {m.identity:m for m in molecules if m.identity not in banned}
16
+ self.molecules = tuple(unique[k] for k in sorted(unique))
17
+ self.identities = tuple(m.identity for m in self.molecules)
18
+ self.identity_to_index = {k:i for i,k in enumerate(self.identities)}
19
+ self.hash = identity_hash(self.molecules)
20
+ self.embeddings = None
21
+ self.version = 0
22
+ self.weight_signature = None
23
+
24
+ @classmethod
25
+ def from_training(cls, examples, forbidden=()):
26
+ if any(e.split != "train" or e.labels is None for e in examples):
27
+ raise ValueError("Never construct a negative bank from validation/test examples")
28
+ return cls([m for e in examples for m in (*e.query.candidates,molecule(e.labels.reference_smiles))],forbidden)
29
+
30
+ @torch.no_grad()
31
+ def refresh(self, teacher):
32
+ if teacher.training:
33
+ raise ValueError("Refresh with frozen eval-mode teacher")
34
+ chunks = []
35
+ for i in range(0,len(self.molecules),128):
36
+ _,_,z = teacher.encode_molecules(self.molecules[i:i+128])
37
+ chunks.append(z.cpu())
38
+ self.embeddings = torch.cat(chunks).numpy() if chunks else np.empty((0,teacher.cfg.model.dim),np.float32)
39
+ h = hashlib.sha256()
40
+ for k,v in sorted(teacher.state_dict().items()):
41
+ h.update(k.encode()); h.update(v.detach().cpu().numpy().tobytes())
42
+ self.weight_signature = h.hexdigest()
43
+ self.version += 1
44
+
45
+
46
+ class DynamicSampler:
47
+ def __init__(self, cfg):
48
+ self.cfg = cfg
49
+ self.rng = np.random.default_rng(cfg.seed)
50
+ self.ema = np.zeros(4,dtype=float)
51
+ self.probe_updates = 0
52
+
53
+ def state_dict(self):
54
+ return {"rng":self.rng.bit_generator.state,"ema":self.ema.tolist(),"probe_updates":self.probe_updates}
55
+
56
+ def load_state_dict(self,state):
57
+ self.rng.bit_generator.state = state["rng"]
58
+ self.ema = np.asarray(state["ema"],float)
59
+ self.probe_updates = state["probe_updates"]
60
+
61
+ def groups(self, query, reference, bank):
62
+ groups = [[],[],[],[]]
63
+ for i,m in enumerate(bank.molecules):
64
+ if m.identity == reference.identity:
65
+ continue
66
+ if m.formula == reference.formula:
67
+ g = 3 if tanimoto(m.whole,reference.whole) >= .65 else 2
68
+ else:
69
+ g = 1 if abs(ppm_error(m.mass,query.precursor_mz,query.adduct)) <= 10 else 0
70
+ groups[g].append(i)
71
+ return groups
72
+
73
+ def quotas(self, groups, epoch):
74
+ progress = epoch/max(1,self.cfg.epochs-1)
75
+ prior = np.array([.4,.3,.2,.1] if progress < .34 else ([.2,.25,.3,.25] if progress < .67 else [.15,.2,.3,.35]))
76
+ if self.cfg.negative_strategy in {"feedback","partition"} and self.probe_updates:
77
+ exp = np.exp((self.ema-self.ema.max())/.2)
78
+ prior = .5*prior+.5*exp/exp.sum()
79
+ prior *= np.array([bool(g) for g in groups])
80
+ return prior/prior.sum() if prior.sum() else prior
81
+
82
+ def update_probe(self, violations):
83
+ # Caller supplies fixed TRAINING-probe measurements, never validation/test feedback.
84
+ for g,values in violations.items():
85
+ if len(values):
86
+ v = float(np.mean(values))
87
+ self.ema[g] = v if not self.probe_updates else .9*self.ema[g]+.1*v
88
+ self.probe_updates += 1
89
+
90
+ def sample(self, query, reference, bank, query_embedding, epoch, forest=None, partition=None):
91
+ if bank.embeddings is None:
92
+ raise ValueError("Negative bank requires a versioned teacher refresh")
93
+ groups = self.groups(query,reference,bank)
94
+ probabilities = self.quotas(groups,epoch)
95
+ strategy = self.cfg.negative_strategy
96
+ all_indices = [i for g in groups for i in g]
97
+ budget = min(self.cfg.negative_budget,len(all_indices))
98
+ if not budget:
99
+ return [], {"selected":0,"groups":[0]*4,"version":bank.version,"subtypes":{}}
100
+ # Bounded stratified proposal set, including random exploration in every available stratum.
101
+ proposals = []
102
+ cap = max(1,self.cfg.proposal_budget//4)
103
+ for g in groups:
104
+ proposals.append(list(self.rng.choice(g,min(cap,len(g)),replace=False)) if g else [])
105
+ # Redistribute unused proposal slots so a sparse/empty stratum cannot reduce the fixed negative budget.
106
+ chosen = {i for group in proposals for i in group}
107
+ slots = min(self.cfg.proposal_budget,len(all_indices))-len(chosen)
108
+ remaining = [(g,i) for g,items in enumerate(groups) for i in items if i not in chosen]
109
+ if slots > 0 and remaining:
110
+ for index in self.rng.choice(len(remaining),min(slots,len(remaining)),replace=False):
111
+ g,i = remaining[index]
112
+ proposals[g].append(i)
113
+ group_of = {i:g for g,items in enumerate(proposals) for i in items}
114
+ available = [i for g in proposals for i in g]
115
+ q = np.asarray(query_embedding,dtype=np.float32)
116
+ hard = bank.embeddings[available]@q if available else np.array([])
117
+ hard_map = dict(zip(available,hard))
118
+ reference_pos = bank.identity_to_index.get(reference.identity)
119
+ pos_score = float(bank.embeddings[reference_pos]@q) if reference_pos is not None else 0.
120
+ inside, boundary = set(),set()
121
+ if forest is not None and partition is not None and reference.identity in forest.identities:
122
+ ip = forest.identities.index(reference.identity)
123
+ own = next(k for k in partition if ip in forest.nodes[k].members)
124
+ inside = {forest.identities[i] for i in forest.nodes[own].members}-{reference.identity}
125
+ # Boundary = members of sibling subtrees along this node's ancestor path.
126
+ current = own
127
+ while True:
128
+ parents = [n for n in forest.nodes.values() if current in n.children]
129
+ if not parents:
130
+ break
131
+ parent = parents[0]
132
+ for k in parent.children:
133
+ if k != current:
134
+ boundary.update(forest.identities[i] for i in forest.nodes[k].members)
135
+ current = parent.key
136
+ subtype = {i:("inside" if bank.identities[i] in inside else "boundary" if bank.identities[i] in boundary else "other") for i in available}
137
+ weights = []
138
+ for i in available:
139
+ g = group_of[i]
140
+ if strategy == "random":
141
+ w = 1.
142
+ elif strategy == "static":
143
+ w = probabilities[g]*(.2+.8*tanimoto(reference.whole,bank.molecules[i].whole))/len(proposals[g])
144
+ else:
145
+ # Mixture with uniform exploration, clip hardness, fixed total negative budget.
146
+ logits = np.array([np.clip((hard_map[j]-pos_score)/.1,-8,8) for j in proposals[g]])
147
+ exp = np.exp(logits-logits.max())
148
+ idx = proposals[g].index(i)
149
+ local = .2/len(proposals[g])+.8*exp[idx]/exp.sum()
150
+ w = probabilities[g]*local
151
+ if strategy == "partition" and g == 3:
152
+ w *= 2. if subtype[i] in {"inside","boundary"} else 1.
153
+ weights.append(w)
154
+ weights = np.asarray(weights,float)
155
+ weights /= weights.sum()
156
+ n = min(budget,len(available))
157
+ selected = list(self.rng.choice(available,n,replace=False,p=weights))
158
+ counts = [sum(group_of[i]==g for i in selected) for g in range(4)]
159
+ return selected,{"selected":n,"requested":self.cfg.negative_budget,"groups":counts,
160
+ "group_probabilities":probabilities.tolist(),"version":bank.version,
161
+ "proposal_count":len(available),"subtypes":{s:sum(subtype[i]==s for i in selected) for s in ("inside","boundary","other")},
162
+ "positive_excluded":all(bank.identities[i] != reference.identity for i in selected)}
163
+
164
+
165
+ @torch.no_grad()
166
+ def update_fixed_training_probe(sampler, teacher, examples, bank):
167
+ # Stable sample-ID hash subset. Same members and negative probes across refreshes.
168
+ probes = sorted(examples,key=lambda e:hashlib.sha256(e.sample_id.encode()).hexdigest())[:sampler.cfg.probe_size]
169
+ violations = {i:[] for i in range(4)}
170
+ for e in probes:
171
+ if e.split != "train" or e.labels is None:
172
+ raise ValueError("Only training examples may update sampling feedback")
173
+ ref = molecule(e.labels.reference_smiles)
174
+ _,q,_ = teacher.spectrum(e.query)
175
+ z = torch.nn.functional.normalize(teacher.query_projection(q),dim=-1).cpu().numpy()
176
+ p = bank.identity_to_index[ref.identity]
177
+ positive = float(bank.embeddings[p]@z)
178
+ groups = sampler.groups(e.query,ref,bank)
179
+ for g,indices in enumerate(groups):
180
+ # Identity order gives a stable, model-independent per-group probe, not hardest current items.
181
+ for i in indices[:32]:
182
+ violations[g].append(float(bank.embeddings[i]@z + sampler.cfg.probe_margin > positive))
183
+ sampler.update_probe(violations)
184
+ return {"sample_ids":[e.sample_id for e in probes],"counts":{str(g):len(v) for g,v in violations.items()},
185
+ "ema":sampler.ema.tolist(),"bank_version":bank.version}
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/offline_data.py ADDED
@@ -0,0 +1,372 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Download -> verified snapshot -> fixed plan -> CPU preprocessing -> GPU.
2
+
3
+ Only owned, hash-verified pickle batches are read; never load third-party pickle.
4
+ The corpus index preserves all source rows. The prepacked training curriculum
5
+ is explicitly bounded, not a full corpus epoch. No live cache is read by GPU training.
6
+ """
7
+ import argparse
8
+ from collections import Counter
9
+ import fcntl
10
+ import hashlib
11
+ import json
12
+ from pathlib import Path
13
+ import pickle
14
+ import shutil
15
+ import sqlite3
16
+ import subprocess
17
+ import sys
18
+ import time
19
+ import zlib
20
+ from .multiview_data import save, sha, utc, unpacked, packed, meta
21
+
22
+
23
+ def readonly(path):
24
+ db=sqlite3.connect(f'file:{Path(path).resolve()}?mode=ro',uri=True,timeout=60)
25
+ db.execute('PRAGMA query_only=ON')
26
+ return db
27
+
28
+
29
+ def digest(value):
30
+ return hashlib.sha256(json.dumps(value,sort_keys=True,separators=(',',':'),allow_nan=False).encode()).hexdigest()
31
+
32
+
33
+ def binding(db):
34
+ return {'sources':list(db.execute('SELECT name,path,sha256,rows,done FROM sources ORDER BY name')),
35
+ 'formulas':list(db.execute('SELECT formula,mass FROM formulas ORDER BY formula'))}
36
+
37
+
38
+ def audit(path,mass_checks=False):
39
+ db=readonly(path)
40
+ queries={
41
+ 'source_rows': 'SELECT name,rows,done FROM sources ORDER BY name',
42
+ 'spectra': 'SELECT source,status,COUNT(*),COUNT(DISTINCT identity),COUNT(DISTINCT formula) FROM spectra GROUP BY source,status',
43
+ 'quarantine': "SELECT source,reason,COUNT(*) FROM spectra WHERE status='quarantined' GROUP BY source,reason ORDER BY COUNT(*) DESC",
44
+ 'jobs': 'SELECT status,COUNT(*) FROM jobs GROUP BY status',
45
+ 'required': 'SELECT COUNT(*) FROM formulas',
46
+ 'ready': 'SELECT COUNT(*),SUM(p.raw_count) FROM formulas f JOIN formula_pools p USING(formula)',
47
+ '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)",
48
+ 'holdout_overlap': "SELECT COUNT(*) FROM spectra s WHERE status='eligible' AND EXISTS(SELECT 1 FROM heldout h WHERE h.identity=s.identity)",
49
+ }
50
+ # Target keys live in compressed spectrum bodies; do not pretend to join
51
+ # them with SMILES representatives from structures. Checked during prepacking.
52
+ result={'utc':utc(),'database':str(Path(path).resolve()),'queries':queries}
53
+ for key,query in queries.items():result[key]=list(db.execute(query))
54
+ result['source_binding_sha256']=digest(binding(db))
55
+ result['free_gib']=shutil.disk_usage(Path(path).parent).free/1024**3
56
+ if mass_checks:
57
+ from .chemistry import ppm_error
58
+ counts=Counter();examples=[]
59
+ for sid,source,blob in db.execute("SELECT id,source,body FROM spectra WHERE status='eligible'"):
60
+ b=unpacked(blob);q=b['features'];ppm=ppm_error(b['mass'],q['precursor_mz'],q['adduct'])
61
+ counts[source+':all']+=1
62
+ if abs(ppm)>10:
63
+ counts[source+':outside_10ppm']+=1
64
+ if len(examples)<5:examples.append({'spectrum_id':sid,'source':source,'ppm':ppm,'adduct':q['adduct']})
65
+ result['mass_quality']={'counts':dict(counts),'examples':examples,'method':'SMILES-derived reference mass compared with experimental precursor and adduct, no candidate lookup'}
66
+ db.close();return result
67
+
68
+
69
+ def disk_guard(root, minimum):
70
+ if shutil.disk_usage(root).free < minimum*1024**3:
71
+ raise RuntimeError('Disk reserve reached; no deletion or partial-pool training allowed')
72
+
73
+
74
+ def initialize_manifest(c):
75
+ root=Path(c['pipeline_dir']);root.mkdir(parents=True,exist_ok=True)
76
+ db=readonly(Path(c['work_dir'])/'data.sqlite')
77
+ if not meta(db,'index_complete') or not meta(db,'registry_complete'):
78
+ raise RuntimeError('Complete source index and heldout registry required')
79
+ b=binding(db)
80
+ if not b['formulas'] or any(not r[4] for r in b['sources']):raise RuntimeError('Incomplete source registry')
81
+ 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]
82
+ if overlap:raise RuntimeError('Eligible labels overlap heldout connectivity')
83
+ # Closed training vocabulary contains every possible Top10 output of the
84
+ # current selector. Retrieve its entire union: no test-derived formula list.
85
+ value={'version':'offline-v04','source_binding':b,'source_binding_sha256':digest(b),
86
+ 'required_formulas':[r[0] for r in b['formulas']],
87
+ 'required_scope':'all closed training-catalog formulas; covers oracle and any selector Top10',
88
+ 'formula_selector_sha256':sha(c['proposal_formula_checkpoint']),
89
+ 'pipeline_config_sha256':digest(c),'created_utc':utc(),
90
+ 'training_batches':sum(c['stages'].values()),'training_exposures':sum(c['stages'].values())*c['batch_size'],
91
+ 'corpus_epoch':False,'raw_sources_modified':False,'truth_injection':False}
92
+ path=root/'required_manifest.json'
93
+ if path.exists():
94
+ old=json.loads(path.read_text())
95
+ for k in ('source_binding_sha256','formula_selector_sha256','pipeline_config_sha256'):
96
+ if old[k]!=value[k]:raise RuntimeError('Immutable required manifest changed: '+k)
97
+ value=old
98
+ else:save(path,value)
99
+ db.close();return value
100
+
101
+
102
+ def verify_pool(formula, row):
103
+ blob,count,digest_expected=row
104
+ if hashlib.sha256(blob).hexdigest()!=digest_expected:raise RuntimeError('PubChem snapshot hash mismatch: '+formula)
105
+ a=unpacked(blob);records=a['records'];p=a['provenance']
106
+ if p.get('formula')!=formula or p.get('cid_count')!=count or len(records)!=count:
107
+ raise RuntimeError('PubChem count/provenance mismatch: '+formula)
108
+ if len({r['CID'] for r in records})!=count:raise RuntimeError('Duplicate PubChem records: '+formula)
109
+ 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']):
110
+ raise RuntimeError('Missing PubChem request provenance: '+formula)
111
+
112
+
113
+ def screen_quality(db):
114
+ """Apply the declared o_data 10ppm protocol, never refilter MSG pools.
115
+
116
+ Outside 10ppm is a protocol conflict, not proof the reference is incorrect.
117
+ Only the derived snapshot's eligibility changes; every source row survives.
118
+ """
119
+ from .chemistry import ppm_error
120
+ db.execute('CREATE TABLE offline_quality(spectrum_id INTEGER PRIMARY KEY,source TEXT,truth_ppm REAL,decision TEXT)')
121
+ counts=Counter();after=0
122
+ while True:
123
+ rows=list(db.execute("SELECT id,source,body FROM spectra WHERE status='eligible' AND id>? ORDER BY id LIMIT 2000",(after,)))
124
+ if not rows:break
125
+ for sid,source,blob in rows:
126
+ b=unpacked(blob);q=b['features'];ppm=ppm_error(b['mass'],q['precursor_mz'],q['adduct'])
127
+ outside=abs(ppm)>10.;counts[source+':inspected']+=1;counts[source+':outside_10ppm']+=int(outside)
128
+ decision='excluded_odata_10ppm_protocol' if outside and source=='odata' else 'retained_msg_official' if source=='msg_train' else 'retained_odata'
129
+ db.execute('INSERT INTO offline_quality VALUES (?,?,?,?)',(sid,source,ppm,decision))
130
+ if decision=='excluded_odata_10ppm_protocol':
131
+ db.execute("UPDATE spectra SET status='quarantined_offline',reason='truth_precursor_outside_declared_10ppm_protocol' WHERE id=?",(sid,))
132
+ counts[decision]+=1
133
+ after=rows[-1][0];db.commit()
134
+ return {'utc':utc(),'counts':dict(counts),'raw_rows_deleted':0,'official_pool_modified':False,
135
+ 'reason':'o_data strict candidate protocol; an outlier is not proof of wrong structural identity',
136
+ 'remaining_eligible':list(db.execute("SELECT source,COUNT(*),COUNT(DISTINCT identity) FROM spectra WHERE status='eligible' GROUP BY source"))}
137
+
138
+
139
+ def download(c,m):
140
+ runtime_path=Path(c['pipeline_dir'])/'download_runtime.json'
141
+ if runtime_path.exists():
142
+ runtime=json.loads(runtime_path.read_text())
143
+ if runtime.get('formula_workers',1)>1:
144
+ from .parallel_download import download_parallel
145
+ return download_parallel(c,m,runtime)
146
+ from .retrieval import PubChemCache
147
+ root=Path(c['pipeline_dir']);live=Path(c['work_dir'])
148
+ db=sqlite3.connect(live/'data.sqlite',timeout=90)
149
+ guard=(live/'pubchem_worker.lock').open('a+')
150
+ fcntl.flock(guard,fcntl.LOCK_EX|fcntl.LOCK_NB)
151
+ if digest(binding(db))!=m['source_binding_sha256']:raise RuntimeError('Source or formula catalog changed')
152
+ db.executemany('INSERT OR IGNORE INTO jobs(formula) VALUES (?)',[(f,) for f in m['required_formulas']]);db.commit()
153
+ cache=PubChemCache(live/'pubchem/requests.sqlite',online=True,property_batch_size=c['property_batch_size'])
154
+ completed=set();verified=[];required=set(m['required_formulas']);failed=[]
155
+ for f,blob,count,h in db.execute('SELECT formula,body,raw_count,sha256 FROM formula_pools'):
156
+ if f not in required:continue
157
+ verify_pool(f,(blob,count,h));completed.add(f);verified.append((f,h,count))
158
+ priorities=dict(db.execute("SELECT formula,COUNT(*) FROM spectra WHERE source='odata' AND status='eligible' GROUP BY formula"))
159
+ todo=sorted(set(m['required_formulas'])-completed,key=lambda f:(-priorities.get(f,0),f))
160
+ for f in todo:
161
+ disk_guard(root,c['download_min_free_gib'])
162
+ attempts=db.execute('SELECT attempts FROM jobs WHERE formula=?',(f,)).fetchone()[0]
163
+ status={'utc':utc(),'phase':'downloading','formula':f,'ready':len(completed),'required':len(m['required_formulas']),
164
+ 'remaining':len(m['required_formulas'])-len(completed),'training_started':False,'requests_per_second_cap':1/.34}
165
+ save(root/'status.json',status);print(json.dumps(status),flush=True)
166
+ while attempts<c['pubchem_max_attempts']:
167
+ attempts+=1
168
+ try:
169
+ records,prov=cache.formula_candidates(f)
170
+ blob=packed({'records':records,'provenance':prov});h=hashlib.sha256(blob).hexdigest()
171
+ verify_pool(f,(blob,len(records),h))
172
+ disk_guard(root,c['download_min_free_gib'])
173
+ db.execute('INSERT OR REPLACE INTO formula_pools VALUES (?,?,?,?,?)',(f,blob,len(records),h,utc()))
174
+ db.execute("UPDATE jobs SET status='completed',attempts=?,error=NULL,updated=? WHERE formula=?",(attempts,utc(),f));db.commit()
175
+ completed.add(f);verified.append((f,h,len(records)))
176
+ 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')
177
+ break
178
+ except Exception as exc:
179
+ 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()
180
+ if attempts>=c['pubchem_max_attempts']:break
181
+ time.sleep(min(30,5*attempts))
182
+ if f not in completed:failed.append(f)
183
+ cache.close();db.close();guard.close()
184
+ result={'utc':utc(),'required':len(m['required_formulas']),'verified':len(completed),'pools':sorted(verified),'failed':failed,'complete':len(completed)==len(m['required_formulas'])}
185
+ save(root/'download_complete.json',result)
186
+ if not result['complete']:raise RuntimeError(f'{len(failed)} formula jobs unresolved; see download_complete.json')
187
+ return result
188
+
189
+
190
+ def freeze(c,m):
191
+ root=Path(c['pipeline_dir']);dest=root/'snapshot';dest.mkdir(exist_ok=True)
192
+ receipt=root/'snapshot.json'
193
+ if receipt.exists():
194
+ r=json.loads(receipt.read_text())
195
+ if sha(dest/'data.sqlite')!=r['database_sha256'] or sha(dest/'formula_selector.pt')!=m['formula_selector_sha256']:
196
+ raise RuntimeError('Frozen snapshot changed')
197
+ return dest
198
+ disk_guard(root,c['preprocess_min_free_gib']+Path(c['work_dir'],'data.sqlite').stat().st_size/1024**3)
199
+ src=readonly(Path(c['work_dir'])/'data.sqlite')
200
+ if digest(binding(src))!=m['source_binding_sha256']:raise RuntimeError('Source binding changed')
201
+ # Re-hash actual raw sources once before freezing; recorded hashes alone do
202
+ # not prove source files are unchanged. Streaming sha avoids loading JSON.
203
+ for name,path,h,rows,done in m['source_binding']['sources']:
204
+ if sha(path)!=h:raise RuntimeError('Raw input changed: '+name)
205
+ tmp=dest/'data.sqlite.building'
206
+ if tmp.exists():tmp.rename(dest/f'data.sqlite.interrupted.{time.time_ns()}')
207
+ dst=sqlite3.connect(tmp);src.backup(dst,pages=2048);src.close()
208
+ save(root/'quality_screen.json',screen_quality(dst));dst.close()
209
+ tmp.replace(dest/'data.sqlite')
210
+ shutil.copyfile(c['proposal_formula_checkpoint'],dest/'formula_selector.pt')
211
+ db=readonly(dest/'data.sqlite')
212
+ if db.execute('PRAGMA integrity_check').fetchone()[0]!='ok':raise RuntimeError('Frozen SQLite integrity failure')
213
+ for f in m['required_formulas']:
214
+ row=db.execute('SELECT body,raw_count,sha256 FROM formula_pools WHERE formula=?',(f,)).fetchone()
215
+ if row is None:raise RuntimeError('Missing frozen formula: '+f)
216
+ verify_pool(f,row)
217
+ db.close()
218
+ save(receipt,{'utc':utc(),'database_sha256':sha(dest/'data.sqlite'),'required_manifest_sha256':sha(root/'required_manifest.json')})
219
+ return dest
220
+
221
+
222
+ def training_binding(c):
223
+ # Extra file hashes are gate outputs; not part of the circular config hash.
224
+ return digest({k:v for k,v in c.items() if k not in {'offline_manifest','offline_manifest_sha256'}})
225
+
226
+
227
+ def prepare(c,m,dest):
228
+ from .data_v03 import ReadyTrainingStream
229
+ from .train_v03 import stage_for
230
+ from .config import Config
231
+ from .prefetch import OrderedPrefetch
232
+ root=Path(c['pipeline_dir']);batchdir=root/'batches';batchdir.mkdir(exist_ok=True)
233
+ cfg={**c,'work_dir':str(dest),'ready_odata_fraction':0.,'require_complete_pools':True,
234
+ 'proposal_formula_checkpoint':str(dest/'formula_selector.pt'),
235
+ 'feature_cache_dir':str(root/'derived_features')}
236
+ total=sum(c['stages'].values());chem=Config().chemistry
237
+ code={p.name:sha(p) for p in Path(__file__).parent.glob('*.py')}
238
+ preparation_binding={'config':digest(cfg),'source_code':code,'snapshot':sha(dest/'data.sqlite'),
239
+ 'selector':sha(dest/'formula_selector.pt')}
240
+ binding_path=root/'preparation_binding.json'
241
+ if binding_path.exists() and json.loads(binding_path.read_text())!=preparation_binding:
242
+ raise RuntimeError('Existing preprocessing belongs to different code/config/snapshot')
243
+ if not binding_path.exists():save(binding_path,preparation_binding)
244
+ plan=root/'sampling_plan.sqlite'
245
+ if not plan.exists():
246
+ temp=root/'sampling_plan.building.sqlite'
247
+ if temp.exists():temp.rename(root/f'sampling_plan.interrupted.{time.time_ns()}.sqlite')
248
+ db=sqlite3.connect(temp);db.execute('CREATE TABLE plan(sequence INTEGER PRIMARY KEY,spectrum_id INTEGER,view TEXT,stage TEXT,rng BLOB)')
249
+ stream=ReadyTrainingStream(cfg)
250
+ for seq in range(total*c['batch_size']):
251
+ stage=stage_for(c,seq//c['batch_size']);sid,body,_,view=stream.plan(seq,stage)
252
+ db.execute('INSERT INTO plan VALUES (?,?,?,?,?)',(seq,sid,view,stage,pickle.dumps(stream.rng.getstate(),protocol=5)))
253
+ db.commit();db.close();stream.db.close();temp.replace(plan)
254
+ cfg['sampling_plan']=str(plan)
255
+ # Persist the exact plan/config before starting preparation workers.
256
+ save(root/'preparation_config.json',cfg)
257
+ gate=root/'prepared_manifest.json'
258
+ if gate.exists():
259
+ out=json.loads((root/'training_config.json').read_text());validate_prepared(out,True);return out
260
+ first=0;files=[];counts=Counter();identities=set()
261
+ def inspect_batch(batch,index):
262
+ if len(batch)!=c['batch_size']:raise RuntimeError('Wrong offline batch size')
263
+ for i,b in enumerate(batch):
264
+ a=b['audit'];ref=b['ref']
265
+ if a['sequence']!=index*c['batch_size']+i or a['pool_status'] not in ('ready','ready_empty'):
266
+ raise RuntimeError('Unresolved or reordered offline sample')
267
+ if any(n.identity==ref.identity for n in b['proposals']):raise RuntimeError('False negative')
268
+ counts[a['source']+':'+a['pool_status']]+=1
269
+ counts['positive_present']+=int(a['positive_in_original_projected_pool'])
270
+ counts['sampled_pool']+=int(a['sampled_pool'])
271
+ identities.add((a['source'],a['spectrum_id']))
272
+ # Resume only complete (batch, receipt) pairs; orphan temp files are ignored.
273
+ while first<total and (batchdir/f'{first:07d}.json').exists():
274
+ rec=json.loads((batchdir/f'{first:07d}.json').read_text())
275
+ data=(batchdir/rec['file']).read_bytes()
276
+ if hashlib.sha256(data).hexdigest()!=rec['sha256']:raise RuntimeError('Prepared batch changed')
277
+ inspect_batch(pickle.loads(zlib.decompress(data)),first);files.append(rec);first+=1
278
+ prefetch=OrderedPrefetch(cfg,first,total,chem,stage_for)
279
+ try:
280
+ for index in range(first,total):
281
+ disk_guard(root,c['preprocess_min_free_gib'])
282
+ batch=prefetch.get(index);inspect_batch(batch,index)
283
+ data=zlib.compress(pickle.dumps(batch,protocol=5),level=1)
284
+ name=f'{index:07d}.pkl.z';tmp=batchdir/(name+'.tmp')
285
+ with tmp.open('wb') as f:f.write(data)
286
+ tmp.replace(batchdir/name)
287
+ rec={'index':index,'file':name,'sha256':hashlib.sha256(data).hexdigest(),'bytes':len(data)}
288
+ save(batchdir/f'{index:07d}.json',rec);files.append(rec)
289
+ save(root/'status.json',{'utc':utc(),'phase':'preprocessing','batches':index+1,'total':total,'counts':dict(counts),'training_started':False})
290
+ finally:prefetch.close()
291
+ result={'version':'offline-v04','status':'ready','utc':utc(),'training_config_binding':training_binding(cfg),
292
+ 'batch_size':c['batch_size'],'batches':files,'batch_directory':str(batchdir),
293
+ 'sample_exposures':total*c['batch_size'],'unique_source_spectrum_ids':len(identities),
294
+ 'counts':dict(counts),'pending':0,'sampling_plan_sha256':sha(plan),'database_sha256':sha(dest/'data.sqlite'),
295
+ 'formula_selector_sha256':sha(dest/'formula_selector.pt'),
296
+ 'source_hashes':{p.name:sha(p) for p in Path(__file__).parent.glob('*.py')},
297
+ 'corpus_epoch':False,'truth_injected':False}
298
+ save(gate,result)
299
+ cfg.update(offline_manifest=str(gate),offline_manifest_sha256=sha(gate))
300
+ save(root/'training_config.json',cfg);validate_prepared(cfg,True);return cfg
301
+
302
+
303
+ def validate_prepared(c,verify_files=False):
304
+ path=Path(c['offline_manifest'])
305
+ if sha(path)!=c['offline_manifest_sha256']:raise RuntimeError('Offline manifest hash mismatch')
306
+ m=json.loads(path.read_text());n=sum(c['stages'].values())
307
+ if m['status']!='ready' or m['pending'] or m['training_config_binding']!=training_binding(c):
308
+ raise RuntimeError('Offline readiness/config gate failed')
309
+ if m['sample_exposures']!=n*c['batch_size'] or [r['index'] for r in m['batches']]!=list(range(n)):
310
+ raise RuntimeError('Offline batch coverage failed')
311
+ if sha(c['sampling_plan'])!=m['sampling_plan_sha256']:raise RuntimeError('Sample plan hash mismatch')
312
+ if sha(Path(c['work_dir'])/'data.sqlite')!=m['database_sha256']:raise RuntimeError('Dataset snapshot hash mismatch')
313
+ if sha(c['proposal_formula_checkpoint'])!=m['formula_selector_sha256']:raise RuntimeError('Formula selector changed')
314
+ if {p.name:sha(p) for p in Path(__file__).parent.glob('*.py')}!=m['source_hashes']:raise RuntimeError('Preprocessing/training code changed')
315
+ if verify_files:
316
+ for r in m['batches']:
317
+ if Path(r['file']).name!=r['file'] or sha(Path(m['batch_directory'])/r['file'])!=r['sha256']:
318
+ raise RuntimeError('Prepared batch hash mismatch')
319
+ return m
320
+
321
+
322
+ class FrozenBatchReader:
323
+ def __init__(self,c):
324
+ self.c=c;self.manifest=validate_prepared(c)
325
+
326
+ def get(self,index):
327
+ r=self.manifest['batches'][index]
328
+ data=(Path(self.manifest['batch_directory'])/r['file']).read_bytes()
329
+ if hashlib.sha256(data).hexdigest()!=r['sha256']:raise RuntimeError('Offline batch mutated')
330
+ batch=pickle.loads(zlib.decompress(data))
331
+ if [b['audit']['sequence'] for b in batch]!=list(range(index*self.c['batch_size'],(index+1)*self.c['batch_size'])):
332
+ raise RuntimeError('Offline sequence mismatch')
333
+ return batch
334
+
335
+ def close(self):pass
336
+
337
+
338
+ def run_pipeline(c):
339
+ root=Path(c['pipeline_dir']);root.mkdir(parents=True,exist_ok=True)
340
+ lock=(root/'pipeline.lock').open('a+');fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
341
+ try:
342
+ m=initialize_manifest(c)
343
+ save(root/'status.json',{'utc':utc(),'phase':'auditing','training_started':False})
344
+ save(root/'initial_audit.json',audit(Path(c['work_dir'])/'data.sqlite',mass_checks=True))
345
+ download(c,m)
346
+ save(root/'status.json',{'utc':utc(),'phase':'freezing','training_started':False})
347
+ dest=freeze(c,m)
348
+ train=prepare(c,m,dest)
349
+ save(root/'status.json',{'utc':utc(),'phase':'ready_for_training','training_started':False,'pending':0})
350
+ if c.get('auto_train_after_validation',False):
351
+ disk_guard(root,c['preprocess_min_free_gib'])
352
+ save(root/'status.json',{'utc':utc(),'phase':'training','training_started':True,
353
+ 'pending':0,'training_status_path':str(Path(train['run_dir'])/'status.json')})
354
+ result=subprocess.run([sys.executable,'-u','-m','specpartition_ms.supervise_v03','--config',str(root/'training_config.json')])
355
+ if result.returncode:raise RuntimeError('Training supervisor exited '+str(result.returncode))
356
+ save(root/'status.json',{'utc':utc(),'phase':'initial_curriculum_verified','training_started':True,'scientific_evaluation_completed':False})
357
+ except BaseException as exc:
358
+ save(root/'status.json',{'utc':utc(),'phase':'blocked','error':type(exc).__name__+': '+str(exc)[:350],
359
+ 'action':'Inspect error; never bypass readiness or delete data'})
360
+ raise
361
+ finally:lock.close()
362
+
363
+
364
+ def main():
365
+ p=argparse.ArgumentParser();p.add_argument('--config',required=True);p.add_argument('--audit-only',action='store_true')
366
+ a=p.parse_args();c=json.loads(Path(a.config).read_text())
367
+ if a.audit_only:
368
+ result=audit(Path(c['work_dir'])/'data.sqlite');print(json.dumps(result,indent=2));return
369
+ run_pipeline(c)
370
+
371
+
372
+ if __name__=='__main__':main()
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/parallel_download.py ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Bounded formula concurrency, pooled HTTPS, one writer, global backpressure.
2
+
3
+ Only scheduling/transport changes: preserve formula IDs, 500-CID property
4
+ batches, full response validation, request keys and the data-before-training gate.
5
+ """
6
+ from collections import Counter
7
+ from concurrent.futures import ThreadPoolExecutor, wait, FIRST_COMPLETED
8
+ from contextlib import contextmanager
9
+ from datetime import datetime, timezone
10
+ from email.utils import parsedate_to_datetime
11
+ import fcntl
12
+ import io
13
+ import json
14
+ from pathlib import Path
15
+ import queue
16
+ import re
17
+ import shutil
18
+ import sqlite3
19
+ import threading
20
+ import time
21
+ from urllib.error import HTTPError, URLError
22
+ from .multiview_data import packed, sha, save, utc
23
+
24
+
25
+ class DownloadCancelled(RuntimeError):
26
+ pass
27
+
28
+
29
+ def retry_after_seconds(value, now=None):
30
+ if not value:return 0.
31
+ try:return max(0.,float(value))
32
+ except ValueError:
33
+ try:
34
+ stamp=parsedate_to_datetime(value)
35
+ if stamp.tzinfo is None:stamp=stamp.replace(tzinfo=timezone.utc)
36
+ return max(0.,stamp.timestamp()-(time.time() if now is None else now))
37
+ except (ValueError,TypeError,OverflowError):return 0.
38
+
39
+
40
+ def feedback_policy(headers,status,now):
41
+ h={k.lower():str(v) for k,v in headers.items()}
42
+ text=h.get('x-throttling-control','')
43
+ colors=re.findall(r'\b(Green|Yellow|Red|Black)\b',text,re.I)
44
+ severity=max(({'green':0,'yellow':1,'red':2,'black':3}[x.lower()] for x in colors),default=0)
45
+ if status in (429,503):severity=max(severity,2)
46
+ pause=max((0.,0.,15.,60.)[severity],retry_after_seconds(h.get('retry-after'),now))
47
+ # A green response from another backend cannot immediately undo a red one.
48
+ return {'severity':severity,'interval':(0.,.5,1.,2.)[severity],
49
+ 'pause_until':now+pause,'expires':now+max(60.,pause),
50
+ 'header':text[:500]}
51
+
52
+
53
+ class RequestController:
54
+ def __init__(self,cache_dir,runtime,events_path,min_free_gib=20,session_factory=None):
55
+ self.root=Path(cache_dir);self.root.mkdir(parents=True,exist_ok=True)
56
+ self.interval=float(runtime.get('min_interval_seconds',.26))
57
+ self.connections=int(runtime.get('http_connections',4))
58
+ if self.interval<.26 or not 1<=self.connections<=4:
59
+ raise ValueError('Policy guard: interval >=0.26s and at most 4 outstanding HTTP requests')
60
+ self.rate=self.root/'pubchem_global_rate.json'
61
+ self.feedback_path=self.root/'pubchem_feedback.json'
62
+ self.locks=self.root/'singleflight';self.locks.mkdir(exist_ok=True)
63
+ self.events_path=Path(events_path)
64
+ self.stop=threading.Event();self.lock=threading.Lock()
65
+ self.min_free_gib=min_free_gib;self.inflight=0;self.peak_inflight=0;self.counts=Counter()
66
+ self.sessions=queue.Queue()
67
+ if session_factory is None:
68
+ import requests
69
+ def session_factory():
70
+ session=requests.Session()
71
+ adapter=requests.adapters.HTTPAdapter(pool_connections=1,pool_maxsize=1,max_retries=0,pool_block=True)
72
+ session.mount('https://',adapter)
73
+ return session
74
+ self.all_sessions=[session_factory() for _ in range(self.connections)]
75
+ for s in self.all_sessions:self.sessions.put(s)
76
+
77
+ @contextmanager
78
+ def key_lock(self,key):
79
+ # 256 stable lock stripes; only colliding requests queue, no duplicate IO.
80
+ with (self.locks/(key[:2]+'.lock')).open('a+') as fh:
81
+ while True:
82
+ if self.stop.is_set():raise DownloadCancelled('Downloader stopping')
83
+ try:fcntl.flock(fh,fcntl.LOCK_EX|fcntl.LOCK_NB);break
84
+ except BlockingIOError:self.stop.wait(.1)
85
+ try:yield
86
+ finally:fcntl.flock(fh,fcntl.LOCK_UN)
87
+
88
+ @contextmanager
89
+ def feedback_state(self):
90
+ with self.feedback_path.open('a+') as fh:
91
+ fcntl.flock(fh,fcntl.LOCK_EX)
92
+ fh.seek(0)
93
+ try:state=json.load(fh)
94
+ except ValueError:state={}
95
+ try:yield state
96
+ finally:
97
+ fh.seek(0);fh.truncate();json.dump(state,fh);fh.flush()
98
+ fcntl.flock(fh,fcntl.LOCK_UN)
99
+
100
+ def observe(self,headers,status):
101
+ now=time.time();p=feedback_policy(headers,status,now)
102
+ with self.feedback_state() as s:
103
+ if s.get('expires',0)<now:s.clear()
104
+ s['severity']=max(s.get('severity',0),p['severity'])
105
+ s['interval']=max(s.get('interval',0.),p['interval'])
106
+ s['pause_until']=max(s.get('pause_until',0.),p['pause_until'])
107
+ if p['severity'] or p['pause_until']>now:s['expires']=max(s.get('expires',0.),p['expires'])
108
+ s['last_header']=p['header'];s['last_status']=status;s['updated']=utc()
109
+ return p['header']
110
+
111
+ def throttle(self):
112
+ while not self.stop.is_set():
113
+ if shutil.disk_usage(self.root).free<self.min_free_gib*1024**3:
114
+ self.stop.set();raise DownloadCancelled('Disk reserve reached before HTTP request')
115
+ with self.feedback_state() as s:
116
+ if s.get('expires',0)<time.time():s.clear()
117
+ interval=max(self.interval,s.get('interval',0.))
118
+ pause=s.get('pause_until',0.)
119
+ # Reuse the previous downloader's global start lock and timestamp.
120
+ with self.rate.open('a+') as fh:
121
+ fcntl.flock(fh,fcntl.LOCK_EX);fh.seek(0)
122
+ try:last=float(fh.read() or 0)
123
+ except ValueError:last=0.
124
+ delay=max(pause-time.time(),interval-(time.time()-last),0.)
125
+ if delay<=0:
126
+ stamp=time.time();fh.seek(0);fh.truncate();fh.write(str(stamp));fh.flush()
127
+ fcntl.flock(fh,fcntl.LOCK_UN);return stamp
128
+ fcntl.flock(fh,fcntl.LOCK_UN)
129
+ self.stop.wait(min(delay,.25))
130
+ raise DownloadCancelled('Downloader stopping')
131
+
132
+ def fetch(self,url,payload,key):
133
+ session=None
134
+ while session is None:
135
+ if self.stop.is_set():raise DownloadCancelled('Downloader stopping')
136
+ try:session=self.sessions.get(timeout=.2)
137
+ except queue.Empty:pass
138
+ started=None;status=None;header='';size=0;error=None
139
+ try:
140
+ started=self.throttle()
141
+ with self.lock:
142
+ self.inflight+=1;self.peak_inflight=max(self.peak_inflight,self.inflight)
143
+ headers={'User-Agent':'SpecPartition-MS/0.4.1 (research candidate audit)','Accept':'application/json'}
144
+ if payload:headers['Content-Type']='application/x-www-form-urlencoded'
145
+ # Session lease is exclusive; cookies cannot become request features.
146
+ session.cookies.clear()
147
+ response=session.request('POST' if payload else 'GET',url,data=payload,headers=headers,
148
+ timeout=(15,65),allow_redirects=False)
149
+ try:
150
+ status=response.status_code;body=response.content;size=len(body)
151
+ header=self.observe(response.headers,status)
152
+ if status>=300:
153
+ raise HTTPError(url,status,'PubChem HTTP '+str(status),response.headers,io.BytesIO(body))
154
+ return body
155
+ finally:response.close()
156
+ except HTTPError as exc:error='HTTP '+str(exc.code);raise
157
+ except DownloadCancelled:raise
158
+ except Exception as exc:
159
+ error=type(exc).__name__
160
+ raise URLError(type(exc).__name__+' during PubChem transport') from exc
161
+ finally:
162
+ if started is not None:
163
+ ended=time.time()
164
+ event={'utc':utc(),'started_epoch':started,'seconds':ended-started,'http_status':status,
165
+ 'request_sha256':key,'kind':'fastformula' if '/fastformula/' in url else 'properties',
166
+ 'bytes':size,'error':error,'throttling':header}
167
+ with self.lock:
168
+ self.inflight-=1;self.counts[str(status) if status else 'network_error']+=1
169
+ with self.events_path.open('a') as out:out.write(json.dumps(event)+'\n')
170
+ self.sessions.put(session)
171
+
172
+ def metrics(self):
173
+ with self.lock:return {'inflight_http':self.inflight,'peak_inflight_http':self.peak_inflight,'http_results':dict(self.counts)}
174
+
175
+ def close(self):
176
+ for s in self.all_sessions:s.close()
177
+
178
+
179
+ def download_parallel(c,m,runtime,controller_factory=RequestController,cache_factory=None):
180
+ from .offline_data import digest,binding,verify_pool,disk_guard
181
+ from .retrieval import PubChemCache
182
+ cache_factory=cache_factory or PubChemCache
183
+ root=Path(c['pipeline_dir']);live=Path(c['work_dir']);cache_dir=live/'pubchem';cache_dir.mkdir(exist_ok=True)
184
+ workers=int(runtime.get('formula_workers',16))
185
+ if not 2<=workers<=32:raise ValueError('formula_workers must be 2..32')
186
+ guard=(live/'pubchem_worker.lock').open('a+');fcntl.flock(guard,fcntl.LOCK_EX|fcntl.LOCK_NB)
187
+ db=sqlite3.connect(live/'data.sqlite',timeout=90)
188
+ controller=None;executor=None;futures={};completed=set();verified=[];failed=[];owned=set()
189
+ try:
190
+ if digest(binding(db))!=m['source_binding_sha256']:raise RuntimeError('Source or formula catalog changed')
191
+ db.executemany('INSERT OR IGNORE INTO jobs(formula) VALUES (?)',[(f,) for f in m['required_formulas']]);db.commit()
192
+ # Only request cache gets WAL; full formula pools are committed by coordinator.
193
+ bootstrap=PubChemCache(cache_dir/'requests.sqlite');bootstrap.db.execute('PRAGMA journal_mode=WAL');bootstrap.close()
194
+ required=set(m['required_formulas'])
195
+ for f,blob,n,h in db.execute('SELECT formula,body,raw_count,sha256 FROM formula_pools'):
196
+ if f in required:verify_pool(f,(blob,n,h));completed.add(f);verified.append((f,h,n))
197
+ priorities=dict(db.execute("SELECT formula,COUNT(*) FROM spectra WHERE source='odata' AND status='eligible' GROUP BY formula"))
198
+ todo=iter(sorted(required-completed,key=lambda f:(-priorities.get(f,0),f)))
199
+ controller=controller_factory(cache_dir,runtime,root/'http_events_parallel.jsonl',c['download_min_free_gib'])
200
+ started=time.time();run_id=str(time.time_ns())
201
+ save(root/f'download_runtime_receipt_{run_id}.json',{'utc':utc(),'runtime':runtime,'runtime_sha256':digest(runtime),
202
+ 'initial_ready':len(completed),'required':len(required),'source_sha256':sha(__file__),'candidate_protocol_changed':False})
203
+ def retrieve(formula,attempts):
204
+ cache=cache_factory(cache_dir/'requests.sqlite',online=True,property_batch_size=c['property_batch_size'],controller=controller)
205
+ try:
206
+ while attempts<c['pubchem_max_attempts'] and not controller.stop.is_set():
207
+ attempts+=1
208
+ try:
209
+ records,prov=cache.formula_candidates(formula)
210
+ blob=packed({'records':records,'provenance':prov});h=__import__('hashlib').sha256(blob).hexdigest()
211
+ verify_pool(formula,(blob,len(records),h))
212
+ return {'blob':blob,'count':len(records),'sha256':h,'attempts':attempts}
213
+ except DownloadCancelled:raise
214
+ except Exception as exc:
215
+ error=type(exc).__name__+': '+str(exc)[:250]
216
+ if attempts<c['pubchem_max_attempts']:controller.stop.wait(min(30,5*attempts))
217
+ return {'error':locals().get('error','prior retry budget exhausted'),'attempts':attempts}
218
+ finally:cache.close()
219
+ def publish():
220
+ save(root/'status.json',{'utc':utc(),'phase':'downloading','mode':'parallel_pooled_http',
221
+ 'ready':len(completed),'required':len(required),'remaining':len(required-completed),
222
+ 'training_started':False,'formula_workers':workers,'active_formulas':sorted(futures.values()),
223
+ 'http_connections':controller.connections,'requests_per_second_cap':1/controller.interval,
224
+ 'elapsed_seconds':time.time()-started,'failed_formulas':failed,**controller.metrics()})
225
+ executor=ThreadPoolExecutor(max_workers=workers,thread_name_prefix='pubchem-formula')
226
+ exhausted=False
227
+ while futures or not exhausted:
228
+ if controller.stop.is_set():raise DownloadCancelled('Global stop or disk reserve reached')
229
+ while len(futures)<workers and not exhausted:
230
+ try:f=next(todo)
231
+ except StopIteration:exhausted=True;break
232
+ disk_guard(root,c['download_min_free_gib'])
233
+ attempts=db.execute('SELECT attempts FROM jobs WHERE formula=?',(f,)).fetchone()[0]
234
+ db.execute("UPDATE jobs SET status='in_progress',updated=? WHERE formula=?",(utc(),f));db.commit()
235
+ owned.add(f)
236
+ futures[executor.submit(retrieve,f,attempts)]=f
237
+ publish()
238
+ if not futures:break
239
+ done,_=wait(futures,timeout=2,return_when=FIRST_COMPLETED)
240
+ for future in done:
241
+ f=futures.pop(future);result=future.result()
242
+ if 'error' in result:
243
+ failed.append(f)
244
+ db.execute("UPDATE jobs SET status='failed',attempts=?,error=?,updated=? WHERE formula=?",(result['attempts'],result['error'],utc(),f));db.commit()
245
+ else:
246
+ disk_guard(root,c['download_min_free_gib'])
247
+ db.execute('INSERT INTO formula_pools VALUES (?,?,?,?,?)',(f,result['blob'],result['count'],result['sha256'],utc()))
248
+ db.execute("UPDATE jobs SET status='completed',attempts=?,error=NULL,updated=? WHERE formula=?",(result['attempts'],utc(),f));db.commit()
249
+ completed.add(f);verified.append((f,result['sha256'],result['count']))
250
+ with (root/'download_events.jsonl').open('a') as out:
251
+ out.write(json.dumps({'utc':utc(),'formula':f,'records':result['count'],'sha256':result['sha256'],'attempts':result['attempts'],'parallel_run_id':run_id})+'\n')
252
+ publish()
253
+ result={'utc':utc(),'required':len(required),'verified':len(completed),'pools':sorted(verified),
254
+ 'failed':failed,'complete':completed==required,'runtime':runtime,'elapsed_seconds':time.time()-started}
255
+ save(root/'download_complete.json',result)
256
+ if not result['complete']:raise RuntimeError(f'{len(failed)} formula jobs unresolved; no training')
257
+ return result
258
+ finally:
259
+ if controller:controller.stop.set()
260
+ if executor:executor.shutdown(wait=True,cancel_futures=True)
261
+ # Uncommitted in-flight work becomes pending. Individual HTTP cache entries survive.
262
+ for f in owned:
263
+ db.execute("UPDATE jobs SET status='pending',updated=? WHERE formula=? AND status='in_progress'",(utc(),f))
264
+ db.commit();db.close()
265
+ if controller:controller.close()
266
+ guard.close()
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/pipeline_epoch.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Only the v06 pipeline is owned. Downloader and prior runs are never managed.
2
+
3
+ wait-prepare attaches read-only to the already started preparation stage.
4
+ GPU admission waits while another compute process occupies the card. Bounded
5
+ CUDA recovery is inherited; OOM/unknown failures never trigger retry loops.
6
+ """
7
+ import argparse
8
+ import fcntl
9
+ import json
10
+ import os
11
+ from pathlib import Path
12
+ import signal
13
+ import subprocess
14
+ import sys
15
+ import time
16
+ from .multiview_data import save,utc,sha
17
+ from .supervise_v03 import restart_decision,terminate_owned_group
18
+
19
+
20
+ def run(config_path,wait_prepare=False):
21
+ path=Path(config_path).resolve();c=json.loads(path.read_text());root=Path(c['run_dir']);root.mkdir(parents=True,exist_ok=True)
22
+ lock=(root/'pipeline.lock').open('a+');fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
23
+ child=None;stamp=str(time.time_ns())
24
+ def record(event,**kw):
25
+ row={'utc':utc(),'event':event,**kw};save(root/'pipeline_status.json',row)
26
+ with (root/'pipeline_events.jsonl').open('a') as f:f.write(json.dumps(row)+'\n')
27
+ print(json.dumps(row),flush=True)
28
+ def interrupt(s,f):raise KeyboardInterrupt()
29
+ for s in (signal.SIGINT,signal.SIGTERM):signal.signal(s,interrupt)
30
+ def command(module,args,logname):
31
+ nonlocal child
32
+ with (root/logname).open('a') as log:
33
+ child=subprocess.Popen([sys.executable,'-u','-m',module,*args],stdout=log,stderr=subprocess.STDOUT,start_new_session=True)
34
+ record('child_started',module=module,pid=child.pid,log=str(root/logname));code=child.wait()
35
+ terminate_owned_group(child);child=None
36
+ return code
37
+ try:
38
+ if wait_prepare:
39
+ record('waiting_for_preparation',prepared_dir=c['prepared_dir'])
40
+ while not (Path(c['prepared_dir'])/'manifest.json').exists():
41
+ failure=Path(c['prepared_dir'])/'failure.json'
42
+ if failure.exists():raise RuntimeError('Preparation failed; '+str(failure))
43
+ # A released preparation lock with no manifest is a real stop.
44
+ try:
45
+ with (Path(c['prepared_dir'])/'prepare.lock').open('a+') as guard:
46
+ fcntl.flock(guard,fcntl.LOCK_EX|fcntl.LOCK_NB)
47
+ raise RuntimeError('Preparation process stopped before manifest')
48
+ except BlockingIOError:pass
49
+ time.sleep(30)
50
+ else:
51
+ if command('specpartition_ms.prepare_epoch',['--config',str(path)],'prepare.log'):raise RuntimeError('Preparation failed')
52
+ from .prepare_epoch import validate
53
+ _,checks=validate(c,True);record('prepared_verified',checks=checks)
54
+ # Do not compete with a new, unrelated GPU task that may have appeared
55
+ # during preparation. Check compute PIDs and available memory.
56
+ waiting=False
57
+ while True:
58
+ gpu=subprocess.check_output(['nvidia-smi','--query-compute-apps=pid','--format=csv,noheader,nounits'],text=True).strip()
59
+ free=float(subprocess.check_output(['nvidia-smi','--query-gpu=memory.free','--format=csv,noheader,nounits'],text=True).splitlines()[0])
60
+ if not gpu and free>29000:break
61
+ if not waiting:record('waiting_for_gpu_admission',compute_pids=gpu,free_mib=free);waiting=True
62
+ time.sleep(30)
63
+ accept=root/'acceptance';accept.mkdir(exist_ok=True)
64
+ if command('specpartition_ms.benchmark_epoch',['--config',str(path),'--sweep-dir',str(accept)],'batch_sweep.log'):
65
+ raise RuntimeError('Batch sweep failed; see real-data acceptance log')
66
+ selected=accept/'selected_config.json';selected_c=json.loads(selected.read_text())
67
+ receipt=json.loads((accept/'batch_selection.json').read_text())
68
+ if receipt['selected_config_sha256']!=sha(selected):raise ValueError('Accepted configuration hash mismatch')
69
+ record('training_configuration_accepted',batch=receipt['selected_batch'],epochs=selected_c['epochs'],config=str(selected))
70
+ restarts=0;seen=set()
71
+ while True:
72
+ args=['--config',str(selected)]
73
+ if (root/'last.pt').exists():args.append('--resume')
74
+ code=command('specpartition_ms.train_epoch',args,f'trainer_{stamp}_{restarts}.log')
75
+ state=json.loads((root/'status.json').read_text()) if (root/'status.json').exists() else {}
76
+ done=root/'completion_verified.json'
77
+ if code==0 and state.get('completion_verified') and done.exists() and json.loads(done.read_text()).get('passed'):
78
+ record('full_epochs_verified',epochs=selected_c['epochs'],checkpoint=str(root/'last.pt'));return 0
79
+ allowed,reason=restart_decision(state,restarts,seen,limit=2)
80
+ record('trainer_exited',returncode=code,recovery_allowed=allowed,reason=reason,status=state)
81
+ if not allowed:return code or 2
82
+ seen.add(state['last_checkpoint_step']);restarts+=1;os.environ['CUDA_LAUNCH_BLOCKING']='1'
83
+ except KeyboardInterrupt:
84
+ record('stopped_no_restart');return 130
85
+ except BaseException as e:
86
+ record('pipeline_failed',error=repr(e));raise
87
+ finally:
88
+ if child is not None:terminate_owned_group(child)
89
+ lock.close()
90
+
91
+
92
+ if __name__=='__main__':
93
+ p=argparse.ArgumentParser();p.add_argument('--config',required=True);p.add_argument('--wait-prepare',action='store_true')
94
+ a=p.parse_args();raise SystemExit(run(a.config,a.wait_prepare))
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/prefetch.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Ordered, bounded, restartable CPU preparation. No training step is skipped."""
2
+ from collections import deque
3
+ from concurrent.futures import ProcessPoolExecutor, TimeoutError
4
+ from concurrent.futures.process import BrokenProcessPool
5
+ import json
6
+ import multiprocessing as mp
7
+ from pathlib import Path
8
+ import time
9
+ from .data_v03 import initialize_worker, prepare_batch
10
+
11
+
12
+ def stop_owned_pool(pool):
13
+ """Bound shutdown to this executor's own children, never broad pkill."""
14
+ processes=list((getattr(pool,'_processes',None) or {}).values())
15
+ for p in processes:
16
+ if p.is_alive():p.terminate()
17
+ deadline=time.monotonic()+5
18
+ for p in processes:p.join(timeout=max(0,deadline-time.monotonic()))
19
+ for p in processes:
20
+ if p.is_alive():p.kill();p.join(timeout=1)
21
+ pool.shutdown(wait=False,cancel_futures=True)
22
+
23
+
24
+ class OrderedPrefetch:
25
+ def __init__(self,c,first,end,chemistry,stage_for,initializer=initialize_worker,prepare=prepare_batch):
26
+ self.c=c;self.end=end;self.chemistry=chemistry;self.stage_for=stage_for
27
+ self.initializer=initializer;self.prepare=prepare;self.next_index=first
28
+ self.pending=deque();self.restarts=0;self.pool=self._new_pool()
29
+
30
+ def _new_pool(self):
31
+ return ProcessPoolExecutor(max_workers=self.c['workers'],mp_context=mp.get_context('spawn'),
32
+ initializer=self.initializer,initargs=(self.c,))
33
+
34
+ def get(self,step):
35
+ attempt=0
36
+ while True:
37
+ try:
38
+ while len(self.pending)<self.c['prefetch_batches'] and self.next_index<self.end:
39
+ n=self.next_index
40
+ task=(n,self.stage_for(self.c,n),self.chemistry)
41
+ self.pending.append((n,self.pool.submit(self.prepare,task)));self.next_index+=1
42
+ index,future=self.pending[0]
43
+ if index!=step:raise RuntimeError(f'Prefetch order violation: {index} != {step}')
44
+ result=future.result(timeout=self.c.get('preparation_timeout_seconds',600))
45
+ self.pending.popleft()
46
+ return result
47
+ except (BrokenProcessPool,TimeoutError) as exc:
48
+ attempt+=1;self.restarts+=1
49
+ processes=list((getattr(self.pool,'_processes',None) or {}).values())
50
+ event={'utc_epoch':time.time(),'step':step,'attempt':attempt,'total_restarts':self.restarts,
51
+ 'error':type(exc).__name__+': '+str(exc),
52
+ 'workers':[{'pid':p.pid,'exitcode':p.exitcode,'alive':p.is_alive()} for p in processes],
53
+ 'action':'replay same unconsumed step/sequence; no optimizer update or skipped sample',
54
+ 'live_pool_readiness_may_change':True}
55
+ path=Path(self.c['run_dir'])/'worker_recovery.jsonl'
56
+ with path.open('a') as f:f.write(json.dumps(event)+'\n')
57
+ stop_owned_pool(self.pool)
58
+ if attempt>self.c.get('worker_restart_limit',3) or self.restarts>8:
59
+ raise RuntimeError(f'CPU worker recovery budget exhausted at step {step}; see {path}') from exc
60
+ self.pending.clear();self.next_index=step;self.pool=self._new_pool()
61
+
62
+ def close(self):
63
+ if self.pending:
64
+ for _,future in self.pending:future.cancel()
65
+ stop_owned_pool(self.pool)
66
+ else:self.pool.shutdown(wait=True,cancel_futures=True)
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/prepare_epoch.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Offline-only, resumable feature preparation; never accesses PubChem tables.
2
+
3
+ Copy eligible spectra, materialize required unique molecular inputs, then build
4
+ both official MSG training views/forests. No online fallback is allowed later.
5
+ All writes target prepared_dir, never work_dir or downloader resources.
6
+ """
7
+ import argparse
8
+ from collections import Counter
9
+ from concurrent.futures import ProcessPoolExecutor
10
+ from dataclasses import asdict
11
+ import fcntl
12
+ import hashlib
13
+ import json
14
+ import multiprocessing as mp
15
+ from pathlib import Path
16
+ import shutil
17
+ import sqlite3
18
+ import time
19
+ import numpy as np
20
+ from rdkit import RDLogger, rdBase
21
+ from .chemistry import _calculate_molecule
22
+ from .config import Config
23
+ from .epoch_features import PreparedQuery, spectrum_arrays, dumps, loads
24
+ from .forest import build_forest
25
+ from .inbatch_data import InbatchStream
26
+ from .multiview_data import unpacked, save, utc, sha
27
+ from .multiview_pools import FormulaCatalog
28
+ from .train_inbatch import source_binding
29
+
30
+
31
+ def readonly(path):
32
+ db = sqlite3.connect(f'file:{path}?mode=ro', uri=True, timeout=60)
33
+ db.execute('PRAGMA query_only=ON')
34
+ return db
35
+
36
+
37
+ def initialize(path):
38
+ db = sqlite3.connect(path, timeout=60)
39
+ db.execute('PRAGMA journal_mode=WAL'); db.execute('PRAGMA synchronous=NORMAL')
40
+ db.executescript('''
41
+ CREATE TABLE IF NOT EXISTS stage(name TEXT PRIMARY KEY, value TEXT);
42
+ CREATE TABLE IF NOT EXISTS spectra(id INTEGER PRIMARY KEY, source TEXT, identity TEXT,
43
+ ref_smiles TEXT, target TEXT, body BLOB NOT NULL);
44
+ CREATE INDEX IF NOT EXISTS spectrum_source ON spectra(source,id);
45
+ CREATE TABLE IF NOT EXISTS molecules(id INTEGER PRIMARY KEY, smiles TEXT UNIQUE,
46
+ value BLOB, error TEXT, identity TEXT, formula TEXT, charge INTEGER, ready INTEGER DEFAULT 0);
47
+ CREATE INDEX IF NOT EXISTS molecule_ready ON molecules(ready,id);
48
+ CREATE TABLE IF NOT EXISTS targets(target TEXT PRIMARY KEY, ref_smiles TEXT, identity TEXT, formula TEXT);
49
+ CREATE TABLE IF NOT EXISTS pools(view TEXT, target TEXT, raw BLOB, sha256 TEXT, raw_count INTEGER,
50
+ prepared BLOB, PRIMARY KEY(view,target));
51
+ CREATE TABLE IF NOT EXISTS training_structures(identity TEXT PRIMARY KEY, smiles TEXT, formula TEXT);
52
+ CREATE TABLE IF NOT EXISTS heldout(identity TEXT PRIMARY KEY);
53
+ ''')
54
+ return db
55
+
56
+
57
+ def stage(db, key, value=None):
58
+ if value is None:
59
+ r = db.execute('SELECT value FROM stage WHERE name=?', (key,)).fetchone()
60
+ return json.loads(r[0]) if r else None
61
+ db.execute('INSERT OR REPLACE INTO stage VALUES (?,?)', (key, json.dumps(value)))
62
+ db.commit()
63
+
64
+
65
+ def guard(root, c):
66
+ if shutil.disk_usage(root).free < c['min_free_gb'] * 1024**3:
67
+ raise RuntimeError('Disk reserve reached; no partial training allowed')
68
+
69
+
70
+ _CAT = None
71
+
72
+
73
+ def worker_init(source_path):
74
+ global _CAT
75
+ import torch
76
+ torch.set_num_threads(1); RDLogger.DisableLog('rdApp.*')
77
+ db = readonly(source_path); db.set_authorizer(InbatchStream.authorize)
78
+ _CAT = FormulaCatalog(db); db.close()
79
+
80
+
81
+ def convert_spectra(rows):
82
+ out = []
83
+ for sid, raw in rows:
84
+ b = unpacked(raw); f = b['features']
85
+ q = PreparedQuery(peaks=tuple(tuple(p) for p in f['peaks']), precursor_mz=f['precursor_mz'],
86
+ adduct=f['adduct'], collision_energy=f.get('collision_energy'), instrument=f.get('instrument'),
87
+ formula_candidates=(), candidates=(), dataset_mode=f['dataset_mode'], candidate_view='warmup')
88
+ from dataclasses import replace
89
+ q = replace(q, spectrum_arrays=spectrum_arrays(q))
90
+ fs = tuple(_CAT.select(q.precursor_mz, q.adduct))
91
+ out.append((sid, b['source'], b['identity'], b['reference_smiles'], b.get('target_smiles'),
92
+ dumps({'query':q, 'independent_formulas':fs, 'source_row':b['source_row']}), b['formula']))
93
+ return out
94
+
95
+
96
+ def convert_molecules(rows):
97
+ out = []
98
+ for mid, smiles in rows:
99
+ try:
100
+ m = _calculate_molecule(smiles)
101
+ out.append((dumps(m), None, m.identity, m.formula, m.charge, mid))
102
+ except (ValueError, TypeError, OverflowError) as e:
103
+ out.append((None, type(e).__name__ + ': ' + str(e)[:240], None, None, None, mid))
104
+ return out
105
+
106
+
107
+ def prepare_pool(task):
108
+ path, view, target, chemistry = task
109
+ db = readonly(path)
110
+ banned = {r[0] for r in db.execute('SELECT identity FROM heldout')}
111
+ raw, digest, count = db.execute('SELECT raw,sha256,raw_count FROM pools WHERE view=? AND target=?', (view,target)).fetchone()
112
+ smiles = unpacked(raw)
113
+ if len(smiles) != count or hashlib.sha256(json.dumps(smiles, separators=(',', ':')).encode()).hexdigest() != digest:
114
+ raise ValueError('Official candidate pool hash/count mismatch')
115
+ retained = {}; removed = Counter()
116
+ for s in smiles:
117
+ r = db.execute('SELECT id,value,error,ready FROM molecules WHERE smiles=?', (s,)).fetchone()
118
+ if not r or r[3] != 1:
119
+ raise ValueError('Molecular preparation incomplete')
120
+ if r[2]: removed['unsupported_structure'] += 1; continue
121
+ m = loads(r[1])
122
+ if m.identity in banned: removed['heldout_connectivity'] += 1; continue
123
+ if m.charge: removed['unsupported_charged_structure'] += 1; continue
124
+ if m.identity not in retained or s < retained[m.identity][0]:
125
+ retained[m.identity] = (s, r[0], m)
126
+ values = [retained[k] for k in sorted(retained)]
127
+ mols = [v[2] for v in values]
128
+ # Official pools are <=256 here. A future larger source requires an explicit
129
+ # sampling/forest policy, never silent truncation or reference injection.
130
+ if len(mols) > 256:
131
+ raise ValueError('Official training pool >256; explicit protocol update required')
132
+ cfg = Config().chemistry
133
+ for k,v in chemistry.items(): setattr(cfg,k,v)
134
+ forest = build_forest(mols, cfg, vectorized=True)
135
+ ref_s, identity, formula = db.execute('SELECT ref_smiles,identity,formula FROM targets WHERE target=?', (target,)).fetchone()
136
+ ref = loads(db.execute('SELECT value FROM molecules WHERE smiles=? AND ready=1 AND error IS NULL', (ref_s,)).fetchone()[0])
137
+ isomers = [(v[1], v[2]) for v in values if v[2].identity != identity and v[2].formula == formula]
138
+ from .chemistry import tanimoto
139
+ isomers.sort(key=lambda v: (-tanimoto(ref.whole, v[1].whole), v[1].identity))
140
+ result = {'molecule_ids':tuple(v[1] for v in values), 'forest':forest,
141
+ 'same_formula_proposal_ids':tuple(v[0] for v in isomers),
142
+ 'raw_count':count, 'projected_count':len(mols), 'removed':dict(removed),
143
+ 'sha256':digest, 'positive_in_original_projected_pool':identity in retained,
144
+ 'identity_hash':hashlib.sha256('\n'.join(sorted(retained)).encode()).hexdigest(),
145
+ 'ppm_filter_applied':False, 'raw_pool_modified':False, 'network_requests':0}
146
+ db.close()
147
+ return view, target, dumps(result)
148
+
149
+
150
+ def validate(c, verify_hash=False):
151
+ root = Path(c['prepared_dir']); p = root/'manifest.json'
152
+ if not p.exists(): raise RuntimeError('No completed preparation manifest')
153
+ m = json.loads(p.read_text())
154
+ if not m.get('complete'): raise RuntimeError('Preparation not complete')
155
+ if m['source_binding'] != source_binding(c)['sha256']: raise RuntimeError('Source registry changed')
156
+ if m['chemistry'] != asdict(Config().chemistry): raise RuntimeError('Chemistry configuration changed')
157
+ if m['rdkit_version'] != rdBase.rdkitVersion: raise RuntimeError('RDKit version changed')
158
+ for name, digest in m['preparation_source_hashes'].items():
159
+ if sha(Path(__file__).parent/name) != digest: raise RuntimeError('Preparation implementation changed: '+name)
160
+ if verify_hash and sha(root/'prepared.sqlite') != m['sha256']: raise RuntimeError('Prepared artifact hash mismatch')
161
+ db = readonly(root/'prepared.sqlite')
162
+ checks = {'spectra':dict(db.execute('SELECT source,COUNT(*) FROM spectra GROUP BY source')) == m['eligible'],
163
+ 'molecules':db.execute('SELECT COUNT(*) FROM molecules WHERE ready=0').fetchone()[0] == 0,
164
+ 'pools':db.execute('SELECT COUNT(*) FROM pools WHERE prepared IS NULL').fetchone()[0] == 0,
165
+ 'all_target_views':db.execute('SELECT COUNT(*) FROM pools').fetchone()[0] == 2*db.execute('SELECT COUNT(*) FROM targets').fetchone()[0],
166
+ 'heldout_labels':db.execute('SELECT COUNT(*) FROM spectra JOIN heldout USING(identity)').fetchone()[0] == 0,
167
+ '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}
168
+ db.close()
169
+ if not all(checks.values()): raise RuntimeError('Preparation checks failed: '+str(checks))
170
+ return m, checks
171
+
172
+
173
+ def run(c):
174
+ root = Path(c['prepared_dir']); root.mkdir(parents=True,exist_ok=True)
175
+ lock = (root/'prepare.lock').open('a+'); fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
176
+ if (root/'manifest.json').exists():
177
+ _, checks = validate(c,True)
178
+ print(json.dumps({'phase':'complete_reused','utc':utc(),'checks':checks}),flush=True)
179
+ lock.close()
180
+ return
181
+ start = time.monotonic()
182
+ def status(phase, **kw):
183
+ guard(root,c); row = {'utc':utc(),'phase':phase,'elapsed_seconds':time.monotonic()-start,**kw}
184
+ save(root/'status.json',row); print(json.dumps(row),flush=True)
185
+ binding = source_binding(c)
186
+ expected = {s:n for s,n,_ in binding['eligible']}
187
+ source = readonly(Path(c['work_dir'])/'data.sqlite'); source.set_authorizer(InbatchStream.authorize)
188
+ db = initialize(root/'prepared.sqlite')
189
+ if stage(db,'binding') not in (None,binding['sha256']): raise ValueError('Preparation source changed')
190
+ stage(db,'binding',binding['sha256'])
191
+ chemistry = asdict(Config().chemistry)
192
+ names = ['prepare_epoch.py','epoch_features.py','chemistry.py','forest.py','schema.py','model.py','multiview_pools.py']
193
+ hashes = {name:sha(Path(__file__).parent/name) for name in names}
194
+ # A changed feature implementation cannot resume an incompatible partial cache.
195
+ if stage(db,'implementation') not in (None,hashes): raise ValueError('Partial cache implementation changed')
196
+ stage(db,'implementation',hashes)
197
+ db.executemany('INSERT OR IGNORE INTO heldout VALUES (?)', source.execute('SELECT identity FROM heldout').fetchall())
198
+ structs = source.execute('SELECT identity,smiles,formula FROM structures').fetchall()
199
+ db.executemany('INSERT OR IGNORE INTO training_structures VALUES (?,?,?)',structs)
200
+ db.executemany('INSERT OR IGNORE INTO molecules(smiles) VALUES (?)',[(s,) for _,s,_ in structs]); db.commit()
201
+ with ProcessPoolExecutor(c['prepare_workers'], mp_context=mp.get_context('spawn'), initializer=worker_init,
202
+ initargs=(str(Path(c['work_dir'])/'data.sqlite'),)) as workers:
203
+ if not stage(db,'spectra_done'):
204
+ last = stage(db,'last_spectrum_id') or 0
205
+ while True:
206
+ # Materialize a bounded read then release the shared SQLite read transaction.
207
+ 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()
208
+ if not rows: break
209
+ chunks = [rows[i:i+256] for i in range(0,len(rows),256)]
210
+ for result in workers.map(convert_spectra,chunks):
211
+ db.executemany('INSERT OR REPLACE INTO spectra VALUES (?,?,?,?,?,?)',[r[:6] for r in result])
212
+ db.executemany('INSERT OR IGNORE INTO molecules(smiles) VALUES (?)',[(r[3],) for r in result])
213
+ 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'])
214
+ last = rows[-1][0]; stage(db,'last_spectrum_id',last)
215
+ status('spectra',processed=db.execute('SELECT COUNT(*) FROM spectra').fetchone()[0],expected=sum(expected.values()))
216
+ if dict(db.execute('SELECT source,COUNT(*) FROM spectra GROUP BY source')) != expected: raise RuntimeError('Spectrum count mismatch')
217
+ stage(db,'spectra_done',True)
218
+ if not stage(db,'pools_copied'):
219
+ targets = [r[0] for r in db.execute('SELECT target FROM targets ORDER BY target')]
220
+ for i,t in enumerate(targets):
221
+ for view in ('msg_mass','msg_formula'):
222
+ raw = source.execute('SELECT body,sha256,count FROM official_pools WHERE view=? AND target=?',(view,t)).fetchone()
223
+ if not raw: raise ValueError('Missing official training pool')
224
+ db.execute('INSERT OR IGNORE INTO pools(view,target,raw,sha256,raw_count) VALUES (?,?,?,?,?)',(view,t,*raw))
225
+ db.executemany('INSERT OR IGNORE INTO molecules(smiles) VALUES (?)',[(s,) for s in unpacked(raw[0])])
226
+ if i%200==0:
227
+ db.commit(); status('collect_official_inputs',targets=i+1,total=len(targets))
228
+ stage(db,'pools_copied',True)
229
+ while True:
230
+ rows = db.execute('SELECT id,smiles FROM molecules WHERE ready=0 ORDER BY id LIMIT 4096').fetchall()
231
+ if not rows: break
232
+ for result in workers.map(convert_molecules,[rows[i:i+64] for i in range(0,len(rows),64)]):
233
+ db.executemany('UPDATE molecules SET value=?,error=?,identity=?,formula=?,charge=?,ready=1 WHERE id=?',result)
234
+ db.commit(); status('molecular_features',counts=dict(db.execute('SELECT ready,COUNT(*) FROM molecules GROUP BY ready')))
235
+ while True:
236
+ rows = db.execute('SELECT view,target FROM pools WHERE prepared IS NULL ORDER BY view,target LIMIT 64').fetchall()
237
+ if not rows: break
238
+ # Workers read only this derived artifact; all molecule writes finished.
239
+ db.commit()
240
+ for view,target,value in workers.map(prepare_pool,[(str(root/'prepared.sqlite'),v,t,chemistry) for v,t in rows]):
241
+ db.execute('UPDATE pools SET prepared=? WHERE view=? AND target=?',(value,view,target))
242
+ 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])
243
+ db.execute('PRAGMA wal_checkpoint(TRUNCATE)'); db.close(); source.close()
244
+ manifest = {'complete':True,'utc':utc(),'eligible':expected,'source_binding':binding['sha256'],
245
+ 'chemistry':chemistry,'rdkit_version':rdBase.rdkitVersion,'preparation_source_hashes':hashes,
246
+ 'sha256':sha(root/'prepared.sqlite'),'file':str(root/'prepared.sqlite'),
247
+ 'network_requests':0,'official_pool_extra_ppm_filter':False,'heldout_label_training':False}
248
+ save(root/'manifest.json',manifest)
249
+ _, checks = validate(c,True); save(root/'validation.json',{'passed':all(checks.values()),'checks':checks,'utc':utc()})
250
+ status('complete',checks=checks,sha256=manifest['sha256'])
251
+ lock.close()
252
+
253
+
254
+ if __name__ == '__main__':
255
+ p=argparse.ArgumentParser(); p.add_argument('--config',required=True)
256
+ c=json.loads(Path(p.parse_args().config).read_text())
257
+ try: run(c)
258
+ except BaseException as e:
259
+ save(Path(c['prepared_dir'])/'failure.json',{'utc':utc(),'error':repr(e)})
260
+ raise
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/resource_guard_v09.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Read-only coordination: yield our GPU before the protected run validates."""
2
+ import json
3
+ from pathlib import Path
4
+
5
+
6
+ def protected_validation_pending(run_dir):
7
+ if not run_dir:return False
8
+ root=Path(run_dir)
9
+ def read(name):
10
+ p=root/name
11
+ return json.loads(p.read_text()) if p.exists() else {}
12
+ pipeline=read('pipeline_status.json')
13
+ if pipeline.get('status')!='running':return False
14
+ if pipeline.get('stage')=='validation_mass_formula':return True
15
+ if pipeline.get('stage')=='joint_training':
16
+ total=read('protocol.json').get('total_steps')
17
+ step=read('status.json').get('step',-1)
18
+ return total is not None and step>=total-21
19
+ return False
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/retrieval.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Opt-in PubChem adapter. Default is replay-only cache; no SIRIUS dependency.
2
+
3
+ Live PubChem is not a frozen database release. Save UTC, request, response hash,
4
+ properties and CIDs to reproduce the exact candidate snapshot.
5
+ """
6
+ from dataclasses import replace
7
+ from datetime import datetime, timezone
8
+ import hashlib
9
+ from http.client import IncompleteRead
10
+ import json
11
+ import sqlite3
12
+ import time
13
+ from urllib.request import Request, urlopen
14
+ from urllib.error import HTTPError, URLError
15
+ from urllib.parse import quote, urlencode
16
+ import numpy as np
17
+ import torch
18
+ from rdkit import Chem
19
+ from .chemistry import enumerate_formulas, molecule, ppm_error
20
+ from .schema import parse_record
21
+
22
+
23
+ def utc_now():
24
+ return datetime.now(timezone.utc).isoformat()
25
+
26
+
27
+ class PubChemCache:
28
+ def __init__(self, path, online=False, transport=None, sleep=time.sleep, property_batch_size=100):
29
+ if not 1 <= property_batch_size <= 500:
30
+ raise ValueError('property_batch_size must be in 1..500')
31
+ self.property_batch_size = property_batch_size
32
+ self.db = sqlite3.connect(path)
33
+ self.db.execute("CREATE TABLE IF NOT EXISTS requests (key TEXT PRIMARY KEY, url TEXT, fetched_utc TEXT, sha256 TEXT, body TEXT)")
34
+ self.db.commit()
35
+ self.online, self.transport, self.sleep = online, transport, sleep
36
+
37
+ def close(self):
38
+ self.db.close()
39
+
40
+ def request(self, path, form=None):
41
+ url = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/"+path
42
+ payload = urlencode(form).encode() if form else None
43
+ key = hashlib.sha256(url.encode()+b"\n"+(payload or b"")).hexdigest()
44
+ row = self.db.execute("SELECT fetched_utc,sha256,body FROM requests WHERE key=?",(key,)).fetchone()
45
+ if row:
46
+ if hashlib.sha256(row[2].encode()).hexdigest()!=row[1]:
47
+ raise RuntimeError('PubChem cached response hash mismatch')
48
+ return json.loads(row[2]),{"url":url,"request_sha256":key,"fetched_utc":row[0],"response_sha256":row[1],"replayed":True}
49
+ if not self.online:
50
+ raise RuntimeError("PubChem cache miss; explicit --online is required for a network request")
51
+ error = None
52
+ for attempt in range(5):
53
+ try:
54
+ self.sleep(.3) # conservative <= 3.3 requests/sec; obey rate-limit backoff
55
+ if self.transport:
56
+ body = self.transport(url,payload)
57
+ else:
58
+ req = Request(url,data=payload,headers={"User-Agent":"SpecPartition-MS/0.1 (research candidate audit)","Accept":"application/json"})
59
+ with urlopen(req,timeout=60) as response:
60
+ body = response.read()
61
+ value = json.loads(body)
62
+ # Async or fault responses are not silently treated as complete candidate sets.
63
+ if "Waiting" in value or "Fault" in value:
64
+ raise RuntimeError("PubChem did not return a complete result: "+json.dumps(value)[:300])
65
+ stamp = utc_now()
66
+ sha = hashlib.sha256(body).hexdigest()
67
+ text = body.decode()
68
+ self.db.execute("INSERT OR REPLACE INTO requests VALUES (?,?,?,?,?)",(key,url,stamp,sha,text))
69
+ self.db.commit()
70
+ return value,{"url":url,"request_sha256":key,"fetched_utc":stamp,"response_sha256":sha,"replayed":False}
71
+ except HTTPError as exc:
72
+ if exc.code == 404 and "fastformula/" in path:
73
+ try:
74
+ fault = json.loads(exc.read())
75
+ except (ValueError,IncompleteRead):
76
+ raise RuntimeError("Unrecognized HTTP404; not a verified empty PubChem formula result") from exc
77
+ if fault.get("Fault",{}).get("Code") != "PUGREST.NotFound":
78
+ raise RuntimeError("HTTP404 is not PubChem's explicit NotFound result") from exc
79
+ body = b'{"IdentifierList":{"CID":[]}}'
80
+ stamp,sha = utc_now(),hashlib.sha256(body).hexdigest()
81
+ self.db.execute("INSERT INTO requests VALUES (?,?,?,?,?)",(key,url,stamp,sha,body.decode()))
82
+ self.db.commit()
83
+ return json.loads(body),{"url":url,"request_sha256":key,"fetched_utc":stamp,"response_sha256":sha,"http_status":404}
84
+ if exc.code not in {429,500,502,503,504}:
85
+ raise
86
+ error = exc
87
+ except (URLError,TimeoutError,ConnectionError,OSError,IncompleteRead,json.JSONDecodeError) as exc:
88
+ error = exc
89
+ self.sleep(min(2**attempt,16))
90
+ raise RuntimeError("PubChem temporary error retries exhausted") from error
91
+
92
+ def formula_candidates(self, formula):
93
+ response,first = self.request("compound/fastformula/"+quote(formula,safe="")+"/cids/JSON")
94
+ cids = response["IdentifierList"]["CID"]
95
+ records, requests = [],[first]
96
+ if len(cids) != len(set(cids)):
97
+ raise RuntimeError('Duplicate CID in formula response')
98
+ for start in range(0,len(cids),self.property_batch_size):
99
+ ids = cids[start:start+self.property_batch_size]
100
+ props,prov = self.request("compound/cid/property/MolecularFormula,IsomericSMILES,InChIKey,MonoisotopicMass,Charge/JSON",{"cid":",".join(map(str,ids))})
101
+ rows = props["PropertyTable"]["Properties"]
102
+ if len(rows) != len(ids) or {r["CID"] for r in rows} != set(ids):
103
+ raise RuntimeError("Incomplete PubChem property batch; refusing a silently truncated pool")
104
+ records.extend(rows); requests.append(prov)
105
+ return records,{"provider":"PubChem PUG REST FastFormula","database_version":"live service; no immutable release identifier supplied",
106
+ "formula":formula,"cid_count":len(cids),"requests":requests}
107
+
108
+
109
+ def filter_candidates(records, mz, adduct, formula, ppm=10.):
110
+ kept, rejected = [],[]
111
+ for r in records:
112
+ smiles = r.get("SMILES",r.get("IsomericSMILES",r.get("ConnectivitySMILES",r.get("CanonicalSMILES"))))
113
+ reason,m,err = None,None,None
114
+ if r.get("Charge",0) != 0:
115
+ reason = "nonzero_pubchem_charge"
116
+ elif not smiles:
117
+ reason = "missing_smiles"
118
+ else:
119
+ try:
120
+ m = molecule(smiles)
121
+ err = ppm_error(m.mass,mz,adduct)
122
+ if m.charge:
123
+ reason = "nonzero_rdkit_charge"
124
+ elif m.formula != formula:
125
+ reason = "formula_mismatch"
126
+ elif abs(err) > ppm:
127
+ reason = "precursor_ppm_exceeded"
128
+ except ValueError as exc:
129
+ reason = "invalid_or_unsupported_structure: "+str(exc)
130
+ record = {"cid":r.get("CID"),"smiles":smiles,"raw_pubchem":r,"ppm_error":err,
131
+ "identity":m.identity if m else None,"reason":reason}
132
+ (rejected if reason else kept).append(record)
133
+ return kept,rejected
134
+
135
+
136
+ @torch.no_grad()
137
+ def prepare_casmi_record(raw, model, cache, bounds, ppm=10., top_formulas=10):
138
+ if raw["features"]["dataset_mode"] != "casmi_autonomous":
139
+ raise ValueError("Only casmi_autonomous may enumerate/formula-filter through this adapter")
140
+ # Discard supplied pools/formula lists: autonomous preparation must derive its formula universe from MS physics.
141
+ clean = {**raw,"features":{**raw["features"],"candidates":[],"formula_candidates":[]}}
142
+ example = parse_record(clean)
143
+ q = example.query
144
+ formulas,enumeration = enumerate_formulas(q.precursor_mz,q.adduct,bounds,ppm)
145
+ q = replace(q,formula_candidates=tuple(formulas))
146
+ _,z,_ = model.spectrum(q)
147
+ fs = model.score_formulas(z,q).cpu().tolist()
148
+ ordered = sorted(range(len(formulas)),key=lambda i:(-fs[i],formulas[i]))
149
+ selected = [formulas[i] for i in ordered[:top_formulas]]
150
+ candidates, branches = [],[]
151
+ for f in selected:
152
+ records,provenance = cache.formula_candidates(f)
153
+ kept,rejected = filter_candidates(records,q.precursor_mz,q.adduct,f,ppm)
154
+ candidates.extend({"smiles":r["smiles"],"source_id":str(r["cid"])} for r in kept)
155
+ branches.append({"formula":f,"raw_count":len(records),"filtered_count":len(kept),
156
+ "unique_connectivity":len({r["identity"] for r in kept}),"kept":kept,"rejected":rejected,
157
+ "provenance":provenance})
158
+ final = {**raw,"features":{**raw["features"],"candidates":candidates,"formula_candidates":formulas,
159
+ "formula_universe_source":"bounded_enumeration","candidate_view":"casmi_predicted_top10"},
160
+ "provenance":{"enumeration":enumeration,"selected_top_formulas":selected,
161
+ "formula_scores":[{"formula":formulas[i],"score":fs[i],"rank":rank+1} for rank,i in enumerate(ordered)],
162
+ "branches":branches,"sirius_used":False,"ground_truth_used_for_generation":False}}
163
+ parse_record(final)
164
+ return final
code/snapshot/workspace/archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09/src/specpartition_ms/schema.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ import gzip
3
+ import json
4
+ import math
5
+ from pathlib import Path
6
+ from typing import Optional
7
+ from .chemistry import ADDUCTS, Molecule, canonical_formula, identity_hash, molecule
8
+
9
+ ALLOWED_FEATURES = {"peaks", "precursor_mz", "adduct", "collision_energy", "instrument",
10
+ "formula_candidates", "candidates", "dataset_mode", "candidate_view", "formula_universe_source"}
11
+ MODES = {"casmi_autonomous", "casmi_fixed_pool_control", "massspecgym_official", "synthetic", "odata_training"}
12
+ VIEWS = {"unspecified", "odata_oracle", "odata_predicted_top10", "msg_mass", "msg_formula",
13
+ "casmi_predicted_top10", "casmi_oracle", "warmup"}
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class Query:
18
+ peaks: tuple
19
+ precursor_mz: float
20
+ adduct: str
21
+ collision_energy: Optional[float]
22
+ instrument: Optional[str]
23
+ formula_candidates: tuple[str, ...]
24
+ candidates: tuple[Molecule, ...]
25
+ dataset_mode: str
26
+ candidate_view: str = "unspecified"
27
+ formula_universe_source: str = "candidate_pool"
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class Labels:
32
+ reference_smiles: str
33
+ identity: str
34
+ formula: str
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class Example:
39
+ sample_id: str
40
+ query: Query
41
+ labels: Optional[Labels]
42
+ aliases: dict
43
+ split: str
44
+
45
+
46
+ def parse_record(d):
47
+ if set(d) - {"sample_id", "features", "labels", "split", "provenance"}:
48
+ raise ValueError("Unknown record fields; annotations must be placed in provenance")
49
+ f = d["features"]
50
+ unknown = set(f) - ALLOWED_FEATURES
51
+ if unknown:
52
+ raise ValueError(f"Forbidden/unknown model feature fields: {sorted(unknown)}")
53
+ if f.get("dataset_mode") not in MODES:
54
+ raise ValueError("Explicit dataset_mode is required")
55
+ mz, adduct = float(f["precursor_mz"]), f["adduct"]
56
+ if not math.isfinite(mz) or mz <= 0 or adduct not in ADDUCTS:
57
+ raise ValueError("Invalid experimental precursor or unsupported adduct")
58
+ peaks = tuple((float(p[0]), float(p[1])) for p in f["peaks"])
59
+ 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:
60
+ raise ValueError("Spectrum must have finite positive m/z and at least one positive intensity")
61
+ candidates, aliases = {}, {}
62
+ for c in f["candidates"]:
63
+ if not isinstance(c, dict) or set(c) - {"smiles", "source_id"}:
64
+ raise ValueError("Candidates accept only smiles and opaque source_id, never score or rank")
65
+ m = molecule(c["smiles"])
66
+ if m.identity not in candidates or m.smiles < candidates[m.identity].smiles:
67
+ candidates[m.identity] = m
68
+ aliases.setdefault(m.identity, []).append({"smiles": c["smiles"], "source_id": c.get("source_id"),
69
+ "inchikey": m.inchikey})
70
+ # Tie-breaking and batching order depend only on identity, never CID or stored position.
71
+ candidates = tuple(candidates[k] for k in sorted(candidates))
72
+ formulas = tuple(sorted({canonical_formula(x) for x in f.get("formula_candidates", [])}))
73
+ if not formulas:
74
+ formulas = tuple(sorted({m.formula for m in candidates}))
75
+ missing = {m.formula for m in candidates} - set(formulas)
76
+ if missing:
77
+ raise ValueError(f"Candidate formulas absent from feature formula universe: {missing}")
78
+ ce = f.get("collision_energy")
79
+ ce = float(ce) if ce is not None else None
80
+ if ce is not None and (not math.isfinite(ce) or ce < 0):
81
+ raise ValueError("Invalid collision energy")
82
+ view = f.get("candidate_view", "unspecified")
83
+ if view not in VIEWS:
84
+ raise ValueError("Unknown candidate view")
85
+ labels = None
86
+ if d.get("labels"):
87
+ if set(d["labels"]) != {"reference_smiles"}:
88
+ raise ValueError("labels must contain only reference_smiles")
89
+ ref = molecule(d["labels"]["reference_smiles"])
90
+ labels = Labels(d["labels"]["reference_smiles"], ref.identity, ref.formula)
91
+ for records in aliases.values():
92
+ records.sort(key=lambda r:(r["smiles"],str(r["source_id"]),r["inchikey"]))
93
+ return Example(str(d["sample_id"]), Query(peaks, mz, adduct, ce, f.get("instrument"), formulas,
94
+ candidates, f["dataset_mode"], view, f.get("formula_universe_source", "candidate_pool")),
95
+ labels, aliases, d.get("split", "inference"))
96
+
97
+
98
+ def iter_records(path):
99
+ """Stream one complete JSON object per line; rejects array exports instead of guessing schemas."""
100
+ opener = gzip.open if str(path).endswith(".gz") else open
101
+ with opener(path, "rt", encoding="utf-8") as fh:
102
+ for line_number, line in enumerate(fh, 1):
103
+ if not line.strip():
104
+ continue
105
+ try:
106
+ yield parse_record(json.loads(line))
107
+ except Exception as exc:
108
+ raise ValueError(f"{path}:{line_number}: {exc}") from exc
109
+
110
+
111
+ def input_manifest(examples):
112
+ return {e.sample_id: {"candidate_count": len(e.query.candidates),
113
+ "candidate_identity_sha256": identity_hash(e.query.candidates),
114
+ "dataset_mode": e.query.dataset_mode} for e in examples}
115
+
116
+
117
+ def assert_train_isolation(train, heldout):
118
+ if any(e.split != "train" or e.labels is None for e in train):
119
+ raise ValueError("Training requires explicit split=train and labels")
120
+ train_keys = {e.labels.identity for e in train}
121
+ heldout_keys = {e.labels.identity for e in heldout if e.labels}
122
+ if train_keys & heldout_keys:
123
+ raise ValueError("Train/heldout connectivity overlap")
124
+ training_pool_keys = {m.identity for e in train for m in e.query.candidates}
125
+ if training_pool_keys & heldout_keys:
126
+ raise ValueError("Training ranking pools contain heldout connectivity; construct training-only pools before training")
127
+ return heldout_keys