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