xiaojie06 commited on
Commit
5e336ae
·
verified ·
1 Parent(s): dbc2c2a

Add exact model code and documentation (5/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/workspace/rebuild/hierarchical_ablation_20261103/coarse_losses.py +110 -0
  2. code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs.py +161 -0
  3. code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C00_sampler_control.json +266 -0
  4. code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C01_ms_fine.json +268 -0
  5. code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C02_mol_fine.json +268 -0
  6. code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C03_both_fine.json +269 -0
  7. code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C04_formula_coarse.json +269 -0
  8. code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C05_mass_coarse.json +269 -0
  9. code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C06_fine_formula.json +271 -0
  10. code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C07_fine_mass.json +271 -0
  11. code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C08_full_separate.json +273 -0
  12. code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C09_shared_head_control.json +273 -0
  13. code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C10_random_sampler_control.json +273 -0
  14. code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C11_hard_mass_bins.json +273 -0
  15. code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C12_no_reverse_crossmodal.json +273 -0
  16. code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C13_fine_budget_matched.json +269 -0
  17. code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C14_fine_formula_budget_matched.json +271 -0
  18. code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C15_fine_mass_budget_matched.json +271 -0
  19. code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C16_include_identity_coarse.json +273 -0
  20. code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C17_mass_metadata_shortcut.json +273 -0
  21. code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/suite_manifest.json +36 -0
  22. code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/test_coarse.py +118 -0
  23. code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/test_configs.py +68 -0
  24. code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/validation_record.json +61 -0
  25. code/snapshot/workspace/rebuild/hierarchical_training_20261103/README.md +60 -0
  26. code/snapshot/workspace/rebuild/hierarchical_training_20261103/acceptance.py +67 -0
  27. code/snapshot/workspace/rebuild/hierarchical_training_20261103/check_all.py +25 -0
  28. code/snapshot/workspace/rebuild/hierarchical_training_20261103/hierarchy.supervisor.conf +68 -0
  29. code/snapshot/workspace/rebuild/hierarchical_training_20261103/kernels.py +61 -0
  30. code/snapshot/workspace/rebuild/hierarchical_training_20261103/launch_record.json +104 -0
  31. code/snapshot/workspace/rebuild/hierarchical_training_20261103/managed.py +31 -0
  32. code/snapshot/workspace/rebuild/hierarchical_training_20261103/objectives.py +140 -0
  33. code/snapshot/workspace/rebuild/hierarchical_training_20261103/runtime_hier.py +85 -0
  34. code/snapshot/workspace/rebuild/hierarchical_training_20261103/sampling.py +84 -0
  35. code/snapshot/workspace/rebuild/hierarchical_training_20261103/test_runtime.py +49 -0
  36. code/snapshot/workspace/rebuild/hierarchical_training_20261103/train.py +123 -0
  37. code/snapshot/workspace/rebuild/hierarchical_training_20261103/validation.py +181 -0
  38. code/snapshot/workspace/rebuild/intra_modal_extension/losses.py +132 -0
  39. code/snapshot/workspace/rebuild/intra_modal_extension/test_losses.py +96 -0
  40. code/snapshot/workspace/rebuild/post_training_evaluation_20261103/acceptance.py +60 -0
  41. code/snapshot/workspace/rebuild/post_training_evaluation_20261103/eval_runtime.py +102 -0
  42. code/snapshot/workspace/rebuild/post_training_evaluation_20261103/evaluate.py +236 -0
  43. code/snapshot/workspace/rebuild/post_training_evaluation_20261103/evaluation.supervisor.conf +15 -0
  44. code/snapshot/workspace/rebuild/post_training_evaluation_20261103/launch_record.json +29 -0
  45. code/snapshot/workspace/rebuild/post_training_evaluation_20261103/managed.py +90 -0
  46. code/snapshot/workspace/rebuild/post_training_evaluation_20261103/prepare.py +172 -0
  47. code/snapshot/workspace/rebuild/training_r04/assets.supervisor.conf +13 -0
  48. code/snapshot/workspace/rebuild/training_r04/batch_pilot.supervisor.conf +13 -0
  49. code/snapshot/workspace/rebuild/training_r04/candidate_pilot.py +32 -0
  50. code/snapshot/workspace/rebuild/training_r04/common.py +146 -0
code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/coarse_losses.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Coarse relation kernels; auxiliary supervision, never ranking filters."""
2
+ import math
3
+ import re
4
+ import torch
5
+ from torch import nn
6
+ from torch.nn import functional as F
7
+
8
+
9
+ def formula_key(formula):
10
+ tokens=re.findall(r'([A-Z][a-z]?)(\d*)',formula)
11
+ if not tokens or ''.join(a+b for a,b in tokens)!=formula:raise ValueError('Neutral elemental formula required')
12
+ counts={}
13
+ for element,n in tokens:
14
+ if element in counts or int(n or 1)<1:raise ValueError('Repeated element or invalid count')
15
+ counts[element]=int(n or 1)
16
+ return tuple(sorted(counts.items()))
17
+
18
+
19
+ def neutral_mass_from_precursor(precursor,absolute_charge,adduct_delta):
20
+ """Caller supplies the verified adduct adapter's delta, not an inferred label.
21
+
22
+ Formula: M_neutral = |z| * measured precursor_mz - Delta_adduct.
23
+ This helper never substitutes a SMILES-derived mass for measured precursor.
24
+ """
25
+ if not math.isfinite(precursor) or precursor<=0 or absolute_charge not in (1,2):raise ValueError('Unsupported precursor or charge')
26
+ if not math.isfinite(adduct_delta):raise ValueError('Finite verified adduct delta required')
27
+ mass=absolute_charge*precursor-adduct_delta
28
+ if mass<=0:raise ValueError('Nonpositive inferred neutral mass')
29
+ return mass
30
+
31
+
32
+ def formula_pairs(formulas,identities,include_same_identity=False):
33
+ if len(formulas)!=len(identities):raise ValueError('Formula/identity dimensions differ')
34
+ keys=[formula_key(f) for f in formulas];n=len(keys)
35
+ mapping={}
36
+ for k,f in zip(identities,keys):
37
+ if k in mapping and mapping[k]!=f:raise ValueError('Conflicting formula labels for same key14')
38
+ mapping[k]=f
39
+ same_formula=torch.tensor([[a==b for b in keys] for a in keys],dtype=torch.bool).reshape(n,n)
40
+ same_identity=torch.tensor([[a==b for b in identities] for a in identities],dtype=torch.bool).reshape(n,n)
41
+ allowed=~torch.eye(n,dtype=torch.bool)
42
+ if not include_same_identity:allowed &= ~same_identity
43
+ return (same_formula & allowed).float(),(~same_formula & allowed),[str(k) for k in keys]
44
+
45
+
46
+ def mass_pairs(masses,identities,positive_radius_da=.5,negative_start_da=2.,sigma_da=.25,
47
+ mode='soft_neighborhood',bin_width_da=1.,bin_offset_da=0.,include_same_identity=False):
48
+ if len(masses)!=len(identities):raise ValueError('Mass/identity dimensions differ')
49
+ if not all(math.isfinite(v) for v in (positive_radius_da,negative_start_da,sigma_da)):raise ValueError('Nonfinite mass configuration')
50
+ if not 0<positive_radius_da<negative_start_da or sigma_da<=0:raise ValueError('Invalid mass neighborhoods')
51
+ if any(not math.isfinite(float(x)) or float(x)<=0 for x in masses):raise ValueError('Finite positive neutral masses required')
52
+ mass=torch.tensor(masses,dtype=torch.float64);n=len(masses);delta=(mass[:,None]-mass[None,:]).abs()
53
+ same=torch.tensor([[a==b for b in identities] for a in identities],dtype=torch.bool).reshape(n,n)
54
+ allowed=~torch.eye(n,dtype=torch.bool)
55
+ if not include_same_identity:allowed &= ~same
56
+ if mode=='soft_neighborhood':
57
+ positive=allowed & (delta<=positive_radius_da)
58
+ weights=torch.exp(-.5*(delta/sigma_da).square())*positive
59
+ elif mode=='hard_bins':
60
+ if not math.isfinite(bin_width_da) or bin_width_da<=0 or not math.isfinite(bin_offset_da):raise ValueError('Invalid mass bins')
61
+ if negative_start_da<bin_width_da:raise ValueError('Bins and far-negative rule could overlap')
62
+ bins=torch.floor((mass-bin_offset_da)/bin_width_da)
63
+ positive=allowed & (bins[:,None]==bins[None,:]);weights=positive.float()
64
+ else:raise ValueError('Unknown mass relation')
65
+ negative=allowed & (delta>=negative_start_da)
66
+ if bool((positive & negative).any()):raise ValueError('Positive/negative overlap')
67
+ # Everything between the positive relation and the far-negative radius is ignored.
68
+ return weights.float(),negative
69
+
70
+
71
+ def weighted_supcon(embeddings,positive_weights,negative_mask,reduction_groups,temperature=.15):
72
+ n=len(embeddings)
73
+ if embeddings.ndim!=2 or len(reduction_groups)!=n:raise ValueError('One reduction label per embedding')
74
+ if positive_weights.shape!=(n,n) or negative_mask.shape!=(n,n):raise ValueError('Relation matrix dimensions')
75
+ if temperature<=0 or not math.isfinite(temperature):raise ValueError('Invalid temperature')
76
+ if negative_mask.dtype!=torch.bool:raise ValueError('Negative mask must be boolean')
77
+ if not bool(torch.isfinite(positive_weights).all()):raise ValueError('Nonfinite positive-pair weight')
78
+ if bool((positive_weights<0).any()):raise ValueError('Negative positive-pair weight')
79
+ if bool(((positive_weights>0)&negative_mask).any()):raise ValueError('Conflicting pair labels')
80
+ dev=embeddings.device;z=F.normalize(embeddings.float(),dim=-1);logits=z@z.T/temperature
81
+ pw=positive_weights.to(dev).float();neg=negative_mask.to(dev).bool()
82
+ diag=torch.eye(n,device=dev,dtype=torch.bool);pw=pw.masked_fill(diag,0);neg=neg & ~diag
83
+ positive=pw>0;allowed=positive|neg;valid=(pw.sum(1)>0)&neg.any(1)
84
+ raw=logits.masked_fill(~allowed,-torch.inf)
85
+ raw=torch.where((~allowed.any(1))[:,None],torch.zeros_like(raw),raw)
86
+ den=torch.logsumexp(raw,dim=1)
87
+ per=-(torch.where(positive,logits-den[:,None],torch.zeros_like(logits))*pw).sum(1)/pw.sum(1).clamp_min(1e-12)
88
+ per=torch.where(valid,per,torch.zeros_like(per))
89
+ keys=sorted(set(reduction_groups));lookup={k:i for i,k in enumerate(keys)}
90
+ idx=torch.tensor([lookup[k] for k in reduction_groups],device=dev,dtype=torch.long)
91
+ sums=z.new_zeros(len(keys)).index_add(0,idx,per)
92
+ counts=z.new_zeros(len(keys)).index_add(0,idx,valid.float())
93
+ loss=(sums/counts.clamp_min(1)).sum()/(counts>0).sum().clamp_min(1)+embeddings.sum()*0.
94
+ stats=dict(valid_anchors=valid.sum().detach(),valid_groups=(counts>0).sum().detach(),
95
+ positive_pairs=positive.sum().detach(),negative_pairs=neg.sum().detach(),
96
+ ignored_pairs=(~allowed & ~diag).sum().detach())
97
+ return loss,stats
98
+
99
+
100
+ class ProjectionBank(nn.Module):
101
+ """All arms register all six heads; sharing is an explicit conflict control."""
102
+ names=('ms_identity','mol_identity','ms_formula','mol_formula','ms_mass','mol_mass')
103
+ def __init__(self,input_dim=256,hidden_dim=256,output_dim=128):
104
+ super().__init__()
105
+ self.heads=nn.ModuleDict({name:nn.Sequential(nn.Linear(input_dim,hidden_dim),nn.GELU(),nn.Linear(hidden_dim,output_dim)) for name in self.names})
106
+
107
+ def forward(self,name,x,share_granularities=False):
108
+ if name not in self.heads:raise ValueError('Unknown projection head')
109
+ actual=name.split('_')[0]+'_identity' if share_granularities else name
110
+ return F.normalize(self.heads[actual](x).float(),dim=-1)
code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Compile standalone ablation configurations, never launch an experiment."""
2
+ import argparse
3
+ from copy import deepcopy
4
+ import hashlib
5
+ import json
6
+ import math
7
+ from pathlib import Path
8
+
9
+ HERE=Path(__file__).resolve().parent
10
+ AUX=('ms_fine','mol_fine','ms_formula','mol_formula','ms_mass','mol_mass')
11
+ DEFAULT=dict(zip(AUX,(.10,.05,.05,.05,.025,.025)))
12
+
13
+
14
+ def check_shape(value,template,path='config'):
15
+ if isinstance(template,dict):
16
+ if not isinstance(value,dict) or set(value)!=set(template):raise ValueError('Unknown or missing keys: '+path)
17
+ for k,t in template.items():check_shape(value[k],t,path+'.'+k)
18
+ elif isinstance(template,list):
19
+ if not isinstance(value,list):raise ValueError('Expected list: '+path)
20
+ if template:
21
+ for v in value:check_shape(v,template[0],path+'[]')
22
+ elif isinstance(template,bool):
23
+ if not isinstance(value,bool):raise ValueError('Expected bool: '+path)
24
+ elif isinstance(template,(int,float)):
25
+ if isinstance(value,bool) or not isinstance(value,(int,float)):raise ValueError('Expected number: '+path)
26
+ if not math.isfinite(value):raise ValueError('Nonfinite number: '+path)
27
+ elif template is None:
28
+ if value is not None:raise ValueError('Expected null: '+path)
29
+ elif not isinstance(value,type(template)):raise ValueError('Wrong type: '+path)
30
+
31
+
32
+ def arms():
33
+ fine=['ms_fine','mol_fine'];formula=['ms_formula','mol_formula'];mass=['ms_mass','mol_mass']
34
+ all_tasks=fine+formula+mass
35
+ return [
36
+ ('C00_sampler_control',[],{},'Matched grouped-sampler control, no auxiliary losses'),
37
+ ('C01_ms_fine',['ms_fine'],{},'MS-to-MS identity SupCon only'),
38
+ ('C02_mol_fine',['mol_fine'],{},'Molecule-to-molecule two-view identity loss only'),
39
+ ('C03_both_fine',fine,{},'Both fine identity losses'),
40
+ ('C04_formula_coarse',formula,{},'Formula coarse losses without new fine losses'),
41
+ ('C05_mass_coarse',mass,{},'Neutral-mass neighborhood losses without new fine losses'),
42
+ ('C06_fine_formula',fine+formula,{},'Fine identity plus exact-formula coarse heads'),
43
+ ('C07_fine_mass',fine+mass,{},'Fine identity plus neutral-mass neighborhood heads'),
44
+ ('C08_full_separate',all_tasks,{},'Full separate-head starting proposal, not proven optimal'),
45
+ ('C09_shared_head_control',all_tasks,{'head_routing':'share_granularities_within_modality'},'Conflict control: coarse and fine share each modality head'),
46
+ ('C10_random_sampler_control',all_tasks,{'sampler':'random_source_shuffle'},'Same losses without hierarchical positive-enriching sampler'),
47
+ ('C11_hard_mass_bins',all_tasks,{'mass_mode':'hard_bins'},'Replace continuous mass neighborhoods with fixed 1 Da bins'),
48
+ ('C12_no_reverse_crossmodal',all_tasks,{'no_reverse':True},'Forward-only cross-modal control, total cross-modal coefficient remains one'),
49
+ ('C13_fine_budget_matched',fine,{'aux_budget':.30},'Fine-only control with total auxiliary coefficient 0.30'),
50
+ ('C14_fine_formula_budget_matched',fine+formula,{'aux_budget':.30},'Fine-plus-formula control with auxiliary coefficient 0.30'),
51
+ ('C15_fine_mass_budget_matched',fine+mass,{'aux_budget':.30},'Fine-plus-mass control with auxiliary coefficient 0.30'),
52
+ ('C16_include_identity_coarse',all_tasks,{'coarse_identity':'include_as_positive'},'Check whether coarse gain merely repeats same-identity alignment'),
53
+ ('C17_mass_metadata_shortcut',all_tasks,{'mass_head_input':'neutral_mass_metadata_only_fixed_256d_features'},'Diagnose trivial mass-metadata shortcut rather than fragment evidence')
54
+ ]
55
+
56
+
57
+ def validate(c):
58
+ template=json.loads((HERE/'base.json').read_text())
59
+ actual={k:v for k,v in c.items() if k!='experiment'};check_shape(actual,template)
60
+ if set(c['experiment'])!={'id','description','active_auxiliary_tasks','auxiliary_coefficient_sum','output_template','priority'}:raise ValueError('Unknown experiment fields')
61
+ if c['schema_version']!=1:raise ValueError('Unsupported configuration version')
62
+ if c['execution']['allow_training'] or c['execution']['runtime_entrypoint'] is not None:
63
+ raise ValueError('This configuration-only package cannot authorize training')
64
+ if not c['execution']['missing_integration']:raise ValueError('Do not claim trainer integration is complete')
65
+ h=c['initialization']['sha256']
66
+ if len(h)!=64 or any(x not in '0123456789abcdef' for x in h):raise ValueError('Fixed parent checksum required')
67
+ if c['initialization']['optimizer_policy']!='new_AdamW_for_every_arm_not_live_run_resume':raise ValueError('Optimizer fairness drift')
68
+ if c['data']['records']!=sum(c['data']['source_counts'].values()):raise ValueError('Source counts mismatch')
69
+ if c['data']['test_or_casmi_labels_in_training'] or c['data']['online_queries_during_training']:raise ValueError('Data leakage or online training queries')
70
+ if c['model']['relation_or_cut_enabled'] or not c['model']['projection_heads']['register_all_heads_in_all_arms']:raise ValueError('Uncontrolled architecture change')
71
+ if c['sampling']['msg_views']!=['mass','formula']:raise ValueError('Both official training views required')
72
+ if c['sampling']['candidate_pool_deduplicate_key14'] or not c['sampling']['same_truth_key14_is_never_negative']:raise ValueError('Candidate policy changed')
73
+ if c['sampling']['force_duplicate_spectra_to_fill_group']:raise ValueError('Duplicating one MS cannot create real positives')
74
+ if c['sampling']['mode'] not in ('hierarchical_formula_identity_spectra','random_source_shuffle'):raise ValueError('Unknown sampler')
75
+ for key,size in [('desired_odata_shape','odata_batch_size'),('desired_msg_shape','msg_batch_size')]:
76
+ dims=c['sampling'][key]
77
+ if dims['formulas']*dims['identities_per_formula']*dims['spectra_per_identity']!=c['sampling'][size]:raise ValueError('Desired batch factorization mismatch')
78
+ if set(c['loss']['auxiliary'])!=set(AUX):raise ValueError('Unknown or missing auxiliary task')
79
+ if any(not isinstance(v,(float,int)) or v<0 or v>1 for v in c['loss']['auxiliary'].values()):raise ValueError('Invalid auxiliary coefficient')
80
+ actual_active=[k for k in AUX if c['loss']['auxiliary'][k]>0]
81
+ if set(actual_active)!=set(c['experiment']['active_auxiliary_tasks']):raise ValueError('Loss switches disagree with declared experiment')
82
+ if abs(sum(c['loss']['auxiliary'].values())-c['experiment']['auxiliary_coefficient_sum'])>1e-8:raise ValueError('Auxiliary budget mismatch')
83
+ if any(v<=0 for v in c['loss']['temperature'].values()):raise ValueError('Temperature must be positive')
84
+ if c['loss']['self_pairs']!='exclude':raise ValueError('Self-positive shortcut')
85
+ m=c['loss']['mass_coarse']
86
+ if m['mode'] not in ('soft_neighborhood','hard_bins'):raise ValueError('Unknown mass relation')
87
+ if not 0<m['positive_radius_da']<m['negative_start_da'] or m['gaussian_sigma_da']<=0:raise ValueError('Mass positive/gray/negative ranges overlap')
88
+ if m['gray_zone']!='exclude' or m['distance_unit']!='Da':raise ValueError('Mass relation units/gray zone drift')
89
+ if m['hard_bin_width_da']<=0 or m['hard_bin_width_da']>m['negative_start_da']:raise ValueError('Mass bins overlap far-negative rule')
90
+ if m['MS_mass']!='abs_charge_times_experimental_precursor_minus_adduct_delta':raise ValueError('Raw m/z and neutral mass cannot be mixed')
91
+ if not m['candidate_10ppm_filter_is_not_mass_bucket_width']:raise ValueError('10ppm is not a coarse mass class')
92
+ if c['model']['head_routing']!='separate_by_modality_and_granularity' and c['experiment']['id']!='C09_shared_head_control':raise ValueError('Coarse/fine shared-space conflict must be explicit control')
93
+ if c['model']['head_routing'] not in ('separate_by_modality_and_granularity','share_granularities_within_modality'):raise ValueError('Unknown head routing')
94
+ if c['model']['mass_head_input'] not in ('shared_encoder_representation','neutral_mass_metadata_only_fixed_256d_features'):raise ValueError('Unknown mass head input')
95
+ if c['evaluation']['casmi_candidate_cap'] is not None or c['evaluation']['casmi_denominator']!=500:raise ValueError('Frozen CASMI evaluation changed')
96
+ if not c['evaluation']['never_filter_official_pools_or_inject_truth']:raise ValueError('Official evaluation changed')
97
+ if c['evaluation']['selection_split']!='MSG_Validation':raise ValueError('Test cannot select hyperparameters')
98
+ if c['budget']['optimizer_updates_per_seed']<=0 or len(set(c['budget']['seeds']))!=3:raise ValueError('Invalid controlled training budget')
99
+ return True
100
+
101
+
102
+ def compile_configs():
103
+ base=json.loads((HERE/'base.json').read_text());result={}
104
+ for name,active,options,description in arms():
105
+ c=deepcopy(base);c['experiment']=dict(id=name,description=description)
106
+ c['loss']['auxiliary']={k:DEFAULT[k] if k in active else 0. for k in AUX}
107
+ if options.get('aux_budget'):
108
+ scale=options['aux_budget']/sum(c['loss']['auxiliary'].values())
109
+ c['loss']['auxiliary']={k:round(v*scale,10) for k,v in c['loss']['auxiliary'].items()}
110
+ if 'head_routing' in options:c['model']['head_routing']=options['head_routing']
111
+ if 'mass_head_input' in options:c['model']['mass_head_input']=options['mass_head_input']
112
+ if 'sampler' in options:c['sampling']['mode']=options['sampler']
113
+ if 'mass_mode' in options:c['loss']['mass_coarse']['mode']=options['mass_mode']
114
+ if options.get('no_reverse'):c['loss']['base'].update(ms_to_mol=1.0,mol_to_ms=0.)
115
+ if options.get('coarse_identity'):
116
+ c['loss']['formula_coarse']['same_key14_pair_policy']='include_as_positive'
117
+ c['loss']['mass_coarse']['same_key14_pair_policy']='include_as_positive'
118
+ c['experiment']['active_auxiliary_tasks']=active
119
+ c['experiment']['auxiliary_coefficient_sum']=round(sum(c['loss']['auxiliary'].values()),10)
120
+ c['experiment']['output_template']=str(Path(c['data']['root'])/'runs'/c['suite_id']/name/'seed_{seed}')
121
+ c['experiment']['priority']='first_pass' if name in ['C00_sampler_control','C03_both_fine','C06_fine_formula','C07_fine_mass','C08_full_separate'] else 'secondary_ablation'
122
+ validate(c);result[name]=c
123
+ return result
124
+
125
+
126
+ def assert_fairness(configs):
127
+ values=list(configs.values());base=values[0]
128
+ for c in values:
129
+ for key in ('initialization','data','budget','views','evaluation'):
130
+ if c[key]!=base[key]:raise ValueError('Uncontrolled common protocol drift: '+key)
131
+ if len({c['experiment']['output_template'] for c in values})!=len(values):raise ValueError('Output collision')
132
+ return True
133
+
134
+
135
+ def main():
136
+ parser=argparse.ArgumentParser();parser.add_argument('--validate-only',action='store_true');a=parser.parse_args()
137
+ configs=compile_configs();assert_fairness(configs);target=HERE/'configs'
138
+ hashes={}
139
+ for name,c in configs.items():
140
+ content=json.dumps(c,ensure_ascii=False,indent=2,allow_nan=False)+'\n'
141
+ path=target/(name+'.json')
142
+ if a.validate_only:
143
+ if not path.exists() or path.read_text()!=content:raise ValueError('Generated configuration missing/drift: '+name)
144
+ else:
145
+ target.mkdir(exist_ok=True)
146
+ if path.exists() and path.read_text()!=content:raise ValueError('Refusing to overwrite a different experiment configuration: '+name)
147
+ path.write_text(content)
148
+ hashes[str(path.relative_to(HERE))]=hashlib.sha256(content.encode()).hexdigest()
149
+ index=dict(configuration_validation_passed=True,training_ready=False,experiments=len(configs),
150
+ seeds_per_experiment=3,planned_replica_jobs=len(configs)*3,automatic_launch=False,
151
+ first_pass=[k for k,c in configs.items() if c['experiment']['priority']=='first_pass'],
152
+ files=hashes,reference_current_run_not_matched_ablation='rebuild_joint_r08data_20261102')
153
+ manifest=HERE/'suite_manifest.json'
154
+ if a.validate_only:
155
+ if not manifest.exists() or json.loads(manifest.read_text())!=index:raise ValueError('Suite manifest missing or stale')
156
+ else:
157
+ manifest.write_text(json.dumps(index,indent=2)+'\n')
158
+ print(json.dumps(index,indent=2))
159
+
160
+
161
+ if __name__=='__main__':main()
code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C00_sampler_control.json ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": 1,
3
+ "suite_id": "hierarchical_intra_modal_20261103",
4
+ "execution": {
5
+ "status": "configuration_and_loss_components_only",
6
+ "allow_training": false,
7
+ "runtime_entrypoint": null,
8
+ "missing_integration": [
9
+ "hierarchical_no_repeat_sampler",
10
+ "independent_stochastic_gnn_views",
11
+ "rng_safe_view_recomputation",
12
+ "joint_loss_router_and_gpu_acceptance"
13
+ ]
14
+ },
15
+ "initialization": {
16
+ "checkpoint": "/workspace/xj/SpecPartition-MS/runs/rebuild_joint_r08data_20261102/epoch_04.pt",
17
+ "sha256": "618aaf195cfdc3a4107e71cf2b3a56d5853b407564acf01de11c67e6af40f3d7",
18
+ "policy": "same_fixed_parent_weights_all_arms",
19
+ "optimizer_policy": "new_AdamW_for_every_arm_not_live_run_resume",
20
+ "selection_source": "Validation_only_fixed_before_ablation",
21
+ "new_heads": "same_initialization_per_seed_for_all_arms"
22
+ },
23
+ "data": {
24
+ "root": "/workspace/xj/SpecPartition-MS",
25
+ "labels": "data/derived/data_release_r07_key14_20261101/train.json",
26
+ "prepared": "data/derived/joint_r09_inputs_20261102/train.sqlite",
27
+ "candidates": "data/derived/training_r08_true_formula_records_20261101/preparation.sqlite",
28
+ "heldout_registry": "data/derived/data_release_r07_key14_20261101/heldout_registry.json",
29
+ "label_policy_sha256": "91971b3f6979586b32c90350330cb6712e60c3c6f4b872de4113311f8a95adf7",
30
+ "candidate_config_sha256": "53a365647ed8c54e216ff2cd25c011ed7f7d47a920f54c0136eea0c8dabade65",
31
+ "parent_training_config_sha256": "5f8f8635c60e37a194660b73f0fae69571a3f97a045f1d5c2f0e5fbf76e450d0",
32
+ "records": 643587,
33
+ "source_counts": {
34
+ "MSG_Train": 162974,
35
+ "MSP_libraries": 261644,
36
+ "MS2_SAN_JSONL": 218969
37
+ },
38
+ "exclude_heldout_labels_and_negatives_by": "key14",
39
+ "test_or_casmi_labels_in_training": false,
40
+ "preserve_same_structure_multiple_spectra": true,
41
+ "online_queries_during_training": false,
42
+ "coarse_labels_are_training_supervision_not_inference_inputs": true
43
+ },
44
+ "budget": {
45
+ "seeds": [
46
+ 20261103,
47
+ 20261104,
48
+ 20261105
49
+ ],
50
+ "optimizer_updates_per_seed": 6000,
51
+ "learning_rate": 3e-05,
52
+ "minimum_learning_rate": 3e-06,
53
+ "warmup_steps": 300,
54
+ "weight_decay": 0.0001,
55
+ "gradient_clip": 5.0,
56
+ "schedule": "cosine",
57
+ "bf16": true,
58
+ "graph_chunk": 128,
59
+ "spectrum_chunk": 64,
60
+ "pool_micro_views": 4,
61
+ "checkpoint_every": 100,
62
+ "validation_every_updates": 2000,
63
+ "source_presence_schedule": "same_R09_5093_step_epoch_plan",
64
+ "same_MS_exposure_and_candidate_draw_budget_across_arms": true,
65
+ "equal_wall_clock_or_FLOPs_claimed": false
66
+ },
67
+ "model": {
68
+ "backbone": "archived_R2_direct_ranker_256d_6Transformer_6MPNN",
69
+ "backbone_registered_parameters": 16409742,
70
+ "relation_or_cut_enabled": false,
71
+ "projection_heads": {
72
+ "input_dim": 256,
73
+ "hidden_dim": 256,
74
+ "output_dim": 128,
75
+ "activation": "GELU",
76
+ "normalize": "L2",
77
+ "names": [
78
+ "ms_identity",
79
+ "mol_identity",
80
+ "ms_formula",
81
+ "mol_formula",
82
+ "ms_mass",
83
+ "mol_mass"
84
+ ],
85
+ "register_all_heads_in_all_arms": true,
86
+ "shared_backbone_receives_auxiliary_gradients": true
87
+ },
88
+ "head_routing": "separate_by_modality_and_granularity",
89
+ "mass_head_input": "shared_encoder_representation",
90
+ "auxiliary_heads_used_at_inference": false,
91
+ "original_final_ranking_score_unchanged": true
92
+ },
93
+ "sampling": {
94
+ "mode": "hierarchical_formula_identity_spectra",
95
+ "odata_batch_size": 256,
96
+ "msg_batch_size": 32,
97
+ "desired_odata_shape": {
98
+ "formulas": 8,
99
+ "identities_per_formula": 8,
100
+ "spectra_per_identity": 4
101
+ },
102
+ "desired_msg_shape": {
103
+ "formulas": 4,
104
+ "identities_per_formula": 4,
105
+ "spectra_per_identity": 2
106
+ },
107
+ "rare_group_fallback": "pack_remaining_real_records_without_replacement",
108
+ "mass_positive_coverage": "measure_same_formula_and_cross_formula_pairs_separately_do_not_assume_formula_sampler_covers_mass_neighbors",
109
+ "force_duplicate_spectra_to_fill_group": false,
110
+ "each_source_record_once_before_next_source_epoch": true,
111
+ "singleton_policy": "retain_existing_objectives_mask_missing_auxiliary_positives",
112
+ "explicit_odata_queries": 16,
113
+ "odata_negative_draws": 128,
114
+ "msg_views": [
115
+ "mass",
116
+ "formula"
117
+ ],
118
+ "msg_negative_draws_per_view": 63,
119
+ "candidate_draws_with_replacement": true,
120
+ "candidate_pool_deduplicate_key14": false,
121
+ "same_truth_key14_is_never_negative": true
122
+ },
123
+ "views": {
124
+ "MS": {
125
+ "positive_source": "distinct_real_spectra_of_same_key14",
126
+ "spectrum_augmentation": "none",
127
+ "repeat_physical_record_is_not_positive": true
128
+ },
129
+ "molecule": {
130
+ "count": 2,
131
+ "strategy": "independent_hidden_feature_dropout",
132
+ "dropout": 0.1,
133
+ "delete_atoms_or_bonds": false,
134
+ "random_SMILES_alone_is_not_new_view": true
135
+ },
136
+ "primary_encoder_path_dropout": 0.0,
137
+ "compute_two_molecule_views_for_all_arms": true,
138
+ "stochastic_view_gradient_cache": "disabled_keep_view_graph_or_verified_RNG_replay"
139
+ },
140
+ "loss": {
141
+ "base": {
142
+ "formula": 1.0,
143
+ "ms_to_mol": 0.5,
144
+ "mol_to_ms": 0.5,
145
+ "odata_pool": 0.5,
146
+ "msg_mass_pool": 0.25,
147
+ "msg_formula_pool": 0.25
148
+ },
149
+ "formula_task": {
150
+ "ce": 1.0,
151
+ "gap": 0.1,
152
+ "hard_wrong_topk": 3,
153
+ "margin": 0.2,
154
+ "element_count": 0.2
155
+ },
156
+ "auxiliary": {
157
+ "ms_fine": 0.0,
158
+ "mol_fine": 0.0,
159
+ "ms_formula": 0.0,
160
+ "mol_formula": 0.0,
161
+ "ms_mass": 0.0,
162
+ "mol_mass": 0.0
163
+ },
164
+ "auxiliary_ramp_steps": 500,
165
+ "temperature": {
166
+ "identity": 0.1,
167
+ "formula": 0.15,
168
+ "mass": 0.2
169
+ },
170
+ "fine_identity": "key14",
171
+ "self_pairs": "exclude",
172
+ "missing_positive_or_negative": "differentiable_zero_and_log_effective_count",
173
+ "anchor_reduction": {
174
+ "fine": "key14_macro",
175
+ "formula": "formula_macro",
176
+ "mass": "key14_macro"
177
+ },
178
+ "formula_coarse": {
179
+ "label": "exact_element_count_canonical_formula",
180
+ "positive": "same_formula_different_key14",
181
+ "negative": "different_formula",
182
+ "same_key14_pair_policy": "exclude_from_coarse",
183
+ "same_scaffold_is_not_identity_positive": true
184
+ },
185
+ "mass_coarse": {
186
+ "mode": "soft_neighborhood",
187
+ "MS_mass": "abs_charge_times_experimental_precursor_minus_adduct_delta",
188
+ "molecule_mass": "cached_candidate_neutral_monoisotopic_mass",
189
+ "distance_unit": "Da",
190
+ "positive_radius_da": 0.5,
191
+ "negative_start_da": 2.0,
192
+ "gaussian_sigma_da": 0.25,
193
+ "gray_zone": "exclude",
194
+ "same_key14_pair_policy": "exclude_from_coarse",
195
+ "hard_bin_width_da": 1.0,
196
+ "hard_bin_offset_da": 0.0,
197
+ "MS_quality_mask": "reference_precursor_consistency_within_10ppm",
198
+ "candidate_10ppm_filter_is_not_mass_bucket_width": true,
199
+ "mass_neighborhood_is_not_chemical_similarity_or_equivalence_class": true
200
+ }
201
+ },
202
+ "evaluation": {
203
+ "selection_split": "MSG_Validation",
204
+ "spectra": 19429,
205
+ "official_views": [
206
+ "mass",
207
+ "formula"
208
+ ],
209
+ "structure_topk": [
210
+ 1,
211
+ 3,
212
+ 5,
213
+ 10,
214
+ 20,
215
+ 50,
216
+ 100,
217
+ 200
218
+ ],
219
+ "formula_topk": [
220
+ 1,
221
+ 2,
222
+ 3,
223
+ 4,
224
+ 5,
225
+ 6,
226
+ 7,
227
+ 8,
228
+ 9,
229
+ 10,
230
+ 20,
231
+ 50,
232
+ 100,
233
+ 200
234
+ ],
235
+ "primary_score": "harmonic_mean_Mass_Formula_structure_Top1",
236
+ "report_formula_Top1_and_Top10_separately": true,
237
+ "report_spectrum_micro_target_macro_key14_macro": true,
238
+ "coarse_and_fine_retrieval_diagnostics": true,
239
+ "never_filter_official_pools_or_inject_truth": true,
240
+ "test_and_casmi_only_after_predeclared_selection": true,
241
+ "casmi_pool": "data/benchmarks/casmi2022_sirius6312_top10_pubchem_10ppm_connectivity_v1",
242
+ "casmi_candidate_cap": null,
243
+ "casmi_denominator": 500,
244
+ "mces_enabled": false
245
+ },
246
+ "logging": {
247
+ "per_branch_valid_anchors_and_groups": true,
248
+ "positive_negative_and_gray_pair_counts": true,
249
+ "mass_positive_same_formula_vs_cross_formula": true,
250
+ "same_key14_false_negative_count": true,
251
+ "raw_and_weighted_losses": true,
252
+ "gradient_norm_per_task_and_pairwise_gradient_cosine": true,
253
+ "projection_variance_effective_rank_and_pair_similarity": true,
254
+ "per_source_polarity_adduct": true,
255
+ "distinct_MS_exposures_and_repeated_draws": true,
256
+ "GPU_seconds_peak_memory_and_molecule_forward_count": true
257
+ },
258
+ "experiment": {
259
+ "id": "C00_sampler_control",
260
+ "description": "Matched grouped-sampler control, no auxiliary losses",
261
+ "active_auxiliary_tasks": [],
262
+ "auxiliary_coefficient_sum": 0.0,
263
+ "output_template": "/workspace/xj/SpecPartition-MS/runs/hierarchical_intra_modal_20261103/C00_sampler_control/seed_{seed}",
264
+ "priority": "first_pass"
265
+ }
266
+ }
code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C01_ms_fine.json ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": 1,
3
+ "suite_id": "hierarchical_intra_modal_20261103",
4
+ "execution": {
5
+ "status": "configuration_and_loss_components_only",
6
+ "allow_training": false,
7
+ "runtime_entrypoint": null,
8
+ "missing_integration": [
9
+ "hierarchical_no_repeat_sampler",
10
+ "independent_stochastic_gnn_views",
11
+ "rng_safe_view_recomputation",
12
+ "joint_loss_router_and_gpu_acceptance"
13
+ ]
14
+ },
15
+ "initialization": {
16
+ "checkpoint": "/workspace/xj/SpecPartition-MS/runs/rebuild_joint_r08data_20261102/epoch_04.pt",
17
+ "sha256": "618aaf195cfdc3a4107e71cf2b3a56d5853b407564acf01de11c67e6af40f3d7",
18
+ "policy": "same_fixed_parent_weights_all_arms",
19
+ "optimizer_policy": "new_AdamW_for_every_arm_not_live_run_resume",
20
+ "selection_source": "Validation_only_fixed_before_ablation",
21
+ "new_heads": "same_initialization_per_seed_for_all_arms"
22
+ },
23
+ "data": {
24
+ "root": "/workspace/xj/SpecPartition-MS",
25
+ "labels": "data/derived/data_release_r07_key14_20261101/train.json",
26
+ "prepared": "data/derived/joint_r09_inputs_20261102/train.sqlite",
27
+ "candidates": "data/derived/training_r08_true_formula_records_20261101/preparation.sqlite",
28
+ "heldout_registry": "data/derived/data_release_r07_key14_20261101/heldout_registry.json",
29
+ "label_policy_sha256": "91971b3f6979586b32c90350330cb6712e60c3c6f4b872de4113311f8a95adf7",
30
+ "candidate_config_sha256": "53a365647ed8c54e216ff2cd25c011ed7f7d47a920f54c0136eea0c8dabade65",
31
+ "parent_training_config_sha256": "5f8f8635c60e37a194660b73f0fae69571a3f97a045f1d5c2f0e5fbf76e450d0",
32
+ "records": 643587,
33
+ "source_counts": {
34
+ "MSG_Train": 162974,
35
+ "MSP_libraries": 261644,
36
+ "MS2_SAN_JSONL": 218969
37
+ },
38
+ "exclude_heldout_labels_and_negatives_by": "key14",
39
+ "test_or_casmi_labels_in_training": false,
40
+ "preserve_same_structure_multiple_spectra": true,
41
+ "online_queries_during_training": false,
42
+ "coarse_labels_are_training_supervision_not_inference_inputs": true
43
+ },
44
+ "budget": {
45
+ "seeds": [
46
+ 20261103,
47
+ 20261104,
48
+ 20261105
49
+ ],
50
+ "optimizer_updates_per_seed": 6000,
51
+ "learning_rate": 3e-05,
52
+ "minimum_learning_rate": 3e-06,
53
+ "warmup_steps": 300,
54
+ "weight_decay": 0.0001,
55
+ "gradient_clip": 5.0,
56
+ "schedule": "cosine",
57
+ "bf16": true,
58
+ "graph_chunk": 128,
59
+ "spectrum_chunk": 64,
60
+ "pool_micro_views": 4,
61
+ "checkpoint_every": 100,
62
+ "validation_every_updates": 2000,
63
+ "source_presence_schedule": "same_R09_5093_step_epoch_plan",
64
+ "same_MS_exposure_and_candidate_draw_budget_across_arms": true,
65
+ "equal_wall_clock_or_FLOPs_claimed": false
66
+ },
67
+ "model": {
68
+ "backbone": "archived_R2_direct_ranker_256d_6Transformer_6MPNN",
69
+ "backbone_registered_parameters": 16409742,
70
+ "relation_or_cut_enabled": false,
71
+ "projection_heads": {
72
+ "input_dim": 256,
73
+ "hidden_dim": 256,
74
+ "output_dim": 128,
75
+ "activation": "GELU",
76
+ "normalize": "L2",
77
+ "names": [
78
+ "ms_identity",
79
+ "mol_identity",
80
+ "ms_formula",
81
+ "mol_formula",
82
+ "ms_mass",
83
+ "mol_mass"
84
+ ],
85
+ "register_all_heads_in_all_arms": true,
86
+ "shared_backbone_receives_auxiliary_gradients": true
87
+ },
88
+ "head_routing": "separate_by_modality_and_granularity",
89
+ "mass_head_input": "shared_encoder_representation",
90
+ "auxiliary_heads_used_at_inference": false,
91
+ "original_final_ranking_score_unchanged": true
92
+ },
93
+ "sampling": {
94
+ "mode": "hierarchical_formula_identity_spectra",
95
+ "odata_batch_size": 256,
96
+ "msg_batch_size": 32,
97
+ "desired_odata_shape": {
98
+ "formulas": 8,
99
+ "identities_per_formula": 8,
100
+ "spectra_per_identity": 4
101
+ },
102
+ "desired_msg_shape": {
103
+ "formulas": 4,
104
+ "identities_per_formula": 4,
105
+ "spectra_per_identity": 2
106
+ },
107
+ "rare_group_fallback": "pack_remaining_real_records_without_replacement",
108
+ "mass_positive_coverage": "measure_same_formula_and_cross_formula_pairs_separately_do_not_assume_formula_sampler_covers_mass_neighbors",
109
+ "force_duplicate_spectra_to_fill_group": false,
110
+ "each_source_record_once_before_next_source_epoch": true,
111
+ "singleton_policy": "retain_existing_objectives_mask_missing_auxiliary_positives",
112
+ "explicit_odata_queries": 16,
113
+ "odata_negative_draws": 128,
114
+ "msg_views": [
115
+ "mass",
116
+ "formula"
117
+ ],
118
+ "msg_negative_draws_per_view": 63,
119
+ "candidate_draws_with_replacement": true,
120
+ "candidate_pool_deduplicate_key14": false,
121
+ "same_truth_key14_is_never_negative": true
122
+ },
123
+ "views": {
124
+ "MS": {
125
+ "positive_source": "distinct_real_spectra_of_same_key14",
126
+ "spectrum_augmentation": "none",
127
+ "repeat_physical_record_is_not_positive": true
128
+ },
129
+ "molecule": {
130
+ "count": 2,
131
+ "strategy": "independent_hidden_feature_dropout",
132
+ "dropout": 0.1,
133
+ "delete_atoms_or_bonds": false,
134
+ "random_SMILES_alone_is_not_new_view": true
135
+ },
136
+ "primary_encoder_path_dropout": 0.0,
137
+ "compute_two_molecule_views_for_all_arms": true,
138
+ "stochastic_view_gradient_cache": "disabled_keep_view_graph_or_verified_RNG_replay"
139
+ },
140
+ "loss": {
141
+ "base": {
142
+ "formula": 1.0,
143
+ "ms_to_mol": 0.5,
144
+ "mol_to_ms": 0.5,
145
+ "odata_pool": 0.5,
146
+ "msg_mass_pool": 0.25,
147
+ "msg_formula_pool": 0.25
148
+ },
149
+ "formula_task": {
150
+ "ce": 1.0,
151
+ "gap": 0.1,
152
+ "hard_wrong_topk": 3,
153
+ "margin": 0.2,
154
+ "element_count": 0.2
155
+ },
156
+ "auxiliary": {
157
+ "ms_fine": 0.1,
158
+ "mol_fine": 0.0,
159
+ "ms_formula": 0.0,
160
+ "mol_formula": 0.0,
161
+ "ms_mass": 0.0,
162
+ "mol_mass": 0.0
163
+ },
164
+ "auxiliary_ramp_steps": 500,
165
+ "temperature": {
166
+ "identity": 0.1,
167
+ "formula": 0.15,
168
+ "mass": 0.2
169
+ },
170
+ "fine_identity": "key14",
171
+ "self_pairs": "exclude",
172
+ "missing_positive_or_negative": "differentiable_zero_and_log_effective_count",
173
+ "anchor_reduction": {
174
+ "fine": "key14_macro",
175
+ "formula": "formula_macro",
176
+ "mass": "key14_macro"
177
+ },
178
+ "formula_coarse": {
179
+ "label": "exact_element_count_canonical_formula",
180
+ "positive": "same_formula_different_key14",
181
+ "negative": "different_formula",
182
+ "same_key14_pair_policy": "exclude_from_coarse",
183
+ "same_scaffold_is_not_identity_positive": true
184
+ },
185
+ "mass_coarse": {
186
+ "mode": "soft_neighborhood",
187
+ "MS_mass": "abs_charge_times_experimental_precursor_minus_adduct_delta",
188
+ "molecule_mass": "cached_candidate_neutral_monoisotopic_mass",
189
+ "distance_unit": "Da",
190
+ "positive_radius_da": 0.5,
191
+ "negative_start_da": 2.0,
192
+ "gaussian_sigma_da": 0.25,
193
+ "gray_zone": "exclude",
194
+ "same_key14_pair_policy": "exclude_from_coarse",
195
+ "hard_bin_width_da": 1.0,
196
+ "hard_bin_offset_da": 0.0,
197
+ "MS_quality_mask": "reference_precursor_consistency_within_10ppm",
198
+ "candidate_10ppm_filter_is_not_mass_bucket_width": true,
199
+ "mass_neighborhood_is_not_chemical_similarity_or_equivalence_class": true
200
+ }
201
+ },
202
+ "evaluation": {
203
+ "selection_split": "MSG_Validation",
204
+ "spectra": 19429,
205
+ "official_views": [
206
+ "mass",
207
+ "formula"
208
+ ],
209
+ "structure_topk": [
210
+ 1,
211
+ 3,
212
+ 5,
213
+ 10,
214
+ 20,
215
+ 50,
216
+ 100,
217
+ 200
218
+ ],
219
+ "formula_topk": [
220
+ 1,
221
+ 2,
222
+ 3,
223
+ 4,
224
+ 5,
225
+ 6,
226
+ 7,
227
+ 8,
228
+ 9,
229
+ 10,
230
+ 20,
231
+ 50,
232
+ 100,
233
+ 200
234
+ ],
235
+ "primary_score": "harmonic_mean_Mass_Formula_structure_Top1",
236
+ "report_formula_Top1_and_Top10_separately": true,
237
+ "report_spectrum_micro_target_macro_key14_macro": true,
238
+ "coarse_and_fine_retrieval_diagnostics": true,
239
+ "never_filter_official_pools_or_inject_truth": true,
240
+ "test_and_casmi_only_after_predeclared_selection": true,
241
+ "casmi_pool": "data/benchmarks/casmi2022_sirius6312_top10_pubchem_10ppm_connectivity_v1",
242
+ "casmi_candidate_cap": null,
243
+ "casmi_denominator": 500,
244
+ "mces_enabled": false
245
+ },
246
+ "logging": {
247
+ "per_branch_valid_anchors_and_groups": true,
248
+ "positive_negative_and_gray_pair_counts": true,
249
+ "mass_positive_same_formula_vs_cross_formula": true,
250
+ "same_key14_false_negative_count": true,
251
+ "raw_and_weighted_losses": true,
252
+ "gradient_norm_per_task_and_pairwise_gradient_cosine": true,
253
+ "projection_variance_effective_rank_and_pair_similarity": true,
254
+ "per_source_polarity_adduct": true,
255
+ "distinct_MS_exposures_and_repeated_draws": true,
256
+ "GPU_seconds_peak_memory_and_molecule_forward_count": true
257
+ },
258
+ "experiment": {
259
+ "id": "C01_ms_fine",
260
+ "description": "MS-to-MS identity SupCon only",
261
+ "active_auxiliary_tasks": [
262
+ "ms_fine"
263
+ ],
264
+ "auxiliary_coefficient_sum": 0.1,
265
+ "output_template": "/workspace/xj/SpecPartition-MS/runs/hierarchical_intra_modal_20261103/C01_ms_fine/seed_{seed}",
266
+ "priority": "secondary_ablation"
267
+ }
268
+ }
code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C02_mol_fine.json ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": 1,
3
+ "suite_id": "hierarchical_intra_modal_20261103",
4
+ "execution": {
5
+ "status": "configuration_and_loss_components_only",
6
+ "allow_training": false,
7
+ "runtime_entrypoint": null,
8
+ "missing_integration": [
9
+ "hierarchical_no_repeat_sampler",
10
+ "independent_stochastic_gnn_views",
11
+ "rng_safe_view_recomputation",
12
+ "joint_loss_router_and_gpu_acceptance"
13
+ ]
14
+ },
15
+ "initialization": {
16
+ "checkpoint": "/workspace/xj/SpecPartition-MS/runs/rebuild_joint_r08data_20261102/epoch_04.pt",
17
+ "sha256": "618aaf195cfdc3a4107e71cf2b3a56d5853b407564acf01de11c67e6af40f3d7",
18
+ "policy": "same_fixed_parent_weights_all_arms",
19
+ "optimizer_policy": "new_AdamW_for_every_arm_not_live_run_resume",
20
+ "selection_source": "Validation_only_fixed_before_ablation",
21
+ "new_heads": "same_initialization_per_seed_for_all_arms"
22
+ },
23
+ "data": {
24
+ "root": "/workspace/xj/SpecPartition-MS",
25
+ "labels": "data/derived/data_release_r07_key14_20261101/train.json",
26
+ "prepared": "data/derived/joint_r09_inputs_20261102/train.sqlite",
27
+ "candidates": "data/derived/training_r08_true_formula_records_20261101/preparation.sqlite",
28
+ "heldout_registry": "data/derived/data_release_r07_key14_20261101/heldout_registry.json",
29
+ "label_policy_sha256": "91971b3f6979586b32c90350330cb6712e60c3c6f4b872de4113311f8a95adf7",
30
+ "candidate_config_sha256": "53a365647ed8c54e216ff2cd25c011ed7f7d47a920f54c0136eea0c8dabade65",
31
+ "parent_training_config_sha256": "5f8f8635c60e37a194660b73f0fae69571a3f97a045f1d5c2f0e5fbf76e450d0",
32
+ "records": 643587,
33
+ "source_counts": {
34
+ "MSG_Train": 162974,
35
+ "MSP_libraries": 261644,
36
+ "MS2_SAN_JSONL": 218969
37
+ },
38
+ "exclude_heldout_labels_and_negatives_by": "key14",
39
+ "test_or_casmi_labels_in_training": false,
40
+ "preserve_same_structure_multiple_spectra": true,
41
+ "online_queries_during_training": false,
42
+ "coarse_labels_are_training_supervision_not_inference_inputs": true
43
+ },
44
+ "budget": {
45
+ "seeds": [
46
+ 20261103,
47
+ 20261104,
48
+ 20261105
49
+ ],
50
+ "optimizer_updates_per_seed": 6000,
51
+ "learning_rate": 3e-05,
52
+ "minimum_learning_rate": 3e-06,
53
+ "warmup_steps": 300,
54
+ "weight_decay": 0.0001,
55
+ "gradient_clip": 5.0,
56
+ "schedule": "cosine",
57
+ "bf16": true,
58
+ "graph_chunk": 128,
59
+ "spectrum_chunk": 64,
60
+ "pool_micro_views": 4,
61
+ "checkpoint_every": 100,
62
+ "validation_every_updates": 2000,
63
+ "source_presence_schedule": "same_R09_5093_step_epoch_plan",
64
+ "same_MS_exposure_and_candidate_draw_budget_across_arms": true,
65
+ "equal_wall_clock_or_FLOPs_claimed": false
66
+ },
67
+ "model": {
68
+ "backbone": "archived_R2_direct_ranker_256d_6Transformer_6MPNN",
69
+ "backbone_registered_parameters": 16409742,
70
+ "relation_or_cut_enabled": false,
71
+ "projection_heads": {
72
+ "input_dim": 256,
73
+ "hidden_dim": 256,
74
+ "output_dim": 128,
75
+ "activation": "GELU",
76
+ "normalize": "L2",
77
+ "names": [
78
+ "ms_identity",
79
+ "mol_identity",
80
+ "ms_formula",
81
+ "mol_formula",
82
+ "ms_mass",
83
+ "mol_mass"
84
+ ],
85
+ "register_all_heads_in_all_arms": true,
86
+ "shared_backbone_receives_auxiliary_gradients": true
87
+ },
88
+ "head_routing": "separate_by_modality_and_granularity",
89
+ "mass_head_input": "shared_encoder_representation",
90
+ "auxiliary_heads_used_at_inference": false,
91
+ "original_final_ranking_score_unchanged": true
92
+ },
93
+ "sampling": {
94
+ "mode": "hierarchical_formula_identity_spectra",
95
+ "odata_batch_size": 256,
96
+ "msg_batch_size": 32,
97
+ "desired_odata_shape": {
98
+ "formulas": 8,
99
+ "identities_per_formula": 8,
100
+ "spectra_per_identity": 4
101
+ },
102
+ "desired_msg_shape": {
103
+ "formulas": 4,
104
+ "identities_per_formula": 4,
105
+ "spectra_per_identity": 2
106
+ },
107
+ "rare_group_fallback": "pack_remaining_real_records_without_replacement",
108
+ "mass_positive_coverage": "measure_same_formula_and_cross_formula_pairs_separately_do_not_assume_formula_sampler_covers_mass_neighbors",
109
+ "force_duplicate_spectra_to_fill_group": false,
110
+ "each_source_record_once_before_next_source_epoch": true,
111
+ "singleton_policy": "retain_existing_objectives_mask_missing_auxiliary_positives",
112
+ "explicit_odata_queries": 16,
113
+ "odata_negative_draws": 128,
114
+ "msg_views": [
115
+ "mass",
116
+ "formula"
117
+ ],
118
+ "msg_negative_draws_per_view": 63,
119
+ "candidate_draws_with_replacement": true,
120
+ "candidate_pool_deduplicate_key14": false,
121
+ "same_truth_key14_is_never_negative": true
122
+ },
123
+ "views": {
124
+ "MS": {
125
+ "positive_source": "distinct_real_spectra_of_same_key14",
126
+ "spectrum_augmentation": "none",
127
+ "repeat_physical_record_is_not_positive": true
128
+ },
129
+ "molecule": {
130
+ "count": 2,
131
+ "strategy": "independent_hidden_feature_dropout",
132
+ "dropout": 0.1,
133
+ "delete_atoms_or_bonds": false,
134
+ "random_SMILES_alone_is_not_new_view": true
135
+ },
136
+ "primary_encoder_path_dropout": 0.0,
137
+ "compute_two_molecule_views_for_all_arms": true,
138
+ "stochastic_view_gradient_cache": "disabled_keep_view_graph_or_verified_RNG_replay"
139
+ },
140
+ "loss": {
141
+ "base": {
142
+ "formula": 1.0,
143
+ "ms_to_mol": 0.5,
144
+ "mol_to_ms": 0.5,
145
+ "odata_pool": 0.5,
146
+ "msg_mass_pool": 0.25,
147
+ "msg_formula_pool": 0.25
148
+ },
149
+ "formula_task": {
150
+ "ce": 1.0,
151
+ "gap": 0.1,
152
+ "hard_wrong_topk": 3,
153
+ "margin": 0.2,
154
+ "element_count": 0.2
155
+ },
156
+ "auxiliary": {
157
+ "ms_fine": 0.0,
158
+ "mol_fine": 0.05,
159
+ "ms_formula": 0.0,
160
+ "mol_formula": 0.0,
161
+ "ms_mass": 0.0,
162
+ "mol_mass": 0.0
163
+ },
164
+ "auxiliary_ramp_steps": 500,
165
+ "temperature": {
166
+ "identity": 0.1,
167
+ "formula": 0.15,
168
+ "mass": 0.2
169
+ },
170
+ "fine_identity": "key14",
171
+ "self_pairs": "exclude",
172
+ "missing_positive_or_negative": "differentiable_zero_and_log_effective_count",
173
+ "anchor_reduction": {
174
+ "fine": "key14_macro",
175
+ "formula": "formula_macro",
176
+ "mass": "key14_macro"
177
+ },
178
+ "formula_coarse": {
179
+ "label": "exact_element_count_canonical_formula",
180
+ "positive": "same_formula_different_key14",
181
+ "negative": "different_formula",
182
+ "same_key14_pair_policy": "exclude_from_coarse",
183
+ "same_scaffold_is_not_identity_positive": true
184
+ },
185
+ "mass_coarse": {
186
+ "mode": "soft_neighborhood",
187
+ "MS_mass": "abs_charge_times_experimental_precursor_minus_adduct_delta",
188
+ "molecule_mass": "cached_candidate_neutral_monoisotopic_mass",
189
+ "distance_unit": "Da",
190
+ "positive_radius_da": 0.5,
191
+ "negative_start_da": 2.0,
192
+ "gaussian_sigma_da": 0.25,
193
+ "gray_zone": "exclude",
194
+ "same_key14_pair_policy": "exclude_from_coarse",
195
+ "hard_bin_width_da": 1.0,
196
+ "hard_bin_offset_da": 0.0,
197
+ "MS_quality_mask": "reference_precursor_consistency_within_10ppm",
198
+ "candidate_10ppm_filter_is_not_mass_bucket_width": true,
199
+ "mass_neighborhood_is_not_chemical_similarity_or_equivalence_class": true
200
+ }
201
+ },
202
+ "evaluation": {
203
+ "selection_split": "MSG_Validation",
204
+ "spectra": 19429,
205
+ "official_views": [
206
+ "mass",
207
+ "formula"
208
+ ],
209
+ "structure_topk": [
210
+ 1,
211
+ 3,
212
+ 5,
213
+ 10,
214
+ 20,
215
+ 50,
216
+ 100,
217
+ 200
218
+ ],
219
+ "formula_topk": [
220
+ 1,
221
+ 2,
222
+ 3,
223
+ 4,
224
+ 5,
225
+ 6,
226
+ 7,
227
+ 8,
228
+ 9,
229
+ 10,
230
+ 20,
231
+ 50,
232
+ 100,
233
+ 200
234
+ ],
235
+ "primary_score": "harmonic_mean_Mass_Formula_structure_Top1",
236
+ "report_formula_Top1_and_Top10_separately": true,
237
+ "report_spectrum_micro_target_macro_key14_macro": true,
238
+ "coarse_and_fine_retrieval_diagnostics": true,
239
+ "never_filter_official_pools_or_inject_truth": true,
240
+ "test_and_casmi_only_after_predeclared_selection": true,
241
+ "casmi_pool": "data/benchmarks/casmi2022_sirius6312_top10_pubchem_10ppm_connectivity_v1",
242
+ "casmi_candidate_cap": null,
243
+ "casmi_denominator": 500,
244
+ "mces_enabled": false
245
+ },
246
+ "logging": {
247
+ "per_branch_valid_anchors_and_groups": true,
248
+ "positive_negative_and_gray_pair_counts": true,
249
+ "mass_positive_same_formula_vs_cross_formula": true,
250
+ "same_key14_false_negative_count": true,
251
+ "raw_and_weighted_losses": true,
252
+ "gradient_norm_per_task_and_pairwise_gradient_cosine": true,
253
+ "projection_variance_effective_rank_and_pair_similarity": true,
254
+ "per_source_polarity_adduct": true,
255
+ "distinct_MS_exposures_and_repeated_draws": true,
256
+ "GPU_seconds_peak_memory_and_molecule_forward_count": true
257
+ },
258
+ "experiment": {
259
+ "id": "C02_mol_fine",
260
+ "description": "Molecule-to-molecule two-view identity loss only",
261
+ "active_auxiliary_tasks": [
262
+ "mol_fine"
263
+ ],
264
+ "auxiliary_coefficient_sum": 0.05,
265
+ "output_template": "/workspace/xj/SpecPartition-MS/runs/hierarchical_intra_modal_20261103/C02_mol_fine/seed_{seed}",
266
+ "priority": "secondary_ablation"
267
+ }
268
+ }
code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C03_both_fine.json ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": 1,
3
+ "suite_id": "hierarchical_intra_modal_20261103",
4
+ "execution": {
5
+ "status": "configuration_and_loss_components_only",
6
+ "allow_training": false,
7
+ "runtime_entrypoint": null,
8
+ "missing_integration": [
9
+ "hierarchical_no_repeat_sampler",
10
+ "independent_stochastic_gnn_views",
11
+ "rng_safe_view_recomputation",
12
+ "joint_loss_router_and_gpu_acceptance"
13
+ ]
14
+ },
15
+ "initialization": {
16
+ "checkpoint": "/workspace/xj/SpecPartition-MS/runs/rebuild_joint_r08data_20261102/epoch_04.pt",
17
+ "sha256": "618aaf195cfdc3a4107e71cf2b3a56d5853b407564acf01de11c67e6af40f3d7",
18
+ "policy": "same_fixed_parent_weights_all_arms",
19
+ "optimizer_policy": "new_AdamW_for_every_arm_not_live_run_resume",
20
+ "selection_source": "Validation_only_fixed_before_ablation",
21
+ "new_heads": "same_initialization_per_seed_for_all_arms"
22
+ },
23
+ "data": {
24
+ "root": "/workspace/xj/SpecPartition-MS",
25
+ "labels": "data/derived/data_release_r07_key14_20261101/train.json",
26
+ "prepared": "data/derived/joint_r09_inputs_20261102/train.sqlite",
27
+ "candidates": "data/derived/training_r08_true_formula_records_20261101/preparation.sqlite",
28
+ "heldout_registry": "data/derived/data_release_r07_key14_20261101/heldout_registry.json",
29
+ "label_policy_sha256": "91971b3f6979586b32c90350330cb6712e60c3c6f4b872de4113311f8a95adf7",
30
+ "candidate_config_sha256": "53a365647ed8c54e216ff2cd25c011ed7f7d47a920f54c0136eea0c8dabade65",
31
+ "parent_training_config_sha256": "5f8f8635c60e37a194660b73f0fae69571a3f97a045f1d5c2f0e5fbf76e450d0",
32
+ "records": 643587,
33
+ "source_counts": {
34
+ "MSG_Train": 162974,
35
+ "MSP_libraries": 261644,
36
+ "MS2_SAN_JSONL": 218969
37
+ },
38
+ "exclude_heldout_labels_and_negatives_by": "key14",
39
+ "test_or_casmi_labels_in_training": false,
40
+ "preserve_same_structure_multiple_spectra": true,
41
+ "online_queries_during_training": false,
42
+ "coarse_labels_are_training_supervision_not_inference_inputs": true
43
+ },
44
+ "budget": {
45
+ "seeds": [
46
+ 20261103,
47
+ 20261104,
48
+ 20261105
49
+ ],
50
+ "optimizer_updates_per_seed": 6000,
51
+ "learning_rate": 3e-05,
52
+ "minimum_learning_rate": 3e-06,
53
+ "warmup_steps": 300,
54
+ "weight_decay": 0.0001,
55
+ "gradient_clip": 5.0,
56
+ "schedule": "cosine",
57
+ "bf16": true,
58
+ "graph_chunk": 128,
59
+ "spectrum_chunk": 64,
60
+ "pool_micro_views": 4,
61
+ "checkpoint_every": 100,
62
+ "validation_every_updates": 2000,
63
+ "source_presence_schedule": "same_R09_5093_step_epoch_plan",
64
+ "same_MS_exposure_and_candidate_draw_budget_across_arms": true,
65
+ "equal_wall_clock_or_FLOPs_claimed": false
66
+ },
67
+ "model": {
68
+ "backbone": "archived_R2_direct_ranker_256d_6Transformer_6MPNN",
69
+ "backbone_registered_parameters": 16409742,
70
+ "relation_or_cut_enabled": false,
71
+ "projection_heads": {
72
+ "input_dim": 256,
73
+ "hidden_dim": 256,
74
+ "output_dim": 128,
75
+ "activation": "GELU",
76
+ "normalize": "L2",
77
+ "names": [
78
+ "ms_identity",
79
+ "mol_identity",
80
+ "ms_formula",
81
+ "mol_formula",
82
+ "ms_mass",
83
+ "mol_mass"
84
+ ],
85
+ "register_all_heads_in_all_arms": true,
86
+ "shared_backbone_receives_auxiliary_gradients": true
87
+ },
88
+ "head_routing": "separate_by_modality_and_granularity",
89
+ "mass_head_input": "shared_encoder_representation",
90
+ "auxiliary_heads_used_at_inference": false,
91
+ "original_final_ranking_score_unchanged": true
92
+ },
93
+ "sampling": {
94
+ "mode": "hierarchical_formula_identity_spectra",
95
+ "odata_batch_size": 256,
96
+ "msg_batch_size": 32,
97
+ "desired_odata_shape": {
98
+ "formulas": 8,
99
+ "identities_per_formula": 8,
100
+ "spectra_per_identity": 4
101
+ },
102
+ "desired_msg_shape": {
103
+ "formulas": 4,
104
+ "identities_per_formula": 4,
105
+ "spectra_per_identity": 2
106
+ },
107
+ "rare_group_fallback": "pack_remaining_real_records_without_replacement",
108
+ "mass_positive_coverage": "measure_same_formula_and_cross_formula_pairs_separately_do_not_assume_formula_sampler_covers_mass_neighbors",
109
+ "force_duplicate_spectra_to_fill_group": false,
110
+ "each_source_record_once_before_next_source_epoch": true,
111
+ "singleton_policy": "retain_existing_objectives_mask_missing_auxiliary_positives",
112
+ "explicit_odata_queries": 16,
113
+ "odata_negative_draws": 128,
114
+ "msg_views": [
115
+ "mass",
116
+ "formula"
117
+ ],
118
+ "msg_negative_draws_per_view": 63,
119
+ "candidate_draws_with_replacement": true,
120
+ "candidate_pool_deduplicate_key14": false,
121
+ "same_truth_key14_is_never_negative": true
122
+ },
123
+ "views": {
124
+ "MS": {
125
+ "positive_source": "distinct_real_spectra_of_same_key14",
126
+ "spectrum_augmentation": "none",
127
+ "repeat_physical_record_is_not_positive": true
128
+ },
129
+ "molecule": {
130
+ "count": 2,
131
+ "strategy": "independent_hidden_feature_dropout",
132
+ "dropout": 0.1,
133
+ "delete_atoms_or_bonds": false,
134
+ "random_SMILES_alone_is_not_new_view": true
135
+ },
136
+ "primary_encoder_path_dropout": 0.0,
137
+ "compute_two_molecule_views_for_all_arms": true,
138
+ "stochastic_view_gradient_cache": "disabled_keep_view_graph_or_verified_RNG_replay"
139
+ },
140
+ "loss": {
141
+ "base": {
142
+ "formula": 1.0,
143
+ "ms_to_mol": 0.5,
144
+ "mol_to_ms": 0.5,
145
+ "odata_pool": 0.5,
146
+ "msg_mass_pool": 0.25,
147
+ "msg_formula_pool": 0.25
148
+ },
149
+ "formula_task": {
150
+ "ce": 1.0,
151
+ "gap": 0.1,
152
+ "hard_wrong_topk": 3,
153
+ "margin": 0.2,
154
+ "element_count": 0.2
155
+ },
156
+ "auxiliary": {
157
+ "ms_fine": 0.1,
158
+ "mol_fine": 0.05,
159
+ "ms_formula": 0.0,
160
+ "mol_formula": 0.0,
161
+ "ms_mass": 0.0,
162
+ "mol_mass": 0.0
163
+ },
164
+ "auxiliary_ramp_steps": 500,
165
+ "temperature": {
166
+ "identity": 0.1,
167
+ "formula": 0.15,
168
+ "mass": 0.2
169
+ },
170
+ "fine_identity": "key14",
171
+ "self_pairs": "exclude",
172
+ "missing_positive_or_negative": "differentiable_zero_and_log_effective_count",
173
+ "anchor_reduction": {
174
+ "fine": "key14_macro",
175
+ "formula": "formula_macro",
176
+ "mass": "key14_macro"
177
+ },
178
+ "formula_coarse": {
179
+ "label": "exact_element_count_canonical_formula",
180
+ "positive": "same_formula_different_key14",
181
+ "negative": "different_formula",
182
+ "same_key14_pair_policy": "exclude_from_coarse",
183
+ "same_scaffold_is_not_identity_positive": true
184
+ },
185
+ "mass_coarse": {
186
+ "mode": "soft_neighborhood",
187
+ "MS_mass": "abs_charge_times_experimental_precursor_minus_adduct_delta",
188
+ "molecule_mass": "cached_candidate_neutral_monoisotopic_mass",
189
+ "distance_unit": "Da",
190
+ "positive_radius_da": 0.5,
191
+ "negative_start_da": 2.0,
192
+ "gaussian_sigma_da": 0.25,
193
+ "gray_zone": "exclude",
194
+ "same_key14_pair_policy": "exclude_from_coarse",
195
+ "hard_bin_width_da": 1.0,
196
+ "hard_bin_offset_da": 0.0,
197
+ "MS_quality_mask": "reference_precursor_consistency_within_10ppm",
198
+ "candidate_10ppm_filter_is_not_mass_bucket_width": true,
199
+ "mass_neighborhood_is_not_chemical_similarity_or_equivalence_class": true
200
+ }
201
+ },
202
+ "evaluation": {
203
+ "selection_split": "MSG_Validation",
204
+ "spectra": 19429,
205
+ "official_views": [
206
+ "mass",
207
+ "formula"
208
+ ],
209
+ "structure_topk": [
210
+ 1,
211
+ 3,
212
+ 5,
213
+ 10,
214
+ 20,
215
+ 50,
216
+ 100,
217
+ 200
218
+ ],
219
+ "formula_topk": [
220
+ 1,
221
+ 2,
222
+ 3,
223
+ 4,
224
+ 5,
225
+ 6,
226
+ 7,
227
+ 8,
228
+ 9,
229
+ 10,
230
+ 20,
231
+ 50,
232
+ 100,
233
+ 200
234
+ ],
235
+ "primary_score": "harmonic_mean_Mass_Formula_structure_Top1",
236
+ "report_formula_Top1_and_Top10_separately": true,
237
+ "report_spectrum_micro_target_macro_key14_macro": true,
238
+ "coarse_and_fine_retrieval_diagnostics": true,
239
+ "never_filter_official_pools_or_inject_truth": true,
240
+ "test_and_casmi_only_after_predeclared_selection": true,
241
+ "casmi_pool": "data/benchmarks/casmi2022_sirius6312_top10_pubchem_10ppm_connectivity_v1",
242
+ "casmi_candidate_cap": null,
243
+ "casmi_denominator": 500,
244
+ "mces_enabled": false
245
+ },
246
+ "logging": {
247
+ "per_branch_valid_anchors_and_groups": true,
248
+ "positive_negative_and_gray_pair_counts": true,
249
+ "mass_positive_same_formula_vs_cross_formula": true,
250
+ "same_key14_false_negative_count": true,
251
+ "raw_and_weighted_losses": true,
252
+ "gradient_norm_per_task_and_pairwise_gradient_cosine": true,
253
+ "projection_variance_effective_rank_and_pair_similarity": true,
254
+ "per_source_polarity_adduct": true,
255
+ "distinct_MS_exposures_and_repeated_draws": true,
256
+ "GPU_seconds_peak_memory_and_molecule_forward_count": true
257
+ },
258
+ "experiment": {
259
+ "id": "C03_both_fine",
260
+ "description": "Both fine identity losses",
261
+ "active_auxiliary_tasks": [
262
+ "ms_fine",
263
+ "mol_fine"
264
+ ],
265
+ "auxiliary_coefficient_sum": 0.15,
266
+ "output_template": "/workspace/xj/SpecPartition-MS/runs/hierarchical_intra_modal_20261103/C03_both_fine/seed_{seed}",
267
+ "priority": "first_pass"
268
+ }
269
+ }
code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C04_formula_coarse.json ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": 1,
3
+ "suite_id": "hierarchical_intra_modal_20261103",
4
+ "execution": {
5
+ "status": "configuration_and_loss_components_only",
6
+ "allow_training": false,
7
+ "runtime_entrypoint": null,
8
+ "missing_integration": [
9
+ "hierarchical_no_repeat_sampler",
10
+ "independent_stochastic_gnn_views",
11
+ "rng_safe_view_recomputation",
12
+ "joint_loss_router_and_gpu_acceptance"
13
+ ]
14
+ },
15
+ "initialization": {
16
+ "checkpoint": "/workspace/xj/SpecPartition-MS/runs/rebuild_joint_r08data_20261102/epoch_04.pt",
17
+ "sha256": "618aaf195cfdc3a4107e71cf2b3a56d5853b407564acf01de11c67e6af40f3d7",
18
+ "policy": "same_fixed_parent_weights_all_arms",
19
+ "optimizer_policy": "new_AdamW_for_every_arm_not_live_run_resume",
20
+ "selection_source": "Validation_only_fixed_before_ablation",
21
+ "new_heads": "same_initialization_per_seed_for_all_arms"
22
+ },
23
+ "data": {
24
+ "root": "/workspace/xj/SpecPartition-MS",
25
+ "labels": "data/derived/data_release_r07_key14_20261101/train.json",
26
+ "prepared": "data/derived/joint_r09_inputs_20261102/train.sqlite",
27
+ "candidates": "data/derived/training_r08_true_formula_records_20261101/preparation.sqlite",
28
+ "heldout_registry": "data/derived/data_release_r07_key14_20261101/heldout_registry.json",
29
+ "label_policy_sha256": "91971b3f6979586b32c90350330cb6712e60c3c6f4b872de4113311f8a95adf7",
30
+ "candidate_config_sha256": "53a365647ed8c54e216ff2cd25c011ed7f7d47a920f54c0136eea0c8dabade65",
31
+ "parent_training_config_sha256": "5f8f8635c60e37a194660b73f0fae69571a3f97a045f1d5c2f0e5fbf76e450d0",
32
+ "records": 643587,
33
+ "source_counts": {
34
+ "MSG_Train": 162974,
35
+ "MSP_libraries": 261644,
36
+ "MS2_SAN_JSONL": 218969
37
+ },
38
+ "exclude_heldout_labels_and_negatives_by": "key14",
39
+ "test_or_casmi_labels_in_training": false,
40
+ "preserve_same_structure_multiple_spectra": true,
41
+ "online_queries_during_training": false,
42
+ "coarse_labels_are_training_supervision_not_inference_inputs": true
43
+ },
44
+ "budget": {
45
+ "seeds": [
46
+ 20261103,
47
+ 20261104,
48
+ 20261105
49
+ ],
50
+ "optimizer_updates_per_seed": 6000,
51
+ "learning_rate": 3e-05,
52
+ "minimum_learning_rate": 3e-06,
53
+ "warmup_steps": 300,
54
+ "weight_decay": 0.0001,
55
+ "gradient_clip": 5.0,
56
+ "schedule": "cosine",
57
+ "bf16": true,
58
+ "graph_chunk": 128,
59
+ "spectrum_chunk": 64,
60
+ "pool_micro_views": 4,
61
+ "checkpoint_every": 100,
62
+ "validation_every_updates": 2000,
63
+ "source_presence_schedule": "same_R09_5093_step_epoch_plan",
64
+ "same_MS_exposure_and_candidate_draw_budget_across_arms": true,
65
+ "equal_wall_clock_or_FLOPs_claimed": false
66
+ },
67
+ "model": {
68
+ "backbone": "archived_R2_direct_ranker_256d_6Transformer_6MPNN",
69
+ "backbone_registered_parameters": 16409742,
70
+ "relation_or_cut_enabled": false,
71
+ "projection_heads": {
72
+ "input_dim": 256,
73
+ "hidden_dim": 256,
74
+ "output_dim": 128,
75
+ "activation": "GELU",
76
+ "normalize": "L2",
77
+ "names": [
78
+ "ms_identity",
79
+ "mol_identity",
80
+ "ms_formula",
81
+ "mol_formula",
82
+ "ms_mass",
83
+ "mol_mass"
84
+ ],
85
+ "register_all_heads_in_all_arms": true,
86
+ "shared_backbone_receives_auxiliary_gradients": true
87
+ },
88
+ "head_routing": "separate_by_modality_and_granularity",
89
+ "mass_head_input": "shared_encoder_representation",
90
+ "auxiliary_heads_used_at_inference": false,
91
+ "original_final_ranking_score_unchanged": true
92
+ },
93
+ "sampling": {
94
+ "mode": "hierarchical_formula_identity_spectra",
95
+ "odata_batch_size": 256,
96
+ "msg_batch_size": 32,
97
+ "desired_odata_shape": {
98
+ "formulas": 8,
99
+ "identities_per_formula": 8,
100
+ "spectra_per_identity": 4
101
+ },
102
+ "desired_msg_shape": {
103
+ "formulas": 4,
104
+ "identities_per_formula": 4,
105
+ "spectra_per_identity": 2
106
+ },
107
+ "rare_group_fallback": "pack_remaining_real_records_without_replacement",
108
+ "mass_positive_coverage": "measure_same_formula_and_cross_formula_pairs_separately_do_not_assume_formula_sampler_covers_mass_neighbors",
109
+ "force_duplicate_spectra_to_fill_group": false,
110
+ "each_source_record_once_before_next_source_epoch": true,
111
+ "singleton_policy": "retain_existing_objectives_mask_missing_auxiliary_positives",
112
+ "explicit_odata_queries": 16,
113
+ "odata_negative_draws": 128,
114
+ "msg_views": [
115
+ "mass",
116
+ "formula"
117
+ ],
118
+ "msg_negative_draws_per_view": 63,
119
+ "candidate_draws_with_replacement": true,
120
+ "candidate_pool_deduplicate_key14": false,
121
+ "same_truth_key14_is_never_negative": true
122
+ },
123
+ "views": {
124
+ "MS": {
125
+ "positive_source": "distinct_real_spectra_of_same_key14",
126
+ "spectrum_augmentation": "none",
127
+ "repeat_physical_record_is_not_positive": true
128
+ },
129
+ "molecule": {
130
+ "count": 2,
131
+ "strategy": "independent_hidden_feature_dropout",
132
+ "dropout": 0.1,
133
+ "delete_atoms_or_bonds": false,
134
+ "random_SMILES_alone_is_not_new_view": true
135
+ },
136
+ "primary_encoder_path_dropout": 0.0,
137
+ "compute_two_molecule_views_for_all_arms": true,
138
+ "stochastic_view_gradient_cache": "disabled_keep_view_graph_or_verified_RNG_replay"
139
+ },
140
+ "loss": {
141
+ "base": {
142
+ "formula": 1.0,
143
+ "ms_to_mol": 0.5,
144
+ "mol_to_ms": 0.5,
145
+ "odata_pool": 0.5,
146
+ "msg_mass_pool": 0.25,
147
+ "msg_formula_pool": 0.25
148
+ },
149
+ "formula_task": {
150
+ "ce": 1.0,
151
+ "gap": 0.1,
152
+ "hard_wrong_topk": 3,
153
+ "margin": 0.2,
154
+ "element_count": 0.2
155
+ },
156
+ "auxiliary": {
157
+ "ms_fine": 0.0,
158
+ "mol_fine": 0.0,
159
+ "ms_formula": 0.05,
160
+ "mol_formula": 0.05,
161
+ "ms_mass": 0.0,
162
+ "mol_mass": 0.0
163
+ },
164
+ "auxiliary_ramp_steps": 500,
165
+ "temperature": {
166
+ "identity": 0.1,
167
+ "formula": 0.15,
168
+ "mass": 0.2
169
+ },
170
+ "fine_identity": "key14",
171
+ "self_pairs": "exclude",
172
+ "missing_positive_or_negative": "differentiable_zero_and_log_effective_count",
173
+ "anchor_reduction": {
174
+ "fine": "key14_macro",
175
+ "formula": "formula_macro",
176
+ "mass": "key14_macro"
177
+ },
178
+ "formula_coarse": {
179
+ "label": "exact_element_count_canonical_formula",
180
+ "positive": "same_formula_different_key14",
181
+ "negative": "different_formula",
182
+ "same_key14_pair_policy": "exclude_from_coarse",
183
+ "same_scaffold_is_not_identity_positive": true
184
+ },
185
+ "mass_coarse": {
186
+ "mode": "soft_neighborhood",
187
+ "MS_mass": "abs_charge_times_experimental_precursor_minus_adduct_delta",
188
+ "molecule_mass": "cached_candidate_neutral_monoisotopic_mass",
189
+ "distance_unit": "Da",
190
+ "positive_radius_da": 0.5,
191
+ "negative_start_da": 2.0,
192
+ "gaussian_sigma_da": 0.25,
193
+ "gray_zone": "exclude",
194
+ "same_key14_pair_policy": "exclude_from_coarse",
195
+ "hard_bin_width_da": 1.0,
196
+ "hard_bin_offset_da": 0.0,
197
+ "MS_quality_mask": "reference_precursor_consistency_within_10ppm",
198
+ "candidate_10ppm_filter_is_not_mass_bucket_width": true,
199
+ "mass_neighborhood_is_not_chemical_similarity_or_equivalence_class": true
200
+ }
201
+ },
202
+ "evaluation": {
203
+ "selection_split": "MSG_Validation",
204
+ "spectra": 19429,
205
+ "official_views": [
206
+ "mass",
207
+ "formula"
208
+ ],
209
+ "structure_topk": [
210
+ 1,
211
+ 3,
212
+ 5,
213
+ 10,
214
+ 20,
215
+ 50,
216
+ 100,
217
+ 200
218
+ ],
219
+ "formula_topk": [
220
+ 1,
221
+ 2,
222
+ 3,
223
+ 4,
224
+ 5,
225
+ 6,
226
+ 7,
227
+ 8,
228
+ 9,
229
+ 10,
230
+ 20,
231
+ 50,
232
+ 100,
233
+ 200
234
+ ],
235
+ "primary_score": "harmonic_mean_Mass_Formula_structure_Top1",
236
+ "report_formula_Top1_and_Top10_separately": true,
237
+ "report_spectrum_micro_target_macro_key14_macro": true,
238
+ "coarse_and_fine_retrieval_diagnostics": true,
239
+ "never_filter_official_pools_or_inject_truth": true,
240
+ "test_and_casmi_only_after_predeclared_selection": true,
241
+ "casmi_pool": "data/benchmarks/casmi2022_sirius6312_top10_pubchem_10ppm_connectivity_v1",
242
+ "casmi_candidate_cap": null,
243
+ "casmi_denominator": 500,
244
+ "mces_enabled": false
245
+ },
246
+ "logging": {
247
+ "per_branch_valid_anchors_and_groups": true,
248
+ "positive_negative_and_gray_pair_counts": true,
249
+ "mass_positive_same_formula_vs_cross_formula": true,
250
+ "same_key14_false_negative_count": true,
251
+ "raw_and_weighted_losses": true,
252
+ "gradient_norm_per_task_and_pairwise_gradient_cosine": true,
253
+ "projection_variance_effective_rank_and_pair_similarity": true,
254
+ "per_source_polarity_adduct": true,
255
+ "distinct_MS_exposures_and_repeated_draws": true,
256
+ "GPU_seconds_peak_memory_and_molecule_forward_count": true
257
+ },
258
+ "experiment": {
259
+ "id": "C04_formula_coarse",
260
+ "description": "Formula coarse losses without new fine losses",
261
+ "active_auxiliary_tasks": [
262
+ "ms_formula",
263
+ "mol_formula"
264
+ ],
265
+ "auxiliary_coefficient_sum": 0.1,
266
+ "output_template": "/workspace/xj/SpecPartition-MS/runs/hierarchical_intra_modal_20261103/C04_formula_coarse/seed_{seed}",
267
+ "priority": "secondary_ablation"
268
+ }
269
+ }
code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C05_mass_coarse.json ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": 1,
3
+ "suite_id": "hierarchical_intra_modal_20261103",
4
+ "execution": {
5
+ "status": "configuration_and_loss_components_only",
6
+ "allow_training": false,
7
+ "runtime_entrypoint": null,
8
+ "missing_integration": [
9
+ "hierarchical_no_repeat_sampler",
10
+ "independent_stochastic_gnn_views",
11
+ "rng_safe_view_recomputation",
12
+ "joint_loss_router_and_gpu_acceptance"
13
+ ]
14
+ },
15
+ "initialization": {
16
+ "checkpoint": "/workspace/xj/SpecPartition-MS/runs/rebuild_joint_r08data_20261102/epoch_04.pt",
17
+ "sha256": "618aaf195cfdc3a4107e71cf2b3a56d5853b407564acf01de11c67e6af40f3d7",
18
+ "policy": "same_fixed_parent_weights_all_arms",
19
+ "optimizer_policy": "new_AdamW_for_every_arm_not_live_run_resume",
20
+ "selection_source": "Validation_only_fixed_before_ablation",
21
+ "new_heads": "same_initialization_per_seed_for_all_arms"
22
+ },
23
+ "data": {
24
+ "root": "/workspace/xj/SpecPartition-MS",
25
+ "labels": "data/derived/data_release_r07_key14_20261101/train.json",
26
+ "prepared": "data/derived/joint_r09_inputs_20261102/train.sqlite",
27
+ "candidates": "data/derived/training_r08_true_formula_records_20261101/preparation.sqlite",
28
+ "heldout_registry": "data/derived/data_release_r07_key14_20261101/heldout_registry.json",
29
+ "label_policy_sha256": "91971b3f6979586b32c90350330cb6712e60c3c6f4b872de4113311f8a95adf7",
30
+ "candidate_config_sha256": "53a365647ed8c54e216ff2cd25c011ed7f7d47a920f54c0136eea0c8dabade65",
31
+ "parent_training_config_sha256": "5f8f8635c60e37a194660b73f0fae69571a3f97a045f1d5c2f0e5fbf76e450d0",
32
+ "records": 643587,
33
+ "source_counts": {
34
+ "MSG_Train": 162974,
35
+ "MSP_libraries": 261644,
36
+ "MS2_SAN_JSONL": 218969
37
+ },
38
+ "exclude_heldout_labels_and_negatives_by": "key14",
39
+ "test_or_casmi_labels_in_training": false,
40
+ "preserve_same_structure_multiple_spectra": true,
41
+ "online_queries_during_training": false,
42
+ "coarse_labels_are_training_supervision_not_inference_inputs": true
43
+ },
44
+ "budget": {
45
+ "seeds": [
46
+ 20261103,
47
+ 20261104,
48
+ 20261105
49
+ ],
50
+ "optimizer_updates_per_seed": 6000,
51
+ "learning_rate": 3e-05,
52
+ "minimum_learning_rate": 3e-06,
53
+ "warmup_steps": 300,
54
+ "weight_decay": 0.0001,
55
+ "gradient_clip": 5.0,
56
+ "schedule": "cosine",
57
+ "bf16": true,
58
+ "graph_chunk": 128,
59
+ "spectrum_chunk": 64,
60
+ "pool_micro_views": 4,
61
+ "checkpoint_every": 100,
62
+ "validation_every_updates": 2000,
63
+ "source_presence_schedule": "same_R09_5093_step_epoch_plan",
64
+ "same_MS_exposure_and_candidate_draw_budget_across_arms": true,
65
+ "equal_wall_clock_or_FLOPs_claimed": false
66
+ },
67
+ "model": {
68
+ "backbone": "archived_R2_direct_ranker_256d_6Transformer_6MPNN",
69
+ "backbone_registered_parameters": 16409742,
70
+ "relation_or_cut_enabled": false,
71
+ "projection_heads": {
72
+ "input_dim": 256,
73
+ "hidden_dim": 256,
74
+ "output_dim": 128,
75
+ "activation": "GELU",
76
+ "normalize": "L2",
77
+ "names": [
78
+ "ms_identity",
79
+ "mol_identity",
80
+ "ms_formula",
81
+ "mol_formula",
82
+ "ms_mass",
83
+ "mol_mass"
84
+ ],
85
+ "register_all_heads_in_all_arms": true,
86
+ "shared_backbone_receives_auxiliary_gradients": true
87
+ },
88
+ "head_routing": "separate_by_modality_and_granularity",
89
+ "mass_head_input": "shared_encoder_representation",
90
+ "auxiliary_heads_used_at_inference": false,
91
+ "original_final_ranking_score_unchanged": true
92
+ },
93
+ "sampling": {
94
+ "mode": "hierarchical_formula_identity_spectra",
95
+ "odata_batch_size": 256,
96
+ "msg_batch_size": 32,
97
+ "desired_odata_shape": {
98
+ "formulas": 8,
99
+ "identities_per_formula": 8,
100
+ "spectra_per_identity": 4
101
+ },
102
+ "desired_msg_shape": {
103
+ "formulas": 4,
104
+ "identities_per_formula": 4,
105
+ "spectra_per_identity": 2
106
+ },
107
+ "rare_group_fallback": "pack_remaining_real_records_without_replacement",
108
+ "mass_positive_coverage": "measure_same_formula_and_cross_formula_pairs_separately_do_not_assume_formula_sampler_covers_mass_neighbors",
109
+ "force_duplicate_spectra_to_fill_group": false,
110
+ "each_source_record_once_before_next_source_epoch": true,
111
+ "singleton_policy": "retain_existing_objectives_mask_missing_auxiliary_positives",
112
+ "explicit_odata_queries": 16,
113
+ "odata_negative_draws": 128,
114
+ "msg_views": [
115
+ "mass",
116
+ "formula"
117
+ ],
118
+ "msg_negative_draws_per_view": 63,
119
+ "candidate_draws_with_replacement": true,
120
+ "candidate_pool_deduplicate_key14": false,
121
+ "same_truth_key14_is_never_negative": true
122
+ },
123
+ "views": {
124
+ "MS": {
125
+ "positive_source": "distinct_real_spectra_of_same_key14",
126
+ "spectrum_augmentation": "none",
127
+ "repeat_physical_record_is_not_positive": true
128
+ },
129
+ "molecule": {
130
+ "count": 2,
131
+ "strategy": "independent_hidden_feature_dropout",
132
+ "dropout": 0.1,
133
+ "delete_atoms_or_bonds": false,
134
+ "random_SMILES_alone_is_not_new_view": true
135
+ },
136
+ "primary_encoder_path_dropout": 0.0,
137
+ "compute_two_molecule_views_for_all_arms": true,
138
+ "stochastic_view_gradient_cache": "disabled_keep_view_graph_or_verified_RNG_replay"
139
+ },
140
+ "loss": {
141
+ "base": {
142
+ "formula": 1.0,
143
+ "ms_to_mol": 0.5,
144
+ "mol_to_ms": 0.5,
145
+ "odata_pool": 0.5,
146
+ "msg_mass_pool": 0.25,
147
+ "msg_formula_pool": 0.25
148
+ },
149
+ "formula_task": {
150
+ "ce": 1.0,
151
+ "gap": 0.1,
152
+ "hard_wrong_topk": 3,
153
+ "margin": 0.2,
154
+ "element_count": 0.2
155
+ },
156
+ "auxiliary": {
157
+ "ms_fine": 0.0,
158
+ "mol_fine": 0.0,
159
+ "ms_formula": 0.0,
160
+ "mol_formula": 0.0,
161
+ "ms_mass": 0.025,
162
+ "mol_mass": 0.025
163
+ },
164
+ "auxiliary_ramp_steps": 500,
165
+ "temperature": {
166
+ "identity": 0.1,
167
+ "formula": 0.15,
168
+ "mass": 0.2
169
+ },
170
+ "fine_identity": "key14",
171
+ "self_pairs": "exclude",
172
+ "missing_positive_or_negative": "differentiable_zero_and_log_effective_count",
173
+ "anchor_reduction": {
174
+ "fine": "key14_macro",
175
+ "formula": "formula_macro",
176
+ "mass": "key14_macro"
177
+ },
178
+ "formula_coarse": {
179
+ "label": "exact_element_count_canonical_formula",
180
+ "positive": "same_formula_different_key14",
181
+ "negative": "different_formula",
182
+ "same_key14_pair_policy": "exclude_from_coarse",
183
+ "same_scaffold_is_not_identity_positive": true
184
+ },
185
+ "mass_coarse": {
186
+ "mode": "soft_neighborhood",
187
+ "MS_mass": "abs_charge_times_experimental_precursor_minus_adduct_delta",
188
+ "molecule_mass": "cached_candidate_neutral_monoisotopic_mass",
189
+ "distance_unit": "Da",
190
+ "positive_radius_da": 0.5,
191
+ "negative_start_da": 2.0,
192
+ "gaussian_sigma_da": 0.25,
193
+ "gray_zone": "exclude",
194
+ "same_key14_pair_policy": "exclude_from_coarse",
195
+ "hard_bin_width_da": 1.0,
196
+ "hard_bin_offset_da": 0.0,
197
+ "MS_quality_mask": "reference_precursor_consistency_within_10ppm",
198
+ "candidate_10ppm_filter_is_not_mass_bucket_width": true,
199
+ "mass_neighborhood_is_not_chemical_similarity_or_equivalence_class": true
200
+ }
201
+ },
202
+ "evaluation": {
203
+ "selection_split": "MSG_Validation",
204
+ "spectra": 19429,
205
+ "official_views": [
206
+ "mass",
207
+ "formula"
208
+ ],
209
+ "structure_topk": [
210
+ 1,
211
+ 3,
212
+ 5,
213
+ 10,
214
+ 20,
215
+ 50,
216
+ 100,
217
+ 200
218
+ ],
219
+ "formula_topk": [
220
+ 1,
221
+ 2,
222
+ 3,
223
+ 4,
224
+ 5,
225
+ 6,
226
+ 7,
227
+ 8,
228
+ 9,
229
+ 10,
230
+ 20,
231
+ 50,
232
+ 100,
233
+ 200
234
+ ],
235
+ "primary_score": "harmonic_mean_Mass_Formula_structure_Top1",
236
+ "report_formula_Top1_and_Top10_separately": true,
237
+ "report_spectrum_micro_target_macro_key14_macro": true,
238
+ "coarse_and_fine_retrieval_diagnostics": true,
239
+ "never_filter_official_pools_or_inject_truth": true,
240
+ "test_and_casmi_only_after_predeclared_selection": true,
241
+ "casmi_pool": "data/benchmarks/casmi2022_sirius6312_top10_pubchem_10ppm_connectivity_v1",
242
+ "casmi_candidate_cap": null,
243
+ "casmi_denominator": 500,
244
+ "mces_enabled": false
245
+ },
246
+ "logging": {
247
+ "per_branch_valid_anchors_and_groups": true,
248
+ "positive_negative_and_gray_pair_counts": true,
249
+ "mass_positive_same_formula_vs_cross_formula": true,
250
+ "same_key14_false_negative_count": true,
251
+ "raw_and_weighted_losses": true,
252
+ "gradient_norm_per_task_and_pairwise_gradient_cosine": true,
253
+ "projection_variance_effective_rank_and_pair_similarity": true,
254
+ "per_source_polarity_adduct": true,
255
+ "distinct_MS_exposures_and_repeated_draws": true,
256
+ "GPU_seconds_peak_memory_and_molecule_forward_count": true
257
+ },
258
+ "experiment": {
259
+ "id": "C05_mass_coarse",
260
+ "description": "Neutral-mass neighborhood losses without new fine losses",
261
+ "active_auxiliary_tasks": [
262
+ "ms_mass",
263
+ "mol_mass"
264
+ ],
265
+ "auxiliary_coefficient_sum": 0.05,
266
+ "output_template": "/workspace/xj/SpecPartition-MS/runs/hierarchical_intra_modal_20261103/C05_mass_coarse/seed_{seed}",
267
+ "priority": "secondary_ablation"
268
+ }
269
+ }
code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C06_fine_formula.json ADDED
@@ -0,0 +1,271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": 1,
3
+ "suite_id": "hierarchical_intra_modal_20261103",
4
+ "execution": {
5
+ "status": "configuration_and_loss_components_only",
6
+ "allow_training": false,
7
+ "runtime_entrypoint": null,
8
+ "missing_integration": [
9
+ "hierarchical_no_repeat_sampler",
10
+ "independent_stochastic_gnn_views",
11
+ "rng_safe_view_recomputation",
12
+ "joint_loss_router_and_gpu_acceptance"
13
+ ]
14
+ },
15
+ "initialization": {
16
+ "checkpoint": "/workspace/xj/SpecPartition-MS/runs/rebuild_joint_r08data_20261102/epoch_04.pt",
17
+ "sha256": "618aaf195cfdc3a4107e71cf2b3a56d5853b407564acf01de11c67e6af40f3d7",
18
+ "policy": "same_fixed_parent_weights_all_arms",
19
+ "optimizer_policy": "new_AdamW_for_every_arm_not_live_run_resume",
20
+ "selection_source": "Validation_only_fixed_before_ablation",
21
+ "new_heads": "same_initialization_per_seed_for_all_arms"
22
+ },
23
+ "data": {
24
+ "root": "/workspace/xj/SpecPartition-MS",
25
+ "labels": "data/derived/data_release_r07_key14_20261101/train.json",
26
+ "prepared": "data/derived/joint_r09_inputs_20261102/train.sqlite",
27
+ "candidates": "data/derived/training_r08_true_formula_records_20261101/preparation.sqlite",
28
+ "heldout_registry": "data/derived/data_release_r07_key14_20261101/heldout_registry.json",
29
+ "label_policy_sha256": "91971b3f6979586b32c90350330cb6712e60c3c6f4b872de4113311f8a95adf7",
30
+ "candidate_config_sha256": "53a365647ed8c54e216ff2cd25c011ed7f7d47a920f54c0136eea0c8dabade65",
31
+ "parent_training_config_sha256": "5f8f8635c60e37a194660b73f0fae69571a3f97a045f1d5c2f0e5fbf76e450d0",
32
+ "records": 643587,
33
+ "source_counts": {
34
+ "MSG_Train": 162974,
35
+ "MSP_libraries": 261644,
36
+ "MS2_SAN_JSONL": 218969
37
+ },
38
+ "exclude_heldout_labels_and_negatives_by": "key14",
39
+ "test_or_casmi_labels_in_training": false,
40
+ "preserve_same_structure_multiple_spectra": true,
41
+ "online_queries_during_training": false,
42
+ "coarse_labels_are_training_supervision_not_inference_inputs": true
43
+ },
44
+ "budget": {
45
+ "seeds": [
46
+ 20261103,
47
+ 20261104,
48
+ 20261105
49
+ ],
50
+ "optimizer_updates_per_seed": 6000,
51
+ "learning_rate": 3e-05,
52
+ "minimum_learning_rate": 3e-06,
53
+ "warmup_steps": 300,
54
+ "weight_decay": 0.0001,
55
+ "gradient_clip": 5.0,
56
+ "schedule": "cosine",
57
+ "bf16": true,
58
+ "graph_chunk": 128,
59
+ "spectrum_chunk": 64,
60
+ "pool_micro_views": 4,
61
+ "checkpoint_every": 100,
62
+ "validation_every_updates": 2000,
63
+ "source_presence_schedule": "same_R09_5093_step_epoch_plan",
64
+ "same_MS_exposure_and_candidate_draw_budget_across_arms": true,
65
+ "equal_wall_clock_or_FLOPs_claimed": false
66
+ },
67
+ "model": {
68
+ "backbone": "archived_R2_direct_ranker_256d_6Transformer_6MPNN",
69
+ "backbone_registered_parameters": 16409742,
70
+ "relation_or_cut_enabled": false,
71
+ "projection_heads": {
72
+ "input_dim": 256,
73
+ "hidden_dim": 256,
74
+ "output_dim": 128,
75
+ "activation": "GELU",
76
+ "normalize": "L2",
77
+ "names": [
78
+ "ms_identity",
79
+ "mol_identity",
80
+ "ms_formula",
81
+ "mol_formula",
82
+ "ms_mass",
83
+ "mol_mass"
84
+ ],
85
+ "register_all_heads_in_all_arms": true,
86
+ "shared_backbone_receives_auxiliary_gradients": true
87
+ },
88
+ "head_routing": "separate_by_modality_and_granularity",
89
+ "mass_head_input": "shared_encoder_representation",
90
+ "auxiliary_heads_used_at_inference": false,
91
+ "original_final_ranking_score_unchanged": true
92
+ },
93
+ "sampling": {
94
+ "mode": "hierarchical_formula_identity_spectra",
95
+ "odata_batch_size": 256,
96
+ "msg_batch_size": 32,
97
+ "desired_odata_shape": {
98
+ "formulas": 8,
99
+ "identities_per_formula": 8,
100
+ "spectra_per_identity": 4
101
+ },
102
+ "desired_msg_shape": {
103
+ "formulas": 4,
104
+ "identities_per_formula": 4,
105
+ "spectra_per_identity": 2
106
+ },
107
+ "rare_group_fallback": "pack_remaining_real_records_without_replacement",
108
+ "mass_positive_coverage": "measure_same_formula_and_cross_formula_pairs_separately_do_not_assume_formula_sampler_covers_mass_neighbors",
109
+ "force_duplicate_spectra_to_fill_group": false,
110
+ "each_source_record_once_before_next_source_epoch": true,
111
+ "singleton_policy": "retain_existing_objectives_mask_missing_auxiliary_positives",
112
+ "explicit_odata_queries": 16,
113
+ "odata_negative_draws": 128,
114
+ "msg_views": [
115
+ "mass",
116
+ "formula"
117
+ ],
118
+ "msg_negative_draws_per_view": 63,
119
+ "candidate_draws_with_replacement": true,
120
+ "candidate_pool_deduplicate_key14": false,
121
+ "same_truth_key14_is_never_negative": true
122
+ },
123
+ "views": {
124
+ "MS": {
125
+ "positive_source": "distinct_real_spectra_of_same_key14",
126
+ "spectrum_augmentation": "none",
127
+ "repeat_physical_record_is_not_positive": true
128
+ },
129
+ "molecule": {
130
+ "count": 2,
131
+ "strategy": "independent_hidden_feature_dropout",
132
+ "dropout": 0.1,
133
+ "delete_atoms_or_bonds": false,
134
+ "random_SMILES_alone_is_not_new_view": true
135
+ },
136
+ "primary_encoder_path_dropout": 0.0,
137
+ "compute_two_molecule_views_for_all_arms": true,
138
+ "stochastic_view_gradient_cache": "disabled_keep_view_graph_or_verified_RNG_replay"
139
+ },
140
+ "loss": {
141
+ "base": {
142
+ "formula": 1.0,
143
+ "ms_to_mol": 0.5,
144
+ "mol_to_ms": 0.5,
145
+ "odata_pool": 0.5,
146
+ "msg_mass_pool": 0.25,
147
+ "msg_formula_pool": 0.25
148
+ },
149
+ "formula_task": {
150
+ "ce": 1.0,
151
+ "gap": 0.1,
152
+ "hard_wrong_topk": 3,
153
+ "margin": 0.2,
154
+ "element_count": 0.2
155
+ },
156
+ "auxiliary": {
157
+ "ms_fine": 0.1,
158
+ "mol_fine": 0.05,
159
+ "ms_formula": 0.05,
160
+ "mol_formula": 0.05,
161
+ "ms_mass": 0.0,
162
+ "mol_mass": 0.0
163
+ },
164
+ "auxiliary_ramp_steps": 500,
165
+ "temperature": {
166
+ "identity": 0.1,
167
+ "formula": 0.15,
168
+ "mass": 0.2
169
+ },
170
+ "fine_identity": "key14",
171
+ "self_pairs": "exclude",
172
+ "missing_positive_or_negative": "differentiable_zero_and_log_effective_count",
173
+ "anchor_reduction": {
174
+ "fine": "key14_macro",
175
+ "formula": "formula_macro",
176
+ "mass": "key14_macro"
177
+ },
178
+ "formula_coarse": {
179
+ "label": "exact_element_count_canonical_formula",
180
+ "positive": "same_formula_different_key14",
181
+ "negative": "different_formula",
182
+ "same_key14_pair_policy": "exclude_from_coarse",
183
+ "same_scaffold_is_not_identity_positive": true
184
+ },
185
+ "mass_coarse": {
186
+ "mode": "soft_neighborhood",
187
+ "MS_mass": "abs_charge_times_experimental_precursor_minus_adduct_delta",
188
+ "molecule_mass": "cached_candidate_neutral_monoisotopic_mass",
189
+ "distance_unit": "Da",
190
+ "positive_radius_da": 0.5,
191
+ "negative_start_da": 2.0,
192
+ "gaussian_sigma_da": 0.25,
193
+ "gray_zone": "exclude",
194
+ "same_key14_pair_policy": "exclude_from_coarse",
195
+ "hard_bin_width_da": 1.0,
196
+ "hard_bin_offset_da": 0.0,
197
+ "MS_quality_mask": "reference_precursor_consistency_within_10ppm",
198
+ "candidate_10ppm_filter_is_not_mass_bucket_width": true,
199
+ "mass_neighborhood_is_not_chemical_similarity_or_equivalence_class": true
200
+ }
201
+ },
202
+ "evaluation": {
203
+ "selection_split": "MSG_Validation",
204
+ "spectra": 19429,
205
+ "official_views": [
206
+ "mass",
207
+ "formula"
208
+ ],
209
+ "structure_topk": [
210
+ 1,
211
+ 3,
212
+ 5,
213
+ 10,
214
+ 20,
215
+ 50,
216
+ 100,
217
+ 200
218
+ ],
219
+ "formula_topk": [
220
+ 1,
221
+ 2,
222
+ 3,
223
+ 4,
224
+ 5,
225
+ 6,
226
+ 7,
227
+ 8,
228
+ 9,
229
+ 10,
230
+ 20,
231
+ 50,
232
+ 100,
233
+ 200
234
+ ],
235
+ "primary_score": "harmonic_mean_Mass_Formula_structure_Top1",
236
+ "report_formula_Top1_and_Top10_separately": true,
237
+ "report_spectrum_micro_target_macro_key14_macro": true,
238
+ "coarse_and_fine_retrieval_diagnostics": true,
239
+ "never_filter_official_pools_or_inject_truth": true,
240
+ "test_and_casmi_only_after_predeclared_selection": true,
241
+ "casmi_pool": "data/benchmarks/casmi2022_sirius6312_top10_pubchem_10ppm_connectivity_v1",
242
+ "casmi_candidate_cap": null,
243
+ "casmi_denominator": 500,
244
+ "mces_enabled": false
245
+ },
246
+ "logging": {
247
+ "per_branch_valid_anchors_and_groups": true,
248
+ "positive_negative_and_gray_pair_counts": true,
249
+ "mass_positive_same_formula_vs_cross_formula": true,
250
+ "same_key14_false_negative_count": true,
251
+ "raw_and_weighted_losses": true,
252
+ "gradient_norm_per_task_and_pairwise_gradient_cosine": true,
253
+ "projection_variance_effective_rank_and_pair_similarity": true,
254
+ "per_source_polarity_adduct": true,
255
+ "distinct_MS_exposures_and_repeated_draws": true,
256
+ "GPU_seconds_peak_memory_and_molecule_forward_count": true
257
+ },
258
+ "experiment": {
259
+ "id": "C06_fine_formula",
260
+ "description": "Fine identity plus exact-formula coarse heads",
261
+ "active_auxiliary_tasks": [
262
+ "ms_fine",
263
+ "mol_fine",
264
+ "ms_formula",
265
+ "mol_formula"
266
+ ],
267
+ "auxiliary_coefficient_sum": 0.25,
268
+ "output_template": "/workspace/xj/SpecPartition-MS/runs/hierarchical_intra_modal_20261103/C06_fine_formula/seed_{seed}",
269
+ "priority": "first_pass"
270
+ }
271
+ }
code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C07_fine_mass.json ADDED
@@ -0,0 +1,271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": 1,
3
+ "suite_id": "hierarchical_intra_modal_20261103",
4
+ "execution": {
5
+ "status": "configuration_and_loss_components_only",
6
+ "allow_training": false,
7
+ "runtime_entrypoint": null,
8
+ "missing_integration": [
9
+ "hierarchical_no_repeat_sampler",
10
+ "independent_stochastic_gnn_views",
11
+ "rng_safe_view_recomputation",
12
+ "joint_loss_router_and_gpu_acceptance"
13
+ ]
14
+ },
15
+ "initialization": {
16
+ "checkpoint": "/workspace/xj/SpecPartition-MS/runs/rebuild_joint_r08data_20261102/epoch_04.pt",
17
+ "sha256": "618aaf195cfdc3a4107e71cf2b3a56d5853b407564acf01de11c67e6af40f3d7",
18
+ "policy": "same_fixed_parent_weights_all_arms",
19
+ "optimizer_policy": "new_AdamW_for_every_arm_not_live_run_resume",
20
+ "selection_source": "Validation_only_fixed_before_ablation",
21
+ "new_heads": "same_initialization_per_seed_for_all_arms"
22
+ },
23
+ "data": {
24
+ "root": "/workspace/xj/SpecPartition-MS",
25
+ "labels": "data/derived/data_release_r07_key14_20261101/train.json",
26
+ "prepared": "data/derived/joint_r09_inputs_20261102/train.sqlite",
27
+ "candidates": "data/derived/training_r08_true_formula_records_20261101/preparation.sqlite",
28
+ "heldout_registry": "data/derived/data_release_r07_key14_20261101/heldout_registry.json",
29
+ "label_policy_sha256": "91971b3f6979586b32c90350330cb6712e60c3c6f4b872de4113311f8a95adf7",
30
+ "candidate_config_sha256": "53a365647ed8c54e216ff2cd25c011ed7f7d47a920f54c0136eea0c8dabade65",
31
+ "parent_training_config_sha256": "5f8f8635c60e37a194660b73f0fae69571a3f97a045f1d5c2f0e5fbf76e450d0",
32
+ "records": 643587,
33
+ "source_counts": {
34
+ "MSG_Train": 162974,
35
+ "MSP_libraries": 261644,
36
+ "MS2_SAN_JSONL": 218969
37
+ },
38
+ "exclude_heldout_labels_and_negatives_by": "key14",
39
+ "test_or_casmi_labels_in_training": false,
40
+ "preserve_same_structure_multiple_spectra": true,
41
+ "online_queries_during_training": false,
42
+ "coarse_labels_are_training_supervision_not_inference_inputs": true
43
+ },
44
+ "budget": {
45
+ "seeds": [
46
+ 20261103,
47
+ 20261104,
48
+ 20261105
49
+ ],
50
+ "optimizer_updates_per_seed": 6000,
51
+ "learning_rate": 3e-05,
52
+ "minimum_learning_rate": 3e-06,
53
+ "warmup_steps": 300,
54
+ "weight_decay": 0.0001,
55
+ "gradient_clip": 5.0,
56
+ "schedule": "cosine",
57
+ "bf16": true,
58
+ "graph_chunk": 128,
59
+ "spectrum_chunk": 64,
60
+ "pool_micro_views": 4,
61
+ "checkpoint_every": 100,
62
+ "validation_every_updates": 2000,
63
+ "source_presence_schedule": "same_R09_5093_step_epoch_plan",
64
+ "same_MS_exposure_and_candidate_draw_budget_across_arms": true,
65
+ "equal_wall_clock_or_FLOPs_claimed": false
66
+ },
67
+ "model": {
68
+ "backbone": "archived_R2_direct_ranker_256d_6Transformer_6MPNN",
69
+ "backbone_registered_parameters": 16409742,
70
+ "relation_or_cut_enabled": false,
71
+ "projection_heads": {
72
+ "input_dim": 256,
73
+ "hidden_dim": 256,
74
+ "output_dim": 128,
75
+ "activation": "GELU",
76
+ "normalize": "L2",
77
+ "names": [
78
+ "ms_identity",
79
+ "mol_identity",
80
+ "ms_formula",
81
+ "mol_formula",
82
+ "ms_mass",
83
+ "mol_mass"
84
+ ],
85
+ "register_all_heads_in_all_arms": true,
86
+ "shared_backbone_receives_auxiliary_gradients": true
87
+ },
88
+ "head_routing": "separate_by_modality_and_granularity",
89
+ "mass_head_input": "shared_encoder_representation",
90
+ "auxiliary_heads_used_at_inference": false,
91
+ "original_final_ranking_score_unchanged": true
92
+ },
93
+ "sampling": {
94
+ "mode": "hierarchical_formula_identity_spectra",
95
+ "odata_batch_size": 256,
96
+ "msg_batch_size": 32,
97
+ "desired_odata_shape": {
98
+ "formulas": 8,
99
+ "identities_per_formula": 8,
100
+ "spectra_per_identity": 4
101
+ },
102
+ "desired_msg_shape": {
103
+ "formulas": 4,
104
+ "identities_per_formula": 4,
105
+ "spectra_per_identity": 2
106
+ },
107
+ "rare_group_fallback": "pack_remaining_real_records_without_replacement",
108
+ "mass_positive_coverage": "measure_same_formula_and_cross_formula_pairs_separately_do_not_assume_formula_sampler_covers_mass_neighbors",
109
+ "force_duplicate_spectra_to_fill_group": false,
110
+ "each_source_record_once_before_next_source_epoch": true,
111
+ "singleton_policy": "retain_existing_objectives_mask_missing_auxiliary_positives",
112
+ "explicit_odata_queries": 16,
113
+ "odata_negative_draws": 128,
114
+ "msg_views": [
115
+ "mass",
116
+ "formula"
117
+ ],
118
+ "msg_negative_draws_per_view": 63,
119
+ "candidate_draws_with_replacement": true,
120
+ "candidate_pool_deduplicate_key14": false,
121
+ "same_truth_key14_is_never_negative": true
122
+ },
123
+ "views": {
124
+ "MS": {
125
+ "positive_source": "distinct_real_spectra_of_same_key14",
126
+ "spectrum_augmentation": "none",
127
+ "repeat_physical_record_is_not_positive": true
128
+ },
129
+ "molecule": {
130
+ "count": 2,
131
+ "strategy": "independent_hidden_feature_dropout",
132
+ "dropout": 0.1,
133
+ "delete_atoms_or_bonds": false,
134
+ "random_SMILES_alone_is_not_new_view": true
135
+ },
136
+ "primary_encoder_path_dropout": 0.0,
137
+ "compute_two_molecule_views_for_all_arms": true,
138
+ "stochastic_view_gradient_cache": "disabled_keep_view_graph_or_verified_RNG_replay"
139
+ },
140
+ "loss": {
141
+ "base": {
142
+ "formula": 1.0,
143
+ "ms_to_mol": 0.5,
144
+ "mol_to_ms": 0.5,
145
+ "odata_pool": 0.5,
146
+ "msg_mass_pool": 0.25,
147
+ "msg_formula_pool": 0.25
148
+ },
149
+ "formula_task": {
150
+ "ce": 1.0,
151
+ "gap": 0.1,
152
+ "hard_wrong_topk": 3,
153
+ "margin": 0.2,
154
+ "element_count": 0.2
155
+ },
156
+ "auxiliary": {
157
+ "ms_fine": 0.1,
158
+ "mol_fine": 0.05,
159
+ "ms_formula": 0.0,
160
+ "mol_formula": 0.0,
161
+ "ms_mass": 0.025,
162
+ "mol_mass": 0.025
163
+ },
164
+ "auxiliary_ramp_steps": 500,
165
+ "temperature": {
166
+ "identity": 0.1,
167
+ "formula": 0.15,
168
+ "mass": 0.2
169
+ },
170
+ "fine_identity": "key14",
171
+ "self_pairs": "exclude",
172
+ "missing_positive_or_negative": "differentiable_zero_and_log_effective_count",
173
+ "anchor_reduction": {
174
+ "fine": "key14_macro",
175
+ "formula": "formula_macro",
176
+ "mass": "key14_macro"
177
+ },
178
+ "formula_coarse": {
179
+ "label": "exact_element_count_canonical_formula",
180
+ "positive": "same_formula_different_key14",
181
+ "negative": "different_formula",
182
+ "same_key14_pair_policy": "exclude_from_coarse",
183
+ "same_scaffold_is_not_identity_positive": true
184
+ },
185
+ "mass_coarse": {
186
+ "mode": "soft_neighborhood",
187
+ "MS_mass": "abs_charge_times_experimental_precursor_minus_adduct_delta",
188
+ "molecule_mass": "cached_candidate_neutral_monoisotopic_mass",
189
+ "distance_unit": "Da",
190
+ "positive_radius_da": 0.5,
191
+ "negative_start_da": 2.0,
192
+ "gaussian_sigma_da": 0.25,
193
+ "gray_zone": "exclude",
194
+ "same_key14_pair_policy": "exclude_from_coarse",
195
+ "hard_bin_width_da": 1.0,
196
+ "hard_bin_offset_da": 0.0,
197
+ "MS_quality_mask": "reference_precursor_consistency_within_10ppm",
198
+ "candidate_10ppm_filter_is_not_mass_bucket_width": true,
199
+ "mass_neighborhood_is_not_chemical_similarity_or_equivalence_class": true
200
+ }
201
+ },
202
+ "evaluation": {
203
+ "selection_split": "MSG_Validation",
204
+ "spectra": 19429,
205
+ "official_views": [
206
+ "mass",
207
+ "formula"
208
+ ],
209
+ "structure_topk": [
210
+ 1,
211
+ 3,
212
+ 5,
213
+ 10,
214
+ 20,
215
+ 50,
216
+ 100,
217
+ 200
218
+ ],
219
+ "formula_topk": [
220
+ 1,
221
+ 2,
222
+ 3,
223
+ 4,
224
+ 5,
225
+ 6,
226
+ 7,
227
+ 8,
228
+ 9,
229
+ 10,
230
+ 20,
231
+ 50,
232
+ 100,
233
+ 200
234
+ ],
235
+ "primary_score": "harmonic_mean_Mass_Formula_structure_Top1",
236
+ "report_formula_Top1_and_Top10_separately": true,
237
+ "report_spectrum_micro_target_macro_key14_macro": true,
238
+ "coarse_and_fine_retrieval_diagnostics": true,
239
+ "never_filter_official_pools_or_inject_truth": true,
240
+ "test_and_casmi_only_after_predeclared_selection": true,
241
+ "casmi_pool": "data/benchmarks/casmi2022_sirius6312_top10_pubchem_10ppm_connectivity_v1",
242
+ "casmi_candidate_cap": null,
243
+ "casmi_denominator": 500,
244
+ "mces_enabled": false
245
+ },
246
+ "logging": {
247
+ "per_branch_valid_anchors_and_groups": true,
248
+ "positive_negative_and_gray_pair_counts": true,
249
+ "mass_positive_same_formula_vs_cross_formula": true,
250
+ "same_key14_false_negative_count": true,
251
+ "raw_and_weighted_losses": true,
252
+ "gradient_norm_per_task_and_pairwise_gradient_cosine": true,
253
+ "projection_variance_effective_rank_and_pair_similarity": true,
254
+ "per_source_polarity_adduct": true,
255
+ "distinct_MS_exposures_and_repeated_draws": true,
256
+ "GPU_seconds_peak_memory_and_molecule_forward_count": true
257
+ },
258
+ "experiment": {
259
+ "id": "C07_fine_mass",
260
+ "description": "Fine identity plus neutral-mass neighborhood heads",
261
+ "active_auxiliary_tasks": [
262
+ "ms_fine",
263
+ "mol_fine",
264
+ "ms_mass",
265
+ "mol_mass"
266
+ ],
267
+ "auxiliary_coefficient_sum": 0.2,
268
+ "output_template": "/workspace/xj/SpecPartition-MS/runs/hierarchical_intra_modal_20261103/C07_fine_mass/seed_{seed}",
269
+ "priority": "first_pass"
270
+ }
271
+ }
code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C08_full_separate.json ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": 1,
3
+ "suite_id": "hierarchical_intra_modal_20261103",
4
+ "execution": {
5
+ "status": "configuration_and_loss_components_only",
6
+ "allow_training": false,
7
+ "runtime_entrypoint": null,
8
+ "missing_integration": [
9
+ "hierarchical_no_repeat_sampler",
10
+ "independent_stochastic_gnn_views",
11
+ "rng_safe_view_recomputation",
12
+ "joint_loss_router_and_gpu_acceptance"
13
+ ]
14
+ },
15
+ "initialization": {
16
+ "checkpoint": "/workspace/xj/SpecPartition-MS/runs/rebuild_joint_r08data_20261102/epoch_04.pt",
17
+ "sha256": "618aaf195cfdc3a4107e71cf2b3a56d5853b407564acf01de11c67e6af40f3d7",
18
+ "policy": "same_fixed_parent_weights_all_arms",
19
+ "optimizer_policy": "new_AdamW_for_every_arm_not_live_run_resume",
20
+ "selection_source": "Validation_only_fixed_before_ablation",
21
+ "new_heads": "same_initialization_per_seed_for_all_arms"
22
+ },
23
+ "data": {
24
+ "root": "/workspace/xj/SpecPartition-MS",
25
+ "labels": "data/derived/data_release_r07_key14_20261101/train.json",
26
+ "prepared": "data/derived/joint_r09_inputs_20261102/train.sqlite",
27
+ "candidates": "data/derived/training_r08_true_formula_records_20261101/preparation.sqlite",
28
+ "heldout_registry": "data/derived/data_release_r07_key14_20261101/heldout_registry.json",
29
+ "label_policy_sha256": "91971b3f6979586b32c90350330cb6712e60c3c6f4b872de4113311f8a95adf7",
30
+ "candidate_config_sha256": "53a365647ed8c54e216ff2cd25c011ed7f7d47a920f54c0136eea0c8dabade65",
31
+ "parent_training_config_sha256": "5f8f8635c60e37a194660b73f0fae69571a3f97a045f1d5c2f0e5fbf76e450d0",
32
+ "records": 643587,
33
+ "source_counts": {
34
+ "MSG_Train": 162974,
35
+ "MSP_libraries": 261644,
36
+ "MS2_SAN_JSONL": 218969
37
+ },
38
+ "exclude_heldout_labels_and_negatives_by": "key14",
39
+ "test_or_casmi_labels_in_training": false,
40
+ "preserve_same_structure_multiple_spectra": true,
41
+ "online_queries_during_training": false,
42
+ "coarse_labels_are_training_supervision_not_inference_inputs": true
43
+ },
44
+ "budget": {
45
+ "seeds": [
46
+ 20261103,
47
+ 20261104,
48
+ 20261105
49
+ ],
50
+ "optimizer_updates_per_seed": 6000,
51
+ "learning_rate": 3e-05,
52
+ "minimum_learning_rate": 3e-06,
53
+ "warmup_steps": 300,
54
+ "weight_decay": 0.0001,
55
+ "gradient_clip": 5.0,
56
+ "schedule": "cosine",
57
+ "bf16": true,
58
+ "graph_chunk": 128,
59
+ "spectrum_chunk": 64,
60
+ "pool_micro_views": 4,
61
+ "checkpoint_every": 100,
62
+ "validation_every_updates": 2000,
63
+ "source_presence_schedule": "same_R09_5093_step_epoch_plan",
64
+ "same_MS_exposure_and_candidate_draw_budget_across_arms": true,
65
+ "equal_wall_clock_or_FLOPs_claimed": false
66
+ },
67
+ "model": {
68
+ "backbone": "archived_R2_direct_ranker_256d_6Transformer_6MPNN",
69
+ "backbone_registered_parameters": 16409742,
70
+ "relation_or_cut_enabled": false,
71
+ "projection_heads": {
72
+ "input_dim": 256,
73
+ "hidden_dim": 256,
74
+ "output_dim": 128,
75
+ "activation": "GELU",
76
+ "normalize": "L2",
77
+ "names": [
78
+ "ms_identity",
79
+ "mol_identity",
80
+ "ms_formula",
81
+ "mol_formula",
82
+ "ms_mass",
83
+ "mol_mass"
84
+ ],
85
+ "register_all_heads_in_all_arms": true,
86
+ "shared_backbone_receives_auxiliary_gradients": true
87
+ },
88
+ "head_routing": "separate_by_modality_and_granularity",
89
+ "mass_head_input": "shared_encoder_representation",
90
+ "auxiliary_heads_used_at_inference": false,
91
+ "original_final_ranking_score_unchanged": true
92
+ },
93
+ "sampling": {
94
+ "mode": "hierarchical_formula_identity_spectra",
95
+ "odata_batch_size": 256,
96
+ "msg_batch_size": 32,
97
+ "desired_odata_shape": {
98
+ "formulas": 8,
99
+ "identities_per_formula": 8,
100
+ "spectra_per_identity": 4
101
+ },
102
+ "desired_msg_shape": {
103
+ "formulas": 4,
104
+ "identities_per_formula": 4,
105
+ "spectra_per_identity": 2
106
+ },
107
+ "rare_group_fallback": "pack_remaining_real_records_without_replacement",
108
+ "mass_positive_coverage": "measure_same_formula_and_cross_formula_pairs_separately_do_not_assume_formula_sampler_covers_mass_neighbors",
109
+ "force_duplicate_spectra_to_fill_group": false,
110
+ "each_source_record_once_before_next_source_epoch": true,
111
+ "singleton_policy": "retain_existing_objectives_mask_missing_auxiliary_positives",
112
+ "explicit_odata_queries": 16,
113
+ "odata_negative_draws": 128,
114
+ "msg_views": [
115
+ "mass",
116
+ "formula"
117
+ ],
118
+ "msg_negative_draws_per_view": 63,
119
+ "candidate_draws_with_replacement": true,
120
+ "candidate_pool_deduplicate_key14": false,
121
+ "same_truth_key14_is_never_negative": true
122
+ },
123
+ "views": {
124
+ "MS": {
125
+ "positive_source": "distinct_real_spectra_of_same_key14",
126
+ "spectrum_augmentation": "none",
127
+ "repeat_physical_record_is_not_positive": true
128
+ },
129
+ "molecule": {
130
+ "count": 2,
131
+ "strategy": "independent_hidden_feature_dropout",
132
+ "dropout": 0.1,
133
+ "delete_atoms_or_bonds": false,
134
+ "random_SMILES_alone_is_not_new_view": true
135
+ },
136
+ "primary_encoder_path_dropout": 0.0,
137
+ "compute_two_molecule_views_for_all_arms": true,
138
+ "stochastic_view_gradient_cache": "disabled_keep_view_graph_or_verified_RNG_replay"
139
+ },
140
+ "loss": {
141
+ "base": {
142
+ "formula": 1.0,
143
+ "ms_to_mol": 0.5,
144
+ "mol_to_ms": 0.5,
145
+ "odata_pool": 0.5,
146
+ "msg_mass_pool": 0.25,
147
+ "msg_formula_pool": 0.25
148
+ },
149
+ "formula_task": {
150
+ "ce": 1.0,
151
+ "gap": 0.1,
152
+ "hard_wrong_topk": 3,
153
+ "margin": 0.2,
154
+ "element_count": 0.2
155
+ },
156
+ "auxiliary": {
157
+ "ms_fine": 0.1,
158
+ "mol_fine": 0.05,
159
+ "ms_formula": 0.05,
160
+ "mol_formula": 0.05,
161
+ "ms_mass": 0.025,
162
+ "mol_mass": 0.025
163
+ },
164
+ "auxiliary_ramp_steps": 500,
165
+ "temperature": {
166
+ "identity": 0.1,
167
+ "formula": 0.15,
168
+ "mass": 0.2
169
+ },
170
+ "fine_identity": "key14",
171
+ "self_pairs": "exclude",
172
+ "missing_positive_or_negative": "differentiable_zero_and_log_effective_count",
173
+ "anchor_reduction": {
174
+ "fine": "key14_macro",
175
+ "formula": "formula_macro",
176
+ "mass": "key14_macro"
177
+ },
178
+ "formula_coarse": {
179
+ "label": "exact_element_count_canonical_formula",
180
+ "positive": "same_formula_different_key14",
181
+ "negative": "different_formula",
182
+ "same_key14_pair_policy": "exclude_from_coarse",
183
+ "same_scaffold_is_not_identity_positive": true
184
+ },
185
+ "mass_coarse": {
186
+ "mode": "soft_neighborhood",
187
+ "MS_mass": "abs_charge_times_experimental_precursor_minus_adduct_delta",
188
+ "molecule_mass": "cached_candidate_neutral_monoisotopic_mass",
189
+ "distance_unit": "Da",
190
+ "positive_radius_da": 0.5,
191
+ "negative_start_da": 2.0,
192
+ "gaussian_sigma_da": 0.25,
193
+ "gray_zone": "exclude",
194
+ "same_key14_pair_policy": "exclude_from_coarse",
195
+ "hard_bin_width_da": 1.0,
196
+ "hard_bin_offset_da": 0.0,
197
+ "MS_quality_mask": "reference_precursor_consistency_within_10ppm",
198
+ "candidate_10ppm_filter_is_not_mass_bucket_width": true,
199
+ "mass_neighborhood_is_not_chemical_similarity_or_equivalence_class": true
200
+ }
201
+ },
202
+ "evaluation": {
203
+ "selection_split": "MSG_Validation",
204
+ "spectra": 19429,
205
+ "official_views": [
206
+ "mass",
207
+ "formula"
208
+ ],
209
+ "structure_topk": [
210
+ 1,
211
+ 3,
212
+ 5,
213
+ 10,
214
+ 20,
215
+ 50,
216
+ 100,
217
+ 200
218
+ ],
219
+ "formula_topk": [
220
+ 1,
221
+ 2,
222
+ 3,
223
+ 4,
224
+ 5,
225
+ 6,
226
+ 7,
227
+ 8,
228
+ 9,
229
+ 10,
230
+ 20,
231
+ 50,
232
+ 100,
233
+ 200
234
+ ],
235
+ "primary_score": "harmonic_mean_Mass_Formula_structure_Top1",
236
+ "report_formula_Top1_and_Top10_separately": true,
237
+ "report_spectrum_micro_target_macro_key14_macro": true,
238
+ "coarse_and_fine_retrieval_diagnostics": true,
239
+ "never_filter_official_pools_or_inject_truth": true,
240
+ "test_and_casmi_only_after_predeclared_selection": true,
241
+ "casmi_pool": "data/benchmarks/casmi2022_sirius6312_top10_pubchem_10ppm_connectivity_v1",
242
+ "casmi_candidate_cap": null,
243
+ "casmi_denominator": 500,
244
+ "mces_enabled": false
245
+ },
246
+ "logging": {
247
+ "per_branch_valid_anchors_and_groups": true,
248
+ "positive_negative_and_gray_pair_counts": true,
249
+ "mass_positive_same_formula_vs_cross_formula": true,
250
+ "same_key14_false_negative_count": true,
251
+ "raw_and_weighted_losses": true,
252
+ "gradient_norm_per_task_and_pairwise_gradient_cosine": true,
253
+ "projection_variance_effective_rank_and_pair_similarity": true,
254
+ "per_source_polarity_adduct": true,
255
+ "distinct_MS_exposures_and_repeated_draws": true,
256
+ "GPU_seconds_peak_memory_and_molecule_forward_count": true
257
+ },
258
+ "experiment": {
259
+ "id": "C08_full_separate",
260
+ "description": "Full separate-head starting proposal, not proven optimal",
261
+ "active_auxiliary_tasks": [
262
+ "ms_fine",
263
+ "mol_fine",
264
+ "ms_formula",
265
+ "mol_formula",
266
+ "ms_mass",
267
+ "mol_mass"
268
+ ],
269
+ "auxiliary_coefficient_sum": 0.3,
270
+ "output_template": "/workspace/xj/SpecPartition-MS/runs/hierarchical_intra_modal_20261103/C08_full_separate/seed_{seed}",
271
+ "priority": "first_pass"
272
+ }
273
+ }
code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C09_shared_head_control.json ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": 1,
3
+ "suite_id": "hierarchical_intra_modal_20261103",
4
+ "execution": {
5
+ "status": "configuration_and_loss_components_only",
6
+ "allow_training": false,
7
+ "runtime_entrypoint": null,
8
+ "missing_integration": [
9
+ "hierarchical_no_repeat_sampler",
10
+ "independent_stochastic_gnn_views",
11
+ "rng_safe_view_recomputation",
12
+ "joint_loss_router_and_gpu_acceptance"
13
+ ]
14
+ },
15
+ "initialization": {
16
+ "checkpoint": "/workspace/xj/SpecPartition-MS/runs/rebuild_joint_r08data_20261102/epoch_04.pt",
17
+ "sha256": "618aaf195cfdc3a4107e71cf2b3a56d5853b407564acf01de11c67e6af40f3d7",
18
+ "policy": "same_fixed_parent_weights_all_arms",
19
+ "optimizer_policy": "new_AdamW_for_every_arm_not_live_run_resume",
20
+ "selection_source": "Validation_only_fixed_before_ablation",
21
+ "new_heads": "same_initialization_per_seed_for_all_arms"
22
+ },
23
+ "data": {
24
+ "root": "/workspace/xj/SpecPartition-MS",
25
+ "labels": "data/derived/data_release_r07_key14_20261101/train.json",
26
+ "prepared": "data/derived/joint_r09_inputs_20261102/train.sqlite",
27
+ "candidates": "data/derived/training_r08_true_formula_records_20261101/preparation.sqlite",
28
+ "heldout_registry": "data/derived/data_release_r07_key14_20261101/heldout_registry.json",
29
+ "label_policy_sha256": "91971b3f6979586b32c90350330cb6712e60c3c6f4b872de4113311f8a95adf7",
30
+ "candidate_config_sha256": "53a365647ed8c54e216ff2cd25c011ed7f7d47a920f54c0136eea0c8dabade65",
31
+ "parent_training_config_sha256": "5f8f8635c60e37a194660b73f0fae69571a3f97a045f1d5c2f0e5fbf76e450d0",
32
+ "records": 643587,
33
+ "source_counts": {
34
+ "MSG_Train": 162974,
35
+ "MSP_libraries": 261644,
36
+ "MS2_SAN_JSONL": 218969
37
+ },
38
+ "exclude_heldout_labels_and_negatives_by": "key14",
39
+ "test_or_casmi_labels_in_training": false,
40
+ "preserve_same_structure_multiple_spectra": true,
41
+ "online_queries_during_training": false,
42
+ "coarse_labels_are_training_supervision_not_inference_inputs": true
43
+ },
44
+ "budget": {
45
+ "seeds": [
46
+ 20261103,
47
+ 20261104,
48
+ 20261105
49
+ ],
50
+ "optimizer_updates_per_seed": 6000,
51
+ "learning_rate": 3e-05,
52
+ "minimum_learning_rate": 3e-06,
53
+ "warmup_steps": 300,
54
+ "weight_decay": 0.0001,
55
+ "gradient_clip": 5.0,
56
+ "schedule": "cosine",
57
+ "bf16": true,
58
+ "graph_chunk": 128,
59
+ "spectrum_chunk": 64,
60
+ "pool_micro_views": 4,
61
+ "checkpoint_every": 100,
62
+ "validation_every_updates": 2000,
63
+ "source_presence_schedule": "same_R09_5093_step_epoch_plan",
64
+ "same_MS_exposure_and_candidate_draw_budget_across_arms": true,
65
+ "equal_wall_clock_or_FLOPs_claimed": false
66
+ },
67
+ "model": {
68
+ "backbone": "archived_R2_direct_ranker_256d_6Transformer_6MPNN",
69
+ "backbone_registered_parameters": 16409742,
70
+ "relation_or_cut_enabled": false,
71
+ "projection_heads": {
72
+ "input_dim": 256,
73
+ "hidden_dim": 256,
74
+ "output_dim": 128,
75
+ "activation": "GELU",
76
+ "normalize": "L2",
77
+ "names": [
78
+ "ms_identity",
79
+ "mol_identity",
80
+ "ms_formula",
81
+ "mol_formula",
82
+ "ms_mass",
83
+ "mol_mass"
84
+ ],
85
+ "register_all_heads_in_all_arms": true,
86
+ "shared_backbone_receives_auxiliary_gradients": true
87
+ },
88
+ "head_routing": "share_granularities_within_modality",
89
+ "mass_head_input": "shared_encoder_representation",
90
+ "auxiliary_heads_used_at_inference": false,
91
+ "original_final_ranking_score_unchanged": true
92
+ },
93
+ "sampling": {
94
+ "mode": "hierarchical_formula_identity_spectra",
95
+ "odata_batch_size": 256,
96
+ "msg_batch_size": 32,
97
+ "desired_odata_shape": {
98
+ "formulas": 8,
99
+ "identities_per_formula": 8,
100
+ "spectra_per_identity": 4
101
+ },
102
+ "desired_msg_shape": {
103
+ "formulas": 4,
104
+ "identities_per_formula": 4,
105
+ "spectra_per_identity": 2
106
+ },
107
+ "rare_group_fallback": "pack_remaining_real_records_without_replacement",
108
+ "mass_positive_coverage": "measure_same_formula_and_cross_formula_pairs_separately_do_not_assume_formula_sampler_covers_mass_neighbors",
109
+ "force_duplicate_spectra_to_fill_group": false,
110
+ "each_source_record_once_before_next_source_epoch": true,
111
+ "singleton_policy": "retain_existing_objectives_mask_missing_auxiliary_positives",
112
+ "explicit_odata_queries": 16,
113
+ "odata_negative_draws": 128,
114
+ "msg_views": [
115
+ "mass",
116
+ "formula"
117
+ ],
118
+ "msg_negative_draws_per_view": 63,
119
+ "candidate_draws_with_replacement": true,
120
+ "candidate_pool_deduplicate_key14": false,
121
+ "same_truth_key14_is_never_negative": true
122
+ },
123
+ "views": {
124
+ "MS": {
125
+ "positive_source": "distinct_real_spectra_of_same_key14",
126
+ "spectrum_augmentation": "none",
127
+ "repeat_physical_record_is_not_positive": true
128
+ },
129
+ "molecule": {
130
+ "count": 2,
131
+ "strategy": "independent_hidden_feature_dropout",
132
+ "dropout": 0.1,
133
+ "delete_atoms_or_bonds": false,
134
+ "random_SMILES_alone_is_not_new_view": true
135
+ },
136
+ "primary_encoder_path_dropout": 0.0,
137
+ "compute_two_molecule_views_for_all_arms": true,
138
+ "stochastic_view_gradient_cache": "disabled_keep_view_graph_or_verified_RNG_replay"
139
+ },
140
+ "loss": {
141
+ "base": {
142
+ "formula": 1.0,
143
+ "ms_to_mol": 0.5,
144
+ "mol_to_ms": 0.5,
145
+ "odata_pool": 0.5,
146
+ "msg_mass_pool": 0.25,
147
+ "msg_formula_pool": 0.25
148
+ },
149
+ "formula_task": {
150
+ "ce": 1.0,
151
+ "gap": 0.1,
152
+ "hard_wrong_topk": 3,
153
+ "margin": 0.2,
154
+ "element_count": 0.2
155
+ },
156
+ "auxiliary": {
157
+ "ms_fine": 0.1,
158
+ "mol_fine": 0.05,
159
+ "ms_formula": 0.05,
160
+ "mol_formula": 0.05,
161
+ "ms_mass": 0.025,
162
+ "mol_mass": 0.025
163
+ },
164
+ "auxiliary_ramp_steps": 500,
165
+ "temperature": {
166
+ "identity": 0.1,
167
+ "formula": 0.15,
168
+ "mass": 0.2
169
+ },
170
+ "fine_identity": "key14",
171
+ "self_pairs": "exclude",
172
+ "missing_positive_or_negative": "differentiable_zero_and_log_effective_count",
173
+ "anchor_reduction": {
174
+ "fine": "key14_macro",
175
+ "formula": "formula_macro",
176
+ "mass": "key14_macro"
177
+ },
178
+ "formula_coarse": {
179
+ "label": "exact_element_count_canonical_formula",
180
+ "positive": "same_formula_different_key14",
181
+ "negative": "different_formula",
182
+ "same_key14_pair_policy": "exclude_from_coarse",
183
+ "same_scaffold_is_not_identity_positive": true
184
+ },
185
+ "mass_coarse": {
186
+ "mode": "soft_neighborhood",
187
+ "MS_mass": "abs_charge_times_experimental_precursor_minus_adduct_delta",
188
+ "molecule_mass": "cached_candidate_neutral_monoisotopic_mass",
189
+ "distance_unit": "Da",
190
+ "positive_radius_da": 0.5,
191
+ "negative_start_da": 2.0,
192
+ "gaussian_sigma_da": 0.25,
193
+ "gray_zone": "exclude",
194
+ "same_key14_pair_policy": "exclude_from_coarse",
195
+ "hard_bin_width_da": 1.0,
196
+ "hard_bin_offset_da": 0.0,
197
+ "MS_quality_mask": "reference_precursor_consistency_within_10ppm",
198
+ "candidate_10ppm_filter_is_not_mass_bucket_width": true,
199
+ "mass_neighborhood_is_not_chemical_similarity_or_equivalence_class": true
200
+ }
201
+ },
202
+ "evaluation": {
203
+ "selection_split": "MSG_Validation",
204
+ "spectra": 19429,
205
+ "official_views": [
206
+ "mass",
207
+ "formula"
208
+ ],
209
+ "structure_topk": [
210
+ 1,
211
+ 3,
212
+ 5,
213
+ 10,
214
+ 20,
215
+ 50,
216
+ 100,
217
+ 200
218
+ ],
219
+ "formula_topk": [
220
+ 1,
221
+ 2,
222
+ 3,
223
+ 4,
224
+ 5,
225
+ 6,
226
+ 7,
227
+ 8,
228
+ 9,
229
+ 10,
230
+ 20,
231
+ 50,
232
+ 100,
233
+ 200
234
+ ],
235
+ "primary_score": "harmonic_mean_Mass_Formula_structure_Top1",
236
+ "report_formula_Top1_and_Top10_separately": true,
237
+ "report_spectrum_micro_target_macro_key14_macro": true,
238
+ "coarse_and_fine_retrieval_diagnostics": true,
239
+ "never_filter_official_pools_or_inject_truth": true,
240
+ "test_and_casmi_only_after_predeclared_selection": true,
241
+ "casmi_pool": "data/benchmarks/casmi2022_sirius6312_top10_pubchem_10ppm_connectivity_v1",
242
+ "casmi_candidate_cap": null,
243
+ "casmi_denominator": 500,
244
+ "mces_enabled": false
245
+ },
246
+ "logging": {
247
+ "per_branch_valid_anchors_and_groups": true,
248
+ "positive_negative_and_gray_pair_counts": true,
249
+ "mass_positive_same_formula_vs_cross_formula": true,
250
+ "same_key14_false_negative_count": true,
251
+ "raw_and_weighted_losses": true,
252
+ "gradient_norm_per_task_and_pairwise_gradient_cosine": true,
253
+ "projection_variance_effective_rank_and_pair_similarity": true,
254
+ "per_source_polarity_adduct": true,
255
+ "distinct_MS_exposures_and_repeated_draws": true,
256
+ "GPU_seconds_peak_memory_and_molecule_forward_count": true
257
+ },
258
+ "experiment": {
259
+ "id": "C09_shared_head_control",
260
+ "description": "Conflict control: coarse and fine share each modality head",
261
+ "active_auxiliary_tasks": [
262
+ "ms_fine",
263
+ "mol_fine",
264
+ "ms_formula",
265
+ "mol_formula",
266
+ "ms_mass",
267
+ "mol_mass"
268
+ ],
269
+ "auxiliary_coefficient_sum": 0.3,
270
+ "output_template": "/workspace/xj/SpecPartition-MS/runs/hierarchical_intra_modal_20261103/C09_shared_head_control/seed_{seed}",
271
+ "priority": "secondary_ablation"
272
+ }
273
+ }
code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C10_random_sampler_control.json ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": 1,
3
+ "suite_id": "hierarchical_intra_modal_20261103",
4
+ "execution": {
5
+ "status": "configuration_and_loss_components_only",
6
+ "allow_training": false,
7
+ "runtime_entrypoint": null,
8
+ "missing_integration": [
9
+ "hierarchical_no_repeat_sampler",
10
+ "independent_stochastic_gnn_views",
11
+ "rng_safe_view_recomputation",
12
+ "joint_loss_router_and_gpu_acceptance"
13
+ ]
14
+ },
15
+ "initialization": {
16
+ "checkpoint": "/workspace/xj/SpecPartition-MS/runs/rebuild_joint_r08data_20261102/epoch_04.pt",
17
+ "sha256": "618aaf195cfdc3a4107e71cf2b3a56d5853b407564acf01de11c67e6af40f3d7",
18
+ "policy": "same_fixed_parent_weights_all_arms",
19
+ "optimizer_policy": "new_AdamW_for_every_arm_not_live_run_resume",
20
+ "selection_source": "Validation_only_fixed_before_ablation",
21
+ "new_heads": "same_initialization_per_seed_for_all_arms"
22
+ },
23
+ "data": {
24
+ "root": "/workspace/xj/SpecPartition-MS",
25
+ "labels": "data/derived/data_release_r07_key14_20261101/train.json",
26
+ "prepared": "data/derived/joint_r09_inputs_20261102/train.sqlite",
27
+ "candidates": "data/derived/training_r08_true_formula_records_20261101/preparation.sqlite",
28
+ "heldout_registry": "data/derived/data_release_r07_key14_20261101/heldout_registry.json",
29
+ "label_policy_sha256": "91971b3f6979586b32c90350330cb6712e60c3c6f4b872de4113311f8a95adf7",
30
+ "candidate_config_sha256": "53a365647ed8c54e216ff2cd25c011ed7f7d47a920f54c0136eea0c8dabade65",
31
+ "parent_training_config_sha256": "5f8f8635c60e37a194660b73f0fae69571a3f97a045f1d5c2f0e5fbf76e450d0",
32
+ "records": 643587,
33
+ "source_counts": {
34
+ "MSG_Train": 162974,
35
+ "MSP_libraries": 261644,
36
+ "MS2_SAN_JSONL": 218969
37
+ },
38
+ "exclude_heldout_labels_and_negatives_by": "key14",
39
+ "test_or_casmi_labels_in_training": false,
40
+ "preserve_same_structure_multiple_spectra": true,
41
+ "online_queries_during_training": false,
42
+ "coarse_labels_are_training_supervision_not_inference_inputs": true
43
+ },
44
+ "budget": {
45
+ "seeds": [
46
+ 20261103,
47
+ 20261104,
48
+ 20261105
49
+ ],
50
+ "optimizer_updates_per_seed": 6000,
51
+ "learning_rate": 3e-05,
52
+ "minimum_learning_rate": 3e-06,
53
+ "warmup_steps": 300,
54
+ "weight_decay": 0.0001,
55
+ "gradient_clip": 5.0,
56
+ "schedule": "cosine",
57
+ "bf16": true,
58
+ "graph_chunk": 128,
59
+ "spectrum_chunk": 64,
60
+ "pool_micro_views": 4,
61
+ "checkpoint_every": 100,
62
+ "validation_every_updates": 2000,
63
+ "source_presence_schedule": "same_R09_5093_step_epoch_plan",
64
+ "same_MS_exposure_and_candidate_draw_budget_across_arms": true,
65
+ "equal_wall_clock_or_FLOPs_claimed": false
66
+ },
67
+ "model": {
68
+ "backbone": "archived_R2_direct_ranker_256d_6Transformer_6MPNN",
69
+ "backbone_registered_parameters": 16409742,
70
+ "relation_or_cut_enabled": false,
71
+ "projection_heads": {
72
+ "input_dim": 256,
73
+ "hidden_dim": 256,
74
+ "output_dim": 128,
75
+ "activation": "GELU",
76
+ "normalize": "L2",
77
+ "names": [
78
+ "ms_identity",
79
+ "mol_identity",
80
+ "ms_formula",
81
+ "mol_formula",
82
+ "ms_mass",
83
+ "mol_mass"
84
+ ],
85
+ "register_all_heads_in_all_arms": true,
86
+ "shared_backbone_receives_auxiliary_gradients": true
87
+ },
88
+ "head_routing": "separate_by_modality_and_granularity",
89
+ "mass_head_input": "shared_encoder_representation",
90
+ "auxiliary_heads_used_at_inference": false,
91
+ "original_final_ranking_score_unchanged": true
92
+ },
93
+ "sampling": {
94
+ "mode": "random_source_shuffle",
95
+ "odata_batch_size": 256,
96
+ "msg_batch_size": 32,
97
+ "desired_odata_shape": {
98
+ "formulas": 8,
99
+ "identities_per_formula": 8,
100
+ "spectra_per_identity": 4
101
+ },
102
+ "desired_msg_shape": {
103
+ "formulas": 4,
104
+ "identities_per_formula": 4,
105
+ "spectra_per_identity": 2
106
+ },
107
+ "rare_group_fallback": "pack_remaining_real_records_without_replacement",
108
+ "mass_positive_coverage": "measure_same_formula_and_cross_formula_pairs_separately_do_not_assume_formula_sampler_covers_mass_neighbors",
109
+ "force_duplicate_spectra_to_fill_group": false,
110
+ "each_source_record_once_before_next_source_epoch": true,
111
+ "singleton_policy": "retain_existing_objectives_mask_missing_auxiliary_positives",
112
+ "explicit_odata_queries": 16,
113
+ "odata_negative_draws": 128,
114
+ "msg_views": [
115
+ "mass",
116
+ "formula"
117
+ ],
118
+ "msg_negative_draws_per_view": 63,
119
+ "candidate_draws_with_replacement": true,
120
+ "candidate_pool_deduplicate_key14": false,
121
+ "same_truth_key14_is_never_negative": true
122
+ },
123
+ "views": {
124
+ "MS": {
125
+ "positive_source": "distinct_real_spectra_of_same_key14",
126
+ "spectrum_augmentation": "none",
127
+ "repeat_physical_record_is_not_positive": true
128
+ },
129
+ "molecule": {
130
+ "count": 2,
131
+ "strategy": "independent_hidden_feature_dropout",
132
+ "dropout": 0.1,
133
+ "delete_atoms_or_bonds": false,
134
+ "random_SMILES_alone_is_not_new_view": true
135
+ },
136
+ "primary_encoder_path_dropout": 0.0,
137
+ "compute_two_molecule_views_for_all_arms": true,
138
+ "stochastic_view_gradient_cache": "disabled_keep_view_graph_or_verified_RNG_replay"
139
+ },
140
+ "loss": {
141
+ "base": {
142
+ "formula": 1.0,
143
+ "ms_to_mol": 0.5,
144
+ "mol_to_ms": 0.5,
145
+ "odata_pool": 0.5,
146
+ "msg_mass_pool": 0.25,
147
+ "msg_formula_pool": 0.25
148
+ },
149
+ "formula_task": {
150
+ "ce": 1.0,
151
+ "gap": 0.1,
152
+ "hard_wrong_topk": 3,
153
+ "margin": 0.2,
154
+ "element_count": 0.2
155
+ },
156
+ "auxiliary": {
157
+ "ms_fine": 0.1,
158
+ "mol_fine": 0.05,
159
+ "ms_formula": 0.05,
160
+ "mol_formula": 0.05,
161
+ "ms_mass": 0.025,
162
+ "mol_mass": 0.025
163
+ },
164
+ "auxiliary_ramp_steps": 500,
165
+ "temperature": {
166
+ "identity": 0.1,
167
+ "formula": 0.15,
168
+ "mass": 0.2
169
+ },
170
+ "fine_identity": "key14",
171
+ "self_pairs": "exclude",
172
+ "missing_positive_or_negative": "differentiable_zero_and_log_effective_count",
173
+ "anchor_reduction": {
174
+ "fine": "key14_macro",
175
+ "formula": "formula_macro",
176
+ "mass": "key14_macro"
177
+ },
178
+ "formula_coarse": {
179
+ "label": "exact_element_count_canonical_formula",
180
+ "positive": "same_formula_different_key14",
181
+ "negative": "different_formula",
182
+ "same_key14_pair_policy": "exclude_from_coarse",
183
+ "same_scaffold_is_not_identity_positive": true
184
+ },
185
+ "mass_coarse": {
186
+ "mode": "soft_neighborhood",
187
+ "MS_mass": "abs_charge_times_experimental_precursor_minus_adduct_delta",
188
+ "molecule_mass": "cached_candidate_neutral_monoisotopic_mass",
189
+ "distance_unit": "Da",
190
+ "positive_radius_da": 0.5,
191
+ "negative_start_da": 2.0,
192
+ "gaussian_sigma_da": 0.25,
193
+ "gray_zone": "exclude",
194
+ "same_key14_pair_policy": "exclude_from_coarse",
195
+ "hard_bin_width_da": 1.0,
196
+ "hard_bin_offset_da": 0.0,
197
+ "MS_quality_mask": "reference_precursor_consistency_within_10ppm",
198
+ "candidate_10ppm_filter_is_not_mass_bucket_width": true,
199
+ "mass_neighborhood_is_not_chemical_similarity_or_equivalence_class": true
200
+ }
201
+ },
202
+ "evaluation": {
203
+ "selection_split": "MSG_Validation",
204
+ "spectra": 19429,
205
+ "official_views": [
206
+ "mass",
207
+ "formula"
208
+ ],
209
+ "structure_topk": [
210
+ 1,
211
+ 3,
212
+ 5,
213
+ 10,
214
+ 20,
215
+ 50,
216
+ 100,
217
+ 200
218
+ ],
219
+ "formula_topk": [
220
+ 1,
221
+ 2,
222
+ 3,
223
+ 4,
224
+ 5,
225
+ 6,
226
+ 7,
227
+ 8,
228
+ 9,
229
+ 10,
230
+ 20,
231
+ 50,
232
+ 100,
233
+ 200
234
+ ],
235
+ "primary_score": "harmonic_mean_Mass_Formula_structure_Top1",
236
+ "report_formula_Top1_and_Top10_separately": true,
237
+ "report_spectrum_micro_target_macro_key14_macro": true,
238
+ "coarse_and_fine_retrieval_diagnostics": true,
239
+ "never_filter_official_pools_or_inject_truth": true,
240
+ "test_and_casmi_only_after_predeclared_selection": true,
241
+ "casmi_pool": "data/benchmarks/casmi2022_sirius6312_top10_pubchem_10ppm_connectivity_v1",
242
+ "casmi_candidate_cap": null,
243
+ "casmi_denominator": 500,
244
+ "mces_enabled": false
245
+ },
246
+ "logging": {
247
+ "per_branch_valid_anchors_and_groups": true,
248
+ "positive_negative_and_gray_pair_counts": true,
249
+ "mass_positive_same_formula_vs_cross_formula": true,
250
+ "same_key14_false_negative_count": true,
251
+ "raw_and_weighted_losses": true,
252
+ "gradient_norm_per_task_and_pairwise_gradient_cosine": true,
253
+ "projection_variance_effective_rank_and_pair_similarity": true,
254
+ "per_source_polarity_adduct": true,
255
+ "distinct_MS_exposures_and_repeated_draws": true,
256
+ "GPU_seconds_peak_memory_and_molecule_forward_count": true
257
+ },
258
+ "experiment": {
259
+ "id": "C10_random_sampler_control",
260
+ "description": "Same losses without hierarchical positive-enriching sampler",
261
+ "active_auxiliary_tasks": [
262
+ "ms_fine",
263
+ "mol_fine",
264
+ "ms_formula",
265
+ "mol_formula",
266
+ "ms_mass",
267
+ "mol_mass"
268
+ ],
269
+ "auxiliary_coefficient_sum": 0.3,
270
+ "output_template": "/workspace/xj/SpecPartition-MS/runs/hierarchical_intra_modal_20261103/C10_random_sampler_control/seed_{seed}",
271
+ "priority": "secondary_ablation"
272
+ }
273
+ }
code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C11_hard_mass_bins.json ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": 1,
3
+ "suite_id": "hierarchical_intra_modal_20261103",
4
+ "execution": {
5
+ "status": "configuration_and_loss_components_only",
6
+ "allow_training": false,
7
+ "runtime_entrypoint": null,
8
+ "missing_integration": [
9
+ "hierarchical_no_repeat_sampler",
10
+ "independent_stochastic_gnn_views",
11
+ "rng_safe_view_recomputation",
12
+ "joint_loss_router_and_gpu_acceptance"
13
+ ]
14
+ },
15
+ "initialization": {
16
+ "checkpoint": "/workspace/xj/SpecPartition-MS/runs/rebuild_joint_r08data_20261102/epoch_04.pt",
17
+ "sha256": "618aaf195cfdc3a4107e71cf2b3a56d5853b407564acf01de11c67e6af40f3d7",
18
+ "policy": "same_fixed_parent_weights_all_arms",
19
+ "optimizer_policy": "new_AdamW_for_every_arm_not_live_run_resume",
20
+ "selection_source": "Validation_only_fixed_before_ablation",
21
+ "new_heads": "same_initialization_per_seed_for_all_arms"
22
+ },
23
+ "data": {
24
+ "root": "/workspace/xj/SpecPartition-MS",
25
+ "labels": "data/derived/data_release_r07_key14_20261101/train.json",
26
+ "prepared": "data/derived/joint_r09_inputs_20261102/train.sqlite",
27
+ "candidates": "data/derived/training_r08_true_formula_records_20261101/preparation.sqlite",
28
+ "heldout_registry": "data/derived/data_release_r07_key14_20261101/heldout_registry.json",
29
+ "label_policy_sha256": "91971b3f6979586b32c90350330cb6712e60c3c6f4b872de4113311f8a95adf7",
30
+ "candidate_config_sha256": "53a365647ed8c54e216ff2cd25c011ed7f7d47a920f54c0136eea0c8dabade65",
31
+ "parent_training_config_sha256": "5f8f8635c60e37a194660b73f0fae69571a3f97a045f1d5c2f0e5fbf76e450d0",
32
+ "records": 643587,
33
+ "source_counts": {
34
+ "MSG_Train": 162974,
35
+ "MSP_libraries": 261644,
36
+ "MS2_SAN_JSONL": 218969
37
+ },
38
+ "exclude_heldout_labels_and_negatives_by": "key14",
39
+ "test_or_casmi_labels_in_training": false,
40
+ "preserve_same_structure_multiple_spectra": true,
41
+ "online_queries_during_training": false,
42
+ "coarse_labels_are_training_supervision_not_inference_inputs": true
43
+ },
44
+ "budget": {
45
+ "seeds": [
46
+ 20261103,
47
+ 20261104,
48
+ 20261105
49
+ ],
50
+ "optimizer_updates_per_seed": 6000,
51
+ "learning_rate": 3e-05,
52
+ "minimum_learning_rate": 3e-06,
53
+ "warmup_steps": 300,
54
+ "weight_decay": 0.0001,
55
+ "gradient_clip": 5.0,
56
+ "schedule": "cosine",
57
+ "bf16": true,
58
+ "graph_chunk": 128,
59
+ "spectrum_chunk": 64,
60
+ "pool_micro_views": 4,
61
+ "checkpoint_every": 100,
62
+ "validation_every_updates": 2000,
63
+ "source_presence_schedule": "same_R09_5093_step_epoch_plan",
64
+ "same_MS_exposure_and_candidate_draw_budget_across_arms": true,
65
+ "equal_wall_clock_or_FLOPs_claimed": false
66
+ },
67
+ "model": {
68
+ "backbone": "archived_R2_direct_ranker_256d_6Transformer_6MPNN",
69
+ "backbone_registered_parameters": 16409742,
70
+ "relation_or_cut_enabled": false,
71
+ "projection_heads": {
72
+ "input_dim": 256,
73
+ "hidden_dim": 256,
74
+ "output_dim": 128,
75
+ "activation": "GELU",
76
+ "normalize": "L2",
77
+ "names": [
78
+ "ms_identity",
79
+ "mol_identity",
80
+ "ms_formula",
81
+ "mol_formula",
82
+ "ms_mass",
83
+ "mol_mass"
84
+ ],
85
+ "register_all_heads_in_all_arms": true,
86
+ "shared_backbone_receives_auxiliary_gradients": true
87
+ },
88
+ "head_routing": "separate_by_modality_and_granularity",
89
+ "mass_head_input": "shared_encoder_representation",
90
+ "auxiliary_heads_used_at_inference": false,
91
+ "original_final_ranking_score_unchanged": true
92
+ },
93
+ "sampling": {
94
+ "mode": "hierarchical_formula_identity_spectra",
95
+ "odata_batch_size": 256,
96
+ "msg_batch_size": 32,
97
+ "desired_odata_shape": {
98
+ "formulas": 8,
99
+ "identities_per_formula": 8,
100
+ "spectra_per_identity": 4
101
+ },
102
+ "desired_msg_shape": {
103
+ "formulas": 4,
104
+ "identities_per_formula": 4,
105
+ "spectra_per_identity": 2
106
+ },
107
+ "rare_group_fallback": "pack_remaining_real_records_without_replacement",
108
+ "mass_positive_coverage": "measure_same_formula_and_cross_formula_pairs_separately_do_not_assume_formula_sampler_covers_mass_neighbors",
109
+ "force_duplicate_spectra_to_fill_group": false,
110
+ "each_source_record_once_before_next_source_epoch": true,
111
+ "singleton_policy": "retain_existing_objectives_mask_missing_auxiliary_positives",
112
+ "explicit_odata_queries": 16,
113
+ "odata_negative_draws": 128,
114
+ "msg_views": [
115
+ "mass",
116
+ "formula"
117
+ ],
118
+ "msg_negative_draws_per_view": 63,
119
+ "candidate_draws_with_replacement": true,
120
+ "candidate_pool_deduplicate_key14": false,
121
+ "same_truth_key14_is_never_negative": true
122
+ },
123
+ "views": {
124
+ "MS": {
125
+ "positive_source": "distinct_real_spectra_of_same_key14",
126
+ "spectrum_augmentation": "none",
127
+ "repeat_physical_record_is_not_positive": true
128
+ },
129
+ "molecule": {
130
+ "count": 2,
131
+ "strategy": "independent_hidden_feature_dropout",
132
+ "dropout": 0.1,
133
+ "delete_atoms_or_bonds": false,
134
+ "random_SMILES_alone_is_not_new_view": true
135
+ },
136
+ "primary_encoder_path_dropout": 0.0,
137
+ "compute_two_molecule_views_for_all_arms": true,
138
+ "stochastic_view_gradient_cache": "disabled_keep_view_graph_or_verified_RNG_replay"
139
+ },
140
+ "loss": {
141
+ "base": {
142
+ "formula": 1.0,
143
+ "ms_to_mol": 0.5,
144
+ "mol_to_ms": 0.5,
145
+ "odata_pool": 0.5,
146
+ "msg_mass_pool": 0.25,
147
+ "msg_formula_pool": 0.25
148
+ },
149
+ "formula_task": {
150
+ "ce": 1.0,
151
+ "gap": 0.1,
152
+ "hard_wrong_topk": 3,
153
+ "margin": 0.2,
154
+ "element_count": 0.2
155
+ },
156
+ "auxiliary": {
157
+ "ms_fine": 0.1,
158
+ "mol_fine": 0.05,
159
+ "ms_formula": 0.05,
160
+ "mol_formula": 0.05,
161
+ "ms_mass": 0.025,
162
+ "mol_mass": 0.025
163
+ },
164
+ "auxiliary_ramp_steps": 500,
165
+ "temperature": {
166
+ "identity": 0.1,
167
+ "formula": 0.15,
168
+ "mass": 0.2
169
+ },
170
+ "fine_identity": "key14",
171
+ "self_pairs": "exclude",
172
+ "missing_positive_or_negative": "differentiable_zero_and_log_effective_count",
173
+ "anchor_reduction": {
174
+ "fine": "key14_macro",
175
+ "formula": "formula_macro",
176
+ "mass": "key14_macro"
177
+ },
178
+ "formula_coarse": {
179
+ "label": "exact_element_count_canonical_formula",
180
+ "positive": "same_formula_different_key14",
181
+ "negative": "different_formula",
182
+ "same_key14_pair_policy": "exclude_from_coarse",
183
+ "same_scaffold_is_not_identity_positive": true
184
+ },
185
+ "mass_coarse": {
186
+ "mode": "hard_bins",
187
+ "MS_mass": "abs_charge_times_experimental_precursor_minus_adduct_delta",
188
+ "molecule_mass": "cached_candidate_neutral_monoisotopic_mass",
189
+ "distance_unit": "Da",
190
+ "positive_radius_da": 0.5,
191
+ "negative_start_da": 2.0,
192
+ "gaussian_sigma_da": 0.25,
193
+ "gray_zone": "exclude",
194
+ "same_key14_pair_policy": "exclude_from_coarse",
195
+ "hard_bin_width_da": 1.0,
196
+ "hard_bin_offset_da": 0.0,
197
+ "MS_quality_mask": "reference_precursor_consistency_within_10ppm",
198
+ "candidate_10ppm_filter_is_not_mass_bucket_width": true,
199
+ "mass_neighborhood_is_not_chemical_similarity_or_equivalence_class": true
200
+ }
201
+ },
202
+ "evaluation": {
203
+ "selection_split": "MSG_Validation",
204
+ "spectra": 19429,
205
+ "official_views": [
206
+ "mass",
207
+ "formula"
208
+ ],
209
+ "structure_topk": [
210
+ 1,
211
+ 3,
212
+ 5,
213
+ 10,
214
+ 20,
215
+ 50,
216
+ 100,
217
+ 200
218
+ ],
219
+ "formula_topk": [
220
+ 1,
221
+ 2,
222
+ 3,
223
+ 4,
224
+ 5,
225
+ 6,
226
+ 7,
227
+ 8,
228
+ 9,
229
+ 10,
230
+ 20,
231
+ 50,
232
+ 100,
233
+ 200
234
+ ],
235
+ "primary_score": "harmonic_mean_Mass_Formula_structure_Top1",
236
+ "report_formula_Top1_and_Top10_separately": true,
237
+ "report_spectrum_micro_target_macro_key14_macro": true,
238
+ "coarse_and_fine_retrieval_diagnostics": true,
239
+ "never_filter_official_pools_or_inject_truth": true,
240
+ "test_and_casmi_only_after_predeclared_selection": true,
241
+ "casmi_pool": "data/benchmarks/casmi2022_sirius6312_top10_pubchem_10ppm_connectivity_v1",
242
+ "casmi_candidate_cap": null,
243
+ "casmi_denominator": 500,
244
+ "mces_enabled": false
245
+ },
246
+ "logging": {
247
+ "per_branch_valid_anchors_and_groups": true,
248
+ "positive_negative_and_gray_pair_counts": true,
249
+ "mass_positive_same_formula_vs_cross_formula": true,
250
+ "same_key14_false_negative_count": true,
251
+ "raw_and_weighted_losses": true,
252
+ "gradient_norm_per_task_and_pairwise_gradient_cosine": true,
253
+ "projection_variance_effective_rank_and_pair_similarity": true,
254
+ "per_source_polarity_adduct": true,
255
+ "distinct_MS_exposures_and_repeated_draws": true,
256
+ "GPU_seconds_peak_memory_and_molecule_forward_count": true
257
+ },
258
+ "experiment": {
259
+ "id": "C11_hard_mass_bins",
260
+ "description": "Replace continuous mass neighborhoods with fixed 1 Da bins",
261
+ "active_auxiliary_tasks": [
262
+ "ms_fine",
263
+ "mol_fine",
264
+ "ms_formula",
265
+ "mol_formula",
266
+ "ms_mass",
267
+ "mol_mass"
268
+ ],
269
+ "auxiliary_coefficient_sum": 0.3,
270
+ "output_template": "/workspace/xj/SpecPartition-MS/runs/hierarchical_intra_modal_20261103/C11_hard_mass_bins/seed_{seed}",
271
+ "priority": "secondary_ablation"
272
+ }
273
+ }
code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C12_no_reverse_crossmodal.json ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": 1,
3
+ "suite_id": "hierarchical_intra_modal_20261103",
4
+ "execution": {
5
+ "status": "configuration_and_loss_components_only",
6
+ "allow_training": false,
7
+ "runtime_entrypoint": null,
8
+ "missing_integration": [
9
+ "hierarchical_no_repeat_sampler",
10
+ "independent_stochastic_gnn_views",
11
+ "rng_safe_view_recomputation",
12
+ "joint_loss_router_and_gpu_acceptance"
13
+ ]
14
+ },
15
+ "initialization": {
16
+ "checkpoint": "/workspace/xj/SpecPartition-MS/runs/rebuild_joint_r08data_20261102/epoch_04.pt",
17
+ "sha256": "618aaf195cfdc3a4107e71cf2b3a56d5853b407564acf01de11c67e6af40f3d7",
18
+ "policy": "same_fixed_parent_weights_all_arms",
19
+ "optimizer_policy": "new_AdamW_for_every_arm_not_live_run_resume",
20
+ "selection_source": "Validation_only_fixed_before_ablation",
21
+ "new_heads": "same_initialization_per_seed_for_all_arms"
22
+ },
23
+ "data": {
24
+ "root": "/workspace/xj/SpecPartition-MS",
25
+ "labels": "data/derived/data_release_r07_key14_20261101/train.json",
26
+ "prepared": "data/derived/joint_r09_inputs_20261102/train.sqlite",
27
+ "candidates": "data/derived/training_r08_true_formula_records_20261101/preparation.sqlite",
28
+ "heldout_registry": "data/derived/data_release_r07_key14_20261101/heldout_registry.json",
29
+ "label_policy_sha256": "91971b3f6979586b32c90350330cb6712e60c3c6f4b872de4113311f8a95adf7",
30
+ "candidate_config_sha256": "53a365647ed8c54e216ff2cd25c011ed7f7d47a920f54c0136eea0c8dabade65",
31
+ "parent_training_config_sha256": "5f8f8635c60e37a194660b73f0fae69571a3f97a045f1d5c2f0e5fbf76e450d0",
32
+ "records": 643587,
33
+ "source_counts": {
34
+ "MSG_Train": 162974,
35
+ "MSP_libraries": 261644,
36
+ "MS2_SAN_JSONL": 218969
37
+ },
38
+ "exclude_heldout_labels_and_negatives_by": "key14",
39
+ "test_or_casmi_labels_in_training": false,
40
+ "preserve_same_structure_multiple_spectra": true,
41
+ "online_queries_during_training": false,
42
+ "coarse_labels_are_training_supervision_not_inference_inputs": true
43
+ },
44
+ "budget": {
45
+ "seeds": [
46
+ 20261103,
47
+ 20261104,
48
+ 20261105
49
+ ],
50
+ "optimizer_updates_per_seed": 6000,
51
+ "learning_rate": 3e-05,
52
+ "minimum_learning_rate": 3e-06,
53
+ "warmup_steps": 300,
54
+ "weight_decay": 0.0001,
55
+ "gradient_clip": 5.0,
56
+ "schedule": "cosine",
57
+ "bf16": true,
58
+ "graph_chunk": 128,
59
+ "spectrum_chunk": 64,
60
+ "pool_micro_views": 4,
61
+ "checkpoint_every": 100,
62
+ "validation_every_updates": 2000,
63
+ "source_presence_schedule": "same_R09_5093_step_epoch_plan",
64
+ "same_MS_exposure_and_candidate_draw_budget_across_arms": true,
65
+ "equal_wall_clock_or_FLOPs_claimed": false
66
+ },
67
+ "model": {
68
+ "backbone": "archived_R2_direct_ranker_256d_6Transformer_6MPNN",
69
+ "backbone_registered_parameters": 16409742,
70
+ "relation_or_cut_enabled": false,
71
+ "projection_heads": {
72
+ "input_dim": 256,
73
+ "hidden_dim": 256,
74
+ "output_dim": 128,
75
+ "activation": "GELU",
76
+ "normalize": "L2",
77
+ "names": [
78
+ "ms_identity",
79
+ "mol_identity",
80
+ "ms_formula",
81
+ "mol_formula",
82
+ "ms_mass",
83
+ "mol_mass"
84
+ ],
85
+ "register_all_heads_in_all_arms": true,
86
+ "shared_backbone_receives_auxiliary_gradients": true
87
+ },
88
+ "head_routing": "separate_by_modality_and_granularity",
89
+ "mass_head_input": "shared_encoder_representation",
90
+ "auxiliary_heads_used_at_inference": false,
91
+ "original_final_ranking_score_unchanged": true
92
+ },
93
+ "sampling": {
94
+ "mode": "hierarchical_formula_identity_spectra",
95
+ "odata_batch_size": 256,
96
+ "msg_batch_size": 32,
97
+ "desired_odata_shape": {
98
+ "formulas": 8,
99
+ "identities_per_formula": 8,
100
+ "spectra_per_identity": 4
101
+ },
102
+ "desired_msg_shape": {
103
+ "formulas": 4,
104
+ "identities_per_formula": 4,
105
+ "spectra_per_identity": 2
106
+ },
107
+ "rare_group_fallback": "pack_remaining_real_records_without_replacement",
108
+ "mass_positive_coverage": "measure_same_formula_and_cross_formula_pairs_separately_do_not_assume_formula_sampler_covers_mass_neighbors",
109
+ "force_duplicate_spectra_to_fill_group": false,
110
+ "each_source_record_once_before_next_source_epoch": true,
111
+ "singleton_policy": "retain_existing_objectives_mask_missing_auxiliary_positives",
112
+ "explicit_odata_queries": 16,
113
+ "odata_negative_draws": 128,
114
+ "msg_views": [
115
+ "mass",
116
+ "formula"
117
+ ],
118
+ "msg_negative_draws_per_view": 63,
119
+ "candidate_draws_with_replacement": true,
120
+ "candidate_pool_deduplicate_key14": false,
121
+ "same_truth_key14_is_never_negative": true
122
+ },
123
+ "views": {
124
+ "MS": {
125
+ "positive_source": "distinct_real_spectra_of_same_key14",
126
+ "spectrum_augmentation": "none",
127
+ "repeat_physical_record_is_not_positive": true
128
+ },
129
+ "molecule": {
130
+ "count": 2,
131
+ "strategy": "independent_hidden_feature_dropout",
132
+ "dropout": 0.1,
133
+ "delete_atoms_or_bonds": false,
134
+ "random_SMILES_alone_is_not_new_view": true
135
+ },
136
+ "primary_encoder_path_dropout": 0.0,
137
+ "compute_two_molecule_views_for_all_arms": true,
138
+ "stochastic_view_gradient_cache": "disabled_keep_view_graph_or_verified_RNG_replay"
139
+ },
140
+ "loss": {
141
+ "base": {
142
+ "formula": 1.0,
143
+ "ms_to_mol": 1.0,
144
+ "mol_to_ms": 0.0,
145
+ "odata_pool": 0.5,
146
+ "msg_mass_pool": 0.25,
147
+ "msg_formula_pool": 0.25
148
+ },
149
+ "formula_task": {
150
+ "ce": 1.0,
151
+ "gap": 0.1,
152
+ "hard_wrong_topk": 3,
153
+ "margin": 0.2,
154
+ "element_count": 0.2
155
+ },
156
+ "auxiliary": {
157
+ "ms_fine": 0.1,
158
+ "mol_fine": 0.05,
159
+ "ms_formula": 0.05,
160
+ "mol_formula": 0.05,
161
+ "ms_mass": 0.025,
162
+ "mol_mass": 0.025
163
+ },
164
+ "auxiliary_ramp_steps": 500,
165
+ "temperature": {
166
+ "identity": 0.1,
167
+ "formula": 0.15,
168
+ "mass": 0.2
169
+ },
170
+ "fine_identity": "key14",
171
+ "self_pairs": "exclude",
172
+ "missing_positive_or_negative": "differentiable_zero_and_log_effective_count",
173
+ "anchor_reduction": {
174
+ "fine": "key14_macro",
175
+ "formula": "formula_macro",
176
+ "mass": "key14_macro"
177
+ },
178
+ "formula_coarse": {
179
+ "label": "exact_element_count_canonical_formula",
180
+ "positive": "same_formula_different_key14",
181
+ "negative": "different_formula",
182
+ "same_key14_pair_policy": "exclude_from_coarse",
183
+ "same_scaffold_is_not_identity_positive": true
184
+ },
185
+ "mass_coarse": {
186
+ "mode": "soft_neighborhood",
187
+ "MS_mass": "abs_charge_times_experimental_precursor_minus_adduct_delta",
188
+ "molecule_mass": "cached_candidate_neutral_monoisotopic_mass",
189
+ "distance_unit": "Da",
190
+ "positive_radius_da": 0.5,
191
+ "negative_start_da": 2.0,
192
+ "gaussian_sigma_da": 0.25,
193
+ "gray_zone": "exclude",
194
+ "same_key14_pair_policy": "exclude_from_coarse",
195
+ "hard_bin_width_da": 1.0,
196
+ "hard_bin_offset_da": 0.0,
197
+ "MS_quality_mask": "reference_precursor_consistency_within_10ppm",
198
+ "candidate_10ppm_filter_is_not_mass_bucket_width": true,
199
+ "mass_neighborhood_is_not_chemical_similarity_or_equivalence_class": true
200
+ }
201
+ },
202
+ "evaluation": {
203
+ "selection_split": "MSG_Validation",
204
+ "spectra": 19429,
205
+ "official_views": [
206
+ "mass",
207
+ "formula"
208
+ ],
209
+ "structure_topk": [
210
+ 1,
211
+ 3,
212
+ 5,
213
+ 10,
214
+ 20,
215
+ 50,
216
+ 100,
217
+ 200
218
+ ],
219
+ "formula_topk": [
220
+ 1,
221
+ 2,
222
+ 3,
223
+ 4,
224
+ 5,
225
+ 6,
226
+ 7,
227
+ 8,
228
+ 9,
229
+ 10,
230
+ 20,
231
+ 50,
232
+ 100,
233
+ 200
234
+ ],
235
+ "primary_score": "harmonic_mean_Mass_Formula_structure_Top1",
236
+ "report_formula_Top1_and_Top10_separately": true,
237
+ "report_spectrum_micro_target_macro_key14_macro": true,
238
+ "coarse_and_fine_retrieval_diagnostics": true,
239
+ "never_filter_official_pools_or_inject_truth": true,
240
+ "test_and_casmi_only_after_predeclared_selection": true,
241
+ "casmi_pool": "data/benchmarks/casmi2022_sirius6312_top10_pubchem_10ppm_connectivity_v1",
242
+ "casmi_candidate_cap": null,
243
+ "casmi_denominator": 500,
244
+ "mces_enabled": false
245
+ },
246
+ "logging": {
247
+ "per_branch_valid_anchors_and_groups": true,
248
+ "positive_negative_and_gray_pair_counts": true,
249
+ "mass_positive_same_formula_vs_cross_formula": true,
250
+ "same_key14_false_negative_count": true,
251
+ "raw_and_weighted_losses": true,
252
+ "gradient_norm_per_task_and_pairwise_gradient_cosine": true,
253
+ "projection_variance_effective_rank_and_pair_similarity": true,
254
+ "per_source_polarity_adduct": true,
255
+ "distinct_MS_exposures_and_repeated_draws": true,
256
+ "GPU_seconds_peak_memory_and_molecule_forward_count": true
257
+ },
258
+ "experiment": {
259
+ "id": "C12_no_reverse_crossmodal",
260
+ "description": "Forward-only cross-modal control, total cross-modal coefficient remains one",
261
+ "active_auxiliary_tasks": [
262
+ "ms_fine",
263
+ "mol_fine",
264
+ "ms_formula",
265
+ "mol_formula",
266
+ "ms_mass",
267
+ "mol_mass"
268
+ ],
269
+ "auxiliary_coefficient_sum": 0.3,
270
+ "output_template": "/workspace/xj/SpecPartition-MS/runs/hierarchical_intra_modal_20261103/C12_no_reverse_crossmodal/seed_{seed}",
271
+ "priority": "secondary_ablation"
272
+ }
273
+ }
code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C13_fine_budget_matched.json ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": 1,
3
+ "suite_id": "hierarchical_intra_modal_20261103",
4
+ "execution": {
5
+ "status": "configuration_and_loss_components_only",
6
+ "allow_training": false,
7
+ "runtime_entrypoint": null,
8
+ "missing_integration": [
9
+ "hierarchical_no_repeat_sampler",
10
+ "independent_stochastic_gnn_views",
11
+ "rng_safe_view_recomputation",
12
+ "joint_loss_router_and_gpu_acceptance"
13
+ ]
14
+ },
15
+ "initialization": {
16
+ "checkpoint": "/workspace/xj/SpecPartition-MS/runs/rebuild_joint_r08data_20261102/epoch_04.pt",
17
+ "sha256": "618aaf195cfdc3a4107e71cf2b3a56d5853b407564acf01de11c67e6af40f3d7",
18
+ "policy": "same_fixed_parent_weights_all_arms",
19
+ "optimizer_policy": "new_AdamW_for_every_arm_not_live_run_resume",
20
+ "selection_source": "Validation_only_fixed_before_ablation",
21
+ "new_heads": "same_initialization_per_seed_for_all_arms"
22
+ },
23
+ "data": {
24
+ "root": "/workspace/xj/SpecPartition-MS",
25
+ "labels": "data/derived/data_release_r07_key14_20261101/train.json",
26
+ "prepared": "data/derived/joint_r09_inputs_20261102/train.sqlite",
27
+ "candidates": "data/derived/training_r08_true_formula_records_20261101/preparation.sqlite",
28
+ "heldout_registry": "data/derived/data_release_r07_key14_20261101/heldout_registry.json",
29
+ "label_policy_sha256": "91971b3f6979586b32c90350330cb6712e60c3c6f4b872de4113311f8a95adf7",
30
+ "candidate_config_sha256": "53a365647ed8c54e216ff2cd25c011ed7f7d47a920f54c0136eea0c8dabade65",
31
+ "parent_training_config_sha256": "5f8f8635c60e37a194660b73f0fae69571a3f97a045f1d5c2f0e5fbf76e450d0",
32
+ "records": 643587,
33
+ "source_counts": {
34
+ "MSG_Train": 162974,
35
+ "MSP_libraries": 261644,
36
+ "MS2_SAN_JSONL": 218969
37
+ },
38
+ "exclude_heldout_labels_and_negatives_by": "key14",
39
+ "test_or_casmi_labels_in_training": false,
40
+ "preserve_same_structure_multiple_spectra": true,
41
+ "online_queries_during_training": false,
42
+ "coarse_labels_are_training_supervision_not_inference_inputs": true
43
+ },
44
+ "budget": {
45
+ "seeds": [
46
+ 20261103,
47
+ 20261104,
48
+ 20261105
49
+ ],
50
+ "optimizer_updates_per_seed": 6000,
51
+ "learning_rate": 3e-05,
52
+ "minimum_learning_rate": 3e-06,
53
+ "warmup_steps": 300,
54
+ "weight_decay": 0.0001,
55
+ "gradient_clip": 5.0,
56
+ "schedule": "cosine",
57
+ "bf16": true,
58
+ "graph_chunk": 128,
59
+ "spectrum_chunk": 64,
60
+ "pool_micro_views": 4,
61
+ "checkpoint_every": 100,
62
+ "validation_every_updates": 2000,
63
+ "source_presence_schedule": "same_R09_5093_step_epoch_plan",
64
+ "same_MS_exposure_and_candidate_draw_budget_across_arms": true,
65
+ "equal_wall_clock_or_FLOPs_claimed": false
66
+ },
67
+ "model": {
68
+ "backbone": "archived_R2_direct_ranker_256d_6Transformer_6MPNN",
69
+ "backbone_registered_parameters": 16409742,
70
+ "relation_or_cut_enabled": false,
71
+ "projection_heads": {
72
+ "input_dim": 256,
73
+ "hidden_dim": 256,
74
+ "output_dim": 128,
75
+ "activation": "GELU",
76
+ "normalize": "L2",
77
+ "names": [
78
+ "ms_identity",
79
+ "mol_identity",
80
+ "ms_formula",
81
+ "mol_formula",
82
+ "ms_mass",
83
+ "mol_mass"
84
+ ],
85
+ "register_all_heads_in_all_arms": true,
86
+ "shared_backbone_receives_auxiliary_gradients": true
87
+ },
88
+ "head_routing": "separate_by_modality_and_granularity",
89
+ "mass_head_input": "shared_encoder_representation",
90
+ "auxiliary_heads_used_at_inference": false,
91
+ "original_final_ranking_score_unchanged": true
92
+ },
93
+ "sampling": {
94
+ "mode": "hierarchical_formula_identity_spectra",
95
+ "odata_batch_size": 256,
96
+ "msg_batch_size": 32,
97
+ "desired_odata_shape": {
98
+ "formulas": 8,
99
+ "identities_per_formula": 8,
100
+ "spectra_per_identity": 4
101
+ },
102
+ "desired_msg_shape": {
103
+ "formulas": 4,
104
+ "identities_per_formula": 4,
105
+ "spectra_per_identity": 2
106
+ },
107
+ "rare_group_fallback": "pack_remaining_real_records_without_replacement",
108
+ "mass_positive_coverage": "measure_same_formula_and_cross_formula_pairs_separately_do_not_assume_formula_sampler_covers_mass_neighbors",
109
+ "force_duplicate_spectra_to_fill_group": false,
110
+ "each_source_record_once_before_next_source_epoch": true,
111
+ "singleton_policy": "retain_existing_objectives_mask_missing_auxiliary_positives",
112
+ "explicit_odata_queries": 16,
113
+ "odata_negative_draws": 128,
114
+ "msg_views": [
115
+ "mass",
116
+ "formula"
117
+ ],
118
+ "msg_negative_draws_per_view": 63,
119
+ "candidate_draws_with_replacement": true,
120
+ "candidate_pool_deduplicate_key14": false,
121
+ "same_truth_key14_is_never_negative": true
122
+ },
123
+ "views": {
124
+ "MS": {
125
+ "positive_source": "distinct_real_spectra_of_same_key14",
126
+ "spectrum_augmentation": "none",
127
+ "repeat_physical_record_is_not_positive": true
128
+ },
129
+ "molecule": {
130
+ "count": 2,
131
+ "strategy": "independent_hidden_feature_dropout",
132
+ "dropout": 0.1,
133
+ "delete_atoms_or_bonds": false,
134
+ "random_SMILES_alone_is_not_new_view": true
135
+ },
136
+ "primary_encoder_path_dropout": 0.0,
137
+ "compute_two_molecule_views_for_all_arms": true,
138
+ "stochastic_view_gradient_cache": "disabled_keep_view_graph_or_verified_RNG_replay"
139
+ },
140
+ "loss": {
141
+ "base": {
142
+ "formula": 1.0,
143
+ "ms_to_mol": 0.5,
144
+ "mol_to_ms": 0.5,
145
+ "odata_pool": 0.5,
146
+ "msg_mass_pool": 0.25,
147
+ "msg_formula_pool": 0.25
148
+ },
149
+ "formula_task": {
150
+ "ce": 1.0,
151
+ "gap": 0.1,
152
+ "hard_wrong_topk": 3,
153
+ "margin": 0.2,
154
+ "element_count": 0.2
155
+ },
156
+ "auxiliary": {
157
+ "ms_fine": 0.2,
158
+ "mol_fine": 0.1,
159
+ "ms_formula": 0.0,
160
+ "mol_formula": 0.0,
161
+ "ms_mass": 0.0,
162
+ "mol_mass": 0.0
163
+ },
164
+ "auxiliary_ramp_steps": 500,
165
+ "temperature": {
166
+ "identity": 0.1,
167
+ "formula": 0.15,
168
+ "mass": 0.2
169
+ },
170
+ "fine_identity": "key14",
171
+ "self_pairs": "exclude",
172
+ "missing_positive_or_negative": "differentiable_zero_and_log_effective_count",
173
+ "anchor_reduction": {
174
+ "fine": "key14_macro",
175
+ "formula": "formula_macro",
176
+ "mass": "key14_macro"
177
+ },
178
+ "formula_coarse": {
179
+ "label": "exact_element_count_canonical_formula",
180
+ "positive": "same_formula_different_key14",
181
+ "negative": "different_formula",
182
+ "same_key14_pair_policy": "exclude_from_coarse",
183
+ "same_scaffold_is_not_identity_positive": true
184
+ },
185
+ "mass_coarse": {
186
+ "mode": "soft_neighborhood",
187
+ "MS_mass": "abs_charge_times_experimental_precursor_minus_adduct_delta",
188
+ "molecule_mass": "cached_candidate_neutral_monoisotopic_mass",
189
+ "distance_unit": "Da",
190
+ "positive_radius_da": 0.5,
191
+ "negative_start_da": 2.0,
192
+ "gaussian_sigma_da": 0.25,
193
+ "gray_zone": "exclude",
194
+ "same_key14_pair_policy": "exclude_from_coarse",
195
+ "hard_bin_width_da": 1.0,
196
+ "hard_bin_offset_da": 0.0,
197
+ "MS_quality_mask": "reference_precursor_consistency_within_10ppm",
198
+ "candidate_10ppm_filter_is_not_mass_bucket_width": true,
199
+ "mass_neighborhood_is_not_chemical_similarity_or_equivalence_class": true
200
+ }
201
+ },
202
+ "evaluation": {
203
+ "selection_split": "MSG_Validation",
204
+ "spectra": 19429,
205
+ "official_views": [
206
+ "mass",
207
+ "formula"
208
+ ],
209
+ "structure_topk": [
210
+ 1,
211
+ 3,
212
+ 5,
213
+ 10,
214
+ 20,
215
+ 50,
216
+ 100,
217
+ 200
218
+ ],
219
+ "formula_topk": [
220
+ 1,
221
+ 2,
222
+ 3,
223
+ 4,
224
+ 5,
225
+ 6,
226
+ 7,
227
+ 8,
228
+ 9,
229
+ 10,
230
+ 20,
231
+ 50,
232
+ 100,
233
+ 200
234
+ ],
235
+ "primary_score": "harmonic_mean_Mass_Formula_structure_Top1",
236
+ "report_formula_Top1_and_Top10_separately": true,
237
+ "report_spectrum_micro_target_macro_key14_macro": true,
238
+ "coarse_and_fine_retrieval_diagnostics": true,
239
+ "never_filter_official_pools_or_inject_truth": true,
240
+ "test_and_casmi_only_after_predeclared_selection": true,
241
+ "casmi_pool": "data/benchmarks/casmi2022_sirius6312_top10_pubchem_10ppm_connectivity_v1",
242
+ "casmi_candidate_cap": null,
243
+ "casmi_denominator": 500,
244
+ "mces_enabled": false
245
+ },
246
+ "logging": {
247
+ "per_branch_valid_anchors_and_groups": true,
248
+ "positive_negative_and_gray_pair_counts": true,
249
+ "mass_positive_same_formula_vs_cross_formula": true,
250
+ "same_key14_false_negative_count": true,
251
+ "raw_and_weighted_losses": true,
252
+ "gradient_norm_per_task_and_pairwise_gradient_cosine": true,
253
+ "projection_variance_effective_rank_and_pair_similarity": true,
254
+ "per_source_polarity_adduct": true,
255
+ "distinct_MS_exposures_and_repeated_draws": true,
256
+ "GPU_seconds_peak_memory_and_molecule_forward_count": true
257
+ },
258
+ "experiment": {
259
+ "id": "C13_fine_budget_matched",
260
+ "description": "Fine-only control with total auxiliary coefficient 0.30",
261
+ "active_auxiliary_tasks": [
262
+ "ms_fine",
263
+ "mol_fine"
264
+ ],
265
+ "auxiliary_coefficient_sum": 0.3,
266
+ "output_template": "/workspace/xj/SpecPartition-MS/runs/hierarchical_intra_modal_20261103/C13_fine_budget_matched/seed_{seed}",
267
+ "priority": "secondary_ablation"
268
+ }
269
+ }
code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C14_fine_formula_budget_matched.json ADDED
@@ -0,0 +1,271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": 1,
3
+ "suite_id": "hierarchical_intra_modal_20261103",
4
+ "execution": {
5
+ "status": "configuration_and_loss_components_only",
6
+ "allow_training": false,
7
+ "runtime_entrypoint": null,
8
+ "missing_integration": [
9
+ "hierarchical_no_repeat_sampler",
10
+ "independent_stochastic_gnn_views",
11
+ "rng_safe_view_recomputation",
12
+ "joint_loss_router_and_gpu_acceptance"
13
+ ]
14
+ },
15
+ "initialization": {
16
+ "checkpoint": "/workspace/xj/SpecPartition-MS/runs/rebuild_joint_r08data_20261102/epoch_04.pt",
17
+ "sha256": "618aaf195cfdc3a4107e71cf2b3a56d5853b407564acf01de11c67e6af40f3d7",
18
+ "policy": "same_fixed_parent_weights_all_arms",
19
+ "optimizer_policy": "new_AdamW_for_every_arm_not_live_run_resume",
20
+ "selection_source": "Validation_only_fixed_before_ablation",
21
+ "new_heads": "same_initialization_per_seed_for_all_arms"
22
+ },
23
+ "data": {
24
+ "root": "/workspace/xj/SpecPartition-MS",
25
+ "labels": "data/derived/data_release_r07_key14_20261101/train.json",
26
+ "prepared": "data/derived/joint_r09_inputs_20261102/train.sqlite",
27
+ "candidates": "data/derived/training_r08_true_formula_records_20261101/preparation.sqlite",
28
+ "heldout_registry": "data/derived/data_release_r07_key14_20261101/heldout_registry.json",
29
+ "label_policy_sha256": "91971b3f6979586b32c90350330cb6712e60c3c6f4b872de4113311f8a95adf7",
30
+ "candidate_config_sha256": "53a365647ed8c54e216ff2cd25c011ed7f7d47a920f54c0136eea0c8dabade65",
31
+ "parent_training_config_sha256": "5f8f8635c60e37a194660b73f0fae69571a3f97a045f1d5c2f0e5fbf76e450d0",
32
+ "records": 643587,
33
+ "source_counts": {
34
+ "MSG_Train": 162974,
35
+ "MSP_libraries": 261644,
36
+ "MS2_SAN_JSONL": 218969
37
+ },
38
+ "exclude_heldout_labels_and_negatives_by": "key14",
39
+ "test_or_casmi_labels_in_training": false,
40
+ "preserve_same_structure_multiple_spectra": true,
41
+ "online_queries_during_training": false,
42
+ "coarse_labels_are_training_supervision_not_inference_inputs": true
43
+ },
44
+ "budget": {
45
+ "seeds": [
46
+ 20261103,
47
+ 20261104,
48
+ 20261105
49
+ ],
50
+ "optimizer_updates_per_seed": 6000,
51
+ "learning_rate": 3e-05,
52
+ "minimum_learning_rate": 3e-06,
53
+ "warmup_steps": 300,
54
+ "weight_decay": 0.0001,
55
+ "gradient_clip": 5.0,
56
+ "schedule": "cosine",
57
+ "bf16": true,
58
+ "graph_chunk": 128,
59
+ "spectrum_chunk": 64,
60
+ "pool_micro_views": 4,
61
+ "checkpoint_every": 100,
62
+ "validation_every_updates": 2000,
63
+ "source_presence_schedule": "same_R09_5093_step_epoch_plan",
64
+ "same_MS_exposure_and_candidate_draw_budget_across_arms": true,
65
+ "equal_wall_clock_or_FLOPs_claimed": false
66
+ },
67
+ "model": {
68
+ "backbone": "archived_R2_direct_ranker_256d_6Transformer_6MPNN",
69
+ "backbone_registered_parameters": 16409742,
70
+ "relation_or_cut_enabled": false,
71
+ "projection_heads": {
72
+ "input_dim": 256,
73
+ "hidden_dim": 256,
74
+ "output_dim": 128,
75
+ "activation": "GELU",
76
+ "normalize": "L2",
77
+ "names": [
78
+ "ms_identity",
79
+ "mol_identity",
80
+ "ms_formula",
81
+ "mol_formula",
82
+ "ms_mass",
83
+ "mol_mass"
84
+ ],
85
+ "register_all_heads_in_all_arms": true,
86
+ "shared_backbone_receives_auxiliary_gradients": true
87
+ },
88
+ "head_routing": "separate_by_modality_and_granularity",
89
+ "mass_head_input": "shared_encoder_representation",
90
+ "auxiliary_heads_used_at_inference": false,
91
+ "original_final_ranking_score_unchanged": true
92
+ },
93
+ "sampling": {
94
+ "mode": "hierarchical_formula_identity_spectra",
95
+ "odata_batch_size": 256,
96
+ "msg_batch_size": 32,
97
+ "desired_odata_shape": {
98
+ "formulas": 8,
99
+ "identities_per_formula": 8,
100
+ "spectra_per_identity": 4
101
+ },
102
+ "desired_msg_shape": {
103
+ "formulas": 4,
104
+ "identities_per_formula": 4,
105
+ "spectra_per_identity": 2
106
+ },
107
+ "rare_group_fallback": "pack_remaining_real_records_without_replacement",
108
+ "mass_positive_coverage": "measure_same_formula_and_cross_formula_pairs_separately_do_not_assume_formula_sampler_covers_mass_neighbors",
109
+ "force_duplicate_spectra_to_fill_group": false,
110
+ "each_source_record_once_before_next_source_epoch": true,
111
+ "singleton_policy": "retain_existing_objectives_mask_missing_auxiliary_positives",
112
+ "explicit_odata_queries": 16,
113
+ "odata_negative_draws": 128,
114
+ "msg_views": [
115
+ "mass",
116
+ "formula"
117
+ ],
118
+ "msg_negative_draws_per_view": 63,
119
+ "candidate_draws_with_replacement": true,
120
+ "candidate_pool_deduplicate_key14": false,
121
+ "same_truth_key14_is_never_negative": true
122
+ },
123
+ "views": {
124
+ "MS": {
125
+ "positive_source": "distinct_real_spectra_of_same_key14",
126
+ "spectrum_augmentation": "none",
127
+ "repeat_physical_record_is_not_positive": true
128
+ },
129
+ "molecule": {
130
+ "count": 2,
131
+ "strategy": "independent_hidden_feature_dropout",
132
+ "dropout": 0.1,
133
+ "delete_atoms_or_bonds": false,
134
+ "random_SMILES_alone_is_not_new_view": true
135
+ },
136
+ "primary_encoder_path_dropout": 0.0,
137
+ "compute_two_molecule_views_for_all_arms": true,
138
+ "stochastic_view_gradient_cache": "disabled_keep_view_graph_or_verified_RNG_replay"
139
+ },
140
+ "loss": {
141
+ "base": {
142
+ "formula": 1.0,
143
+ "ms_to_mol": 0.5,
144
+ "mol_to_ms": 0.5,
145
+ "odata_pool": 0.5,
146
+ "msg_mass_pool": 0.25,
147
+ "msg_formula_pool": 0.25
148
+ },
149
+ "formula_task": {
150
+ "ce": 1.0,
151
+ "gap": 0.1,
152
+ "hard_wrong_topk": 3,
153
+ "margin": 0.2,
154
+ "element_count": 0.2
155
+ },
156
+ "auxiliary": {
157
+ "ms_fine": 0.12,
158
+ "mol_fine": 0.06,
159
+ "ms_formula": 0.06,
160
+ "mol_formula": 0.06,
161
+ "ms_mass": 0.0,
162
+ "mol_mass": 0.0
163
+ },
164
+ "auxiliary_ramp_steps": 500,
165
+ "temperature": {
166
+ "identity": 0.1,
167
+ "formula": 0.15,
168
+ "mass": 0.2
169
+ },
170
+ "fine_identity": "key14",
171
+ "self_pairs": "exclude",
172
+ "missing_positive_or_negative": "differentiable_zero_and_log_effective_count",
173
+ "anchor_reduction": {
174
+ "fine": "key14_macro",
175
+ "formula": "formula_macro",
176
+ "mass": "key14_macro"
177
+ },
178
+ "formula_coarse": {
179
+ "label": "exact_element_count_canonical_formula",
180
+ "positive": "same_formula_different_key14",
181
+ "negative": "different_formula",
182
+ "same_key14_pair_policy": "exclude_from_coarse",
183
+ "same_scaffold_is_not_identity_positive": true
184
+ },
185
+ "mass_coarse": {
186
+ "mode": "soft_neighborhood",
187
+ "MS_mass": "abs_charge_times_experimental_precursor_minus_adduct_delta",
188
+ "molecule_mass": "cached_candidate_neutral_monoisotopic_mass",
189
+ "distance_unit": "Da",
190
+ "positive_radius_da": 0.5,
191
+ "negative_start_da": 2.0,
192
+ "gaussian_sigma_da": 0.25,
193
+ "gray_zone": "exclude",
194
+ "same_key14_pair_policy": "exclude_from_coarse",
195
+ "hard_bin_width_da": 1.0,
196
+ "hard_bin_offset_da": 0.0,
197
+ "MS_quality_mask": "reference_precursor_consistency_within_10ppm",
198
+ "candidate_10ppm_filter_is_not_mass_bucket_width": true,
199
+ "mass_neighborhood_is_not_chemical_similarity_or_equivalence_class": true
200
+ }
201
+ },
202
+ "evaluation": {
203
+ "selection_split": "MSG_Validation",
204
+ "spectra": 19429,
205
+ "official_views": [
206
+ "mass",
207
+ "formula"
208
+ ],
209
+ "structure_topk": [
210
+ 1,
211
+ 3,
212
+ 5,
213
+ 10,
214
+ 20,
215
+ 50,
216
+ 100,
217
+ 200
218
+ ],
219
+ "formula_topk": [
220
+ 1,
221
+ 2,
222
+ 3,
223
+ 4,
224
+ 5,
225
+ 6,
226
+ 7,
227
+ 8,
228
+ 9,
229
+ 10,
230
+ 20,
231
+ 50,
232
+ 100,
233
+ 200
234
+ ],
235
+ "primary_score": "harmonic_mean_Mass_Formula_structure_Top1",
236
+ "report_formula_Top1_and_Top10_separately": true,
237
+ "report_spectrum_micro_target_macro_key14_macro": true,
238
+ "coarse_and_fine_retrieval_diagnostics": true,
239
+ "never_filter_official_pools_or_inject_truth": true,
240
+ "test_and_casmi_only_after_predeclared_selection": true,
241
+ "casmi_pool": "data/benchmarks/casmi2022_sirius6312_top10_pubchem_10ppm_connectivity_v1",
242
+ "casmi_candidate_cap": null,
243
+ "casmi_denominator": 500,
244
+ "mces_enabled": false
245
+ },
246
+ "logging": {
247
+ "per_branch_valid_anchors_and_groups": true,
248
+ "positive_negative_and_gray_pair_counts": true,
249
+ "mass_positive_same_formula_vs_cross_formula": true,
250
+ "same_key14_false_negative_count": true,
251
+ "raw_and_weighted_losses": true,
252
+ "gradient_norm_per_task_and_pairwise_gradient_cosine": true,
253
+ "projection_variance_effective_rank_and_pair_similarity": true,
254
+ "per_source_polarity_adduct": true,
255
+ "distinct_MS_exposures_and_repeated_draws": true,
256
+ "GPU_seconds_peak_memory_and_molecule_forward_count": true
257
+ },
258
+ "experiment": {
259
+ "id": "C14_fine_formula_budget_matched",
260
+ "description": "Fine-plus-formula control with auxiliary coefficient 0.30",
261
+ "active_auxiliary_tasks": [
262
+ "ms_fine",
263
+ "mol_fine",
264
+ "ms_formula",
265
+ "mol_formula"
266
+ ],
267
+ "auxiliary_coefficient_sum": 0.3,
268
+ "output_template": "/workspace/xj/SpecPartition-MS/runs/hierarchical_intra_modal_20261103/C14_fine_formula_budget_matched/seed_{seed}",
269
+ "priority": "secondary_ablation"
270
+ }
271
+ }
code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C15_fine_mass_budget_matched.json ADDED
@@ -0,0 +1,271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": 1,
3
+ "suite_id": "hierarchical_intra_modal_20261103",
4
+ "execution": {
5
+ "status": "configuration_and_loss_components_only",
6
+ "allow_training": false,
7
+ "runtime_entrypoint": null,
8
+ "missing_integration": [
9
+ "hierarchical_no_repeat_sampler",
10
+ "independent_stochastic_gnn_views",
11
+ "rng_safe_view_recomputation",
12
+ "joint_loss_router_and_gpu_acceptance"
13
+ ]
14
+ },
15
+ "initialization": {
16
+ "checkpoint": "/workspace/xj/SpecPartition-MS/runs/rebuild_joint_r08data_20261102/epoch_04.pt",
17
+ "sha256": "618aaf195cfdc3a4107e71cf2b3a56d5853b407564acf01de11c67e6af40f3d7",
18
+ "policy": "same_fixed_parent_weights_all_arms",
19
+ "optimizer_policy": "new_AdamW_for_every_arm_not_live_run_resume",
20
+ "selection_source": "Validation_only_fixed_before_ablation",
21
+ "new_heads": "same_initialization_per_seed_for_all_arms"
22
+ },
23
+ "data": {
24
+ "root": "/workspace/xj/SpecPartition-MS",
25
+ "labels": "data/derived/data_release_r07_key14_20261101/train.json",
26
+ "prepared": "data/derived/joint_r09_inputs_20261102/train.sqlite",
27
+ "candidates": "data/derived/training_r08_true_formula_records_20261101/preparation.sqlite",
28
+ "heldout_registry": "data/derived/data_release_r07_key14_20261101/heldout_registry.json",
29
+ "label_policy_sha256": "91971b3f6979586b32c90350330cb6712e60c3c6f4b872de4113311f8a95adf7",
30
+ "candidate_config_sha256": "53a365647ed8c54e216ff2cd25c011ed7f7d47a920f54c0136eea0c8dabade65",
31
+ "parent_training_config_sha256": "5f8f8635c60e37a194660b73f0fae69571a3f97a045f1d5c2f0e5fbf76e450d0",
32
+ "records": 643587,
33
+ "source_counts": {
34
+ "MSG_Train": 162974,
35
+ "MSP_libraries": 261644,
36
+ "MS2_SAN_JSONL": 218969
37
+ },
38
+ "exclude_heldout_labels_and_negatives_by": "key14",
39
+ "test_or_casmi_labels_in_training": false,
40
+ "preserve_same_structure_multiple_spectra": true,
41
+ "online_queries_during_training": false,
42
+ "coarse_labels_are_training_supervision_not_inference_inputs": true
43
+ },
44
+ "budget": {
45
+ "seeds": [
46
+ 20261103,
47
+ 20261104,
48
+ 20261105
49
+ ],
50
+ "optimizer_updates_per_seed": 6000,
51
+ "learning_rate": 3e-05,
52
+ "minimum_learning_rate": 3e-06,
53
+ "warmup_steps": 300,
54
+ "weight_decay": 0.0001,
55
+ "gradient_clip": 5.0,
56
+ "schedule": "cosine",
57
+ "bf16": true,
58
+ "graph_chunk": 128,
59
+ "spectrum_chunk": 64,
60
+ "pool_micro_views": 4,
61
+ "checkpoint_every": 100,
62
+ "validation_every_updates": 2000,
63
+ "source_presence_schedule": "same_R09_5093_step_epoch_plan",
64
+ "same_MS_exposure_and_candidate_draw_budget_across_arms": true,
65
+ "equal_wall_clock_or_FLOPs_claimed": false
66
+ },
67
+ "model": {
68
+ "backbone": "archived_R2_direct_ranker_256d_6Transformer_6MPNN",
69
+ "backbone_registered_parameters": 16409742,
70
+ "relation_or_cut_enabled": false,
71
+ "projection_heads": {
72
+ "input_dim": 256,
73
+ "hidden_dim": 256,
74
+ "output_dim": 128,
75
+ "activation": "GELU",
76
+ "normalize": "L2",
77
+ "names": [
78
+ "ms_identity",
79
+ "mol_identity",
80
+ "ms_formula",
81
+ "mol_formula",
82
+ "ms_mass",
83
+ "mol_mass"
84
+ ],
85
+ "register_all_heads_in_all_arms": true,
86
+ "shared_backbone_receives_auxiliary_gradients": true
87
+ },
88
+ "head_routing": "separate_by_modality_and_granularity",
89
+ "mass_head_input": "shared_encoder_representation",
90
+ "auxiliary_heads_used_at_inference": false,
91
+ "original_final_ranking_score_unchanged": true
92
+ },
93
+ "sampling": {
94
+ "mode": "hierarchical_formula_identity_spectra",
95
+ "odata_batch_size": 256,
96
+ "msg_batch_size": 32,
97
+ "desired_odata_shape": {
98
+ "formulas": 8,
99
+ "identities_per_formula": 8,
100
+ "spectra_per_identity": 4
101
+ },
102
+ "desired_msg_shape": {
103
+ "formulas": 4,
104
+ "identities_per_formula": 4,
105
+ "spectra_per_identity": 2
106
+ },
107
+ "rare_group_fallback": "pack_remaining_real_records_without_replacement",
108
+ "mass_positive_coverage": "measure_same_formula_and_cross_formula_pairs_separately_do_not_assume_formula_sampler_covers_mass_neighbors",
109
+ "force_duplicate_spectra_to_fill_group": false,
110
+ "each_source_record_once_before_next_source_epoch": true,
111
+ "singleton_policy": "retain_existing_objectives_mask_missing_auxiliary_positives",
112
+ "explicit_odata_queries": 16,
113
+ "odata_negative_draws": 128,
114
+ "msg_views": [
115
+ "mass",
116
+ "formula"
117
+ ],
118
+ "msg_negative_draws_per_view": 63,
119
+ "candidate_draws_with_replacement": true,
120
+ "candidate_pool_deduplicate_key14": false,
121
+ "same_truth_key14_is_never_negative": true
122
+ },
123
+ "views": {
124
+ "MS": {
125
+ "positive_source": "distinct_real_spectra_of_same_key14",
126
+ "spectrum_augmentation": "none",
127
+ "repeat_physical_record_is_not_positive": true
128
+ },
129
+ "molecule": {
130
+ "count": 2,
131
+ "strategy": "independent_hidden_feature_dropout",
132
+ "dropout": 0.1,
133
+ "delete_atoms_or_bonds": false,
134
+ "random_SMILES_alone_is_not_new_view": true
135
+ },
136
+ "primary_encoder_path_dropout": 0.0,
137
+ "compute_two_molecule_views_for_all_arms": true,
138
+ "stochastic_view_gradient_cache": "disabled_keep_view_graph_or_verified_RNG_replay"
139
+ },
140
+ "loss": {
141
+ "base": {
142
+ "formula": 1.0,
143
+ "ms_to_mol": 0.5,
144
+ "mol_to_ms": 0.5,
145
+ "odata_pool": 0.5,
146
+ "msg_mass_pool": 0.25,
147
+ "msg_formula_pool": 0.25
148
+ },
149
+ "formula_task": {
150
+ "ce": 1.0,
151
+ "gap": 0.1,
152
+ "hard_wrong_topk": 3,
153
+ "margin": 0.2,
154
+ "element_count": 0.2
155
+ },
156
+ "auxiliary": {
157
+ "ms_fine": 0.15,
158
+ "mol_fine": 0.075,
159
+ "ms_formula": 0.0,
160
+ "mol_formula": 0.0,
161
+ "ms_mass": 0.0375,
162
+ "mol_mass": 0.0375
163
+ },
164
+ "auxiliary_ramp_steps": 500,
165
+ "temperature": {
166
+ "identity": 0.1,
167
+ "formula": 0.15,
168
+ "mass": 0.2
169
+ },
170
+ "fine_identity": "key14",
171
+ "self_pairs": "exclude",
172
+ "missing_positive_or_negative": "differentiable_zero_and_log_effective_count",
173
+ "anchor_reduction": {
174
+ "fine": "key14_macro",
175
+ "formula": "formula_macro",
176
+ "mass": "key14_macro"
177
+ },
178
+ "formula_coarse": {
179
+ "label": "exact_element_count_canonical_formula",
180
+ "positive": "same_formula_different_key14",
181
+ "negative": "different_formula",
182
+ "same_key14_pair_policy": "exclude_from_coarse",
183
+ "same_scaffold_is_not_identity_positive": true
184
+ },
185
+ "mass_coarse": {
186
+ "mode": "soft_neighborhood",
187
+ "MS_mass": "abs_charge_times_experimental_precursor_minus_adduct_delta",
188
+ "molecule_mass": "cached_candidate_neutral_monoisotopic_mass",
189
+ "distance_unit": "Da",
190
+ "positive_radius_da": 0.5,
191
+ "negative_start_da": 2.0,
192
+ "gaussian_sigma_da": 0.25,
193
+ "gray_zone": "exclude",
194
+ "same_key14_pair_policy": "exclude_from_coarse",
195
+ "hard_bin_width_da": 1.0,
196
+ "hard_bin_offset_da": 0.0,
197
+ "MS_quality_mask": "reference_precursor_consistency_within_10ppm",
198
+ "candidate_10ppm_filter_is_not_mass_bucket_width": true,
199
+ "mass_neighborhood_is_not_chemical_similarity_or_equivalence_class": true
200
+ }
201
+ },
202
+ "evaluation": {
203
+ "selection_split": "MSG_Validation",
204
+ "spectra": 19429,
205
+ "official_views": [
206
+ "mass",
207
+ "formula"
208
+ ],
209
+ "structure_topk": [
210
+ 1,
211
+ 3,
212
+ 5,
213
+ 10,
214
+ 20,
215
+ 50,
216
+ 100,
217
+ 200
218
+ ],
219
+ "formula_topk": [
220
+ 1,
221
+ 2,
222
+ 3,
223
+ 4,
224
+ 5,
225
+ 6,
226
+ 7,
227
+ 8,
228
+ 9,
229
+ 10,
230
+ 20,
231
+ 50,
232
+ 100,
233
+ 200
234
+ ],
235
+ "primary_score": "harmonic_mean_Mass_Formula_structure_Top1",
236
+ "report_formula_Top1_and_Top10_separately": true,
237
+ "report_spectrum_micro_target_macro_key14_macro": true,
238
+ "coarse_and_fine_retrieval_diagnostics": true,
239
+ "never_filter_official_pools_or_inject_truth": true,
240
+ "test_and_casmi_only_after_predeclared_selection": true,
241
+ "casmi_pool": "data/benchmarks/casmi2022_sirius6312_top10_pubchem_10ppm_connectivity_v1",
242
+ "casmi_candidate_cap": null,
243
+ "casmi_denominator": 500,
244
+ "mces_enabled": false
245
+ },
246
+ "logging": {
247
+ "per_branch_valid_anchors_and_groups": true,
248
+ "positive_negative_and_gray_pair_counts": true,
249
+ "mass_positive_same_formula_vs_cross_formula": true,
250
+ "same_key14_false_negative_count": true,
251
+ "raw_and_weighted_losses": true,
252
+ "gradient_norm_per_task_and_pairwise_gradient_cosine": true,
253
+ "projection_variance_effective_rank_and_pair_similarity": true,
254
+ "per_source_polarity_adduct": true,
255
+ "distinct_MS_exposures_and_repeated_draws": true,
256
+ "GPU_seconds_peak_memory_and_molecule_forward_count": true
257
+ },
258
+ "experiment": {
259
+ "id": "C15_fine_mass_budget_matched",
260
+ "description": "Fine-plus-mass control with auxiliary coefficient 0.30",
261
+ "active_auxiliary_tasks": [
262
+ "ms_fine",
263
+ "mol_fine",
264
+ "ms_mass",
265
+ "mol_mass"
266
+ ],
267
+ "auxiliary_coefficient_sum": 0.3,
268
+ "output_template": "/workspace/xj/SpecPartition-MS/runs/hierarchical_intra_modal_20261103/C15_fine_mass_budget_matched/seed_{seed}",
269
+ "priority": "secondary_ablation"
270
+ }
271
+ }
code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C16_include_identity_coarse.json ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": 1,
3
+ "suite_id": "hierarchical_intra_modal_20261103",
4
+ "execution": {
5
+ "status": "configuration_and_loss_components_only",
6
+ "allow_training": false,
7
+ "runtime_entrypoint": null,
8
+ "missing_integration": [
9
+ "hierarchical_no_repeat_sampler",
10
+ "independent_stochastic_gnn_views",
11
+ "rng_safe_view_recomputation",
12
+ "joint_loss_router_and_gpu_acceptance"
13
+ ]
14
+ },
15
+ "initialization": {
16
+ "checkpoint": "/workspace/xj/SpecPartition-MS/runs/rebuild_joint_r08data_20261102/epoch_04.pt",
17
+ "sha256": "618aaf195cfdc3a4107e71cf2b3a56d5853b407564acf01de11c67e6af40f3d7",
18
+ "policy": "same_fixed_parent_weights_all_arms",
19
+ "optimizer_policy": "new_AdamW_for_every_arm_not_live_run_resume",
20
+ "selection_source": "Validation_only_fixed_before_ablation",
21
+ "new_heads": "same_initialization_per_seed_for_all_arms"
22
+ },
23
+ "data": {
24
+ "root": "/workspace/xj/SpecPartition-MS",
25
+ "labels": "data/derived/data_release_r07_key14_20261101/train.json",
26
+ "prepared": "data/derived/joint_r09_inputs_20261102/train.sqlite",
27
+ "candidates": "data/derived/training_r08_true_formula_records_20261101/preparation.sqlite",
28
+ "heldout_registry": "data/derived/data_release_r07_key14_20261101/heldout_registry.json",
29
+ "label_policy_sha256": "91971b3f6979586b32c90350330cb6712e60c3c6f4b872de4113311f8a95adf7",
30
+ "candidate_config_sha256": "53a365647ed8c54e216ff2cd25c011ed7f7d47a920f54c0136eea0c8dabade65",
31
+ "parent_training_config_sha256": "5f8f8635c60e37a194660b73f0fae69571a3f97a045f1d5c2f0e5fbf76e450d0",
32
+ "records": 643587,
33
+ "source_counts": {
34
+ "MSG_Train": 162974,
35
+ "MSP_libraries": 261644,
36
+ "MS2_SAN_JSONL": 218969
37
+ },
38
+ "exclude_heldout_labels_and_negatives_by": "key14",
39
+ "test_or_casmi_labels_in_training": false,
40
+ "preserve_same_structure_multiple_spectra": true,
41
+ "online_queries_during_training": false,
42
+ "coarse_labels_are_training_supervision_not_inference_inputs": true
43
+ },
44
+ "budget": {
45
+ "seeds": [
46
+ 20261103,
47
+ 20261104,
48
+ 20261105
49
+ ],
50
+ "optimizer_updates_per_seed": 6000,
51
+ "learning_rate": 3e-05,
52
+ "minimum_learning_rate": 3e-06,
53
+ "warmup_steps": 300,
54
+ "weight_decay": 0.0001,
55
+ "gradient_clip": 5.0,
56
+ "schedule": "cosine",
57
+ "bf16": true,
58
+ "graph_chunk": 128,
59
+ "spectrum_chunk": 64,
60
+ "pool_micro_views": 4,
61
+ "checkpoint_every": 100,
62
+ "validation_every_updates": 2000,
63
+ "source_presence_schedule": "same_R09_5093_step_epoch_plan",
64
+ "same_MS_exposure_and_candidate_draw_budget_across_arms": true,
65
+ "equal_wall_clock_or_FLOPs_claimed": false
66
+ },
67
+ "model": {
68
+ "backbone": "archived_R2_direct_ranker_256d_6Transformer_6MPNN",
69
+ "backbone_registered_parameters": 16409742,
70
+ "relation_or_cut_enabled": false,
71
+ "projection_heads": {
72
+ "input_dim": 256,
73
+ "hidden_dim": 256,
74
+ "output_dim": 128,
75
+ "activation": "GELU",
76
+ "normalize": "L2",
77
+ "names": [
78
+ "ms_identity",
79
+ "mol_identity",
80
+ "ms_formula",
81
+ "mol_formula",
82
+ "ms_mass",
83
+ "mol_mass"
84
+ ],
85
+ "register_all_heads_in_all_arms": true,
86
+ "shared_backbone_receives_auxiliary_gradients": true
87
+ },
88
+ "head_routing": "separate_by_modality_and_granularity",
89
+ "mass_head_input": "shared_encoder_representation",
90
+ "auxiliary_heads_used_at_inference": false,
91
+ "original_final_ranking_score_unchanged": true
92
+ },
93
+ "sampling": {
94
+ "mode": "hierarchical_formula_identity_spectra",
95
+ "odata_batch_size": 256,
96
+ "msg_batch_size": 32,
97
+ "desired_odata_shape": {
98
+ "formulas": 8,
99
+ "identities_per_formula": 8,
100
+ "spectra_per_identity": 4
101
+ },
102
+ "desired_msg_shape": {
103
+ "formulas": 4,
104
+ "identities_per_formula": 4,
105
+ "spectra_per_identity": 2
106
+ },
107
+ "rare_group_fallback": "pack_remaining_real_records_without_replacement",
108
+ "mass_positive_coverage": "measure_same_formula_and_cross_formula_pairs_separately_do_not_assume_formula_sampler_covers_mass_neighbors",
109
+ "force_duplicate_spectra_to_fill_group": false,
110
+ "each_source_record_once_before_next_source_epoch": true,
111
+ "singleton_policy": "retain_existing_objectives_mask_missing_auxiliary_positives",
112
+ "explicit_odata_queries": 16,
113
+ "odata_negative_draws": 128,
114
+ "msg_views": [
115
+ "mass",
116
+ "formula"
117
+ ],
118
+ "msg_negative_draws_per_view": 63,
119
+ "candidate_draws_with_replacement": true,
120
+ "candidate_pool_deduplicate_key14": false,
121
+ "same_truth_key14_is_never_negative": true
122
+ },
123
+ "views": {
124
+ "MS": {
125
+ "positive_source": "distinct_real_spectra_of_same_key14",
126
+ "spectrum_augmentation": "none",
127
+ "repeat_physical_record_is_not_positive": true
128
+ },
129
+ "molecule": {
130
+ "count": 2,
131
+ "strategy": "independent_hidden_feature_dropout",
132
+ "dropout": 0.1,
133
+ "delete_atoms_or_bonds": false,
134
+ "random_SMILES_alone_is_not_new_view": true
135
+ },
136
+ "primary_encoder_path_dropout": 0.0,
137
+ "compute_two_molecule_views_for_all_arms": true,
138
+ "stochastic_view_gradient_cache": "disabled_keep_view_graph_or_verified_RNG_replay"
139
+ },
140
+ "loss": {
141
+ "base": {
142
+ "formula": 1.0,
143
+ "ms_to_mol": 0.5,
144
+ "mol_to_ms": 0.5,
145
+ "odata_pool": 0.5,
146
+ "msg_mass_pool": 0.25,
147
+ "msg_formula_pool": 0.25
148
+ },
149
+ "formula_task": {
150
+ "ce": 1.0,
151
+ "gap": 0.1,
152
+ "hard_wrong_topk": 3,
153
+ "margin": 0.2,
154
+ "element_count": 0.2
155
+ },
156
+ "auxiliary": {
157
+ "ms_fine": 0.1,
158
+ "mol_fine": 0.05,
159
+ "ms_formula": 0.05,
160
+ "mol_formula": 0.05,
161
+ "ms_mass": 0.025,
162
+ "mol_mass": 0.025
163
+ },
164
+ "auxiliary_ramp_steps": 500,
165
+ "temperature": {
166
+ "identity": 0.1,
167
+ "formula": 0.15,
168
+ "mass": 0.2
169
+ },
170
+ "fine_identity": "key14",
171
+ "self_pairs": "exclude",
172
+ "missing_positive_or_negative": "differentiable_zero_and_log_effective_count",
173
+ "anchor_reduction": {
174
+ "fine": "key14_macro",
175
+ "formula": "formula_macro",
176
+ "mass": "key14_macro"
177
+ },
178
+ "formula_coarse": {
179
+ "label": "exact_element_count_canonical_formula",
180
+ "positive": "same_formula_different_key14",
181
+ "negative": "different_formula",
182
+ "same_key14_pair_policy": "include_as_positive",
183
+ "same_scaffold_is_not_identity_positive": true
184
+ },
185
+ "mass_coarse": {
186
+ "mode": "soft_neighborhood",
187
+ "MS_mass": "abs_charge_times_experimental_precursor_minus_adduct_delta",
188
+ "molecule_mass": "cached_candidate_neutral_monoisotopic_mass",
189
+ "distance_unit": "Da",
190
+ "positive_radius_da": 0.5,
191
+ "negative_start_da": 2.0,
192
+ "gaussian_sigma_da": 0.25,
193
+ "gray_zone": "exclude",
194
+ "same_key14_pair_policy": "include_as_positive",
195
+ "hard_bin_width_da": 1.0,
196
+ "hard_bin_offset_da": 0.0,
197
+ "MS_quality_mask": "reference_precursor_consistency_within_10ppm",
198
+ "candidate_10ppm_filter_is_not_mass_bucket_width": true,
199
+ "mass_neighborhood_is_not_chemical_similarity_or_equivalence_class": true
200
+ }
201
+ },
202
+ "evaluation": {
203
+ "selection_split": "MSG_Validation",
204
+ "spectra": 19429,
205
+ "official_views": [
206
+ "mass",
207
+ "formula"
208
+ ],
209
+ "structure_topk": [
210
+ 1,
211
+ 3,
212
+ 5,
213
+ 10,
214
+ 20,
215
+ 50,
216
+ 100,
217
+ 200
218
+ ],
219
+ "formula_topk": [
220
+ 1,
221
+ 2,
222
+ 3,
223
+ 4,
224
+ 5,
225
+ 6,
226
+ 7,
227
+ 8,
228
+ 9,
229
+ 10,
230
+ 20,
231
+ 50,
232
+ 100,
233
+ 200
234
+ ],
235
+ "primary_score": "harmonic_mean_Mass_Formula_structure_Top1",
236
+ "report_formula_Top1_and_Top10_separately": true,
237
+ "report_spectrum_micro_target_macro_key14_macro": true,
238
+ "coarse_and_fine_retrieval_diagnostics": true,
239
+ "never_filter_official_pools_or_inject_truth": true,
240
+ "test_and_casmi_only_after_predeclared_selection": true,
241
+ "casmi_pool": "data/benchmarks/casmi2022_sirius6312_top10_pubchem_10ppm_connectivity_v1",
242
+ "casmi_candidate_cap": null,
243
+ "casmi_denominator": 500,
244
+ "mces_enabled": false
245
+ },
246
+ "logging": {
247
+ "per_branch_valid_anchors_and_groups": true,
248
+ "positive_negative_and_gray_pair_counts": true,
249
+ "mass_positive_same_formula_vs_cross_formula": true,
250
+ "same_key14_false_negative_count": true,
251
+ "raw_and_weighted_losses": true,
252
+ "gradient_norm_per_task_and_pairwise_gradient_cosine": true,
253
+ "projection_variance_effective_rank_and_pair_similarity": true,
254
+ "per_source_polarity_adduct": true,
255
+ "distinct_MS_exposures_and_repeated_draws": true,
256
+ "GPU_seconds_peak_memory_and_molecule_forward_count": true
257
+ },
258
+ "experiment": {
259
+ "id": "C16_include_identity_coarse",
260
+ "description": "Check whether coarse gain merely repeats same-identity alignment",
261
+ "active_auxiliary_tasks": [
262
+ "ms_fine",
263
+ "mol_fine",
264
+ "ms_formula",
265
+ "mol_formula",
266
+ "ms_mass",
267
+ "mol_mass"
268
+ ],
269
+ "auxiliary_coefficient_sum": 0.3,
270
+ "output_template": "/workspace/xj/SpecPartition-MS/runs/hierarchical_intra_modal_20261103/C16_include_identity_coarse/seed_{seed}",
271
+ "priority": "secondary_ablation"
272
+ }
273
+ }
code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C17_mass_metadata_shortcut.json ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": 1,
3
+ "suite_id": "hierarchical_intra_modal_20261103",
4
+ "execution": {
5
+ "status": "configuration_and_loss_components_only",
6
+ "allow_training": false,
7
+ "runtime_entrypoint": null,
8
+ "missing_integration": [
9
+ "hierarchical_no_repeat_sampler",
10
+ "independent_stochastic_gnn_views",
11
+ "rng_safe_view_recomputation",
12
+ "joint_loss_router_and_gpu_acceptance"
13
+ ]
14
+ },
15
+ "initialization": {
16
+ "checkpoint": "/workspace/xj/SpecPartition-MS/runs/rebuild_joint_r08data_20261102/epoch_04.pt",
17
+ "sha256": "618aaf195cfdc3a4107e71cf2b3a56d5853b407564acf01de11c67e6af40f3d7",
18
+ "policy": "same_fixed_parent_weights_all_arms",
19
+ "optimizer_policy": "new_AdamW_for_every_arm_not_live_run_resume",
20
+ "selection_source": "Validation_only_fixed_before_ablation",
21
+ "new_heads": "same_initialization_per_seed_for_all_arms"
22
+ },
23
+ "data": {
24
+ "root": "/workspace/xj/SpecPartition-MS",
25
+ "labels": "data/derived/data_release_r07_key14_20261101/train.json",
26
+ "prepared": "data/derived/joint_r09_inputs_20261102/train.sqlite",
27
+ "candidates": "data/derived/training_r08_true_formula_records_20261101/preparation.sqlite",
28
+ "heldout_registry": "data/derived/data_release_r07_key14_20261101/heldout_registry.json",
29
+ "label_policy_sha256": "91971b3f6979586b32c90350330cb6712e60c3c6f4b872de4113311f8a95adf7",
30
+ "candidate_config_sha256": "53a365647ed8c54e216ff2cd25c011ed7f7d47a920f54c0136eea0c8dabade65",
31
+ "parent_training_config_sha256": "5f8f8635c60e37a194660b73f0fae69571a3f97a045f1d5c2f0e5fbf76e450d0",
32
+ "records": 643587,
33
+ "source_counts": {
34
+ "MSG_Train": 162974,
35
+ "MSP_libraries": 261644,
36
+ "MS2_SAN_JSONL": 218969
37
+ },
38
+ "exclude_heldout_labels_and_negatives_by": "key14",
39
+ "test_or_casmi_labels_in_training": false,
40
+ "preserve_same_structure_multiple_spectra": true,
41
+ "online_queries_during_training": false,
42
+ "coarse_labels_are_training_supervision_not_inference_inputs": true
43
+ },
44
+ "budget": {
45
+ "seeds": [
46
+ 20261103,
47
+ 20261104,
48
+ 20261105
49
+ ],
50
+ "optimizer_updates_per_seed": 6000,
51
+ "learning_rate": 3e-05,
52
+ "minimum_learning_rate": 3e-06,
53
+ "warmup_steps": 300,
54
+ "weight_decay": 0.0001,
55
+ "gradient_clip": 5.0,
56
+ "schedule": "cosine",
57
+ "bf16": true,
58
+ "graph_chunk": 128,
59
+ "spectrum_chunk": 64,
60
+ "pool_micro_views": 4,
61
+ "checkpoint_every": 100,
62
+ "validation_every_updates": 2000,
63
+ "source_presence_schedule": "same_R09_5093_step_epoch_plan",
64
+ "same_MS_exposure_and_candidate_draw_budget_across_arms": true,
65
+ "equal_wall_clock_or_FLOPs_claimed": false
66
+ },
67
+ "model": {
68
+ "backbone": "archived_R2_direct_ranker_256d_6Transformer_6MPNN",
69
+ "backbone_registered_parameters": 16409742,
70
+ "relation_or_cut_enabled": false,
71
+ "projection_heads": {
72
+ "input_dim": 256,
73
+ "hidden_dim": 256,
74
+ "output_dim": 128,
75
+ "activation": "GELU",
76
+ "normalize": "L2",
77
+ "names": [
78
+ "ms_identity",
79
+ "mol_identity",
80
+ "ms_formula",
81
+ "mol_formula",
82
+ "ms_mass",
83
+ "mol_mass"
84
+ ],
85
+ "register_all_heads_in_all_arms": true,
86
+ "shared_backbone_receives_auxiliary_gradients": true
87
+ },
88
+ "head_routing": "separate_by_modality_and_granularity",
89
+ "mass_head_input": "neutral_mass_metadata_only_fixed_256d_features",
90
+ "auxiliary_heads_used_at_inference": false,
91
+ "original_final_ranking_score_unchanged": true
92
+ },
93
+ "sampling": {
94
+ "mode": "hierarchical_formula_identity_spectra",
95
+ "odata_batch_size": 256,
96
+ "msg_batch_size": 32,
97
+ "desired_odata_shape": {
98
+ "formulas": 8,
99
+ "identities_per_formula": 8,
100
+ "spectra_per_identity": 4
101
+ },
102
+ "desired_msg_shape": {
103
+ "formulas": 4,
104
+ "identities_per_formula": 4,
105
+ "spectra_per_identity": 2
106
+ },
107
+ "rare_group_fallback": "pack_remaining_real_records_without_replacement",
108
+ "mass_positive_coverage": "measure_same_formula_and_cross_formula_pairs_separately_do_not_assume_formula_sampler_covers_mass_neighbors",
109
+ "force_duplicate_spectra_to_fill_group": false,
110
+ "each_source_record_once_before_next_source_epoch": true,
111
+ "singleton_policy": "retain_existing_objectives_mask_missing_auxiliary_positives",
112
+ "explicit_odata_queries": 16,
113
+ "odata_negative_draws": 128,
114
+ "msg_views": [
115
+ "mass",
116
+ "formula"
117
+ ],
118
+ "msg_negative_draws_per_view": 63,
119
+ "candidate_draws_with_replacement": true,
120
+ "candidate_pool_deduplicate_key14": false,
121
+ "same_truth_key14_is_never_negative": true
122
+ },
123
+ "views": {
124
+ "MS": {
125
+ "positive_source": "distinct_real_spectra_of_same_key14",
126
+ "spectrum_augmentation": "none",
127
+ "repeat_physical_record_is_not_positive": true
128
+ },
129
+ "molecule": {
130
+ "count": 2,
131
+ "strategy": "independent_hidden_feature_dropout",
132
+ "dropout": 0.1,
133
+ "delete_atoms_or_bonds": false,
134
+ "random_SMILES_alone_is_not_new_view": true
135
+ },
136
+ "primary_encoder_path_dropout": 0.0,
137
+ "compute_two_molecule_views_for_all_arms": true,
138
+ "stochastic_view_gradient_cache": "disabled_keep_view_graph_or_verified_RNG_replay"
139
+ },
140
+ "loss": {
141
+ "base": {
142
+ "formula": 1.0,
143
+ "ms_to_mol": 0.5,
144
+ "mol_to_ms": 0.5,
145
+ "odata_pool": 0.5,
146
+ "msg_mass_pool": 0.25,
147
+ "msg_formula_pool": 0.25
148
+ },
149
+ "formula_task": {
150
+ "ce": 1.0,
151
+ "gap": 0.1,
152
+ "hard_wrong_topk": 3,
153
+ "margin": 0.2,
154
+ "element_count": 0.2
155
+ },
156
+ "auxiliary": {
157
+ "ms_fine": 0.1,
158
+ "mol_fine": 0.05,
159
+ "ms_formula": 0.05,
160
+ "mol_formula": 0.05,
161
+ "ms_mass": 0.025,
162
+ "mol_mass": 0.025
163
+ },
164
+ "auxiliary_ramp_steps": 500,
165
+ "temperature": {
166
+ "identity": 0.1,
167
+ "formula": 0.15,
168
+ "mass": 0.2
169
+ },
170
+ "fine_identity": "key14",
171
+ "self_pairs": "exclude",
172
+ "missing_positive_or_negative": "differentiable_zero_and_log_effective_count",
173
+ "anchor_reduction": {
174
+ "fine": "key14_macro",
175
+ "formula": "formula_macro",
176
+ "mass": "key14_macro"
177
+ },
178
+ "formula_coarse": {
179
+ "label": "exact_element_count_canonical_formula",
180
+ "positive": "same_formula_different_key14",
181
+ "negative": "different_formula",
182
+ "same_key14_pair_policy": "exclude_from_coarse",
183
+ "same_scaffold_is_not_identity_positive": true
184
+ },
185
+ "mass_coarse": {
186
+ "mode": "soft_neighborhood",
187
+ "MS_mass": "abs_charge_times_experimental_precursor_minus_adduct_delta",
188
+ "molecule_mass": "cached_candidate_neutral_monoisotopic_mass",
189
+ "distance_unit": "Da",
190
+ "positive_radius_da": 0.5,
191
+ "negative_start_da": 2.0,
192
+ "gaussian_sigma_da": 0.25,
193
+ "gray_zone": "exclude",
194
+ "same_key14_pair_policy": "exclude_from_coarse",
195
+ "hard_bin_width_da": 1.0,
196
+ "hard_bin_offset_da": 0.0,
197
+ "MS_quality_mask": "reference_precursor_consistency_within_10ppm",
198
+ "candidate_10ppm_filter_is_not_mass_bucket_width": true,
199
+ "mass_neighborhood_is_not_chemical_similarity_or_equivalence_class": true
200
+ }
201
+ },
202
+ "evaluation": {
203
+ "selection_split": "MSG_Validation",
204
+ "spectra": 19429,
205
+ "official_views": [
206
+ "mass",
207
+ "formula"
208
+ ],
209
+ "structure_topk": [
210
+ 1,
211
+ 3,
212
+ 5,
213
+ 10,
214
+ 20,
215
+ 50,
216
+ 100,
217
+ 200
218
+ ],
219
+ "formula_topk": [
220
+ 1,
221
+ 2,
222
+ 3,
223
+ 4,
224
+ 5,
225
+ 6,
226
+ 7,
227
+ 8,
228
+ 9,
229
+ 10,
230
+ 20,
231
+ 50,
232
+ 100,
233
+ 200
234
+ ],
235
+ "primary_score": "harmonic_mean_Mass_Formula_structure_Top1",
236
+ "report_formula_Top1_and_Top10_separately": true,
237
+ "report_spectrum_micro_target_macro_key14_macro": true,
238
+ "coarse_and_fine_retrieval_diagnostics": true,
239
+ "never_filter_official_pools_or_inject_truth": true,
240
+ "test_and_casmi_only_after_predeclared_selection": true,
241
+ "casmi_pool": "data/benchmarks/casmi2022_sirius6312_top10_pubchem_10ppm_connectivity_v1",
242
+ "casmi_candidate_cap": null,
243
+ "casmi_denominator": 500,
244
+ "mces_enabled": false
245
+ },
246
+ "logging": {
247
+ "per_branch_valid_anchors_and_groups": true,
248
+ "positive_negative_and_gray_pair_counts": true,
249
+ "mass_positive_same_formula_vs_cross_formula": true,
250
+ "same_key14_false_negative_count": true,
251
+ "raw_and_weighted_losses": true,
252
+ "gradient_norm_per_task_and_pairwise_gradient_cosine": true,
253
+ "projection_variance_effective_rank_and_pair_similarity": true,
254
+ "per_source_polarity_adduct": true,
255
+ "distinct_MS_exposures_and_repeated_draws": true,
256
+ "GPU_seconds_peak_memory_and_molecule_forward_count": true
257
+ },
258
+ "experiment": {
259
+ "id": "C17_mass_metadata_shortcut",
260
+ "description": "Diagnose trivial mass-metadata shortcut rather than fragment evidence",
261
+ "active_auxiliary_tasks": [
262
+ "ms_fine",
263
+ "mol_fine",
264
+ "ms_formula",
265
+ "mol_formula",
266
+ "ms_mass",
267
+ "mol_mass"
268
+ ],
269
+ "auxiliary_coefficient_sum": 0.3,
270
+ "output_template": "/workspace/xj/SpecPartition-MS/runs/hierarchical_intra_modal_20261103/C17_mass_metadata_shortcut/seed_{seed}",
271
+ "priority": "secondary_ablation"
272
+ }
273
+ }
code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/suite_manifest.json ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "configuration_validation_passed": true,
3
+ "training_ready": false,
4
+ "experiments": 18,
5
+ "seeds_per_experiment": 3,
6
+ "planned_replica_jobs": 54,
7
+ "automatic_launch": false,
8
+ "first_pass": [
9
+ "C00_sampler_control",
10
+ "C03_both_fine",
11
+ "C06_fine_formula",
12
+ "C07_fine_mass",
13
+ "C08_full_separate"
14
+ ],
15
+ "files": {
16
+ "configs/C00_sampler_control.json": "f2ab69f60109ba1e37326c8b095a7cbcb979eaf3e904c79219647374a6403062",
17
+ "configs/C01_ms_fine.json": "b8b15b61e8b6061ac8e23db6e2fde16925401ea561379418e8763960f45ac8c7",
18
+ "configs/C02_mol_fine.json": "756068818e7672dbe812037cad980aa1ddd4be794865fb661aba85af62bdd51f",
19
+ "configs/C03_both_fine.json": "1999d280924b950900b8509194413c34bc7f8dd9a691a82daf8ce557f8e6e959",
20
+ "configs/C04_formula_coarse.json": "c303010e517b4fabc60f9940bbf3a15c9504c2886e1fbcaa6f34f4aac67a5ccc",
21
+ "configs/C05_mass_coarse.json": "1ae1118cad164180dcc0b7cfc994c9f0a5ca385efb28acceb06986fc0e19072f",
22
+ "configs/C06_fine_formula.json": "d40629d6b03662a3eedb92ea33604fe33ab3877b3c66c2ad4242bbb2cfc7c813",
23
+ "configs/C07_fine_mass.json": "72ae9009ba2d45f864ae18a140075c1f45ea78b58cfe4d92abce0970ac0f1980",
24
+ "configs/C08_full_separate.json": "4436623c51d97e11bd041213275e629266b88d9c34fd12a9ef2ee48e1079a682",
25
+ "configs/C09_shared_head_control.json": "f51f65041ebb14be950def6890cc217611aca6e451c9e8a60f4c349dc985c512",
26
+ "configs/C10_random_sampler_control.json": "21b0602287af9a3eea41e4f2cedffdf3e1e3b8e99523ab291a87c60cb8209fc4",
27
+ "configs/C11_hard_mass_bins.json": "2358ddab6dca0433deddbbe6e84ef2839cd59e98442af109077912308ca6338d",
28
+ "configs/C12_no_reverse_crossmodal.json": "d7984ab5700619252d32cd1402667bd7de5ec52a2840342165048126575191e4",
29
+ "configs/C13_fine_budget_matched.json": "7e4fc8bf8e9ae2e64bf744c57162cb4a635d32b7869c8fb2044cf9a32208b0b5",
30
+ "configs/C14_fine_formula_budget_matched.json": "a837ba7c2464baf3226b13eb905ab462f962b45bb550811d752565e3063b9dc9",
31
+ "configs/C15_fine_mass_budget_matched.json": "1a6e8c7a9ca336f1e560fa1ed9fc4b932a2d51fefb895563cbfb7fe0583e7194",
32
+ "configs/C16_include_identity_coarse.json": "95f4ea6fbcc38c119b7f3f60becd028e40c19ffc275535141cb9588f96b02687",
33
+ "configs/C17_mass_metadata_shortcut.json": "dbfdb2834a1dc1afefe4d45fa3b8e8d561a6def89da21b7ab3579fb218cd47ca"
34
+ },
35
+ "reference_current_run_not_matched_ablation": "rebuild_joint_r08data_20261102"
36
+ }
code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/test_coarse.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import unittest
3
+ import torch
4
+ from torch.nn import functional as F
5
+ from coarse_losses import (formula_key, formula_pairs, mass_pairs,
6
+ neutral_mass_from_precursor, weighted_supcon, ProjectionBank)
7
+
8
+
9
+ class CoarseLossTests(unittest.TestCase):
10
+ def setUp(self):
11
+ torch.manual_seed(19)
12
+ torch.set_num_threads(1)
13
+
14
+ def test_formula_order_independent(self):
15
+ self.assertEqual(formula_key('C6H12O6'),formula_key('H12C6O6'))
16
+
17
+ def test_invalid_formula(self):
18
+ for formula in ['','C0H2','C2H5OH','C6H12O6+','[13C]H4']:
19
+ with self.assertRaises(ValueError):formula_key(formula)
20
+
21
+ def test_same_formula_different_identity_is_coarse_positive(self):
22
+ p,n,g=formula_pairs(['C2H6O','C2H6O','C2H6O','C3H8O'],['A','A','B','C'])
23
+ self.assertEqual(float(p[0,1]),0.)
24
+ self.assertEqual(float(p[0,2]),1.)
25
+ self.assertTrue(n[0,3]);self.assertFalse(n[0,1])
26
+ self.assertFalse(torch.diag(p.bool()).any())
27
+
28
+ def test_include_identity_is_explicit_control(self):
29
+ p,_,_=formula_pairs(['C2H6O','C2H6O'],['A','A'],True)
30
+ self.assertEqual(float(p.sum()),2.)
31
+
32
+ def test_same_identity_formula_conflict_rejected(self):
33
+ with self.assertRaises(ValueError):formula_pairs(['C2H6O','C3H8O'],['A','A'])
34
+
35
+ def test_neutral_mass_adduct_and_charge(self):
36
+ proton=1.007276466621
37
+ self.assertAlmostEqual(neutral_mass_from_precursor(100+proton,1,proton),100.)
38
+ self.assertAlmostEqual(neutral_mass_from_precursor(100-proton,1,-proton),100.)
39
+ self.assertAlmostEqual(neutral_mass_from_precursor((100+2*proton)/2,2,2*proton),100.)
40
+ with self.assertRaises(ValueError):neutral_mass_from_precursor(100,0,proton)
41
+
42
+ def test_mass_neighborhood_gray_zone_and_gaussian(self):
43
+ p,n=mass_pairs([100.,100.25,101.,102.],['A','B','C','D'])
44
+ self.assertAlmostEqual(float(p[0,1]),math.exp(-.5),places=6)
45
+ self.assertEqual(float(p[0,2]),0.);self.assertFalse(n[0,2])
46
+ self.assertTrue(n[0,3]);self.assertFalse(torch.diag(n).any())
47
+
48
+ def test_same_identity_mass_pair_not_coarse_positive_or_negative(self):
49
+ p,n=mass_pairs([100.,100.01,103.],['A','A','B'])
50
+ self.assertEqual(float(p[0,1]),0.);self.assertFalse(n[0,1])
51
+
52
+ def test_hard_bin_boundary_is_not_forced_negative(self):
53
+ p,n=mass_pairs([100.99,101.01,104.],['A','B','C'],mode='hard_bins')
54
+ self.assertEqual(float(p[0,1]),0.);self.assertFalse(n[0,1])
55
+ self.assertTrue(n[0,2])
56
+
57
+ def test_mass_relation_not_transitive(self):
58
+ p,_=mass_pairs([100.,100.4,100.8],['A','B','C'])
59
+ self.assertGreater(float(p[0,1]),0.);self.assertGreater(float(p[1,2]),0.)
60
+ self.assertEqual(float(p[0,2]),0.)
61
+
62
+ def test_invalid_mass_config(self):
63
+ for kw in [dict(positive_radius_da=2.),dict(sigma_da=float('nan')),
64
+ dict(mode='hard_bins',bin_width_da=3.),dict(mode='wrong')]:
65
+ with self.assertRaises(ValueError):mass_pairs([100.,103.],['A','B'],**kw)
66
+
67
+ def test_manual_group_macro_supcon(self):
68
+ x=torch.randn(5,7,requires_grad=True)
69
+ p,n,g=formula_pairs(['C2H6O']*2+['C3H8O']*2+['C4H10O'],list('ABCDE'))
70
+ loss,stats=weighted_supcon(x,p,n,g,.2)
71
+ s=F.normalize(x,dim=1)@F.normalize(x,dim=1).T/.2;expected=[]
72
+ for i,j in [(0,1),(1,0),(2,3),(3,2)]:
73
+ expected.append(torch.logsumexp(s[i,torch.arange(5)!=i],0)-s[i,j])
74
+ torch.testing.assert_close(loss,torch.stack(expected).mean())
75
+ self.assertEqual(int(stats['valid_anchors']),4)
76
+ self.assertEqual(int(stats['valid_groups']),2)
77
+ loss.backward();self.assertTrue(torch.isfinite(x.grad).all())
78
+
79
+ def test_no_positive_or_no_negative_returns_differentiable_zero(self):
80
+ for formulas in [['CH4','C2H6'],['CH4','CH4']]:
81
+ x=torch.randn(2,8,requires_grad=True);p,n,g=formula_pairs(formulas,['A','B'])
82
+ loss,stats=weighted_supcon(x,p,n,g)
83
+ self.assertEqual(float(loss),0.);self.assertEqual(int(stats['valid_anchors']),0)
84
+ loss.backward();self.assertTrue(torch.isfinite(x.grad).all())
85
+
86
+ def test_empty_batch(self):
87
+ x=torch.empty(0,8,requires_grad=True);p,n,g=formula_pairs([],[])
88
+ loss,_=weighted_supcon(x,p,n,g);self.assertEqual(float(loss),0.);loss.backward()
89
+
90
+ def test_permutation_invariance(self):
91
+ x=torch.randn(6,8);ids=list('ABCDEF');m=[100.,100.1,103.,103.1,106.,106.1]
92
+ p,n=mass_pairs(m,ids);a,_=weighted_supcon(x,p,n,ids)
93
+ order=[5,0,3,1,4,2];p,n=mass_pairs([m[i] for i in order],[ids[i] for i in order])
94
+ b,_=weighted_supcon(x[order],p,n,[ids[i] for i in order]);torch.testing.assert_close(a,b)
95
+
96
+ def test_invalid_weight_mask_and_temperature(self):
97
+ x=torch.randn(2,8);p=torch.tensor([[0.,1.],[1.,0.]])
98
+ for temp in [0.,float('nan')]:
99
+ with self.assertRaises(ValueError):weighted_supcon(x,p,torch.zeros(2,2,dtype=torch.bool),['A','B'],temp)
100
+ with self.assertRaises(ValueError):weighted_supcon(x,p,p.bool(),['A','B'])
101
+ with self.assertRaises(ValueError):weighted_supcon(x,p,torch.zeros(2,2),['A','B'])
102
+
103
+ def test_projection_count_and_gradient_isolation(self):
104
+ bank=ProjectionBank();self.assertEqual(sum(p.numel() for p in bank.parameters()),592128)
105
+ x=torch.randn(5,256,requires_grad=True)
106
+ out=bank('ms_formula',x);out[:,0].sum().backward()
107
+ self.assertIsNotNone(bank.heads['ms_formula'][0].weight.grad)
108
+ self.assertIsNone(bank.heads['ms_identity'][0].weight.grad)
109
+ self.assertGreater(float(x.grad.abs().sum()),0.)
110
+ torch.testing.assert_close(torch.linalg.vector_norm(out,dim=1),torch.ones(5))
111
+
112
+ def test_shared_head_control_is_explicit(self):
113
+ bank=ProjectionBank();x=torch.randn(5,256)
114
+ torch.testing.assert_close(bank('ms_formula',x,True),bank('ms_identity',x))
115
+ with self.assertRaises(ValueError):bank('unknown',x)
116
+
117
+
118
+ if __name__=='__main__':unittest.main()
code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/test_configs.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from copy import deepcopy
2
+ import math
3
+ import unittest
4
+ from configs import compile_configs,validate,assert_fairness,AUX
5
+
6
+
7
+ class ConfigurationTests(unittest.TestCase):
8
+ def setUp(self):self.configs=compile_configs();self.c=deepcopy(self.configs['C08_full_separate'])
9
+
10
+ def test_18_resolved_configs_three_seeds(self):
11
+ self.assertEqual(len(self.configs),18);self.assertTrue(assert_fairness(self.configs))
12
+ for c in self.configs.values():
13
+ self.assertTrue(validate(c));self.assertEqual(len(c['budget']['seeds']),3)
14
+ self.assertEqual(set(c['loss']['auxiliary']),set(AUX))
15
+
16
+ def test_first_pass_count(self):
17
+ self.assertEqual(sum(c['experiment']['priority']=='first_pass' for c in self.configs.values()),5)
18
+
19
+ def test_no_training_launcher_or_overlapping_outputs(self):
20
+ self.assertFalse(self.c['execution']['allow_training'])
21
+ self.assertIsNone(self.c['execution']['runtime_entrypoint'])
22
+ self.assertEqual(len(set(c['experiment']['output_template'] for c in self.configs.values())),18)
23
+
24
+ def test_unknown_keys_rejected(self):
25
+ self.c['loss']['auxiliary']['typo']=.1
26
+ with self.assertRaises(ValueError):validate(self.c)
27
+
28
+ def test_nonfinite_numbers_rejected(self):
29
+ for v in [math.nan,math.inf,-math.inf]:
30
+ c=deepcopy(self.c);c['loss']['temperature']['mass']=v
31
+ with self.assertRaises(ValueError):validate(c)
32
+
33
+ def test_illegal_training_activation_rejected(self):
34
+ self.c['execution']['allow_training']=True
35
+ with self.assertRaises(ValueError):validate(self.c)
36
+
37
+ def test_test_label_leakage_rejected(self):
38
+ self.c['data']['test_or_casmi_labels_in_training']=True
39
+ with self.assertRaises(ValueError):validate(self.c)
40
+
41
+ def test_raw_precursor_mass_and_duplicate_ms_rejected(self):
42
+ c=deepcopy(self.c);c['loss']['mass_coarse']['MS_mass']='raw_precursor_mz'
43
+ with self.assertRaises(ValueError):validate(c)
44
+ c=deepcopy(self.c);c['sampling']['force_duplicate_spectra_to_fill_group']=True
45
+ with self.assertRaises(ValueError):validate(c)
46
+
47
+ def test_fairness_drift_rejected(self):
48
+ self.configs['C01_ms_fine']['budget']['optimizer_updates_per_seed']+=1
49
+ with self.assertRaises(ValueError):assert_fairness(self.configs)
50
+
51
+ def test_budget_matched_controls(self):
52
+ for name in ['C08_full_separate','C13_fine_budget_matched','C14_fine_formula_budget_matched','C15_fine_mass_budget_matched']:
53
+ self.assertAlmostEqual(sum(self.configs[name]['loss']['auxiliary'].values()),.3)
54
+
55
+ def test_shared_head_only_explicit_control(self):
56
+ self.c['model']['head_routing']='share_granularities_within_modality'
57
+ with self.assertRaises(ValueError):validate(self.c)
58
+
59
+ def test_official_candidate_policy_preserved(self):
60
+ self.assertFalse(self.c['sampling']['candidate_pool_deduplicate_key14'])
61
+ self.assertTrue(self.c['sampling']['same_truth_key14_is_never_negative'])
62
+ self.assertIsNone(self.c['evaluation']['casmi_candidate_cap'])
63
+ self.assertEqual(self.c['evaluation']['casmi_denominator'],500)
64
+ self.c['evaluation']['casmi_candidate_cap']=256
65
+ with self.assertRaises(ValueError):validate(self.c)
66
+
67
+
68
+ if __name__=='__main__':unittest.main()
code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/validation_record.json ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "validation_date": "2026-11-03",
3
+ "local_cpu_tests": 45,
4
+ "server_cpu_tests": 45,
5
+ "configuration_count": 18,
6
+ "configured_seeds": 3,
7
+ "planned_replica_jobs": 54,
8
+ "launched_replica_jobs": 0,
9
+ "training_ready": false,
10
+ "matched_files": 27,
11
+ "hash_mismatches": [],
12
+ "original_training": {
13
+ "supervisor": "specpartition-r09-train",
14
+ "pid": 3742868,
15
+ "current_epoch": 5,
16
+ "updates": 23960,
17
+ "step": 3588,
18
+ "steps_in_epoch": 5093,
19
+ "updated_unix": 1793670735.5774226
20
+ },
21
+ "file_sha256": {
22
+ "hierarchical_ablation_20261103/test_configs.py": "703e9ae2e0544ebf63e66dd10caf18578ddafd7240e8ee7168a6537dc8b3ea7d",
23
+ "hierarchical_ablation_20261103/test_coarse.py": "b4429263876704ff76bae4abf9001f4b12eac23baa831aeaccdd0c1d40b0bf20",
24
+ "hierarchical_ablation_20261103/coarse_losses.py": "9e9980b2eff391e0fb1b065b2eb4a41c212192e12e0852efb44e1da741146904",
25
+ "hierarchical_ablation_20261103/configs.py": "cc31f3d1127415e28da9ac101bbe6df085b0f0c83e50117a8169c90b4e0a8b5e",
26
+ "hierarchical_ablation_20261103/README.md": "797841a785554acb3a254f43b5ceae26411445c32cde2f2404ca0794b11ec520",
27
+ "hierarchical_ablation_20261103/suite_manifest.json": "6293b691cff85f077f3d3adec61676f4bfc109e304eb3062f2029801fd975ca6",
28
+ "hierarchical_ablation_20261103/configs/C00_sampler_control.json": "f2ab69f60109ba1e37326c8b095a7cbcb979eaf3e904c79219647374a6403062",
29
+ "hierarchical_ablation_20261103/configs/C01_ms_fine.json": "b8b15b61e8b6061ac8e23db6e2fde16925401ea561379418e8763960f45ac8c7",
30
+ "hierarchical_ablation_20261103/configs/C05_mass_coarse.json": "1ae1118cad164180dcc0b7cfc994c9f0a5ca385efb28acceb06986fc0e19072f",
31
+ "hierarchical_ablation_20261103/configs/C10_random_sampler_control.json": "21b0602287af9a3eea41e4f2cedffdf3e1e3b8e99523ab291a87c60cb8209fc4",
32
+ "hierarchical_ablation_20261103/configs/C02_mol_fine.json": "756068818e7672dbe812037cad980aa1ddd4be794865fb661aba85af62bdd51f",
33
+ "hierarchical_ablation_20261103/configs/C08_full_separate.json": "4436623c51d97e11bd041213275e629266b88d9c34fd12a9ef2ee48e1079a682",
34
+ "hierarchical_ablation_20261103/configs/C09_shared_head_control.json": "f51f65041ebb14be950def6890cc217611aca6e451c9e8a60f4c349dc985c512",
35
+ "hierarchical_ablation_20261103/configs/C17_mass_metadata_shortcut.json": "dbfdb2834a1dc1afefe4d45fa3b8e8d561a6def89da21b7ab3579fb218cd47ca",
36
+ "hierarchical_ablation_20261103/configs/C15_fine_mass_budget_matched.json": "1a6e8c7a9ca336f1e560fa1ed9fc4b932a2d51fefb895563cbfb7fe0583e7194",
37
+ "hierarchical_ablation_20261103/configs/C06_fine_formula.json": "d40629d6b03662a3eedb92ea33604fe33ab3877b3c66c2ad4242bbb2cfc7c813",
38
+ "hierarchical_ablation_20261103/configs/C07_fine_mass.json": "72ae9009ba2d45f864ae18a140075c1f45ea78b58cfe4d92abce0970ac0f1980",
39
+ "hierarchical_ablation_20261103/configs/C11_hard_mass_bins.json": "2358ddab6dca0433deddbbe6e84ef2839cd59e98442af109077912308ca6338d",
40
+ "hierarchical_ablation_20261103/configs/C13_fine_budget_matched.json": "7e4fc8bf8e9ae2e64bf744c57162cb4a635d32b7869c8fb2044cf9a32208b0b5",
41
+ "hierarchical_ablation_20261103/configs/C12_no_reverse_crossmodal.json": "d7984ab5700619252d32cd1402667bd7de5ec52a2840342165048126575191e4",
42
+ "hierarchical_ablation_20261103/configs/C16_include_identity_coarse.json": "95f4ea6fbcc38c119b7f3f60becd028e40c19ffc275535141cb9588f96b02687",
43
+ "hierarchical_ablation_20261103/configs/C04_formula_coarse.json": "c303010e517b4fabc60f9940bbf3a15c9504c2886e1fbcaa6f34f4aac67a5ccc",
44
+ "hierarchical_ablation_20261103/configs/C14_fine_formula_budget_matched.json": "a837ba7c2464baf3226b13eb905ab462f962b45bb550811d752565e3063b9dc9",
45
+ "hierarchical_ablation_20261103/configs/C03_both_fine.json": "1999d280924b950900b8509194413c34bc7f8dd9a691a82daf8ce557f8e6e959",
46
+ "hierarchical_ablation_20261103/base.json": "c83c3192a0b7ab6353ed17d2eba0ab138bfd3672f3285c0ced8496b880c405d3",
47
+ "intra_modal_extension/test_losses.py": "553dd4389fc5b59f50a807560257bae01e4550096940f9218a2970e732d4a3f3",
48
+ "intra_modal_extension/losses.py": "b4a0b57e46417822e946b6b4f39566a191ce4d2ffdeee47e6eff776ae6fae18f"
49
+ },
50
+ "scope": "configuration_and_standalone_CPU_loss_components_not_full_training_integration",
51
+ "server_directory": "/workspace/xj/SpecPartition-MS/rebuild/hierarchical_ablation_20261103",
52
+ "hash_scope": "27 package files, excluding generated __pycache__ and this validation record",
53
+ "gpu_or_real_batch_acceptance": false,
54
+ "missing_integration": [
55
+ "hierarchical_no_repeat_sampler",
56
+ "independent_stochastic_gnn_views",
57
+ "rng_safe_view_recomputation",
58
+ "joint_loss_router_quality_masks_and_gpu_acceptance",
59
+ "mass_metadata_control_routing"
60
+ ]
61
+ }
code/snapshot/workspace/rebuild/hierarchical_training_20261103/README.md ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SpecPartition-MS 粗细粒度四组训练
2
+
3
+ 2026年11月3日,C03、C06、C07、C08通过真实GPU验收并启动独立训练。四组均从固定R09 epoch04主干权重微调,不是随机初始化,也不是恢复旧服务器V系列。R09代码、运行目录、优化器及主管服务未修改。
4
+
5
+ ## 实验和预算
6
+
7
+ | 组 | 新增辅助任务 | 本次seed | 更新次数 |
8
+ | --- | --- | --- | ---: |
9
+ | C03_both_fine | MS细粒度+分子细粒度 | 20261103 | 6,000 |
10
+ | C06_fine_formula | 细粒度+公式粗粒度 | 20261103 | 6,000 |
11
+ | C07_fine_mass | 细粒度+质量粗粒度 | 20261103 | 6,000 |
12
+ | C08_full_separate | 细粒度+公式+质量 | 20261103 | 6,000 |
13
+
14
+ 各组使用同一父权重和相同的新头初始化、同样的数据顺序及候选抽样seed,统一新建AdamW。父权重SHA256为 `618aaf195cfdc3a4107e71cf2b3a56d5853b407564acf01de11c67e6af40f3d7`。学习率3e-5、warmup300步、cosine最低3e-6,辅助Loss前500步线性升权。每2,000步运行完整MSG Validation两种官方池,每100步保存可恢复checkpoint;训练总预算为更新次数,不把6,000步误称为6个epoch。
15
+
16
+ 训练标签643,587条,保留同结构多MS。分组采样目标为o_data的8公式×8结构×4MS、MSG的4公式×4结构×2MS;稀有组用剩余真实记录填充,不复制物理谱图。每个完整数据epoch恰好覆盖源记录一次,实际首轮采样计划哈希四组一致:`cb7a05da276b9158cf806a777878b674c21ab48efab51cac7698db17d1d2cc88`。
17
+
18
+ MSG每条查询同时使用Mass/Formula两个官方训练视图,各63次有放回负例抽样;o_data轮换16条显式查询,各128次负例抽样。候选记录不按key14合并,但真值key14的所有别名均禁止作为负例,沿用已验收的heldout隔离规则。
19
+
20
+ ## 模型和损失接入
21
+
22
+ 256维R2谱图/分子主干保留,加入六个256→256→128投影头,登记参数共17,001,870。分子式预测、双向MS↔分子InfoNCE和最终候选池InfoNCE继续联合优化。
23
+
24
+ MS细粒度按key14组织不同真实谱图正例;分子细粒度用两次独立隐藏原子特征dropout得到分子视图,不改变原子或键拓扑。两个随机视图保留各自计算图正常反传,未复用旧学生embedding或不安全重放随机图。
25
+
26
+ 公式粗粒度以同公式、不同key14为正例。质量粗粒度采用实验precursor和adduct换算中性质量;0.5 Da以内为加权正例,2 Da以外为负例,中间灰区不监督,质量冲突记录屏蔽该项。粗细任务使用独立投影头,不改变推理时原有最终排序分数。
27
+
28
+ 所有六项都记录raw Loss用于诊断;关闭项的weighted Loss为0,不参与目标贡献。辅助任务梯度诊断每100步检查一次,范围是共享缓存表征,不将其冒称为全部参数、公式LF和池LP的完整梯度冲突审计。
29
+
30
+ 新入口还采用等价的向量化反向InfoNCE、公式CE/gap及已知输出长度的图池化,旧R09源码未改。四组之间使用同一实现,不将效率优化混作组间算法差异。
31
+
32
+ ## 验收结果
33
+
34
+ - CPU回归测试53项通过。
35
+ - 真实batch为288条谱图;启用的辅助项均有有效正例,无重复物理MS。
36
+ - C03基础目标FP32对照:Loss绝对差4.7684e-7,裁剪后梯度相对L2差2.6686e-5,分别通过预设1e-5、1e-4容差。
37
+ - 四组均通过模型、AdamW和随机状态的保存/恢复测试;重复更新的参数最大差与Loss差均为0。
38
+ - 验收更新单独保存,不计入正式6,000步,不继承为正式训练起点。
39
+
40
+ ## 并发和恢复
41
+
42
+ 四个主管服务同时运行;新实验共用两个GPU工作槽,每组1个DataLoader worker、1个CPU计算线程。每个进程显存上限为整卡25%,退出工作槽时释放可回收的临时CUDA缓存。该机制只限制新实验,不停止或重配R09及其他任务;共享GPU仍会产生吞吐竞争。
43
+
44
+ 主管入口是 `managed.py`,先核对这份运行配置、代码和数据绑定的GPU验收,再启动训练,失败最多尝试3次。`last.pt`包含模型、优化器、数据位置和随机状态;恢复不从头重训,日志领先checkpoint的未保存步可能重做。部分Validation已完成时复用同一权重的已保存逐目标结果。
45
+
46
+ 原18份配置保留为不可变方案档案,其`allow_training=false`不会被伪装修改。实际执行依据是新入口的`resolved_config.json`和与代码、父权重、数据严格绑定的`acceptance.json`。本次仅这四组已完成运行接入,不能据此宣称其余14组均可运行。
47
+
48
+ ## 服务器路径
49
+
50
+ ```text
51
+ /workspace/xj/SpecPartition-MS/rebuild/hierarchical_training_20261103/
52
+ /workspace/xj/SpecPartition-MS/runs/hierarchical_intra_modal_20261103/runtime_readiness.json
53
+ /workspace/xj/SpecPartition-MS/runs/hierarchical_intra_modal_20261103/<组名>/seed_20261103/
54
+ ```
55
+
56
+ 每组目录包含`resolved_config.json`、`acceptance.json`、`status.json`、`loss.jsonl`、`manager.log`、`last.pt`,以及2,000/4,000/6,000步的Validation与checkpoint。
57
+
58
+ 主管名称为`specpartition-hierarchy-C03`、`specpartition-hierarchy-C06`、`specpartition-hierarchy-C07`、`specpartition-hierarchy-C08`。只读查看使用`supervisorctl status`,不要另起第二个手工trainer。
59
+
60
+ MSG Test和固定CASMI池不参与这四组的选模;尚无新实验的完整Validation/Test指标。仍需后续补充匹配基线和3-seed确认,不能从早期Loss直接判断最终增益。
code/snapshot/workspace/rebuild/hierarchical_training_20261103/acceptance.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Real full-batch GPU checks. Synthetic checks alone cannot activate training."""
2
+ import argparse
3
+ from copy import deepcopy
4
+ import json
5
+ import time
6
+ import torch
7
+ from runtime_hier import bootstrap,binding,save,gpu_slot
8
+
9
+
10
+ def run(arm):
11
+ spec,resolved,run,legacy=bootstrap(arm);run.mkdir(parents=True,exist_ok=True)
12
+ from train import setup,make_model,optimizer,checkpoint,restore
13
+ from sampling import epoch_plans,plan_hash,PlanDataset
14
+ from objectives import train_step
15
+ setup(legacy,resolved);bound=binding(spec,resolved,legacy)
16
+ ready=run/'acceptance.json'
17
+ if ready.exists():
18
+ old=json.loads(ready.read_text())
19
+ if old.get('complete') and old['binding']==bound:return
20
+ raise RuntimeError('Existing acceptance has different binding; do not overwrite')
21
+ plans=epoch_plans(0,resolved['seed']);index=next(i for i,p in enumerate(plans) if p[2]['odata'] and p[2]['msg'])
22
+ dataset=PlanDataset([plans[index]]);batch=dataset[0];started=time.monotonic()
23
+ report=dict(arm=arm,binding=bound,sampler_sha256=plan_hash(plans),steps_in_data_epoch=len(plans),
24
+ actual_queries=len(batch['rows']),no_repeated_physical_MS=len(batch['rows'])==len({r['record_id'] for r in batch['rows']}),
25
+ original_R09_not_modified=True,complete=False)
26
+ with gpu_slot(run,'GPU_acceptance'):
27
+ model=make_model(spec,legacy);opt=optimizer(model,legacy);model.train()
28
+ if sum(p.numel() for p in model.parameters())!=17001870:raise RuntimeError('Model parameter count mismatch')
29
+ # FP32 reduction/replay equivalence against the accepted old objective.
30
+ # Auxiliary coefficients are all zero ONLY in this control check.
31
+ if arm=='C03_both_fine':
32
+ import objectives09
33
+ legacy.C['bf16']=False
34
+ reference=objectives09.train_step(model,opt,batch,update=False)
35
+ old_grads={n:p.grad.detach().clone() for n,p in model.named_parameters() if p.grad is not None}
36
+ off=deepcopy(spec);off['loss']['auxiliary']={k:0. for k in off['loss']['auxiliary']}
37
+ candidate=train_step(model,opt,batch,off,0,update=False)
38
+ diff=sum((model.get_parameter(n).grad-g).double().square().sum() for n,g in old_grads.items()).sqrt()
39
+ norm=sum(g.double().square().sum() for g in old_grads.values()).sqrt()
40
+ relative=float(diff/norm.clamp_min(1e-12));gap=abs(reference['loss']-candidate['loss'])
41
+ report['base_FP32_equivalence']=dict(loss_abs_difference=gap,clipped_gradient_relative_L2=relative,loss_tolerance=1e-5,gradient_tolerance=1e-4)
42
+ if gap>1e-5 or relative>1e-4:raise RuntimeError('Base loss/gradient equivalence failed: '+str(report['base_FP32_equivalence']))
43
+ del old_grads;legacy.C['bf16']=True
44
+ model.zero_grad(set_to_none=True);torch.cuda.reset_peak_memory_stats()
45
+ # The formal training model is loaded separately; these updates are tests.
46
+ a=train_step(model,opt,batch,spec,0,diagnose=True)
47
+ active=spec['experiment']['active_auxiliary_tasks']
48
+ if not report['no_repeated_physical_MS']:raise RuntimeError('Sampler duplicated real MS')
49
+ if a['molecule_view_mean_abs_difference']<=1e-7:raise RuntimeError('Molecule views are not independent')
50
+ for k in active:
51
+ if a[k+'_valid_anchors']<=0:raise RuntimeError('No valid real-batch anchors for '+k)
52
+ report['first_joint_update']=a
53
+ progress=dict(update=1,epoch=0,next_step=1,validated_updates=[])
54
+ checkpoint(run/'acceptance_checkpoint.pt',model,opt,progress,bound)
55
+ expected=train_step(model,opt,batch,spec,1,diagnose=False)
56
+ state_after={n:p.detach().cpu().clone() for n,p in model.named_parameters()}
57
+ restored=restore(run/'acceptance_checkpoint.pt',model,opt,bound)
58
+ repeated=train_step(model,opt,batch,spec,1,diagnose=False)
59
+ error=max(float((p.detach().cpu()-state_after[n]).abs().max()) for n,p in model.named_parameters())
60
+ if error!=0. or expected['loss']!=repeated['loss'] or restored!=progress:raise RuntimeError('Stochastic checkpoint replay is not exact')
61
+ report['resume_test']=dict(parameter_max_abs_difference=error,loss_abs_difference=abs(expected['loss']-repeated['loss']),optimizer_and_rng_restored=True)
62
+ report.update(complete=True,parameters=sum(p.numel() for p in model.parameters()),seconds=time.monotonic()-started,updated_unix=time.time(),formal_training_updates=0)
63
+ save(ready,report);print(json.dumps(report,ensure_ascii=False),flush=True)
64
+
65
+
66
+ if __name__=='__main__':
67
+ p=argparse.ArgumentParser();p.add_argument('--arm',required=True);args=p.parse_args();run(args.arm)
code/snapshot/workspace/rebuild/hierarchical_training_20261103/check_all.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Supervised preflight for the four selected arms, never a training launcher."""
2
+ import json
3
+ from pathlib import Path
4
+ import subprocess
5
+ import sys
6
+ import time
7
+ from runtime_hier import HERE,ROOT,ARMS,bootstrap,save
8
+
9
+
10
+ def main():
11
+ path=ROOT/'runs/hierarchical_intra_modal_20261103/runtime_readiness.json'
12
+ logpath=ROOT/'logs/hierarchical_preflight_20261103.log';logpath.parent.mkdir(exist_ok=True)
13
+ with logpath.open('a',buffering=1) as log:
14
+ for folder in [HERE,HERE.parent/'hierarchical_ablation_20261103',HERE.parent/'intra_modal_extension']:
15
+ subprocess.run([sys.executable,'-m','unittest','discover','-s',str(folder),'-p','test_*.py','-v'],check=True,stdout=log,stderr=subprocess.STDOUT)
16
+ accepted=[]
17
+ for arm in ARMS:
18
+ save(path,dict(phase='GPU_acceptance',current_arm=arm,accepted=accepted,complete=False,updated_unix=time.time()))
19
+ subprocess.run([sys.executable,'-u',str(HERE/'acceptance.py'),'--arm',arm],check=True,stdout=log,stderr=subprocess.STDOUT)
20
+ accepted.append(arm)
21
+ save(path,dict(complete=True,accepted=accepted,cpu_tests=53,real_GPU_acceptance=True,updated_unix=time.time(),automatic_training_launch=False))
22
+ print(json.dumps(dict(complete=True,accepted=accepted)),flush=True)
23
+
24
+
25
+ if __name__=='__main__':main()
code/snapshot/workspace/rebuild/hierarchical_training_20261103/hierarchy.supervisor.conf ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [program:specpartition-hierarchy-preflight]
2
+ command=/workspace/xj/SpecPartition-MS/.venv/bin/python -u /workspace/xj/SpecPartition-MS/rebuild/hierarchical_training_20261103/check_all.py
3
+ directory=/workspace/xj/SpecPartition-MS
4
+ environment=PROC_NAME="specpartition-hierarchy-preflight",OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1",CUBLAS_WORKSPACE_CONFIG=":4096:8"
5
+ autostart=false
6
+ autorestart=false
7
+ startsecs=1
8
+ stopasgroup=true
9
+ killasgroup=true
10
+ stdout_logfile=/dev/stdout
11
+ stdout_logfile_maxbytes=0
12
+ redirect_stderr=true
13
+
14
+ [program:specpartition-hierarchy-C03]
15
+ command=/workspace/xj/SpecPartition-MS/.venv/bin/python -u /workspace/xj/SpecPartition-MS/rebuild/hierarchical_training_20261103/managed.py --arm C03_both_fine
16
+ directory=/workspace/xj/SpecPartition-MS
17
+ environment=PROC_NAME="specpartition-hierarchy-C03",OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1",CUBLAS_WORKSPACE_CONFIG=":4096:8"
18
+ autostart=false
19
+ autorestart=false
20
+ startsecs=10
21
+ stopasgroup=true
22
+ killasgroup=true
23
+ stopwaitsecs=90
24
+ stdout_logfile=/dev/stdout
25
+ stdout_logfile_maxbytes=0
26
+ redirect_stderr=true
27
+
28
+ [program:specpartition-hierarchy-C06]
29
+ command=/workspace/xj/SpecPartition-MS/.venv/bin/python -u /workspace/xj/SpecPartition-MS/rebuild/hierarchical_training_20261103/managed.py --arm C06_fine_formula
30
+ directory=/workspace/xj/SpecPartition-MS
31
+ environment=PROC_NAME="specpartition-hierarchy-C06",OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1",CUBLAS_WORKSPACE_CONFIG=":4096:8"
32
+ autostart=false
33
+ autorestart=false
34
+ startsecs=10
35
+ stopasgroup=true
36
+ killasgroup=true
37
+ stopwaitsecs=90
38
+ stdout_logfile=/dev/stdout
39
+ stdout_logfile_maxbytes=0
40
+ redirect_stderr=true
41
+
42
+ [program:specpartition-hierarchy-C07]
43
+ command=/workspace/xj/SpecPartition-MS/.venv/bin/python -u /workspace/xj/SpecPartition-MS/rebuild/hierarchical_training_20261103/managed.py --arm C07_fine_mass
44
+ directory=/workspace/xj/SpecPartition-MS
45
+ environment=PROC_NAME="specpartition-hierarchy-C07",OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1",CUBLAS_WORKSPACE_CONFIG=":4096:8"
46
+ autostart=false
47
+ autorestart=false
48
+ startsecs=10
49
+ stopasgroup=true
50
+ killasgroup=true
51
+ stopwaitsecs=90
52
+ stdout_logfile=/dev/stdout
53
+ stdout_logfile_maxbytes=0
54
+ redirect_stderr=true
55
+
56
+ [program:specpartition-hierarchy-C08]
57
+ command=/workspace/xj/SpecPartition-MS/.venv/bin/python -u /workspace/xj/SpecPartition-MS/rebuild/hierarchical_training_20261103/managed.py --arm C08_full_separate
58
+ directory=/workspace/xj/SpecPartition-MS
59
+ environment=PROC_NAME="specpartition-hierarchy-C08",OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1",CUBLAS_WORKSPACE_CONFIG=":4096:8"
60
+ autostart=false
61
+ autorestart=false
62
+ startsecs=10
63
+ stopasgroup=true
64
+ killasgroup=true
65
+ stopwaitsecs=90
66
+ stdout_logfile=/dev/stdout
67
+ stdout_logfile_maxbytes=0
68
+ redirect_stderr=true
code/snapshot/workspace/rebuild/hierarchical_training_20261103/kernels.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Equivalent base reductions and graph pooling, isolated from the live run."""
2
+ import types
3
+ import numpy as np
4
+ import torch
5
+ from torch.nn import functional as F
6
+ from torch.nn.utils.rnn import pad_sequence
7
+
8
+
9
+ def grouped_contrastive(logits,identities,columns):
10
+ if len(columns)!=len(set(columns)) or logits.shape!=(len(identities),len(columns)):raise ValueError('Invalid connectivity columns')
11
+ if len(columns)<2:return logits.sum()*0.,logits.sum()*0.
12
+ lookup={k:i for i,k in enumerate(columns)}
13
+ target=torch.tensor([lookup[k] for k in identities],device=logits.device)
14
+ forward=F.cross_entropy(logits.float(),target)
15
+ reverse=logits.float().T.log_softmax(-1)
16
+ positive=target[None,:]==torch.arange(len(columns),device=logits.device)[:,None]
17
+ backward=-(reverse*positive).sum(1).div(positive.sum(1).clamp_min(1)).mean()
18
+ return forward,backward
19
+
20
+
21
+ def formula_objective(model,qs,tokens,rows,denominator,aux_denominator):
22
+ from runtime09 import C
23
+ from specpartition_ms.fast_formula_r2 import forward_batch,auxiliary_batch
24
+ scores=forward_batch(model.formula_v07,qs,[r['query'] for r in rows],tokens)
25
+ valid=[i for i,r in enumerate(rows) if r['mass_ok'] and len(r['formulas'])>1 and r['formula'] in r['formulas']]
26
+ zero=qs.float().sum()*0.;ce=zero;gap=zero;correct=zero
27
+ if valid:
28
+ vv=[scores[i].float() for i in valid];s=pad_sequence(vv,batch_first=True,padding_value=-torch.inf)
29
+ pos=torch.tensor([rows[i]['formulas'].index(rows[i]['formula']) for i in valid],device=qs.device)
30
+ ii=torch.arange(len(valid),device=qs.device);ps=s[ii,pos]
31
+ ce=(torch.logsumexp(s,1)-ps).sum()/max(1,denominator)
32
+ negatives=s.scatter(1,pos[:,None],-torch.inf);k=min(C['r2']['formula_gap_topk'],s.shape[1]-1)
33
+ hard=negatives.topk(k,dim=1).values
34
+ actual=qs.new_tensor([min(k,len(v)-1) for v in vv])
35
+ gap=(F.softplus(C['r2']['formula_gap_margin']+hard-ps[:,None]).sum(1)/actual).sum()/max(1,denominator)
36
+ correct=(s.argmax(1)==pos).float().sum()
37
+ elem,_,_=auxiliary_batch(model.formula_v07,qs,[r['formula'] for r in rows]);aux=elem.sum()/max(1,aux_denominator)
38
+ loss=ce+C['r2']['formula_gap_weight']*gap+C['r2']['element_weight']*aux
39
+ return loss,dict(formula_ce=ce.detach(),formula_gap=gap.detach(),element_ce=aux.detach(),formula_correct=correct.detach(),formula_valid=len(valid))
40
+
41
+
42
+ def graph_forward(self,mols,device):
43
+ sizes=[len(m.atom_features) for m in mols];offsets=np.cumsum([0]+sizes)
44
+ atoms=torch.as_tensor(np.concatenate([m.atom_features for m in mols]),device=device)
45
+ edges=torch.as_tensor(np.concatenate([m.edge_index+o for m,o in zip(mols,offsets)],axis=1),device=device)
46
+ bonds=torch.as_tensor(np.concatenate([m.bond_features for m in mols]),device=device)
47
+ h,e=self.atom(atoms),self.edge(bonds);src,dst=edges
48
+ degree=torch.bincount(dst,minlength=len(h)).clamp_min(1).to(h.dtype)[:,None]
49
+ for msg,gate,norm,ffn,ffnorm in zip(self.messages,self.gates,self.norms,self.ffns,self.ffnorms):
50
+ context=torch.cat((h[src],h[dst],e),-1);messages=msg(context)*torch.sigmoid(gate(context))
51
+ aggregate=torch.zeros_like(h).index_add(0,dst,messages.to(h.dtype))/degree
52
+ h=norm(h+aggregate);h=ffnorm(h+ffn(h))
53
+ graph_ids=torch.repeat_interleave(torch.arange(len(mols),device=device),torch.tensor(sizes,device=device),output_size=sum(sizes))
54
+ sums=h.new_zeros((len(mols),h.shape[-1])).index_add(0,graph_ids,h)
55
+ maxima=h.new_full((len(mols),h.shape[-1]),-torch.inf).scatter_reduce(0,graph_ids[:,None].expand_as(h),h,reduce='amax',include_self=True)
56
+ mean=sums/torch.tensor(sizes,device=device,dtype=h.dtype)[:,None]
57
+ return self.pool(torch.cat((mean,maxima),-1)),list(h.split(sizes)),sizes
58
+
59
+
60
+ def install_graph_kernel(model):model.graph.forward=types.MethodType(graph_forward,model.graph)
61
+
code/snapshot/workspace/rebuild/hierarchical_training_20261103/launch_record.json ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "checked_beijing": "2026-11-03T11:28:34.713657+08:00",
3
+ "arms": {
4
+ "C03_both_fine": {
5
+ "phase": "training",
6
+ "update": 20,
7
+ "planned_updates": 6000,
8
+ "recent_loss": 2.3888111293315886,
9
+ "wall_seconds_last_step": 2.2231585329864174,
10
+ "step_compute_seconds": 2.1941177148837596,
11
+ "duplicate_physical_MS": 0,
12
+ "acceptance_complete": true,
13
+ "checkpoint_replay": {
14
+ "parameter_max_abs_difference": 0,
15
+ "loss_abs_difference": 0,
16
+ "optimizer_and_rng_restored": true
17
+ },
18
+ "sampler_sha256": "cb7a05da276b9158cf806a777878b674c21ab48efab51cac7698db17d1d2cc88",
19
+ "parameters": 17001870,
20
+ "failure": null,
21
+ "run": "/workspace/xj/SpecPartition-MS/runs/hierarchical_intra_modal_20261103/C03_both_fine/seed_20261103",
22
+ "updated_unix": 1793676448.7650301
23
+ },
24
+ "C06_fine_formula": {
25
+ "phase": "training",
26
+ "update": 30,
27
+ "planned_updates": 6000,
28
+ "recent_loss": 2.3129605929056805,
29
+ "wall_seconds_last_step": 6.089658526005223,
30
+ "step_compute_seconds": 3.0294100581668317,
31
+ "duplicate_physical_MS": 0,
32
+ "acceptance_complete": true,
33
+ "checkpoint_replay": {
34
+ "parameter_max_abs_difference": 0,
35
+ "loss_abs_difference": 0,
36
+ "optimizer_and_rng_restored": true
37
+ },
38
+ "sampler_sha256": "cb7a05da276b9158cf806a777878b674c21ab48efab51cac7698db17d1d2cc88",
39
+ "parameters": 17001870,
40
+ "failure": null,
41
+ "run": "/workspace/xj/SpecPartition-MS/runs/hierarchical_intra_modal_20261103/C06_fine_formula/seed_20261103",
42
+ "updated_unix": 1793676509.6618648
43
+ },
44
+ "C07_fine_mass": {
45
+ "phase": "training",
46
+ "update": 20,
47
+ "planned_updates": 6000,
48
+ "recent_loss": 2.39136745929718,
49
+ "wall_seconds_last_step": 3.9946198910474777,
50
+ "step_compute_seconds": 2.1618069540709257,
51
+ "duplicate_physical_MS": 0,
52
+ "acceptance_complete": true,
53
+ "checkpoint_replay": {
54
+ "parameter_max_abs_difference": 0,
55
+ "loss_abs_difference": 0,
56
+ "optimizer_and_rng_restored": true
57
+ },
58
+ "sampler_sha256": "cb7a05da276b9158cf806a777878b674c21ab48efab51cac7698db17d1d2cc88",
59
+ "parameters": 17001870,
60
+ "failure": null,
61
+ "run": "/workspace/xj/SpecPartition-MS/runs/hierarchical_intra_modal_20261103/C07_fine_mass/seed_20261103",
62
+ "updated_unix": 1793676491.789096
63
+ },
64
+ "C08_full_separate": {
65
+ "phase": "training",
66
+ "update": 20,
67
+ "planned_updates": 6000,
68
+ "recent_loss": 2.396870124340057,
69
+ "wall_seconds_last_step": 7.80469659389928,
70
+ "step_compute_seconds": 2.058299479074776,
71
+ "duplicate_physical_MS": 0,
72
+ "acceptance_complete": true,
73
+ "checkpoint_replay": {
74
+ "parameter_max_abs_difference": 0,
75
+ "loss_abs_difference": 0,
76
+ "optimizer_and_rng_restored": true
77
+ },
78
+ "sampler_sha256": "cb7a05da276b9158cf806a777878b674c21ab48efab51cac7698db17d1d2cc88",
79
+ "parameters": 17001870,
80
+ "failure": null,
81
+ "run": "/workspace/xj/SpecPartition-MS/runs/hierarchical_intra_modal_20261103/C08_full_separate/seed_20261103",
82
+ "updated_unix": 1793676501.1649323
83
+ }
84
+ },
85
+ "R09": {
86
+ "current_epoch": 6,
87
+ "update": 26040,
88
+ "phase": "training",
89
+ "running": true
90
+ },
91
+ "experiment_scope": {
92
+ "selected_arms": 4,
93
+ "seeds_launched": [
94
+ 20261103
95
+ ],
96
+ "updates_per_arm": 6000,
97
+ "parent": "R09 epoch04",
98
+ "optimizer": "new AdamW",
99
+ "GPU_work_concurrency": 2,
100
+ "original_R09_restarted": false,
101
+ "cpu_tests_passed": 53,
102
+ "real_GPU_acceptance": "all four arms passed"
103
+ }
104
+ }
code/snapshot/workspace/rebuild/hierarchical_training_20261103/managed.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Supervisor foreground entry with bounded recovery, no duplicate trainer."""
2
+ import argparse
3
+ import fcntl
4
+ import json
5
+ from pathlib import Path
6
+ import subprocess
7
+ import sys
8
+ import time
9
+ from runtime_hier import bootstrap,save,HERE
10
+
11
+
12
+ def main(arm):
13
+ _,_,run,_=bootstrap(arm);run.mkdir(parents=True,exist_ok=True)
14
+ owner=(run/'manager.lock').open('a+');fcntl.flock(owner,fcntl.LOCK_EX|fcntl.LOCK_NB)
15
+ if (run/'COMPLETE.json').exists():return
16
+ with (run/'manager.log').open('a',buffering=1) as log:
17
+ subprocess.run([sys.executable,str(HERE/'acceptance.py'),'--arm',arm],check=True,stdout=log,stderr=subprocess.STDOUT)
18
+ path=run/'attempts.json';history=json.loads(path.read_text()) if path.exists() else []
19
+ if len(history)>=3:raise RuntimeError('Three training attempts exhausted; manual diagnosis required')
20
+ for attempt in range(len(history),3):
21
+ history.append(dict(attempt=attempt+1,started_unix=time.time()));save(path,history)
22
+ with (run/'manager.log').open('a',buffering=1) as log:
23
+ result=subprocess.run([sys.executable,'-u',str(HERE/'train.py'),'--arm',arm],stdout=log,stderr=subprocess.STDOUT)
24
+ history[-1].update(exit_code=result.returncode,finished_unix=time.time());save(path,history)
25
+ if result.returncode==0:return
26
+ time.sleep(15)
27
+ raise RuntimeError('Training retries exhausted')
28
+
29
+
30
+ if __name__=='__main__':
31
+ p=argparse.ArgumentParser();p.add_argument('--arm',required=True);a=p.parse_args();main(a.arm)
code/snapshot/workspace/rebuild/hierarchical_training_20261103/objectives.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Joint base ranking plus genuine encoder-gradient coarse/fine auxiliaries."""
2
+ from collections import Counter
3
+ import time
4
+ import torch
5
+ from torch.nn import functional as F
6
+ from kernels import grouped_contrastive,formula_objective
7
+
8
+
9
+ def amp():
10
+ from runtime09 import C
11
+ return torch.autocast('cuda',dtype=torch.bfloat16,enabled=C['bf16'])
12
+
13
+
14
+ def molecular_views(model,mols,probability):
15
+ """Independent hidden-node dropout, no topology edits, retain both graphs."""
16
+ def drop(module,inputs,output):return F.dropout(output,p=probability,training=True)
17
+ handle=model.graph.atom.register_forward_hook(drop)
18
+ try:
19
+ with amp():
20
+ one=model.encode_molecules(mols)[0].float()
21
+ two=model.encode_molecules(mols)[0].float()
22
+ finally:handle.remove()
23
+ return one,two
24
+
25
+
26
+ def auxiliary_loss(model,q,mols,rows,spec,step,diagnose=False):
27
+ from losses import ms_ms_supcon,molecule_molecule_two_view
28
+ from coarse_losses import formula_pairs,mass_pairs,weighted_supcon,neutral_mass_from_precursor
29
+ from specpartition_ms.chemistry import ADDUCTS,exact_mass
30
+ ids=[r['identity'] for r in rows];rids=[r['record_id'] for r in rows]
31
+ mid=[m.identity for m in mols];mf=[m.formula for m in mols];t=spec['loss']['temperature'];head=model.hierarchy
32
+ v1,v2=molecular_views(model,mols,spec['views']['molecule']['dropout'])
33
+ losses={};stats={}
34
+ out=ms_ms_supcon(head('ms_identity',q),ids,rids,t['identity']);losses['ms_fine']=out.loss;stats['ms_fine']=out.diagnostics
35
+ out=molecule_molecule_two_view(head('mol_identity',v1),head('mol_identity',v2),mid,t['identity']);losses['mol_fine']=out.loss;stats['mol_fine']=out.diagnostics
36
+ for name,x,formulas,identities in [('ms_formula',q,[r['formula'] for r in rows],ids),('mol_formula',torch.cat((v1,v2)),mf*2,mid*2)]:
37
+ p,n,g=formula_pairs(formulas,identities)
38
+ losses[name],stats[name]=weighted_supcon(head(name,x),p,n,g,t['formula'])
39
+ valid=[i for i,r in enumerate(rows) if r['mass_ok']]
40
+ ms_mass=[]
41
+ for i in valid:
42
+ delta,charge=ADDUCTS[rows[i]['query'].adduct]
43
+ ms_mass.append(neutral_mass_from_precursor(rows[i]['query'].precursor_mz,abs(charge),delta))
44
+ settings=spec['loss']['mass_coarse']
45
+ for name,x,masses,identities,formulas in [
46
+ ('ms_mass',q[valid],ms_mass,[ids[i] for i in valid],[rows[i]['formula'] for i in valid]),
47
+ ('mol_mass',torch.cat((v1,v2)),[exact_mass(f) for f in mf]*2,mid*2,mf*2)]:
48
+ p,n=mass_pairs(masses,identities,settings['positive_radius_da'],settings['negative_start_da'],settings['gaussian_sigma_da'],settings['mode'],settings['hard_bin_width_da'],settings['hard_bin_offset_da'])
49
+ losses[name],stats[name]=weighted_supcon(head(name,x),p,n,identities,t['mass'])
50
+ same=torch.tensor([[a==b for b in formulas] for a in formulas],dtype=torch.bool).reshape(len(formulas),len(formulas))
51
+ stats[name]['same_formula_positive_pairs']=(p.gt(0)&same).sum()
52
+ stats[name]['cross_formula_positive_pairs']=(p.gt(0)&~same).sum()
53
+ ramp=min(1.,(step+1)/spec['loss']['auxiliary_ramp_steps']);w=spec['loss']['auxiliary']
54
+ total=sum(losses[k]*w[k]*ramp for k in losses)
55
+ flat={}
56
+ for k,v in losses.items():
57
+ flat[k+'_raw']=v.detach();flat[k+'_weighted']=(v*w[k]*ramp).detach()
58
+ for sk,sv in stats[k].items():flat[k+'_'+sk]=sv.detach() if torch.is_tensor(sv) else sv
59
+ # Aux tasks only, at declared intervals; not a full-parameter task conflict audit.
60
+ if diagnose:
61
+ gradients={}
62
+ for name,value in losses.items():
63
+ if w[name]==0:continue
64
+ gs=torch.autograd.grad(value,(q,v1,v2),retain_graph=True,allow_unused=True)
65
+ gradients[name]=torch.cat([(g if g is not None else torch.zeros_like(x)).reshape(-1) for g,x in zip(gs,(q,v1,v2))]).detach()
66
+ flat[name+'_representation_gradient_norm']=gradients[name].norm()
67
+ names=list(gradients)
68
+ for a,i in enumerate(names):
69
+ for j in names[a+1:]:
70
+ flat['gradient_cosine_'+i+'__'+j]=F.cosine_similarity(gradients[i][None],gradients[j][None])[0]
71
+ for name,x in [('ms',head('ms_identity',q)),('mol',head('mol_identity',v1))]:
72
+ flat[name+'_projection_mean_std']=x.detach().std(0,unbiased=False).mean()
73
+ if diagnose:
74
+ singular=torch.linalg.svdvals(x.detach()-x.detach().mean(0));p=singular/singular.sum().clamp_min(1e-12)
75
+ flat[name+'_projection_effective_rank']=torch.exp(-(p*p.clamp_min(1e-12).log()).sum())
76
+ flat['molecule_view_mean_abs_difference']=(v1.detach()-v2.detach()).abs().mean()
77
+ flat['molecule_view_cosine']=F.cosine_similarity(v1.detach(),v2.detach()).mean()
78
+ flat['auxiliary_total']=total.detach();flat['auxiliary_ramp']=ramp
79
+ return total,flat
80
+
81
+
82
+ def train_step(model,opt,batch,spec,step,update=True,diagnose=False):
83
+ from runtime09 import C
84
+ start=time.monotonic();rows=batch['rows'];queries=[r['query'] for r in rows];ids=[r['identity'] for r in rows]
85
+ reps={}
86
+ for r in rows:
87
+ k=r['identity'];m=r['ref']
88
+ if k not in reps or m.smiles<reps[k].smiles:reps[k]=m
89
+ columns=sorted(reps);mols=[reps[k] for k in columns];w=C['loss_weights'];opt.zero_grad(set_to_none=True)
90
+ # Exact deterministic gradient cache for base identity matching; stochastic
91
+ # molecule views below keep their own graphs and are NOT replayed.
92
+ with torch.no_grad(),amp():
93
+ qc=torch.cat([model.spectrum.forward_batch(queries[a:a+C['spectrum_chunk']])[1] for a in range(0,len(rows),C['spectrum_chunk'])])
94
+ mc=torch.cat([model.encode_molecules(mols[a:a+C['graph_chunk']])[0] for a in range(0,len(mols),C['graph_chunk'])])
95
+ qc=qc.float().detach().requires_grad_();mc=mc.float().detach().requires_grad_()
96
+ with amp():
97
+ zq=F.normalize(model.query_projection(qc).float(),dim=-1);zm=F.normalize(model.mol_projection(mc).float(),dim=-1)
98
+ f,b=grouped_contrastive(zq@zm.T/C['contrastive_temperature'],ids,columns)
99
+ base=w['inbatch_ms_to_mol']*f+w['inbatch_mol_to_ms']*b
100
+ aux,details=auxiliary_loss(model,qc,mols,rows,spec,step,diagnose)
101
+ (base+aux).backward();dq=qc.grad.detach();dm=mc.grad.detach()
102
+ metrics=dict(inbatch_ms_to_mol=f.detach(),inbatch_mol_to_ms=b.detach(),formula_loss=0.,formula_ce=0.,formula_gap=0.,element_ce=0.,formula_correct=0.)
103
+ valid=sum(r['mass_ok'] and len(r['formulas'])>1 and r['formula'] in r['formulas'] for r in rows)
104
+ for a in range(0,len(rows),C['spectrum_chunk']):
105
+ block=rows[a:a+C['spectrum_chunk']]
106
+ with amp():
107
+ tokens,q,_=model.spectrum.forward_batch([r['query'] for r in block])
108
+ lf,d=formula_objective(model,q,tokens,block,valid,len(rows))
109
+ loss=(q*dq[a:a+len(block)]).sum()+w['formula']*lf
110
+ loss.backward();metrics['formula_loss']+=lf.detach()
111
+ for k in ('formula_ce','formula_gap','element_ce','formula_correct'):metrics[k]+=d[k]
112
+ for a in range(0,len(mols),C['graph_chunk']):
113
+ with amp():u=model.encode_molecules(mols[a:a+C['graph_chunk']])[0];loss=(u*dm[a:a+len(u)]).sum()
114
+ loss.backward()
115
+ pools=[p for r in rows for p in r['pools']];counts=Counter(p['kind'] for p in pools)
116
+ pm={k:torch.zeros((),device=model.device) for k in ('odata','mass','formula')}
117
+ for a in range(0,len(pools),C['pool_micro_views']):
118
+ block=pools[a:a+C['pool_micro_views']]
119
+ with amp():
120
+ encs,_=model.encode_batch([p['query'] for p in block]);loss=encs[0].q.sum()*0.
121
+ for p,enc in zip(block,encs):
122
+ ce=torch.logsumexp(enc.base.float(),0)-enc.base[0].float();kind=p['kind']
123
+ pm[kind]+=ce.detach()/counts[kind]
124
+ loss+=w[{'odata':'odata_pool','mass':'msg_mass_pool','formula':'msg_formula_pool'}[kind]]*ce/counts[kind]
125
+ loss.backward()
126
+ total=base.detach()+aux.detach()+w['formula']*metrics['formula_loss']
127
+ for k,value in pm.items():
128
+ metrics[k+'_pool']=value;total+=w[{'odata':'odata_pool','mass':'msg_mass_pool','formula':'msg_formula_pool'}[k]]*value
129
+ if not torch.isfinite(total):raise RuntimeError('Nonfinite training objective')
130
+ norm=torch.nn.utils.clip_grad_norm_(model.parameters(),C['gradient_clip'],error_if_nonfinite=True)
131
+ if update:opt.step()
132
+ metrics.update(details);metrics.update(loss=total,gradient_norm=norm.detach())
133
+ packed=torch.stack([v.detach().float().to(model.device) if torch.is_tensor(v) else torch.tensor(v,device=model.device).float() for v in metrics.values()]).cpu().tolist()
134
+ result=dict(zip(metrics,packed));result.update(queries=len(rows),unique_connectivity=len(columns),formula_valid=valid,pool_valid=dict(counts),
135
+ sources=dict(Counter(r['source'] for r in rows)),negative_draws=sum(p['negative_draws'] for p in pools),
136
+ negative_unique_key14=sum(p['unique_negative_key14'] for p in pools),duplicate_physical_MS=len(rows)-len({r['record_id'] for r in rows}),
137
+ molecular_encoder_views=2,data_preparation_seconds=batch['data_seconds'],step_compute_seconds=time.monotonic()-start,
138
+ peak_allocated_mib=torch.cuda.max_memory_allocated()/2**20)
139
+ return result
140
+
code/snapshot/workspace/rebuild/hierarchical_training_20261103/runtime_hier.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Isolated four-arm runtime. Never writes to the accepted R09 source or run."""
2
+ import contextlib
3
+ import fcntl
4
+ import hashlib
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+ import sys
9
+ import time
10
+
11
+ HERE=Path(__file__).resolve().parent
12
+ ROOT=Path(os.environ.get('SPECPARTITION_ROOT','/workspace/xj/SpecPartition-MS'))
13
+ ARMS=('C03_both_fine','C06_fine_formula','C07_fine_mass','C08_full_separate')
14
+ SEED=20261103
15
+
16
+
17
+ def sha(p):
18
+ h=hashlib.sha256()
19
+ with Path(p).open('rb') as f:
20
+ for block in iter(lambda:f.read(8*1024**2),b''):h.update(block)
21
+ return h.hexdigest()
22
+
23
+
24
+ def save(p,value):
25
+ p=Path(p);p.parent.mkdir(parents=True,exist_ok=True)
26
+ q=p.with_suffix(p.suffix+'.tmp');q.write_text(json.dumps(value,ensure_ascii=False,indent=2,allow_nan=False)+'\n');q.replace(p)
27
+
28
+
29
+ def bootstrap(arm):
30
+ if arm not in ARMS:raise ValueError('Unapproved arm')
31
+ sys.path[:0]=[str(HERE.parent/'training_r09'),str(HERE.parent/'hierarchical_ablation_20261103'),str(HERE.parent/'intra_modal_extension')]
32
+ import runtime09 as legacy
33
+ from configs import validate
34
+ p=HERE.parent/'hierarchical_ablation_20261103/configs'/(arm+'.json')
35
+ spec=json.loads(p.read_text());validate(spec)
36
+ # In-process overrides only. The on-disk accepted legacy run is immutable.
37
+ legacy.C.update(seed=SEED,threads=1,workers=1,prefetch_batches=2,
38
+ learning_rate=spec['budget']['learning_rate'],minimum_learning_rate=spec['budget']['minimum_learning_rate'],
39
+ warmup_steps=spec['budget']['warmup_steps'])
40
+ run=ROOT/'runs'/spec['suite_id']/arm/('seed_%d'%SEED)
41
+ legacy.RUN=run
42
+ resolved=dict(arm=arm,seed=SEED,updates=6000,validation_every=2000,checkpoint_every=100,
43
+ execution_authority='new_runtime_requires_exact_real_GPU_acceptance_not_archived_proposal_flag',
44
+ proposal_sha256=sha(p),parent=spec['initialization'],
45
+ workers=1,threads=1,gpu_work_slots=2,gpu_memory_fraction=.25,
46
+ empty_allocator_cache_between_guarded_work=True,
47
+ original_R09_unchanged=True,new_AdamW=True,training_entrypoint=str(HERE/'train.py'),
48
+ gradient_diagnostics_scope='auxiliary_losses_wrt_shared_cached_representations_every_100_updates',
49
+ original_projection_and_pool_score_semantics=True)
50
+ return spec,resolved,run,legacy
51
+
52
+
53
+ def binding(spec,resolved,legacy):
54
+ b=legacy.bind()
55
+ if b['records']!=spec['data']['records'] or b['label_policy_sha256']!=spec['data']['label_policy_sha256']:
56
+ raise RuntimeError('Training data binding mismatch')
57
+ if sha(spec['initialization']['checkpoint'])!=spec['initialization']['sha256']:raise RuntimeError('Parent hash mismatch')
58
+ files=list(HERE.glob('*.py'))+list((HERE.parent/'intra_modal_extension').glob('*.py'))
59
+ files += [HERE.parent/'hierarchical_ablation_20261103/coarse_losses.py']
60
+ return dict(resolved=resolved,data=b,code={str(p.relative_to(ROOT)) if p.is_relative_to(ROOT) else p.name:sha(p) for p in sorted(files)})
61
+
62
+
63
+ @contextlib.contextmanager
64
+ def gpu_slot(run,phase):
65
+ """Only these new jobs share two GPU slots; existing services are untouched."""
66
+ directory=ROOT/'runs/hierarchical_intra_modal_20261103/gpu_slots';directory.mkdir(parents=True,exist_ok=True)
67
+ streams=[(directory/('slot_%d.lock'%i)).open('a+') for i in range(2)];held=None
68
+ try:
69
+ while held is None:
70
+ for f in streams:
71
+ try:fcntl.flock(f,fcntl.LOCK_EX|fcntl.LOCK_NB);held=f;break
72
+ except BlockingIOError:pass
73
+ if held is None:
74
+ save(run/'resource_status.json',dict(phase=phase,state='waiting_for_new_experiment_gpu_slot',updated_unix=time.time()))
75
+ time.sleep(.3)
76
+ save(run/'resource_status.json',dict(phase=phase,state='gpu_work',updated_unix=time.time()))
77
+ yield
78
+ finally:
79
+ if held is not None:
80
+ # Release temporary activations before another new experiment enters.
81
+ import torch
82
+ if torch.cuda.is_initialized():torch.cuda.empty_cache()
83
+ fcntl.flock(held,fcntl.LOCK_UN)
84
+ for f in streams:f.close()
85
+
code/snapshot/workspace/rebuild/hierarchical_training_20261103/sampling.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Formula / identity / real-record grouping with no within-source repetition."""
2
+ from collections import deque,defaultdict
3
+ from functools import lru_cache
4
+ import hashlib
5
+ import random
6
+
7
+
8
+ def grouped_chunks(records,batch_size,formulas_per_batch,identities_per_formula,spectra_per_identity,seed):
9
+ rng=random.Random(seed);by=defaultdict(lambda:defaultdict(list))
10
+ seen=set()
11
+ for rid,identity,formula in records:
12
+ if rid in seen:raise ValueError('Duplicate physical spectrum ID')
13
+ seen.add(rid);by[formula][identity].append(rid)
14
+ formula_keys=sorted(by);rng.shuffle(formula_keys);queues={};groups={}
15
+ for f in formula_keys:
16
+ keys=sorted(by[f]);rng.shuffle(keys);queues[f]=deque(keys)
17
+ groups[f]={}
18
+ for k in keys:
19
+ rr=by[f][k];rng.shuffle(rr);groups[f][k]=deque(rr)
20
+ active=deque(formula_keys);batch=[];result=[]
21
+ while active:
22
+ # Desired shape when available; rare groups are packed without duplication.
23
+ for _ in range(min(formulas_per_batch,len(active))):
24
+ f=active.popleft();iq=queues[f]
25
+ for _ in range(min(identities_per_formula,len(iq))):
26
+ key=iq.popleft();rr=groups[f][key]
27
+ for _ in range(min(spectra_per_identity,len(rr),batch_size-len(batch))):batch.append(rr.popleft())
28
+ if rr:iq.append(key)
29
+ if len(batch)==batch_size:break
30
+ if iq:active.append(f)
31
+ if len(batch)==batch_size:
32
+ result.append(batch);batch=[];break
33
+ if batch:result.append(batch)
34
+ if sum(map(len,result))!=len(records) or len({r for b in result for r in b})!=len(records):raise RuntimeError('Sampler exposure loss/repetition')
35
+ return result
36
+
37
+
38
+ @lru_cache(maxsize=1)
39
+ def metadata():
40
+ from runtime09 import readonly,OUT
41
+ db=readonly(OUT/'preparation.sqlite');out={'msg':[],'odata':[]}
42
+ for rid,source,identity,formula in db.execute('SELECT record_id,source,identity,formula FROM records ORDER BY record_id'):
43
+ out['msg' if source=='MSG_Train' else 'odata'].append((rid,identity,formula))
44
+ db.close()
45
+ if sum(map(len,out.values()))!=643587:raise RuntimeError('Incomplete accepted training release')
46
+ return out
47
+
48
+
49
+ def epoch_plans(epoch,seed=20261103):
50
+ rows=metadata();chunks={}
51
+ chunks['odata']=grouped_chunks(rows['odata'],256,8,8,4,seed+epoch*104729)
52
+ chunks['msg']=grouped_chunks(rows['msg'],32,4,4,2,seed+epoch*104729+1)
53
+ total=max(map(len,chunks.values()));plans=[]
54
+ for step in range(total):
55
+ plan={}
56
+ for k,blocks in chunks.items():
57
+ a=step*len(blocks)//total;b=(step+1)*len(blocks)//total
58
+ plan[k]=[rid for block in blocks[a:b] for rid in block]
59
+ plans.append((epoch,step,plan))
60
+ return plans
61
+
62
+
63
+ def plan_hash(plans):
64
+ h=hashlib.sha256()
65
+ for epoch,step,p in plans:
66
+ h.update(('%d:%d\n'%(epoch,step)).encode())
67
+ for group,ids in p.items():h.update((group+':'+','.join(ids)+'\n').encode())
68
+ return h.hexdigest()
69
+
70
+
71
+ class PlanDataset:
72
+ def __init__(self,plans,seed=20261103):self.plans=plans;self.reader=None;self.seed=seed
73
+ def __len__(self):return len(self.plans)
74
+ def __getitem__(self,i):
75
+ import time
76
+ from data09 import Reader
77
+ if self.reader is None:self.reader=Reader()
78
+ epoch,step,plan=self.plans[i];start=time.monotonic();rows=[]
79
+ for source,ids in plan.items():
80
+ for j,rid in enumerate(ids):
81
+ seed=self.seed+epoch*100000000+step*10000+j+(1000000 if source=='msg' else 0)
82
+ rows.append(self.reader.sample(rid,seed,source=='odata' and j<16))
83
+ return dict(epoch=epoch,step=step,rows=rows,data_seconds=time.monotonic()-start)
84
+
code/snapshot/workspace/rebuild/hierarchical_training_20261103/test_runtime.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+ from collections import Counter
3
+ import torch
4
+ from torch.nn import functional as F
5
+ from kernels import grouped_contrastive
6
+ from sampling import grouped_chunks
7
+
8
+
9
+ class RuntimeTests(unittest.TestCase):
10
+ def setUp(self):torch.manual_seed(29);torch.set_num_threads(1)
11
+
12
+ def test_reverse_multiple_positive_loss_and_gradient_equivalence(self):
13
+ ids=['A','B','A','C','B','D'];columns=list('ABCD')
14
+ a=torch.randn(6,4,requires_grad=True);b=a.detach().clone().requires_grad_()
15
+ f,r=grouped_contrastive(a,ids,columns);target=torch.tensor([columns.index(k) for k in ids])
16
+ expected=F.cross_entropy(b,target)+torch.stack([-b.T.log_softmax(-1)[j,target==j].mean() for j in range(4)]).mean()
17
+ (f+r).backward();expected.backward();torch.testing.assert_close(f+r,expected);torch.testing.assert_close(a.grad,b.grad)
18
+
19
+ def test_single_structure_differentiable_zero(self):
20
+ x=torch.randn(4,1,requires_grad=True);f,r=grouped_contrastive(x,['A']*4,['A']);(f+r).backward()
21
+ self.assertEqual(float(f+r),0.);self.assertEqual(float(x.grad.abs().sum()),0.)
22
+
23
+ def test_duplicate_molecule_columns_rejected(self):
24
+ with self.assertRaises(ValueError):grouped_contrastive(torch.randn(3,2),['A']*3,['A','A'])
25
+
26
+ def rows(self):
27
+ return [(f'{f}_{k}_{s}',f'{f}_{k}',f) for f in ['F1','F2','F3'] for k in range(5) for s in range(k+1)]
28
+
29
+ def test_sampler_exact_coverage_no_physical_repetition(self):
30
+ rows=self.rows();chunks=grouped_chunks(rows,16,2,2,2,7)
31
+ flat=[r for b in chunks for r in b];self.assertEqual(Counter(flat),Counter(r[0] for r in rows))
32
+ self.assertTrue(all(len(x)==16 for x in chunks[:-1]));self.assertLessEqual(len(chunks[-1]),16)
33
+
34
+ def test_sampler_reproducible_and_seed_sensitive(self):
35
+ rows=self.rows();a=grouped_chunks(rows,16,2,2,2,7)
36
+ self.assertEqual(a,grouped_chunks(rows,16,2,2,2,7));self.assertNotEqual(a,grouped_chunks(rows,16,2,2,2,8))
37
+
38
+ def test_rare_singletons_retained(self):
39
+ rows=[(str(i),str(i),'F'+str(i)) for i in range(43)]
40
+ chunks=grouped_chunks(rows,16,2,2,4,3)
41
+ self.assertEqual(len({r for b in chunks for r in b}),43)
42
+
43
+ def test_duplicate_ms_input_rejected(self):
44
+ with self.assertRaises(ValueError):grouped_chunks([('x','A','F'),('x','A','F')],16,2,2,2,7)
45
+
46
+ def test_empty_source(self):self.assertEqual(grouped_chunks([],16,2,2,2,7),[])
47
+
48
+
49
+ if __name__=='__main__':unittest.main()
code/snapshot/workspace/rebuild/hierarchical_training_20261103/train.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Managed resumable fine-tuning; real acceptance must precede training."""
2
+ import argparse
3
+ from collections import deque
4
+ import fcntl
5
+ import json
6
+ import math
7
+ from pathlib import Path
8
+ import random
9
+ import shutil
10
+ import time
11
+ import traceback
12
+ import numpy as np
13
+ import torch
14
+ from torch.utils.data import DataLoader
15
+ from runtime_hier import bootstrap,binding,save,gpu_slot,ROOT
16
+
17
+
18
+ def setup(legacy,resolved):
19
+ torch.set_num_threads(1);torch.set_float32_matmul_precision('high');torch.use_deterministic_algorithms(True)
20
+ legacy.seed_all(resolved['seed']);torch.cuda.set_per_process_memory_fraction(resolved['gpu_memory_fraction'])
21
+
22
+
23
+ def make_model(spec,legacy):
24
+ from coarse_losses import ProjectionBank
25
+ from kernels import install_graph_kernel
26
+ model=legacy.make_model()
27
+ parent=torch.load(spec['initialization']['checkpoint'],map_location='cpu',weights_only=False)
28
+ model.load_state_dict(parent['model'],strict=True)
29
+ model.hierarchy=ProjectionBank()
30
+ install_graph_kernel(model)
31
+ return model.to(legacy.C['device'])
32
+
33
+
34
+ def optimizer(model,legacy):return torch.optim.AdamW(model.parameters(),lr=legacy.C['learning_rate'],weight_decay=legacy.C['weight_decay'])
35
+
36
+
37
+ def checkpoint(path,model,opt,progress,bound):
38
+ tmp=Path(str(path)+'.tmp')
39
+ torch.save(dict(model=model.state_dict(),optimizer=opt.state_dict(),progress=progress,binding=bound,
40
+ torch_rng=torch.get_rng_state(),cuda_rng=torch.cuda.get_rng_state_all(),numpy_rng=np.random.get_state(),python_rng=random.getstate()),tmp)
41
+ tmp.replace(path)
42
+
43
+
44
+ def restore(path,model,opt,bound):
45
+ d=torch.load(path,map_location='cpu',weights_only=False)
46
+ if d['binding']!=bound:raise RuntimeError('Resume configuration/code/data binding changed')
47
+ model.load_state_dict(d['model'],strict=True);opt.load_state_dict(d['optimizer'])
48
+ torch.set_rng_state(d['torch_rng']);torch.cuda.set_rng_state_all(d['cuda_rng']);np.random.set_state(d['numpy_rng']);random.setstate(d['python_rng'])
49
+ return d['progress']
50
+
51
+
52
+ def lr_at(step,spec):
53
+ b=spec['budget'];warm=b['warmup_steps'];maximum=b['learning_rate'];minimum=b['minimum_learning_rate']
54
+ if step<warm:return maximum*(step+1)/warm
55
+ return minimum+.5*(maximum-minimum)*(1+math.cos(math.pi*min(1.,(step-warm)/max(1,b['optimizer_updates_per_seed']-warm))))
56
+
57
+
58
+ def run(arm):
59
+ spec,resolved,run,legacy=bootstrap(arm);run.mkdir(parents=True,exist_ok=True)
60
+ lock=(run/'train.lock').open('a+');fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
61
+ bound=binding(spec,resolved,legacy)
62
+ accepted=json.loads((run/'acceptance.json').read_text())
63
+ if not accepted.get('complete') or accepted['binding']!=bound:raise RuntimeError('This exact arm has not passed GPU acceptance')
64
+ if shutil.disk_usage(ROOT).free<43*2**30:raise RuntimeError('Insufficient disk reserve for four arms and original run')
65
+ if not (legacy.PREP/'validation_ready.json').exists():raise RuntimeError('Official Validation inputs not prepared')
66
+ setup(legacy,resolved)
67
+ from sampling import epoch_plans,plan_hash,PlanDataset
68
+ from objectives import train_step
69
+ from validation import evaluate
70
+ with gpu_slot(run,'initialization'):
71
+ model=make_model(spec,legacy);opt=optimizer(model,legacy)
72
+ progress=dict(update=0,epoch=0,next_step=0,validated_updates=[])
73
+ if (run/'last.pt').exists():progress=restore(run/'last.pt',model,opt,bound)
74
+ else:checkpoint(run/'last.pt',model,opt,progress,bound)
75
+ save(run/'resolved_config.json',dict(runtime=resolved,proposal=spec,binding=bound,parameters=sum(p.numel() for p in model.parameters()),
76
+ initialization='fixed_R09_e4_backbone_new_heads_new_optimizer_not_scratch',test_used_for_training=False,
77
+ implemented=['hierarchical_no_repeat_sampler','independent_hidden_atom_dropout_views','stochastic_graphs_retained_no_replay','six_auxiliary_losses_and_quality_mask','equivalent_vectorized_base_kernels']))
78
+ def validate_pending():
79
+ u=progress['update']
80
+ if u and u%2000==0 and u not in progress['validated_updates']:
81
+ save(run/'status.json',dict(phase='validation',update=u,running=True,updated_unix=time.time()))
82
+ with gpu_slot(run,'validation'):
83
+ if not (run/('step_%06d.pt'%u)).exists():checkpoint(run/('step_%06d.pt'%u),model,opt,progress,bound)
84
+ evaluate(model,u);progress['validated_updates'].append(u);checkpoint(run/'last.pt',model,opt,progress,bound)
85
+ validate_pending();window=deque(maxlen=100)
86
+ while progress['update']<resolved['updates']:
87
+ plans=epoch_plans(progress['epoch'],resolved['seed']);save(run/('sampler_epoch_%02d.json'%progress['epoch']),dict(epoch=progress['epoch'],steps=len(plans),sha256=plan_hash(plans),records_once=True))
88
+ dataset=PlanDataset(plans[progress['next_step']:],resolved['seed'])
89
+ loader=DataLoader(dataset,batch_size=None,num_workers=1,prefetch_factor=2,multiprocessing_context='spawn')
90
+ start_step=progress['next_step']
91
+ for step,batch in enumerate(loader,start_step):
92
+ started=time.monotonic()
93
+ with gpu_slot(run,'training'):
94
+ model.train();lr=lr_at(progress['update'],spec)
95
+ for g in opt.param_groups:g['lr']=lr
96
+ torch.cuda.reset_peak_memory_stats()
97
+ m=train_step(model,opt,batch,spec,progress['update'],diagnose=progress['update']%100==0)
98
+ progress.update(update=progress['update']+1,next_step=step+1)
99
+ if progress['update']%100==0:checkpoint(run/'last.pt',model,opt,progress,bound)
100
+ m.update(update=progress['update'],planned_updates=resolved['updates'],data_epoch=progress['epoch']+1,step=step+1,
101
+ steps_in_data_epoch=len(plans),learning_rate=lr,wall_seconds=time.monotonic()-started,unix_time=time.time(),arm=arm)
102
+ with (run/'loss.jsonl').open('a') as f:f.write(json.dumps(m,allow_nan=False)+'\n')
103
+ window.append(m)
104
+ if progress['update']%10==0 or progress['update']==1:
105
+ status=dict(phase='training',running=True,**progress,recent_loss=sum(x['loss'] for x in window)/len(window),latest=m,updated_unix=time.time())
106
+ save(run/'status.json',status);print(json.dumps(status,allow_nan=False),flush=True)
107
+ validate_pending()
108
+ if progress['update']>=resolved['updates']:break
109
+ if progress['next_step']>=len(plans):progress.update(epoch=progress['epoch']+1,next_step=0)
110
+ with gpu_slot(run,'final_checkpoint'):checkpoint(run/'last.pt',model,opt,progress,bound)
111
+ save(run/'COMPLETE.json',dict(complete=True,updates=progress['update'],validated_updates=progress['validated_updates'],updated_unix=time.time()))
112
+ save(run/'status.json',dict(phase='complete',running=False,**progress,updated_unix=time.time()))
113
+
114
+
115
+ if __name__=='__main__':
116
+ p=argparse.ArgumentParser();p.add_argument('--arm',required=True);a=p.parse_args()
117
+ try:run(a.arm)
118
+ except Exception:
119
+ try:
120
+ _,_,directory,_=bootstrap(a.arm)
121
+ save(directory/'failure.json',dict(traceback=traceback.format_exc(),updated_unix=time.time(),resume_from_last_checkpoint=True))
122
+ finally:raise
123
+
code/snapshot/workspace/rebuild/hierarchical_training_20261103/validation.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Full official Validation pools; evaluation-only graph store, never training assets."""
2
+ from collections import defaultdict, Counter
3
+ from concurrent.futures import ProcessPoolExecutor
4
+ from dataclasses import replace
5
+ from functools import lru_cache
6
+ import csv
7
+ import gzip
8
+ import hashlib
9
+ import json
10
+ import multiprocessing
11
+ import sqlite3
12
+ import time
13
+ from runtime09 import *
14
+ from data09 import prepared_query
15
+ from specpartition_ms.epoch_features import dumps, loads
16
+
17
+ KS=(1,3,5,10,20,50,100,200)
18
+ FKS=tuple(range(1,11))+(20,50,100,200)
19
+
20
+
21
+ def supported_truth_formula(raw):
22
+ from specpartition_ms.chemistry import canonical_formula,formula_vector
23
+ try:
24
+ canonical=canonical_formula(raw);formula_vector(canonical)
25
+ return canonical
26
+ except ValueError:return None
27
+
28
+
29
+ def structure(s):
30
+ from rdkit import Chem,RDLogger
31
+ from rdkit.Chem import rdMolDescriptors
32
+ from specpartition_ms.chemistry import _calculate_molecule,canonical_formula,formula_vector
33
+ RDLogger.DisableLog('rdApp.*')
34
+ formula=None;identity=None
35
+ try:
36
+ mol=Chem.MolFromSmiles(s)
37
+ if mol is None:raise ValueError('invalid_SMILES')
38
+ identity=Chem.MolToInchiKey(mol).split('-')[0]
39
+ formula=canonical_formula(rdMolDescriptors.CalcMolFormula(mol));formula_vector(formula)
40
+ m=_calculate_molecule(s); key=hashlib.sha256(m.smiles.encode()).hexdigest()
41
+ return s,key,m.identity,formula,dumps(m),None
42
+ except Exception as exc:return s,None,identity,formula,None,repr(exc)
43
+
44
+
45
+ def prepare_validation():
46
+ import ijson
47
+ PREP.mkdir(parents=True,exist_ok=True);path=PREP/'validation.sqlite'
48
+ official=ROOT/'data/raw/massspecgym_v1_5/data/molecules'
49
+ table=ROOT/'data/derived/massspecgym_v1_5_splits/val.tsv'
50
+ binding=dict(tsv_sha256=sha(table),pools={kind:sha(official/f'MassSpecGym1.5_retrieval_candidates_{kind}.json') for kind in ('mass','formula')},
51
+ chemistry_sha256=sha(V09/'src/specpartition_ms/chemistry.py'),no_training_writes=True)
52
+ marker=PREP/'validation_ready.json'
53
+ if marker.exists():
54
+ if json.loads(marker.read_text())['binding']!=binding:raise RuntimeError('Validation binding changed')
55
+ return
56
+ db=sqlite3.connect(path);db.execute('PRAGMA journal_mode=WAL')
57
+ db.executescript('''CREATE TABLE IF NOT EXISTS spectra(identifier TEXT PRIMARY KEY,target TEXT,identity TEXT,formula TEXT,body BLOB);
58
+ CREATE INDEX IF NOT EXISTS spectrum_target ON spectra(target);
59
+ CREATE TABLE IF NOT EXISTS pools(target TEXT,view TEXT,body TEXT,PRIMARY KEY(target,view));
60
+ CREATE TABLE IF NOT EXISTS aliases(smiles TEXT PRIMARY KEY,graph_key TEXT,identity TEXT,formula TEXT,error TEXT);
61
+ CREATE TABLE IF NOT EXISTS graphs(graph_key TEXT PRIMARY KEY,body BLOB);''')
62
+ targets=set()
63
+ with table.open() as f:
64
+ for row in csv.DictReader(f,delimiter='\t'):
65
+ targets.add(row['smiles'])
66
+ ms=dict(peaks=list(zip(map(float,row['mzs'].split(',')),map(float,row['intensities'].split(',')))),
67
+ precursor_mz=float(row['precursor_mz']),adduct=row['adduct'],collision_energy=row.get('collision_energy'),instrument=row.get('instrument_type'))
68
+ payload=dict(identifier=row['identifier'],target=row['smiles'],identity=row['inchikey'][:14],formula=row['formula'],
69
+ query=prepared_query(ms,'massspecgym_official'))
70
+ db.execute('INSERT OR IGNORE INTO spectra VALUES (?,?,?,?,?)',(row['identifier'],row['smiles'],row['inchikey'][:14],row['formula'],dumps(payload)))
71
+ wanted=set(targets)
72
+ for kind in ('mass','formula'):
73
+ with (official/f'MassSpecGym1.5_retrieval_candidates_{kind}.json').open('rb') as f:
74
+ for target,pool in ijson.kvitems(f,''):
75
+ if target not in targets:continue
76
+ db.execute('INSERT OR IGNORE INTO pools VALUES (?,?,?)',(target,kind,json.dumps(pool,separators=(',',':'))));wanted.update(pool)
77
+ db.commit();done={r[0] for r in db.execute('SELECT smiles FROM aliases')};todo=sorted(wanted-done)
78
+ started=time.monotonic();processed=0
79
+ with ProcessPoolExecutor(max_workers=4,mp_context=multiprocessing.get_context('spawn')) as workers:
80
+ for s,key,identity,formula,blob,error in workers.map(structure,todo,chunksize=32):
81
+ db.execute('INSERT OR IGNORE INTO aliases VALUES (?,?,?,?,?)',(s,key,identity,formula,error))
82
+ if blob is not None:db.execute('INSERT OR IGNORE INTO graphs VALUES (?,?)',(key,blob))
83
+ processed+=1
84
+ if processed%2000==0:
85
+ db.commit();save(PREP/'validation_prepare_status.json',dict(processed=processed,already=len(done),total=len(wanted),seconds=time.monotonic()-started))
86
+ db.commit();counts={t:db.execute('SELECT COUNT(*) FROM '+t).fetchone()[0] for t in ('spectra','pools','aliases','graphs')}
87
+ if counts['spectra']!=19429 or counts['pools']!=6772:raise RuntimeError('Incomplete official Validation')
88
+ db.execute('PRAGMA wal_checkpoint(TRUNCATE)');db.close()
89
+ save(marker,dict(complete=True,binding=binding,counts=counts,evaluation_only=True))
90
+
91
+
92
+ def metric(rows,field,ks):
93
+ result={}
94
+ for k in ks:
95
+ hits=sum(r[field] is not None and r[field]<=k for r in rows)
96
+ bytarget=defaultdict(list);byidentity=defaultdict(list)
97
+ for r in rows:
98
+ hit=r[field] is not None and r[field]<=k
99
+ bytarget[r['target']].append(hit);byidentity[r['reference_identity']].append(hit)
100
+ result[str(k)]=dict(hits=hits,denominator=len(rows),micro=hits/len(rows),
101
+ target_macro=sum(sum(v)/len(v) for v in bytarget.values())/len(bytarget),
102
+ key14_macro=sum(sum(v)/len(v) for v in byidentity.values())/len(byidentity))
103
+ return result
104
+
105
+
106
+ def evaluate(model,update):
107
+ import torch
108
+ from specpartition_ms.fast_formula_r2 import forward_batch as formula_forward
109
+ from specpartition_ms.chemistry import canonical_formula,formula_vector
110
+ from objectives import amp
111
+ dest=RUN/('validation_update_%06d'%update);dest.mkdir(parents=True,exist_ok=True)
112
+ if (dest/'metrics.json').exists():return json.loads((dest/'metrics.json').read_text())
113
+ prepare_validation();db=readonly(PREP/'validation.sqlite');model.eval();summary=[];started=time.monotonic()
114
+ targets=[r[0] for r in db.execute('SELECT DISTINCT target FROM spectra ORDER BY target')]
115
+ for ti,target in enumerate(targets):
116
+ filename=hashlib.sha256(target.encode()).hexdigest()+'.json.gz';output=dest/filename
117
+ if output.exists():
118
+ with gzip.open(output,'rt') as f:summary.extend(json.load(f)['rows'])
119
+ continue
120
+ pools={kind:json.loads(db.execute('SELECT body FROM pools WHERE target=? AND view=?',(target,kind)).fetchone()[0]) for kind in ('mass','formula')}
121
+ aliases={s:db.execute('SELECT graph_key,identity,formula,error FROM aliases WHERE smiles=?',(s,)).fetchone() for s in set(sum(pools.values(),[]))}
122
+ graphs={}
123
+ for s,(key,identity,formula,error) in aliases.items():
124
+ if key is not None and key not in graphs:graphs[key]=loads(db.execute('SELECT body FROM graphs WHERE graph_key=?',(key,)).fetchone()[0])
125
+ keys=sorted(graphs);mols=[graphs[k] for k in keys];positions={k:i for i,k in enumerate(keys)}
126
+ data=[loads(r[0]) for r in db.execute('SELECT body FROM spectra WHERE target=? ORDER BY identifier',(target,))];rows=[]
127
+ with torch.inference_mode(),amp():
128
+ u,atoms,zm=model.encode_molecules(mols)
129
+ for a in range(0,len(data),C['validation_batch_views']):
130
+ block=data[a:a+C['validation_batch_views']]
131
+ tokens,qs,_=model.spectrum.forward_batch([r['query'] for r in block])
132
+ views=[];qvalues=[];tvalues=[]
133
+ for i,r in enumerate(block):
134
+ for kind in ('mass','formula'):
135
+ fs=set()
136
+ for s in pools[kind]:
137
+ f=aliases[s][2]
138
+ if f:
139
+ try:formula_vector(f);fs.add(canonical_formula(f))
140
+ except ValueError:pass
141
+ q=replace(r['query'],formula_candidates=tuple(sorted(fs)))
142
+ views.append((i,kind,q));qvalues.append(qs[i]);tvalues.append(tokens[i])
143
+ fscores=formula_forward(model.formula_v07,torch.stack(qvalues),[x[2] for x in views],tvalues)
144
+ for vi,(i,kind,q) in enumerate(views):
145
+ r=block[i];selected=sorted({aliases[s][0] for s in pools[kind] if aliases[s][0] is not None})
146
+ idx=[positions[k] for k in selected];scores={}
147
+ if idx:
148
+ zi=zm[idx];sf=[graphs[k].formula for k in selected]
149
+ _,joint,_=model.conditioned(qs[i],q,sf,zi,fscores[vi])
150
+ local=model.local_weight*model.local_scores(tokens[i],[atoms[j] for j in idx])
151
+ scores=dict(zip(selected,(joint+local).float().cpu().tolist()))
152
+ expanded=[dict(smiles=s,identity=aliases[s][1],score=scores.get(aliases[s][0]),scoreable=aliases[s][0] in scores) for s in pools[kind]]
153
+ expanded.sort(key=lambda x:(not x['scoreable'],-x['score'] if x['scoreable'] else 0,x['identity'] or '',x['smiles']))
154
+ rank=next((j+1 for j,c in enumerate(expanded) if c['scoreable'] and c['identity']==r['identity']),None)
155
+ formula_values=fscores[vi].float().cpu().tolist();order=sorted(range(len(q.formula_candidates)),key=lambda j:(-formula_values[j],q.formula_candidates[j]))
156
+ truth=supported_truth_formula(r['formula']);frank=next((j+1 for j,k in enumerate(order) if q.formula_candidates[k]==truth),None)
157
+ row=dict(identifier=r['identifier'],target=target,view=kind,reference_identity=r['identity'],reference_formula=truth,
158
+ reference_formula_raw=r['formula'],reference_formula_supported=truth is not None,
159
+ rank=rank,formula_rank=frank,formula_count=len(q.formula_candidates),candidate_count=len(expanded),
160
+ unscoreable=sum(not c['scoreable'] for c in expanded),adduct=q.adduct,
161
+ top1_smiles=expanded[0]['smiles'] if expanded and expanded[0]['scoreable'] else None)
162
+ rows.append(row)
163
+ with gzip.open(output.with_suffix('.tmp'),'wt',compresslevel=3) as f:json.dump(dict(rows=rows,raw_pools=pools),f,separators=(',',':'))
164
+ output.with_suffix('.tmp').replace(output);summary.extend(rows)
165
+ if (ti+1)%25==0:save(dest/'status.json',dict(targets=ti+1,total=3386,spectral_views=len(summary),seconds=time.monotonic()-started,updated_unix=time.time()))
166
+ metrics={}
167
+ for kind in ('mass','formula'):
168
+ rr=[r for r in summary if r['view']==kind]
169
+ if len(rr)!=19429 or len({r['identifier'] for r in rr})!=19429:raise RuntimeError('Validation denominator mismatch')
170
+ metrics[kind]=dict(spectra=len(rr),structure=metric(rr,'rank',KS),formula=metric(rr,'formula_rank',FKS),
171
+ unscoreable_candidates=sum(r['unscoreable'] for r in rr))
172
+ metrics.update(update=update,protocol='full_official_raw_entry_rank_2D_connectivity_no_truth_injection',
173
+ formula_scope='distinct_formulas_in_official_pool_not_open_formula_generation',mces='disabled_by_user',seconds=time.monotonic()-started)
174
+ save(dest/'metrics.json',metrics)
175
+ # Harmonic mean keeps Formula-view precision from being hidden by Mass gains.
176
+ x=metrics['mass']['structure']['1']['micro'];y=metrics['formula']['structure']['1']['micro'];selection=2*x*y/max(x+y,1e-12)
177
+ prior=RUN/'best_validation.json';old=json.loads(prior.read_text()) if prior.exists() else {}
178
+ if selection>old.get('selection_score',-1):
179
+ save(prior,dict(update=update,checkpoint=str(RUN/('step_%06d.pt'%update)),selection_score=selection,
180
+ selection='harmonic_mean_mass_formula_structure_top1',formula_top1=metrics['mass']['formula']['1']['micro']))
181
+ db.close();model.train();return metrics
code/snapshot/workspace/rebuild/intra_modal_extension/losses.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Training-only intra-modal identity losses; NOT attached to the running R09 run.
2
+
3
+ Identities must already be standardized key14 labels for a 2D retrieval task.
4
+ These losses do not parse SMILES, generate augmentations, fetch remote data, or
5
+ read heldout labels. Both views must flow through the trainable encoder.
6
+
7
+ Reference: Khosla et al., Supervised Contrastive Learning, NeurIPS 2020, Eq. 2.
8
+ The identity-macro reduction below is our application choice, not a new claim
9
+ about the original paper. Candidate-pool retrieval CE remains a separate loss.
10
+ """
11
+ from dataclasses import dataclass
12
+ import math
13
+ from typing import Dict, Sequence
14
+
15
+ import torch
16
+ from torch.nn import functional as F
17
+
18
+
19
+ @dataclass
20
+ class ContrastiveResult:
21
+ loss: torch.Tensor
22
+ # Scalars remain detached tensors; convert to CPU only at the log boundary.
23
+ diagnostics: Dict[str, torch.Tensor]
24
+
25
+
26
+ def identity_supcon(embeddings, identities: Sequence[str], temperature=0.1,
27
+ pair_allowed=None, identity_macro=True):
28
+ """Mean log probability of ALL other same-identity positives, excluding self.
29
+
30
+ An anchor needs both another positive and at least one negative. Without
31
+ these it contributes neither loss nor reduction weight. A batch with only
32
+ singletons or one identity returns differentiable zero, not NaN or a fake
33
+ self-positive objective. ``pair_allowed`` can remove repeated physical MS
34
+ records from both the positive and negative universes.
35
+ """
36
+ if embeddings.ndim != 2 or embeddings.shape[0] != len(identities):
37
+ raise ValueError('Expected one identity per embedding row')
38
+ if not math.isfinite(temperature) or temperature <= 0:
39
+ raise ValueError('Temperature must be finite and positive')
40
+ if not all(isinstance(k, str) and k for k in identities):
41
+ raise ValueError('Nonempty standardized identity labels required')
42
+ if embeddings.shape[1] == 0:
43
+ raise ValueError('Embedding dimension must be positive')
44
+ device = embeddings.device
45
+ n = len(identities)
46
+ classes = sorted(set(identities))
47
+ lookup = {k:i for i,k in enumerate(classes)}
48
+ label = torch.tensor([lookup[k] for k in identities], dtype=torch.long, device=device)
49
+ z = F.normalize(embeddings.float(), dim=-1)
50
+ sim = z @ z.T
51
+ allowed = ~torch.eye(n, dtype=torch.bool, device=device)
52
+ if pair_allowed is not None:
53
+ if pair_allowed.shape != (n,n) or pair_allowed.dtype != torch.bool:
54
+ raise ValueError('pair_allowed must be a square bool mask')
55
+ allowed = allowed & pair_allowed.to(device)
56
+ same = label[:,None] == label[None,:]
57
+ positives = allowed & same
58
+ negatives = allowed & ~same
59
+ pcount = positives.sum(1)
60
+ ncount = negatives.sum(1)
61
+ valid = (pcount > 0) & (ncount > 0)
62
+ logits = sim / temperature
63
+ # Avoid (-inf) - (-inf) for rows with no other allowed records.
64
+ denominator_logits = logits.masked_fill(~allowed, -torch.inf)
65
+ empty = ~allowed.any(1)
66
+ denominator_logits = torch.where(empty[:,None], torch.zeros_like(logits), denominator_logits)
67
+ logden = torch.logsumexp(denominator_logits, dim=1)
68
+ positive_logprob = torch.where(positives, logits - logden[:,None], torch.zeros_like(logits))
69
+ per_anchor = -positive_logprob.sum(1) / pcount.clamp_min(1)
70
+ values = torch.where(valid, per_anchor, torch.zeros_like(per_anchor))
71
+ if identity_macro:
72
+ sums = z.new_zeros(len(classes)).index_add(0, label, values)
73
+ counts = z.new_zeros(len(classes)).index_add(0, label, valid.to(z.dtype))
74
+ active_groups = counts > 0
75
+ loss = (sums / counts.clamp_min(1)).sum() / active_groups.sum().clamp_min(1)
76
+ else:
77
+ active_groups = z.new_zeros(len(classes)).index_add(0,label,valid.to(z.dtype)) > 0
78
+ loss = values.sum() / valid.sum().clamp_min(1)
79
+ # Keep a differentiable zero even for a truly empty batch.
80
+ loss = loss + embeddings.sum() * 0.
81
+ positive_total = positives.sum()
82
+ negative_total = negatives.sum()
83
+ diagnostics = dict(
84
+ anchors=label.new_tensor(n), identities=label.new_tensor(len(classes)),
85
+ valid_anchors=valid.sum().detach(), valid_identities=active_groups.sum().detach(),
86
+ positive_pairs=positive_total.detach(), negative_pairs=negative_total.detach(),
87
+ mean_positive_cosine=(torch.where(positives,sim,torch.zeros_like(sim)).sum()/positive_total.clamp_min(1)).detach(),
88
+ mean_negative_cosine=(torch.where(negatives,sim,torch.zeros_like(sim)).sum()/negative_total.clamp_min(1)).detach(),
89
+ )
90
+ return ContrastiveResult(loss, diagnostics)
91
+
92
+
93
+ def ms_ms_supcon(embeddings, identities, record_ids, temperature=0.1):
94
+ """Real multi-MS positives. Repeating one physical record is NOT a new view.
95
+
96
+ This first adapter deliberately has no synthetic peak augmentation fallback.
97
+ Singleton identities contribute only to other anchors' negative denominators,
98
+ and retain their existing cross-modal/pool/formula supervision elsewhere.
99
+ """
100
+ if len(record_ids) != len(identities):
101
+ raise ValueError('One physical spectrum ID is required per MS row')
102
+ seen = {};keep=[]
103
+ for rid,key in zip(record_ids,identities):
104
+ if rid in seen and seen[rid] != key:
105
+ raise ValueError('Same physical spectrum has conflicting structure labels')
106
+ keep.append(rid not in seen)
107
+ seen[rid] = key
108
+ allowed = torch.tensor([[a != b for b in record_ids] for a in record_ids],
109
+ device=embeddings.device, dtype=torch.bool).reshape(len(record_ids),len(record_ids))
110
+ unique=torch.tensor(keep,device=embeddings.device,dtype=torch.bool)
111
+ allowed=allowed & unique[:,None] & unique[None,:]
112
+ result=identity_supcon(embeddings, identities, temperature, allowed, identity_macro=True)
113
+ result.diagnostics['duplicate_physical_records_excluded']=unique.new_tensor(len(keep),dtype=torch.long)-unique.sum()
114
+ return result
115
+
116
+
117
+ def molecule_molecule_two_view(view1, view2, identities, temperature=0.1):
118
+ """Two trainable, independently stochastic views of each unique molecule.
119
+
120
+ Reusing one cached representation as both sides is rejected when storage is
121
+ shared. A clone can still be identical; callers must really construct encoder
122
+ views and audit their similarity/variation. A mere randomized SMILES string
123
+ is not a new view for this canonicalized permutation-invariant graph encoder.
124
+ """
125
+ if view1.shape != view2.shape or view1.ndim != 2 or len(identities) != view1.shape[0]:
126
+ raise ValueError('View dimensions and identities must match')
127
+ if len(set(identities)) != len(identities):
128
+ raise ValueError('Use one graph identity per view; aliases must not become negatives')
129
+ if view1 is view2 or (view1.numel() and view1.data_ptr() == view2.data_ptr()):
130
+ raise ValueError('Two independently encoded views required, not one cached tensor twice')
131
+ return identity_supcon(torch.cat((view1,view2),dim=0),list(identities)*2,
132
+ temperature,identity_macro=True)
code/snapshot/workspace/rebuild/intra_modal_extension/test_losses.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+ import torch
3
+ from torch.nn import functional as F
4
+ from losses import identity_supcon, ms_ms_supcon, molecule_molecule_two_view
5
+
6
+
7
+ class IntraModalTests(unittest.TestCase):
8
+ def setUp(self):
9
+ torch.manual_seed(17)
10
+ torch.set_num_threads(1)
11
+
12
+ def test_manual_multiple_positive_formula(self):
13
+ x=torch.randn(5,7,requires_grad=True);ids=['A','A','A','B','B']
14
+ z=F.normalize(x,dim=-1);s=z@z.T/.1;per=[]
15
+ for i in range(5):
16
+ pos=[j for j in range(5) if j!=i and ids[j]==ids[i]]
17
+ denominator=torch.logsumexp(torch.stack([s[i,j] for j in range(5) if j!=i]),0)
18
+ per.append(torch.stack([denominator-s[i,j] for j in pos]).mean())
19
+ expected=(torch.stack(per[:3]).mean()+torch.stack(per[3:]).mean())/2
20
+ actual=identity_supcon(x,ids)
21
+ torch.testing.assert_close(actual.loss,expected)
22
+ actual.loss.backward();self.assertTrue(torch.isfinite(x.grad).all())
23
+
24
+ def test_different_smiles_same_identity_are_positives(self):
25
+ out=identity_supcon(torch.randn(4,8),['same_key','same_key','other_key','other_key'])
26
+ self.assertEqual(int(out.diagnostics['positive_pairs']),4)
27
+ self.assertEqual(int(out.diagnostics['negative_pairs']),8)
28
+
29
+ def test_no_diagonal_positive(self):
30
+ out=identity_supcon(torch.randn(4,8),['A','A','B','B'])
31
+ self.assertEqual(int(out.diagnostics['positive_pairs']),4) # not 8
32
+
33
+ def test_singletons_zero_loss_finite_gradient(self):
34
+ x=torch.randn(3,8,requires_grad=True);out=identity_supcon(x,['A','B','C'])
35
+ self.assertEqual(float(out.loss),0.);self.assertEqual(int(out.diagnostics['valid_anchors']),0)
36
+ out.loss.backward();self.assertTrue(torch.equal(x.grad,torch.zeros_like(x)))
37
+
38
+ def test_one_identity_without_negatives_is_masked(self):
39
+ x=torch.randn(4,8,requires_grad=True);out=identity_supcon(x,['A']*4)
40
+ self.assertEqual(float(out.loss),0.);out.loss.backward()
41
+ self.assertTrue(torch.isfinite(x.grad).all())
42
+
43
+ def test_one_row(self):
44
+ x=torch.randn(1,8,requires_grad=True);out=identity_supcon(x,['A'])
45
+ self.assertEqual(float(out.loss),0.);out.loss.backward()
46
+ self.assertTrue(torch.isfinite(x.grad).all())
47
+
48
+ def test_empty_batch(self):
49
+ x=torch.empty(0,8,requires_grad=True);out=identity_supcon(x,[])
50
+ self.assertEqual(float(out.loss),0.);out.loss.backward()
51
+
52
+ def test_permutation_invariance(self):
53
+ x=torch.randn(6,8);ids=['A','A','B','B','C','C'];order=[5,2,0,4,3,1]
54
+ a=identity_supcon(x,ids);b=identity_supcon(x[order],[ids[i] for i in order])
55
+ torch.testing.assert_close(a.loss,b.loss)
56
+
57
+ def test_duplicate_physical_ms_not_new_positive(self):
58
+ out=ms_ms_supcon(torch.randn(4,8),['A','A','B','B'],['a','a','b','c'])
59
+ self.assertEqual(int(out.diagnostics['positive_pairs']),2)
60
+ self.assertEqual(int(out.diagnostics['valid_anchors']),2)
61
+ self.assertEqual(int(out.diagnostics['negative_pairs']),4)
62
+ self.assertEqual(int(out.diagnostics['duplicate_physical_records_excluded']),1)
63
+
64
+ def test_conflicting_physical_ms_labels_rejected(self):
65
+ with self.assertRaises(ValueError):
66
+ ms_ms_supcon(torch.randn(2,8),['A','B'],['record','record'])
67
+
68
+ def test_two_molecular_views_both_receive_gradients(self):
69
+ a=torch.randn(3,8,requires_grad=True);b=torch.randn(3,8,requires_grad=True)
70
+ out=molecule_molecule_two_view(a,b,['A','B','C']);out.loss.backward()
71
+ self.assertEqual(int(out.diagnostics['positive_pairs']),6)
72
+ self.assertTrue(torch.isfinite(a.grad).all() and torch.isfinite(b.grad).all())
73
+ self.assertGreater(float(a.grad.abs().sum()),0.);self.assertGreater(float(b.grad.abs().sum()),0.)
74
+
75
+ def test_shared_molecular_tensor_is_not_independent_view(self):
76
+ a=torch.randn(3,8)
77
+ with self.assertRaises(ValueError):molecule_molecule_two_view(a,a,['A','B','C'])
78
+
79
+ def test_molecular_aliases_cannot_be_negative_classes(self):
80
+ with self.assertRaises(ValueError):
81
+ molecule_molecule_two_view(torch.randn(3,8),torch.randn(3,8),['A','A','B'])
82
+
83
+ def test_temperature_validation(self):
84
+ for t in [0.,-1.,float('nan'),float('inf')]:
85
+ with self.assertRaises(ValueError):identity_supcon(torch.randn(2,8),['A','A'],t)
86
+
87
+ def test_small_gradient_step_reduces_loss(self):
88
+ x=torch.tensor([[1.,.1],[.7,.7],[-1.,-.1],[-.7,-.7]],requires_grad=True)
89
+ ids=['A','A','B','B'];before=identity_supcon(x,ids,temperature=.3)
90
+ initial_cos=float(before.diagnostics['mean_positive_cosine']);before.loss.backward()
91
+ after=identity_supcon(x.detach()-.1*x.grad,ids,temperature=.3)
92
+ self.assertLess(float(after.loss),float(before.loss))
93
+ self.assertGreater(float(after.diagnostics['mean_positive_cosine']),initial_cos)
94
+
95
+
96
+ if __name__=='__main__':unittest.main()
code/snapshot/workspace/rebuild/post_training_evaluation_20261103/acceptance.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Real Validation-only GPU parity; Test labels never select or tune weights."""
2
+ from dataclasses import replace
3
+ import json
4
+ from eval_runtime import *
5
+ from evaluate import score_group, rank_entries, metric
6
+
7
+
8
+ def run():
9
+ import torch
10
+ from specpartition_ms.fast_formula_r2 import forward_batch
11
+ db = readonly(legacy.PREP / 'validation.sqlite')
12
+ target = db.execute('SELECT target FROM spectra ORDER BY target LIMIT 1').fetchone()[0]
13
+ data = [loads(db.execute('SELECT body FROM spectra WHERE target=? ORDER BY identifier LIMIT 1', (target,)).fetchone()[0])]
14
+ pools = {v:json.loads(body) for v,body in db.execute('SELECT view,body FROM pools WHERE target=?', (target,))}
15
+ aliases = {s:db.execute('SELECT graph_key,identity,formula,error FROM aliases WHERE smiles=?', (s,)).fetchone()
16
+ for s in set(s for p in pools.values() for s in p)}
17
+ universe = {v:tuple(sorted({aliases[s][2] for s in p} - {None})) for v,p in pools.items()}
18
+ checks = []
19
+ for name in ('R09','C08_full_separate'):
20
+ model, frozen = load_model(name)
21
+ actual, _, _ = score_group(model, db, data, pools, aliases, universe)
22
+ permuted, _, _ = score_group(model, db, data, {v:list(reversed(p)) for v,p in pools.items()}, aliases, universe)
23
+ largest = 0.
24
+ with torch.inference_mode(), amp():
25
+ tokens, qs, _ = model.spectrum.forward_batch([data[0]['query']])
26
+ # Monolithic original Validation semantics versus streamed graph scoring.
27
+ keys = sorted({a[0] for a in aliases.values() if a[0]})
28
+ molecules = [loads(db.execute('SELECT body FROM graphs WHERE graph_key=?',(k,)).fetchone()[0]) for k in keys]
29
+ _, atoms, zm = model.encode_molecules(molecules)
30
+ for view,pool in pools.items():
31
+ selected = {aliases[s][0] for s in pool}
32
+ indices = [j for j,k in enumerate(keys) if k in selected]
33
+ q = replace(data[0]['query'],formula_candidates=universe[view])
34
+ fs = forward_batch(model.formula_v07,qs,[q],tokens)[0]
35
+ _,joint,_ = model.conditioned(qs[0],q,[molecules[j].formula for j in indices],zm[indices],fs)
36
+ reference = (joint+model.local_weight*model.local_scores(tokens[0],[atoms[j] for j in indices])).float().cpu().tolist()
37
+ for j,value in zip(indices,reference):
38
+ largest=max(largest,abs(value-actual[0][view][keys[j]]))
39
+ if actual[0][view] != permuted[0][view]:
40
+ raise RuntimeError('Candidate order affects identity-aligned score')
41
+ if largest > 1e-4:
42
+ raise RuntimeError('Chunked score parity failed: '+str(largest))
43
+ checks.append(dict(model=name,strict_checkpoint_load=True,chunk_score_max_error=largest,permutation_invariant=True))
44
+ del model, atoms, zm
45
+ torch.cuda.empty_cache()
46
+ # No credit for null-score matching identities, and duplicate raw positions retained.
47
+ aliases={'a':('ga','ka'),'b':('gb','kb'),'c':(None,'kc')}
48
+ scores,order=rank_entries(['a','b','b','c'],aliases,{'ga':1.,'gb':2.})
49
+ if order != [1,2,0,3] or scores[-1] is not None:
50
+ raise RuntimeError('Raw-pool multiplicity/scoreability semantics failed')
51
+ rows=[dict(rank=1,target='a',reference_identity='a'),dict(rank=None,target='b',reference_identity='b')]
52
+ if metric(rows,'rank',(1,))['1'] != dict(hits=1,denominator=2,micro=.5,target_macro=.5,key14_macro=.5):
53
+ raise RuntimeError('Missing truth was excluded from denominator')
54
+ db.close()
55
+ save(BASE/'acceptance.json',dict(complete=True,checks=checks,missing_truth_kept=True,raw_duplicates_kept=True,
56
+ source_binding=source_binding(),validation_only_preflight=True))
57
+ print(json.dumps(dict(event='gpu_evaluation_acceptance_passed',checks=checks)),flush=True)
58
+
59
+
60
+ if __name__=='__main__':run()
code/snapshot/workspace/rebuild/post_training_evaluation_20261103/eval_runtime.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Isolated post-training evaluation. Never imports training entry points."""
2
+ import hashlib
3
+ import json
4
+ import os
5
+ from pathlib import Path
6
+ import sys
7
+
8
+ os.environ.setdefault('CUBLAS_WORKSPACE_CONFIG', ':4096:8')
9
+ os.environ.setdefault('OMP_NUM_THREADS', '1')
10
+ os.environ.setdefault('OPENBLAS_NUM_THREADS', '1')
11
+
12
+ HERE = Path(__file__).resolve().parent
13
+ ROOT = Path(os.environ.get('SPECPARTITION_ROOT', '/workspace/xj/SpecPartition-MS'))
14
+ sys.path.insert(0, str(ROOT / 'rebuild/training_r09'))
15
+ import runtime09 as legacy
16
+ from specpartition_ms.epoch_features import dumps, loads
17
+
18
+ sha, save, readonly = legacy.sha, legacy.save, legacy.readonly
19
+ BASE = ROOT / 'runs/post_training_evaluation_20261103'
20
+ PREP = ROOT / 'data/derived/post_training_evaluation_20261103'
21
+ CASMI = ROOT / 'data/benchmarks/casmi2022_sirius6312_top10_pubchem_10ppm_connectivity_v1'
22
+ OFFICIAL = ROOT / 'data/raw/massspecgym_v1_5/data/molecules'
23
+ KS = (1, 3, 5, 10, 20, 50, 100, 200)
24
+ FKS = tuple(range(1, 11)) + (20, 50, 100, 200)
25
+ ARMS = ('C03_both_fine', 'C06_fine_formula', 'C07_fine_mass', 'C08_full_separate')
26
+ RUNS = {'R09': ROOT / 'runs/rebuild_joint_r08data_20261102', **{
27
+ arm: ROOT / 'runs/hierarchical_intra_modal_20261103' / arm / 'seed_20261103' for arm in ARMS}}
28
+
29
+
30
+ def digest(obj):
31
+ return hashlib.sha256(json.dumps(obj, sort_keys=True, separators=(',', ':'), ensure_ascii=False).encode()).hexdigest()
32
+
33
+
34
+ def source_binding():
35
+ return {str(p.relative_to(HERE)): sha(p) for p in sorted(HERE.glob('*.py'))}
36
+
37
+
38
+ def supported_formula(raw):
39
+ from specpartition_ms.chemistry import canonical_formula, formula_vector
40
+ try:
41
+ value = canonical_formula(raw)
42
+ formula_vector(value)
43
+ return value
44
+ except (ValueError, TypeError):
45
+ return None
46
+
47
+
48
+ def freeze_model(name):
49
+ """Wait for COMPLETE; freeze Validation's choice before any Test inference."""
50
+ run = RUNS[name]
51
+ complete = run / 'COMPLETE.json'
52
+ if not complete.exists() or not json.loads(complete.read_text()).get('complete'):
53
+ return None
54
+ best_path = run / 'best_validation.json'
55
+ best = json.loads(best_path.read_text())
56
+ if best.get('selection') != 'harmonic_mean_mass_formula_structure_top1':
57
+ raise RuntimeError('Unapproved checkpoint selection criterion')
58
+ checkpoint = Path(best['checkpoint']).resolve()
59
+ if not checkpoint.is_relative_to(run.resolve()) or not checkpoint.is_file():
60
+ raise RuntimeError('Selected checkpoint is outside this registered training run')
61
+ path = BASE / 'models' / (name + '.json')
62
+ prior = json.loads(path.read_text()) if path.exists() else None
63
+ # The model loader checks file bytes again; do not re-read 1 GB every polling cycle.
64
+ if prior:
65
+ if prior['validation_selection'] != best or prior['checkpoint'] != str(checkpoint):
66
+ raise RuntimeError('Frozen model selection changed; create a new evaluation release')
67
+ return prior
68
+ frozen = dict(name=name, checkpoint=str(checkpoint), checkpoint_sha256=sha(checkpoint),
69
+ validation_selection=best, training_complete=json.loads(complete.read_text()),
70
+ hierarchical=name != 'R09', test_used_for_selection=False)
71
+ save(path, frozen)
72
+ return frozen
73
+
74
+
75
+ def load_model(name):
76
+ import torch
77
+ torch.set_num_threads(1)
78
+ torch.set_float32_matmul_precision('high')
79
+ torch.use_deterministic_algorithms(True)
80
+ torch.cuda.set_per_process_memory_fraction(.25)
81
+ legacy.seed_all(20261103)
82
+ frozen = json.loads((BASE / 'models' / (name + '.json')).read_text())
83
+ if sha(frozen['checkpoint']) != frozen['checkpoint_sha256']:
84
+ raise RuntimeError('Checkpoint hash changed')
85
+ model = legacy.make_model()
86
+ if frozen['hierarchical']:
87
+ sys.path.insert(0, str(ROOT / 'rebuild/hierarchical_ablation_20261103'))
88
+ from coarse_losses import ProjectionBank
89
+ model.hierarchy = ProjectionBank()
90
+ state = torch.load(frozen['checkpoint'], map_location='cpu', weights_only=False)
91
+ model.load_state_dict(state['model'], strict=True)
92
+ del state
93
+ # Identical, previously parity-tested graph pooling for every model.
94
+ sys.path.insert(0, str(ROOT / 'rebuild/hierarchical_training_20261103'))
95
+ from kernels import install_graph_kernel
96
+ install_graph_kernel(model)
97
+ return model.to(legacy.C['device']).eval(), frozen
98
+
99
+
100
+ def amp():
101
+ import torch
102
+ return torch.autocast('cuda', dtype=torch.bfloat16, enabled=legacy.C['bf16'])
code/snapshot/workspace/rebuild/post_training_evaluation_20261103/evaluate.py ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Full-pool, bounded-memory inference with identity-aligned restart files."""
2
+ from collections import defaultdict, Counter
3
+ from dataclasses import replace
4
+ import fcntl
5
+ import gzip
6
+ import json
7
+ import math
8
+ import time
9
+ from eval_runtime import *
10
+
11
+
12
+ def gzip_save(path, value):
13
+ path.parent.mkdir(parents=True, exist_ok=True)
14
+ temporary = path.with_suffix(path.suffix + '.tmp')
15
+ with gzip.open(temporary, 'wt', compresslevel=3) as f:
16
+ json.dump(value, f, ensure_ascii=False, separators=(',', ':'), allow_nan=False)
17
+ temporary.replace(path)
18
+
19
+
20
+ def metric(rows, field, ks):
21
+ result = {}
22
+ for k in ks:
23
+ targets, identities = defaultdict(list), defaultdict(list)
24
+ hits = 0
25
+ for r in rows:
26
+ hit = r[field] is not None and r[field] <= k
27
+ hits += hit; targets[r['target']].append(hit); identities[r['reference_identity']].append(hit)
28
+ result[str(k)] = dict(hits=hits, denominator=len(rows), micro=hits/len(rows),
29
+ target_macro=sum(sum(v)/len(v) for v in targets.values())/len(targets),
30
+ key14_macro=sum(sum(v)/len(v) for v in identities.values())/len(identities))
31
+ return result
32
+
33
+
34
+ def aggregate(rows):
35
+ if not rows:
36
+ return dict(spectra=0)
37
+ result = dict(spectra=len(rows), targets=len({r['target'] for r in rows}),
38
+ structure=metric(rows, 'rank', KS), canonical_smiles=metric(rows, 'canonical_rank', KS),
39
+ full_inchikey=metric(rows, 'inchikey_rank', KS), formula=metric(rows, 'formula_rank', FKS),
40
+ candidate_entries=sum(r['candidate_count'] for r in rows),
41
+ unscoreable_entries=sum(r['unscoreable'] for r in rows),
42
+ reference_in_original_pool=sum(r['reference_in_pool'] for r in rows),
43
+ reference_scoreable_in_pool=sum(r['reference_scoreable_in_pool'] for r in rows),
44
+ reference_formula_in_supported_universe=sum(r['reference_formula_in_pool'] for r in rows),
45
+ query_errors=dict(Counter(r['query_error'] for r in rows if r['query_error'])))
46
+ covered = [r for r in rows if r['reference_in_pool']]
47
+ result['conditional_structure_given_pool_coverage'] = metric(covered, 'rank', KS) if covered else {}
48
+ return result
49
+
50
+
51
+ def rank_entries(pool, aliases, values):
52
+ # Raw official aliases/multiplicity still consume rank positions. No positional model feature.
53
+ scores = [values.get(aliases[s][0]) for s in pool]
54
+ order = sorted(range(len(pool)), key=lambda i: (scores[i] is None, -scores[i] if scores[i] is not None else 0.,
55
+ aliases[pool[i]][1] or '', pool[i]))
56
+ return scores, order
57
+
58
+
59
+ def score_group(model, db, data, pools, aliases, universe, graph_batch=128, spectrum_batch=16):
60
+ import torch
61
+ from specpartition_ms.fast_formula_r2 import forward_batch
62
+ from specpartition_ms.chemistry import ADDUCTS
63
+ # No reference field is used to form any query, formula universe, graph or model score.
64
+ values = [{view: {} for view in pools} for _ in data]
65
+ formula_values = [{view: [] for view in pools} for _ in data]
66
+ allowed_by_view = {view: {aliases[s][0] for s in pool} for view, pool in pools.items()}
67
+ queries, qs, tokens, errors = [], [], [], []
68
+ valid = [i for i, r in enumerate(data) if r['query'].adduct in ADDUCTS]
69
+ encoded = {}
70
+ with torch.inference_mode(), amp():
71
+ for a in range(0, len(valid), spectrum_batch):
72
+ indices = valid[a:a+spectrum_batch]
73
+ tt, qq, _ = model.spectrum.forward_batch([data[i]['query'] for i in indices])
74
+ for j, i in enumerate(indices):
75
+ encoded[i] = (qq[j], tt[j])
76
+ for i, r in enumerate(data):
77
+ error = None if i in encoded else 'unsupported_adduct:' + r['query'].adduct
78
+ errors.append(error)
79
+ views = {view: replace(r['query'], formula_candidates=universe[view]) for view in pools}
80
+ queries.append(views)
81
+ qs.append(encoded[i][0] if i in encoded else None)
82
+ tokens.append(encoded[i][1] if i in encoded else None)
83
+ if not error:
84
+ for view, q in views.items():
85
+ scores = forward_batch(model.formula_v07, qs[i][None], [q], [tokens[i]])[0]
86
+ if not bool(torch.isfinite(scores).all()):
87
+ raise RuntimeError('Nonfinite formula scores')
88
+ formula_values[i][view] = scores
89
+ keys = sorted({v[0] for v in aliases.values() if v[0]})
90
+ # encode_molecules already streams graph forwards in blocks of 128. Retain
91
+ # only final atom embeddings, and use exactly the original per-view local
92
+ # block order: BF16 padding/group changes can otherwise perturb near ties.
93
+ mols = [loads(db.execute('SELECT body FROM graphs WHERE graph_key=?', (key,)).fetchone()[0]) for key in keys]
94
+ _, atoms, zm = model.encode_molecules(mols)
95
+ for i, r in enumerate(data):
96
+ if errors[i]:
97
+ continue
98
+ for view, pool in pools.items():
99
+ indices = [j for j, key in enumerate(keys) if key in allowed_by_view[view]]
100
+ if not indices:
101
+ continue
102
+ _, joint, _ = model.conditioned(qs[i], queries[i][view], [mols[j].formula for j in indices], zm[indices], formula_values[i][view])
103
+ local = model.local_weight * model.local_scores(tokens[i], [atoms[j] for j in indices])
104
+ scores = (joint + local).float().cpu().tolist()
105
+ if not all(math.isfinite(s) for s in scores):
106
+ raise RuntimeError('Nonfinite structure scores')
107
+ values[i][view].update(zip([keys[j] for j in indices], scores))
108
+ del mols, atoms, zm
109
+ for i in valid:
110
+ for view in pools:
111
+ formula_values[i][view] = formula_values[i][view].float().cpu().tolist()
112
+ return values, formula_values, errors
113
+
114
+
115
+ def evaluate(name, dataset, limit=None):
116
+ directory = BASE / name / dataset
117
+ directory.mkdir(parents=True, exist_ok=True)
118
+ lock = (directory / 'job.lock').open('a+')
119
+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
120
+ ready = json.loads((PREP / (dataset + '_ready.json')).read_text())
121
+ if not ready['complete']:
122
+ raise RuntimeError('Inputs not ready')
123
+ model, frozen = load_model(name)
124
+ bound = dict(model=frozen, inputs=ready['binding'], evaluation_code=source_binding(),
125
+ graph_batch=128, spectrum_batch=16, precision='bf16_main_fp32_scores', candidate_limit=None,
126
+ reference_injection=False, structure_identity='recomputed_key14', mces='disabled_by_user')
127
+ binding_id = digest(bound)
128
+ if (directory / 'binding.json').exists() and json.loads((directory / 'binding.json').read_text()) != bound:
129
+ raise RuntimeError('Inference binding changed')
130
+ save(directory / 'binding.json', bound)
131
+ if (directory / 'COMPLETE.json').exists():
132
+ return
133
+ db = readonly(PREP / (dataset + '.sqlite'))
134
+ targets = [r[0] for r in db.execute('SELECT DISTINCT target FROM spectra ORDER BY target')]
135
+ if limit:
136
+ targets = targets[:limit]
137
+ summary = []; started = time.monotonic()
138
+ for ti, target in enumerate(targets):
139
+ filename = hashlib.sha256(target.encode()).hexdigest() + '.json.gz'
140
+ output = directory / 'per_target' / filename
141
+ if output.exists():
142
+ with gzip.open(output, 'rt') as f:
143
+ prior = json.load(f)
144
+ if prior['binding_id'] != binding_id:
145
+ raise RuntimeError('Restart result binding mismatch')
146
+ summary.extend(prior['rows'])
147
+ continue
148
+ data = [loads(r[0]) for r in db.execute('SELECT body FROM spectra WHERE target=? ORDER BY identifier', (target,))]
149
+ p = db.execute('SELECT view,body,formulas,source FROM pools WHERE target=? ORDER BY view', (target,)).fetchall()
150
+ pools = {view: json.loads(body) for view, body, _, _ in p}
151
+ source = {view: source for view, _, _, source in p}
152
+ aliases = {s: db.execute('SELECT graph_key,identity,formula,canonical,fullkey,error FROM aliases WHERE smiles=?', (s,)).fetchone()
153
+ for s in set(s for pool in pools.values() for s in pool)}
154
+ universe = {}
155
+ for view, _, fs, _ in p:
156
+ universe[view] = tuple(sorted({supported_formula(f) for f in json.loads(fs)} - {None})) if dataset == 'casmi2022' else \
157
+ tuple(sorted({aliases[s][2] for s in pools[view]} - {None}))
158
+ for view, pool in pools.items():
159
+ if any(aliases[s][0] and aliases[s][2] not in universe[view] for s in pool):
160
+ raise RuntimeError('Scorable molecule formula absent from fixed inference universe')
161
+ values, fvalues, errors = score_group(model, db, data, pools, aliases, universe)
162
+ rows = []; predictions = []
163
+ for i, r in enumerate(data):
164
+ ref = db.execute('SELECT canonical,fullkey FROM aliases WHERE smiles=?', (r['reference_smiles'],)).fetchone()
165
+ for view, pool in pools.items():
166
+ scores, order = rank_entries(pool, aliases, values[i][view])
167
+ def match_rank(column, value):
168
+ return next((j+1 for j, index in enumerate(order) if scores[index] is not None and value is not None and aliases[pool[index]][column] == value), None)
169
+ rank = match_rank(1, r['identity'])
170
+ canonical_rank = match_rank(3, ref[0]); inchikey_rank = match_rank(4, ref[1])
171
+ truth = supported_formula(r['formula']); fs = universe[view]; fv = fvalues[i][view]
172
+ fo = sorted(range(len(fv)), key=lambda j: (-fv[j], fs[j]))
173
+ frank = next((j+1 for j, index in enumerate(fo) if fs[index] == truth), None)
174
+ covered = any(aliases[s][1] == r['identity'] for s in pool)
175
+ row = dict(identifier=r['identifier'], target=target, view=view, reference_identity=r['identity'],
176
+ reference_smiles=r['reference_smiles'], reference_formula=r['formula'],
177
+ reference_formula_supported=truth is not None, formula_rank=frank, formula_count=len(fs),
178
+ reference_formula_in_pool=truth is not None and truth in fs, rank=rank,
179
+ canonical_rank=canonical_rank, inchikey_rank=inchikey_rank, reference_in_pool=covered,
180
+ reference_scoreable_in_pool=any(aliases[s][1] == r['identity'] and scores[j] is not None for j,s in enumerate(pool)),
181
+ candidate_count=len(pool), unscoreable=sum(s is None for s in scores), query_error=errors[i],
182
+ adduct=r['query'].adduct, polarity='negative' if r['query'].adduct.endswith('-') else 'positive',
183
+ top1_smiles=pool[order[0]] if order and scores[order[0]] is not None else None,
184
+ recall_at_k={str(k): rank is not None and rank <= k for k in KS},
185
+ formula_recall_at_k={str(k): frank is not None and frank <= k for k in FKS}, extra=r['extra'])
186
+ rows.append(row)
187
+ predictions.append(dict(identifier=r['identifier'], view=view, scores_in_raw_pool_order=scores,
188
+ ranked_raw_pool_indices=order, formulas=list(fs), formula_scores=fv,
189
+ ranked_formula_indices=fo))
190
+ pool_file = PREP / (dataset + '_pools') / filename
191
+ pool_file.parent.mkdir(parents=True, exist_ok=True)
192
+ with pool_file.with_suffix('.lock').open('a+') as shared_lock:
193
+ fcntl.flock(shared_lock, fcntl.LOCK_EX)
194
+ if not pool_file.exists():
195
+ gzip_save(pool_file, dict(target=target, pools={view: [dict(smiles=s, graph_key=aliases[s][0], key14=aliases[s][1],
196
+ formula=aliases[s][2], canonical_smiles=aliases[s][3], full_inchikey=aliases[s][4], error=aliases[s][5]) for s in pool]
197
+ for view,pool in pools.items()}, source=source, candidate_order_sha256={v:digest(p) for v,p in pools.items()}))
198
+ gzip_save(output, dict(binding_id=binding_id, target=target, static_candidate_file=str(pool_file),
199
+ candidate_order_sha256={v:digest(p) for v,p in pools.items()}, rows=rows, predictions=predictions))
200
+ summary.extend(rows)
201
+ save(directory / 'status.json', dict(phase='inference', targets=ti+1, total_targets=len(targets), spectral_views=len(summary),
202
+ seconds=time.monotonic()-started, candidate_entries=sum(r['candidate_count'] for r in summary), updated_unix=time.time()))
203
+ if (ti+1) % 25 == 0 or ti == 0:
204
+ print(json.dumps(dict(model=name, dataset=dataset, targets=ti+1, total=len(targets), spectral_views=len(summary))), flush=True)
205
+ db.close()
206
+ if limit:
207
+ save(directory / 'partial_acceptance_metrics.json', {v:aggregate([r for r in summary if r['view']==v]) for v in pools})
208
+ return
209
+ views = sorted({r['view'] for r in summary})
210
+ expected = 17556 if dataset == 'msg_test' else 500
211
+ result = dict(model=name, dataset=dataset, binding_id=binding_id, views={}, checkpoint=frozen,
212
+ protocol='official_raw_entry_ranking' if dataset=='msg_test' else 'frozen_blind_top10_pubchem_10ppm_full_pool',
213
+ formula_scope='supported_distinct_official_pool_formulas' if dataset=='msg_test' else 'reranking_frozen_SIRIUS_top10_formulas_not_independent_prediction',
214
+ no_test_checkpoint_selection=True, mces='disabled_by_user', seconds=time.monotonic()-started)
215
+ for view in views:
216
+ rr = [r for r in summary if r['view']==view]
217
+ if len(rr)!=expected or len({r['identifier'] for r in rr})!=expected:
218
+ raise RuntimeError('Evaluation denominator incomplete or duplicated')
219
+ result['views'][view] = aggregate(rr)
220
+ result['views'][view]['by_adduct'] = {key:aggregate([r for r in rr if r['adduct']==key]) for key in sorted({r['adduct'] for r in rr})}
221
+ result['views'][view]['by_polarity'] = {key:aggregate([r for r in rr if r['polarity']==key]) for key in sorted({r['polarity'] for r in rr})}
222
+ if dataset=='casmi2022':
223
+ if sum(r['candidate_count'] for r in rr)!=1765420:
224
+ raise RuntimeError('CASMI candidate truncation detected')
225
+ result['views'][view]['frozen_reference_covered'] = sum(r['extra']['frozen_reference_covered'] for r in rr)
226
+ gzip_save(directory / 'per_spectrum_summary.json.gz', summary)
227
+ save(directory / 'metrics.json', result)
228
+ save(directory / 'COMPLETE.json', dict(complete=True, binding_id=binding_id, model=name, dataset=dataset,
229
+ metrics_sha256=sha(directory/'metrics.json'), updated_unix=time.time()))
230
+
231
+
232
+ if __name__ == '__main__':
233
+ import argparse
234
+ p=argparse.ArgumentParser();p.add_argument('--model',choices=list(RUNS),required=True)
235
+ p.add_argument('--dataset',choices=['msg_test','casmi2022'],required=True);p.add_argument('--limit',type=int)
236
+ args=p.parse_args();evaluate(args.model,args.dataset,args.limit)
code/snapshot/workspace/rebuild/post_training_evaluation_20261103/evaluation.supervisor.conf ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [program:specpartition-post-training-eval-20261103]
2
+ directory=/workspace/xj/SpecPartition-MS
3
+ command=/workspace/xj/SpecPartition-MS/.venv/bin/python -u /workspace/xj/SpecPartition-MS/rebuild/post_training_evaluation_20261103/managed.py
4
+ environment=OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1",CUBLAS_WORKSPACE_CONFIG=":4096:8",PYTHONHASHSEED="20261103"
5
+ autostart=true
6
+ autorestart=false
7
+ startsecs=5
8
+ startretries=0
9
+ stopasgroup=true
10
+ killasgroup=true
11
+ stopwaitsecs=30
12
+ redirect_stderr=true
13
+ stdout_logfile=/workspace/xj/SpecPartition-MS/runs/post_training_evaluation_20261103/supervisor.log
14
+ stdout_logfile_maxbytes=20MB
15
+ stdout_logfile_backups=2
code/snapshot/workspace/rebuild/post_training_evaluation_20261103/launch_record.json ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "release": "post_training_evaluation_20261103",
3
+ "server_root": "/workspace/xj/SpecPartition-MS",
4
+ "service": "specpartition-post-training-eval-20261103",
5
+ "results": "/workspace/xj/SpecPartition-MS/runs/post_training_evaluation_20261103",
6
+ "evaluation_only_assets": "/workspace/xj/SpecPartition-MS/data/derived/post_training_evaluation_20261103",
7
+ "registered_models": {
8
+ "R09": {"validation_selected_checkpoint": "epoch_04.pt", "sha256": "618aaf195cfdc3a4107e71cf2b3a56d5853b407564acf01de11c67e6af40f3d7"},
9
+ "C03_both_fine": {"validation_selected_checkpoint": "step_002000.pt", "sha256": "8a2982f3821fad501ba4f39ac8b1495affeb0c1b09051f2103317f36027d48b6"},
10
+ "C06_fine_formula": {"validation_selected_checkpoint": "step_002000.pt", "sha256": "8d5378dda69ef18b909922e2779ba63fc2a539e5741c83c2a2cb76e3747522dc"},
11
+ "C07_fine_mass": {"validation_selected_checkpoint": "step_002000.pt", "sha256": "16944fa1c2d3903dcb722eabc96da5a9f24a51bbeaee19429001a15520940c22"},
12
+ "C08_full_separate": {"validation_selected_checkpoint": "step_002000.pt", "sha256": "d29b58a9ffb45416c9b1ed8c90ad5e009d6b4bd1720e65c2819648ceacb04e2a"}
13
+ },
14
+ "selection": "harmonic_mean_mass_formula_structure_top1_on_Validation_only",
15
+ "msg_test": {"spectra": 17556, "targets": 3170, "views": ["official_mass", "official_formula"], "candidate_retrieval_or_refiltering": false},
16
+ "casmi2022": {"spectra": 500, "protocol": "frozen_SIRIUS6312_blind_top10_PubChem_10ppm_connectivity_v1", "candidates": 1765420, "original_truth_covered": 467, "candidate_limit": null, "truth_injection": false},
17
+ "structure_recall_k": [1, 3, 5, 10, 20, 50, 100, 200],
18
+ "formula_recall_k": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 50, 100, 200],
19
+ "formula_scope": "reranking_supported_distinct_formulas_in_given_candidate_universe_not_independent_open_formula_generation",
20
+ "primary_match": "InChIKey_first_block",
21
+ "secondary_matches": ["canonical_SMILES_with_stereochemistry", "full_InChIKey_recomputed_from_SMILES"],
22
+ "mces": "disabled_by_user",
23
+ "max_gpu_evaluation_jobs": 2,
24
+ "spectrum_inference_batch": 16,
25
+ "graph_chunk": 128,
26
+ "gpu_acceptance": {"strict_load": ["R09", "C08_full_separate"], "score_max_error": 0.0, "candidate_permutation_invariant": true, "missing_truth_kept_in_denominator": true},
27
+ "other_tasks": "not_modified_or_restarted",
28
+ "state_at_launch": "managed_service_RUNNING_MSG_Test_static_feature_preparation_active_no_final_metrics_yet"
29
+ }
code/snapshot/workspace/rebuild/post_training_evaluation_20261103/managed.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Registered training-completion dependencies, bounded concurrent evaluation."""
2
+ import fcntl
3
+ import json
4
+ import os
5
+ import shutil
6
+ import subprocess
7
+ import sys
8
+ import time
9
+ from eval_runtime import *
10
+
11
+
12
+ def launch(script,args,log):
13
+ log.parent.mkdir(parents=True,exist_ok=True)
14
+ handle=log.open('a',buffering=1)
15
+ child=subprocess.Popen([sys.executable,'-u',str(HERE/script)]+args,stdout=handle,stderr=subprocess.STDOUT,
16
+ env={**os.environ,'OMP_NUM_THREADS':'1','OPENBLAS_NUM_THREADS':'1','MKL_NUM_THREADS':'1',
17
+ 'CUBLAS_WORKSPACE_CONFIG':':4096:8','PYTHONHASHSEED':'20261103'})
18
+ handle.close();return child
19
+
20
+
21
+ def main():
22
+ BASE.mkdir(parents=True,exist_ok=True)
23
+ lock=(BASE/'manager.lock').open('a+');fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
24
+ save(BASE/'registry.json',dict(models={n:str(p) for n,p in RUNS.items()},datasets=['msg_test','casmi2022'],
25
+ max_gpu_jobs=2,selection='best_Validation_harmonic_Top1_after_COMPLETE',
26
+ future_behavior='registered_models_wait_for_training_COMPLETE_then_freeze_Validation_choice',
27
+ excludes_historical_lost_weights=True,candidate_limit=None,truth_injection=False,mces=False))
28
+ if shutil.disk_usage(ROOT).free<40*2**30:raise RuntimeError('Insufficient disk reserve to start full evaluation')
29
+ prep=None;prep_dataset=None;gpu={};attempts_path=BASE/'attempts.json'
30
+ attempts=json.loads(attempts_path.read_text()) if attempts_path.exists() else {}
31
+ def start_job(key,script,args):
32
+ record=attempts.setdefault(key,[])
33
+ if len(record)>=3:raise RuntimeError('Three attempts exhausted for '+key+'; inspect its log')
34
+ child=launch(script,args,BASE/'logs'/(key+'.log'))
35
+ record.append(dict(pid=child.pid,started_unix=time.time()));save(attempts_path,attempts)
36
+ return child
37
+ try:
38
+ while True:
39
+ frozen={name:freeze_model(name) for name in RUNS}
40
+ if prep is not None and prep.poll() is not None:
41
+ attempts['prepare_'+prep_dataset][-1].update(exit_code=prep.returncode,finished_unix=time.time());save(attempts_path,attempts)
42
+ prep=None;prep_dataset=None
43
+ for key,child in list(gpu.items()):
44
+ if child.poll() is not None:
45
+ attempts[key][-1].update(exit_code=child.returncode,finished_unix=time.time());save(attempts_path,attempts)
46
+ del gpu[key]
47
+ if prep is None:
48
+ for dataset in ('msg_test','casmi2022'):
49
+ if not (PREP/(dataset+'_ready.json')).exists():
50
+ prep_dataset=dataset;prep=start_job('prepare_'+dataset,'prepare.py',['--dataset',dataset]);break
51
+ accepted=BASE/'acceptance.json'
52
+ if not accepted.exists() and not gpu and frozen['R09'] and frozen['C08_full_separate']:
53
+ gpu['acceptance']=start_job('acceptance','acceptance.py',[])
54
+ if accepted.exists():
55
+ acceptance=json.loads(accepted.read_text())
56
+ if not acceptance.get('complete') or acceptance['source_binding']!=source_binding():
57
+ raise RuntimeError('Acceptance/code binding changed')
58
+ for dataset in ('msg_test','casmi2022'):
59
+ if not (PREP/(dataset+'_ready.json')).exists():continue
60
+ for name in RUNS:
61
+ key=name+'_'+dataset
62
+ if frozen[name] and key not in gpu and not (BASE/name/dataset/'COMPLETE.json').exists() and len(gpu)<2:
63
+ gpu[key]=start_job(key,'evaluate.py',['--model',name,'--dataset',dataset])
64
+ completed=[name+'_'+dataset for name in RUNS for dataset in ('msg_test','casmi2022')
65
+ if (BASE/name/dataset/'COMPLETE.json').exists()]
66
+ save(BASE/'status.json',dict(phase='evaluation',registered_models=len(RUNS),total_jobs=2*len(RUNS),
67
+ complete_jobs=completed,running_gpu_jobs={k:v.pid for k,v in gpu.items()},
68
+ preparing_dataset=prep_dataset,waiting_training=[n for n,v in frozen.items() if not v],updated_unix=time.time()))
69
+ if len(completed)==2*len(RUNS):
70
+ results={name:{dataset:json.loads((BASE/name/dataset/'metrics.json').read_text())
71
+ for dataset in ('msg_test','casmi2022')} for name in RUNS}
72
+ save(BASE/'all_results.json',results)
73
+ save(BASE/'COMPLETE.json',dict(complete=True,jobs=len(completed),updated_unix=time.time()))
74
+ return
75
+ time.sleep(15)
76
+ finally:
77
+ # Never leave orphan GPU workers when the owning managed service exits.
78
+ for child in list(gpu.values())+([prep] if prep else []):
79
+ if child.poll() is None:child.terminate()
80
+ for child in list(gpu.values())+([prep] if prep else []):
81
+ try:child.wait(timeout=15)
82
+ except subprocess.TimeoutExpired:child.kill();child.wait()
83
+
84
+
85
+ if __name__=='__main__':
86
+ try:main()
87
+ except Exception:
88
+ import traceback
89
+ save(BASE/'failure.json',dict(traceback=traceback.format_exc(),updated_unix=time.time()))
90
+ raise
code/snapshot/workspace/rebuild/post_training_evaluation_20261103/prepare.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Evaluation-only static assets; raw candidate entries are never filtered."""
2
+ from collections import Counter
3
+ from concurrent.futures import ProcessPoolExecutor
4
+ import csv
5
+ import fcntl
6
+ import gzip
7
+ import json
8
+ import multiprocessing
9
+ import shutil
10
+ import sqlite3
11
+ import time
12
+ from eval_runtime import *
13
+ from data09 import prepared_query
14
+
15
+ _old = None
16
+
17
+
18
+ def worker_init():
19
+ global _old
20
+ from rdkit import RDLogger
21
+ RDLogger.DisableLog('rdApp.*')
22
+ _old = readonly(legacy.PREP / 'validation.sqlite')
23
+
24
+
25
+ def feature(smiles):
26
+ from rdkit import Chem
27
+ from rdkit.Chem import rdMolDescriptors
28
+ from specpartition_ms.chemistry import _calculate_molecule
29
+ identity = formula = canonical = fullkey = None
30
+ try:
31
+ mol = Chem.MolFromSmiles(smiles)
32
+ if mol is None:
33
+ raise ValueError('invalid_smiles')
34
+ canonical = Chem.MolToSmiles(mol, canonical=True)
35
+ fullkey = Chem.MolToInchiKey(mol)
36
+ identity = fullkey.split('-')[0]
37
+ formula = supported_formula(rdMolDescriptors.CalcMolFormula(mol))
38
+ old = _old.execute('SELECT graph_key FROM aliases WHERE smiles=?', (smiles,)).fetchone() if _old else None
39
+ if old and old[0]:
40
+ blob = _old.execute('SELECT body FROM graphs WHERE graph_key=?', (old[0],)).fetchone()[0]
41
+ return smiles, old[0], identity, formula, canonical, fullkey, None, blob
42
+ m = _calculate_molecule(smiles)
43
+ key = hashlib.sha256(m.smiles.encode()).hexdigest()
44
+ return smiles, key, identity, m.formula, canonical, fullkey, None, dumps(m)
45
+ except Exception as exc:
46
+ return smiles, None, identity, formula, canonical, fullkey, repr(exc), None
47
+
48
+
49
+ def binding(dataset):
50
+ result = dict(dataset=dataset, chemistry_sha256=sha(legacy.V09 / 'src/specpartition_ms/chemistry.py'),
51
+ evaluation_code=source_binding(), evaluation_only=True, no_training_asset_writes=True)
52
+ if dataset == 'msg_test':
53
+ result.update(tsv_sha256=sha(ROOT / 'data/derived/massspecgym_v1_5_splits/test.tsv'),
54
+ pools={k: sha(OFFICIAL / f'MassSpecGym1.5_retrieval_candidates_{k}.json') for k in ('mass', 'formula')})
55
+ else:
56
+ result.update(freeze_manifest_sha256=sha(CASMI / 'freeze_manifest.json'),
57
+ protocol_sha256=sha(CASMI / 'protocol.json'))
58
+ return result
59
+
60
+
61
+ def disk_guard():
62
+ if shutil.disk_usage(ROOT).free < 35 * 2**30:
63
+ raise RuntimeError('Evaluation paused: less than 35 GiB disk reserve; no data deleted')
64
+
65
+
66
+ def add_spectrum(db, dataset, identifier, target, smiles, formula, identity, ms, extra=None):
67
+ # Reference information is stored separately from the model's PreparedQuery.
68
+ q = prepared_query(ms, 'evaluation_' + dataset)
69
+ p = dict(identifier=identifier, target=target, reference_smiles=smiles, identity=identity,
70
+ formula=formula, query=q, extra=extra or {})
71
+ db.execute('INSERT OR IGNORE INTO spectra VALUES (?,?,?,?,?)', (identifier, target, identity, formula, dumps(p)))
72
+
73
+
74
+ def prepare(dataset):
75
+ PREP.mkdir(parents=True, exist_ok=True)
76
+ lock = (PREP / (dataset + '.lock')).open('a+')
77
+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
78
+ bound = binding(dataset)
79
+ marker = PREP / (dataset + '_ready.json')
80
+ if marker.exists():
81
+ if json.loads(marker.read_text())['binding'] != bound:
82
+ raise RuntimeError('Prepared evaluation inputs changed')
83
+ return
84
+ disk_guard()
85
+ db = sqlite3.connect(PREP / (dataset + '.sqlite'))
86
+ db.execute('PRAGMA journal_mode=WAL')
87
+ db.executescript('''CREATE TABLE IF NOT EXISTS spectra(identifier TEXT PRIMARY KEY,target TEXT,identity TEXT,formula TEXT,body BLOB);
88
+ CREATE INDEX IF NOT EXISTS spectrum_target ON spectra(target);
89
+ CREATE TABLE IF NOT EXISTS pools(target TEXT,view TEXT,body TEXT,formulas TEXT,source TEXT,PRIMARY KEY(target,view));
90
+ CREATE TABLE IF NOT EXISTS aliases(smiles TEXT PRIMARY KEY,graph_key TEXT,identity TEXT,formula TEXT,canonical TEXT,fullkey TEXT,error TEXT);
91
+ CREATE TABLE IF NOT EXISTS graphs(graph_key TEXT PRIMARY KEY,body BLOB);''')
92
+ targets = set()
93
+ if dataset == 'msg_test':
94
+ import ijson
95
+ with (ROOT / 'data/derived/massspecgym_v1_5_splits/test.tsv').open() as f:
96
+ for row in csv.DictReader(f, delimiter='\t'):
97
+ target = row['smiles']; targets.add(target)
98
+ ms = dict(peaks=list(zip(map(float, row['mzs'].split(',')), map(float, row['intensities'].split(',')))),
99
+ precursor_mz=float(row['precursor_mz']), adduct=row['adduct'],
100
+ collision_energy=row.get('collision_energy'), instrument=row.get('instrument_type'))
101
+ add_spectrum(db, dataset, row['identifier'], target, target, row['formula'], row['inchikey'][:14], ms)
102
+ for view in ('mass', 'formula'):
103
+ with (OFFICIAL / f'MassSpecGym1.5_retrieval_candidates_{view}.json').open('rb') as f:
104
+ for target, pool in ijson.kvitems(f, ''):
105
+ if target in targets:
106
+ db.execute('INSERT OR IGNORE INTO pools VALUES (?,?,?,?,?)',
107
+ (target, view, json.dumps(pool, separators=(',', ':')), '[]', 'official_' + view))
108
+ else:
109
+ manifest = json.loads((CASMI / 'freeze_manifest.json').read_text())
110
+ total = covered = 0
111
+ for item in manifest['samples']:
112
+ path = CASMI / item['file']
113
+ if sha(path) != item['sha256']:
114
+ raise RuntimeError('Frozen CASMI sample hash mismatch')
115
+ with gzip.open(path, 'rt') as f:
116
+ obj = json.load(f)
117
+ sample = obj['sample']; ref = sample['reference']; target = f"casmi_{sample['casmi_id']:03d}"
118
+ targets.add(target)
119
+ ms = dict(sample['ms']); ms['adduct'] = ms['adduct_normalized']
120
+ add_spectrum(db, dataset, target, target, ref['smiles'], ref['formula'], ref['connectivity_key'], ms,
121
+ dict(casmi_id=sample['casmi_id'], reference_full_inchikey_reported=ref['full_inchikey'],
122
+ frozen_file=item['file'], frozen_file_sha256=item['sha256'],
123
+ frozen_reference_covered=item['reference_connectivity_in_pool']))
124
+ pool = [c['smiles'] for c in obj['pre_csi_candidates']]
125
+ formulas = [f['formula'] for f in obj['formula_candidates']]
126
+ if len(pool) != item['candidate_count']:
127
+ raise RuntimeError('Frozen candidate count mismatch')
128
+ total += len(pool); covered += item['reference_connectivity_in_pool']
129
+ db.execute('INSERT OR IGNORE INTO pools VALUES (?,?,?,?,?)',
130
+ (target, 'top10_blind', json.dumps(pool, separators=(',', ':')),
131
+ json.dumps(formulas), item['file']))
132
+ if (len(targets), total, covered) != (500, 1765420, 467):
133
+ raise RuntimeError('CASMI release totals changed')
134
+ db.commit()
135
+ # A disk-backed unique alias set avoids expanding millions of repeated candidates in RAM.
136
+ for body, in db.execute('SELECT body FROM pools').fetchall():
137
+ db.executemany('INSERT OR IGNORE INTO aliases(smiles) VALUES (?)', ((s,) for s in json.loads(body)))
138
+ for blob, in db.execute('SELECT body FROM spectra').fetchall():
139
+ db.execute('INSERT OR IGNORE INTO aliases(smiles) VALUES (?)', (loads(blob)['reference_smiles'],))
140
+ db.commit()
141
+ todo = [r[0] for r in db.execute('SELECT smiles FROM aliases WHERE graph_key IS NULL AND error IS NULL ORDER BY smiles')]
142
+ started = time.monotonic(); total_alias = db.execute('SELECT COUNT(*) FROM aliases').fetchone()[0]
143
+ save(PREP / (dataset + '_status.json'), dict(phase='features', complete=False, total=total_alias, remaining=len(todo), updated_unix=time.time()))
144
+ with ProcessPoolExecutor(max_workers=6, initializer=worker_init, mp_context=multiprocessing.get_context('spawn')) as workers:
145
+ for i, (s, key, identity, formula, canonical, fullkey, error, blob) in enumerate(workers.map(feature, todo, chunksize=64)):
146
+ db.execute('UPDATE aliases SET graph_key=?,identity=?,formula=?,canonical=?,fullkey=?,error=? WHERE smiles=?',
147
+ (key, identity, formula, canonical, fullkey, error, s))
148
+ if blob is not None:
149
+ db.execute('INSERT OR IGNORE INTO graphs VALUES (?,?)', (key, blob))
150
+ if (i + 1) % 2000 == 0:
151
+ db.commit(); disk_guard()
152
+ save(PREP / (dataset + '_status.json'), dict(phase='features', complete=False, processed=i+1,
153
+ already=total_alias-len(todo), total=total_alias, seconds=time.monotonic()-started, updated_unix=time.time()))
154
+ db.commit()
155
+ counts = {t: db.execute('SELECT COUNT(*) FROM ' + t).fetchone()[0] for t in ('spectra', 'pools', 'aliases', 'graphs')}
156
+ expected = (17556, 6340) if dataset == 'msg_test' else (500, 500)
157
+ if (counts['spectra'], counts['pools']) != expected:
158
+ raise RuntimeError('Wrong evaluation denominator')
159
+ pending = db.execute('SELECT COUNT(*) FROM aliases WHERE graph_key IS NULL AND error IS NULL').fetchone()[0]
160
+ if pending:
161
+ raise RuntimeError('Unfinished evaluation structures')
162
+ errors = dict(db.execute('SELECT error,COUNT(*) FROM aliases WHERE error IS NOT NULL GROUP BY error'))
163
+ db.execute('PRAGMA wal_checkpoint(TRUNCATE)'); db.close()
164
+ save(marker, dict(complete=True, binding=bound, counts=counts, errors=errors,
165
+ candidate_limit=None, truth_injection=False, seconds=time.monotonic()-started, updated_unix=time.time()))
166
+ print(json.dumps(dict(event='evaluation_inputs_ready', dataset=dataset, counts=counts)), flush=True)
167
+
168
+
169
+ if __name__ == '__main__':
170
+ import argparse
171
+ parser = argparse.ArgumentParser(); parser.add_argument('--dataset', choices=['msg_test', 'casmi2022'], required=True)
172
+ prepare(parser.parse_args().dataset)
code/snapshot/workspace/rebuild/training_r04/assets.supervisor.conf ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [program:specpartition-assets-r04]
2
+ directory=/workspace/xj/SpecPartition-MS/rebuild/training_r04
3
+ command=/usr/bin/nice -n 15 /workspace/xj/SpecPartition-MS/.venv-data-r02/bin/python -u structure_assets.py
4
+ autostart=false
5
+ autorestart=false
6
+ startsecs=5
7
+ stopasgroup=true
8
+ killasgroup=true
9
+ stdout_logfile=/workspace/xj/SpecPartition-MS/logs/structure_assets_r04.log
10
+ stderr_logfile=/workspace/xj/SpecPartition-MS/logs/structure_assets_r04.err.log
11
+ stdout_logfile_maxbytes=20MB
12
+ stderr_logfile_maxbytes=20MB
13
+ environment=OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1"
code/snapshot/workspace/rebuild/training_r04/batch_pilot.supervisor.conf ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [program:specpartition-sirius-r04-batch-pilot]
2
+ directory=/workspace/xj/SpecPartition-MS/rebuild/training_r04
3
+ command=/usr/bin/nice -n 10 /workspace/xj/SpecPartition-MS/.venv-data-r02/bin/python -u sirius_batch.py --pilot
4
+ autostart=false
5
+ autorestart=false
6
+ startsecs=5
7
+ stopasgroup=true
8
+ killasgroup=true
9
+ stdout_logfile=/workspace/xj/SpecPartition-MS/logs/sirius_r04_batch_pilot.log
10
+ stderr_logfile=/workspace/xj/SpecPartition-MS/logs/sirius_r04_batch_pilot.err.log
11
+ stdout_logfile_maxbytes=20MB
12
+ stderr_logfile_maxbytes=20MB
13
+ environment=OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1"
code/snapshot/workspace/rebuild/training_r04/candidate_pilot.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from pathlib import Path
3
+ from common import OUT, connect, save
4
+ from pubchem_stage import Client, query_pool
5
+
6
+
7
+ def main():
8
+ base=OUT/'sirius_pilot/attempt_1'
9
+ pilot=json.loads((base/'status.json').read_text())
10
+ assert len(pilot['results'])==2 and all(x['status']=='completed' for x in pilot['results'])
11
+ db=connect(readonly=True);client=Client();results=[]
12
+ try:
13
+ for row in pilot['results']:
14
+ key=row['query_hash']
15
+ command=json.loads((base/key/'command.json').read_text())
16
+ assert command['contains_reference'] is False
17
+ q=json.loads(db.execute('SELECT body FROM queries WHERE query_hash=?',(key,)).fetchone()[0])
18
+ result=query_pool(client,q,key,row['formulas'],base)
19
+ label=json.loads((base/(row['source']+'_label_audit.json')).read_text())['reference']
20
+ # Coverage is a separate loss/audit field, NEVER added to the pool.
21
+ item={'source':row['source'],'query_hash':key,'counts':result['counts'],
22
+ 'formula_count':len(row['formulas']),'per_formula':result['per_formula'],
23
+ 'reference_formula_present':label['formula'] in row['formulas'],
24
+ 'reference_connectivity_present':label['connectivity'] in {x['connectivity'] for x in result['candidates']},
25
+ 'reference_injected':False,'candidate_pool_path':str(base/key/'candidate_pool.json.gz')}
26
+ results.append(item)
27
+ save(OUT/'candidate_pilot.json',{'pilot':True,'results':results,'negative_safety_complete':False,'training_started':False})
28
+ print(json.dumps(item),flush=True)
29
+ finally:client.close();db.close()
30
+
31
+
32
+ if __name__=='__main__':main()
code/snapshot/workspace/rebuild/training_r04/common.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Immutable source bindings and fail-closed training gates for the rebuild."""
2
+ import hashlib
3
+ import json
4
+ import math
5
+ from pathlib import Path
6
+ import shutil
7
+ import sqlite3
8
+ import time
9
+
10
+ CONFIG_PATH = Path(__file__).with_name('config.json')
11
+ C = json.loads(CONFIG_PATH.read_text())
12
+ ROOT = Path(C['root'])
13
+ OUT = ROOT / C['output']
14
+ LABELS = ROOT / C['label_release']
15
+ CODE = ROOT / C['source_code']
16
+
17
+
18
+ def sha(path):
19
+ h = hashlib.sha256()
20
+ with Path(path).open('rb') as f:
21
+ for b in iter(lambda: f.read(8 * 1024**2), b''): h.update(b)
22
+ return h.hexdigest()
23
+
24
+
25
+ def digest(x):
26
+ return hashlib.sha256(json.dumps(x, sort_keys=True, separators=(',', ':'), allow_nan=False).encode()).hexdigest()
27
+
28
+
29
+ ACTIVE_POLICY = {}
30
+ POLICY_MODE = 'legacy_mces'
31
+ _policy_pointer = OUT / 'active_data_policy.json'
32
+ if _policy_pointer.exists():
33
+ ACTIVE_POLICY = json.loads(_policy_pointer.read_text())
34
+ if (ACTIVE_POLICY.get('separation_method') != 'inchikey14_exact'
35
+ or ACTIVE_POLICY.get('mces_required') is not False
36
+ or ACTIVE_POLICY.get('original_config_sha256') != sha(CONFIG_PATH)):
37
+ raise RuntimeError('Invalid active data policy override')
38
+ LABELS = Path(ACTIVE_POLICY['label_release'])
39
+ if not LABELS.is_relative_to(ROOT / 'data/derived'):
40
+ raise RuntimeError('Active label release is outside this project')
41
+ _registry = json.loads((LABELS / 'heldout_registry.json').read_text())
42
+ if _registry['policy_sha256'] != ACTIVE_POLICY['policy_sha256']:
43
+ raise RuntimeError('Active key14 registry binding mismatch')
44
+ _registry_payload = dict(_registry)
45
+ _registry_payload.pop('policy_sha256')
46
+ if digest(_registry_payload) != ACTIVE_POLICY['policy_sha256']:
47
+ raise RuntimeError('Active registry content hash mismatch')
48
+ POLICY_MODE = 'inchikey14_exact'
49
+
50
+
51
+ def label_release_complete(summary):
52
+ if summary.get('stage') != 'final':
53
+ return False
54
+ if summary.get('separation_method') == 'inchikey14_exact':
55
+ return bool(summary.get('exact_connectivity_complete') is True
56
+ and summary.get('mces_required') is False
57
+ and summary.get('file', {}).get('heldout_connectivity_overlap') == 0
58
+ and summary.get('file', {}).get('validation_source_records') == 0)
59
+ # Historical releases retain their original, stricter acceptance semantics.
60
+ return summary.get('mces_complete') is True
61
+
62
+
63
+ def save(path, obj):
64
+ path = Path(path); path.parent.mkdir(parents=True, exist_ok=True)
65
+ tmp = path.with_suffix(path.suffix + '.tmp')
66
+ tmp.write_text(json.dumps(obj, ensure_ascii=False, indent=2, allow_nan=False) + '\n')
67
+ tmp.replace(path)
68
+
69
+
70
+ def status(stage, **kwargs):
71
+ r = dict(stage=stage, unix_time=time.time(), training_started=False, **kwargs)
72
+ save(OUT / 'preparation_status.json', r)
73
+ print(json.dumps(r, ensure_ascii=False), flush=True)
74
+
75
+
76
+ def disk_guard():
77
+ if shutil.disk_usage(ROOT).free < C['reserve_disk_gib'] * 1024**3:
78
+ raise RuntimeError('Disk reserve reached; do not delete source assets')
79
+
80
+
81
+ def connect(readonly=False):
82
+ OUT.mkdir(parents=True, exist_ok=True)
83
+ path = OUT / 'index.sqlite'
84
+ db = sqlite3.connect(f'file:{path}?mode=ro' if readonly else str(path), uri=readonly, timeout=60)
85
+ if readonly: db.execute('PRAGMA query_only=ON')
86
+ else:
87
+ db.execute('PRAGMA journal_mode=WAL')
88
+ db.execute('PRAGMA synchronous=NORMAL')
89
+ db.executescript('''
90
+ CREATE TABLE IF NOT EXISTS metadata(key TEXT PRIMARY KEY,value TEXT);
91
+ CREATE TABLE IF NOT EXISTS records(record_id TEXT PRIMARY KEY,source TEXT,identity TEXT,
92
+ reference_smiles TEXT,formula TEXT,query_hash TEXT,body TEXT);
93
+ CREATE INDEX IF NOT EXISTS record_identity ON records(identity);
94
+ CREATE INDEX IF NOT EXISTS record_query ON records(query_hash);
95
+ CREATE TABLE IF NOT EXISTS queries(query_hash TEXT PRIMARY KEY,body TEXT,state TEXT DEFAULT 'pending',
96
+ formulas TEXT,error TEXT);
97
+ CREATE TABLE IF NOT EXISTS official_pools(view TEXT,target TEXT,body TEXT,sha256 TEXT,
98
+ PRIMARY KEY(view,target));
99
+ CREATE TABLE IF NOT EXISTS structures(smiles TEXT PRIMARY KEY,identity TEXT,formula TEXT,
100
+ state TEXT DEFAULT 'pending',error TEXT);
101
+ CREATE TABLE IF NOT EXISTS formula_pools(formula TEXT PRIMARY KEY,state TEXT DEFAULT 'pending',
102
+ path TEXT,sha256 TEXT,error TEXT);
103
+ ''')
104
+ return db
105
+
106
+
107
+ def bind(db, key, value):
108
+ old = db.execute('SELECT value FROM metadata WHERE key=?', (key,)).fetchone()
109
+ text = json.dumps(value, sort_keys=True)
110
+ if old and old[0] != text: raise RuntimeError('Source/config changed: ' + key)
111
+ db.execute('INSERT OR IGNORE INTO metadata VALUES (?,?)', (key, text)); db.commit()
112
+
113
+
114
+ def has(db, key):
115
+ return db.execute('SELECT 1 FROM metadata WHERE key=?', (key,)).fetchone() is not None
116
+
117
+
118
+ def query_features(record):
119
+ """Allowlist only MS evidence; no label, formula, CID, original position or scores."""
120
+ m = record['ms']
121
+ peaks = sorted([[float(a), float(b)] for a,b in m['peaks']])
122
+ mz = float(m['precursor_mz'])
123
+ if not math.isfinite(mz) or mz <= 0 or not peaks:
124
+ raise ValueError('Missing experimental MS evidence')
125
+ if any(not math.isfinite(a+b) or a <= 0 or b < 0 for a,b in peaks) or max(b for a,b in peaks) <= 0:
126
+ raise ValueError('Invalid peaks')
127
+ return {'peaks':peaks, 'precursor_mz':mz, 'adduct':m['adduct'], 'polarity':m['polarity']}
128
+
129
+
130
+ def formula_ce_eligible(formulas, true_formula):
131
+ return len(set(formulas)) > 1 and true_formula in formulas
132
+
133
+
134
+ def training_gate(label_summary, negative_report, feature_report):
135
+ """Missing files, pending safety or a pilot are NEVER permission to train."""
136
+ exact = label_summary.get('separation_method') == 'inchikey14_exact'
137
+ return bool(label_release_complete(label_summary)
138
+ and negative_report.get('complete') is True
139
+ and negative_report.get('pending', -1) == 0
140
+ and negative_report.get('errors', -1) == 0
141
+ and negative_report.get('policy_sha256') == label_summary.get('policy_sha256')
142
+ and (not exact or (negative_report.get('separation_method') == 'inchikey14_exact'
143
+ and negative_report.get('mces_required') is False))
144
+ and feature_report.get('complete') is True
145
+ and feature_report.get('pilot') is False
146
+ and feature_report.get('label_sha256') == label_summary.get('file', {}).get('sha256'))