diff --git a/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/coarse_losses.py b/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/coarse_losses.py new file mode 100644 index 0000000000000000000000000000000000000000..33a5b4a2fd2ecde68726b62e2c8e04a961cbcd68 --- /dev/null +++ b/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/coarse_losses.py @@ -0,0 +1,110 @@ +"""Coarse relation kernels; auxiliary supervision, never ranking filters.""" +import math +import re +import torch +from torch import nn +from 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=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) diff --git a/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs.py b/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs.py new file mode 100644 index 0000000000000000000000000000000000000000..fb427d44b9e2b711efb082eb18c18818cb6b1532 --- /dev/null +++ b/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs.py @@ -0,0 +1,161 @@ +"""Compile standalone ablation configurations, never launch an experiment.""" +import argparse +from copy import deepcopy +import hashlib +import json +import math +from pathlib import Path + +HERE=Path(__file__).resolve().parent +AUX=('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 0m['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() diff --git a/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C00_sampler_control.json b/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C00_sampler_control.json new file mode 100644 index 0000000000000000000000000000000000000000..6f94e62a1916241a1912259cf710ad466613c7c3 --- /dev/null +++ b/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C00_sampler_control.json @@ -0,0 +1,266 @@ +{ + "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" + } +} diff --git a/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C01_ms_fine.json b/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C01_ms_fine.json new file mode 100644 index 0000000000000000000000000000000000000000..7e39474f79e80b843b58306538849c4c2df98455 --- /dev/null +++ b/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C01_ms_fine.json @@ -0,0 +1,268 @@ +{ + "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" + } +} diff --git a/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C02_mol_fine.json b/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C02_mol_fine.json new file mode 100644 index 0000000000000000000000000000000000000000..d38491488045b4a39f020096f8a76ad46f704f9e --- /dev/null +++ b/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C02_mol_fine.json @@ -0,0 +1,268 @@ +{ + "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" + } +} diff --git a/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C03_both_fine.json b/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C03_both_fine.json new file mode 100644 index 0000000000000000000000000000000000000000..06d79306249cdc54926bcc29ceb2acc6c8dbbe96 --- /dev/null +++ b/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C03_both_fine.json @@ -0,0 +1,269 @@ +{ + "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" + } +} diff --git a/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C04_formula_coarse.json b/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C04_formula_coarse.json new file mode 100644 index 0000000000000000000000000000000000000000..8460bf521b5094c7da77a78ce88a208234716328 --- /dev/null +++ b/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C04_formula_coarse.json @@ -0,0 +1,269 @@ +{ + "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" + } +} diff --git a/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C05_mass_coarse.json b/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C05_mass_coarse.json new file mode 100644 index 0000000000000000000000000000000000000000..e0beaf48382fa1a425550bca3bec405d7853cd94 --- /dev/null +++ b/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C05_mass_coarse.json @@ -0,0 +1,269 @@ +{ + "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" + } +} diff --git a/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C06_fine_formula.json b/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C06_fine_formula.json new file mode 100644 index 0000000000000000000000000000000000000000..3d56724cf325cf273f3303568815a9d6ce9f0b71 --- /dev/null +++ b/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C06_fine_formula.json @@ -0,0 +1,271 @@ +{ + "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" + } +} diff --git a/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C07_fine_mass.json b/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C07_fine_mass.json new file mode 100644 index 0000000000000000000000000000000000000000..1044cfacc3ef8e2ccef89cf2b2a131c164ab8dfc --- /dev/null +++ b/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C07_fine_mass.json @@ -0,0 +1,271 @@ +{ + "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" + } +} diff --git a/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C08_full_separate.json b/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C08_full_separate.json new file mode 100644 index 0000000000000000000000000000000000000000..673d2f75c9fec3ebf792fa1eb3e47d17ca24023e --- /dev/null +++ b/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C08_full_separate.json @@ -0,0 +1,273 @@ +{ + "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" + } +} diff --git a/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C09_shared_head_control.json b/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C09_shared_head_control.json new file mode 100644 index 0000000000000000000000000000000000000000..cfe7da61ec8900e2450d9e2824a1b5cab34fc081 --- /dev/null +++ b/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C09_shared_head_control.json @@ -0,0 +1,273 @@ +{ + "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" + } +} diff --git a/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C10_random_sampler_control.json b/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C10_random_sampler_control.json new file mode 100644 index 0000000000000000000000000000000000000000..ed23600d79db5ca7b35894a092cf16308121d6cf --- /dev/null +++ b/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C10_random_sampler_control.json @@ -0,0 +1,273 @@ +{ + "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" + } +} diff --git a/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C11_hard_mass_bins.json b/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C11_hard_mass_bins.json new file mode 100644 index 0000000000000000000000000000000000000000..c4c5fe879d83a5e54fad29193459f040be5df8d2 --- /dev/null +++ b/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C11_hard_mass_bins.json @@ -0,0 +1,273 @@ +{ + "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" + } +} diff --git a/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C12_no_reverse_crossmodal.json b/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C12_no_reverse_crossmodal.json new file mode 100644 index 0000000000000000000000000000000000000000..86fecf60a4ae83848bc62504530d2e14471f0da6 --- /dev/null +++ b/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C12_no_reverse_crossmodal.json @@ -0,0 +1,273 @@ +{ + "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" + } +} diff --git a/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C13_fine_budget_matched.json b/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C13_fine_budget_matched.json new file mode 100644 index 0000000000000000000000000000000000000000..77ceeafb3a92a77ac19043afae2981031f3a15f8 --- /dev/null +++ b/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C13_fine_budget_matched.json @@ -0,0 +1,269 @@ +{ + "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" + } +} diff --git a/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C14_fine_formula_budget_matched.json b/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C14_fine_formula_budget_matched.json new file mode 100644 index 0000000000000000000000000000000000000000..d9707212be3ec93076c62e24f8ac00dd987fa0eb --- /dev/null +++ b/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C14_fine_formula_budget_matched.json @@ -0,0 +1,271 @@ +{ + "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" + } +} diff --git a/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C15_fine_mass_budget_matched.json b/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C15_fine_mass_budget_matched.json new file mode 100644 index 0000000000000000000000000000000000000000..e670628016e8a0b2312274879f7a4262dc4626c5 --- /dev/null +++ b/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C15_fine_mass_budget_matched.json @@ -0,0 +1,271 @@ +{ + "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" + } +} diff --git a/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C16_include_identity_coarse.json b/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C16_include_identity_coarse.json new file mode 100644 index 0000000000000000000000000000000000000000..750f07916ef8ad5b776baecfe0bd5402e61c1f94 --- /dev/null +++ b/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C16_include_identity_coarse.json @@ -0,0 +1,273 @@ +{ + "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" + } +} diff --git a/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C17_mass_metadata_shortcut.json b/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C17_mass_metadata_shortcut.json new file mode 100644 index 0000000000000000000000000000000000000000..fce5f869cfa40432c75dca4b1928c9fe0e7119c3 --- /dev/null +++ b/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/configs/C17_mass_metadata_shortcut.json @@ -0,0 +1,273 @@ +{ + "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" + } +} diff --git a/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/suite_manifest.json b/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/suite_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..faa8ccae8248ec99315f8991dc9a24440d13fe64 --- /dev/null +++ b/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/suite_manifest.json @@ -0,0 +1,36 @@ +{ + "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" +} diff --git a/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/test_coarse.py b/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/test_coarse.py new file mode 100644 index 0000000000000000000000000000000000000000..1efe5edfa84bbbaf9e6b150a9420a2256ee8e5b9 --- /dev/null +++ b/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/test_coarse.py @@ -0,0 +1,118 @@ +import math +import unittest +import torch +from torch.nn import functional as F +from 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() diff --git a/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/test_configs.py b/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/test_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..5fa98a103360ef95d6dc7efb5d4b4faf07934ffa --- /dev/null +++ b/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/test_configs.py @@ -0,0 +1,68 @@ +from copy import deepcopy +import math +import unittest +from 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() diff --git a/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/validation_record.json b/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/validation_record.json new file mode 100644 index 0000000000000000000000000000000000000000..6bbde1b38b817851e62ee5c0d6e11b8b483218ee --- /dev/null +++ b/code/snapshot/workspace/rebuild/hierarchical_ablation_20261103/validation_record.json @@ -0,0 +1,61 @@ +{ + "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" + ] +} diff --git a/code/snapshot/workspace/rebuild/hierarchical_training_20261103/README.md b/code/snapshot/workspace/rebuild/hierarchical_training_20261103/README.md new file mode 100644 index 0000000000000000000000000000000000000000..bed67b01f45926f586bb4de7360824793f9865e7 --- /dev/null +++ b/code/snapshot/workspace/rebuild/hierarchical_training_20261103/README.md @@ -0,0 +1,60 @@ +# 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直接判断最终增益。 diff --git a/code/snapshot/workspace/rebuild/hierarchical_training_20261103/acceptance.py b/code/snapshot/workspace/rebuild/hierarchical_training_20261103/acceptance.py new file mode 100644 index 0000000000000000000000000000000000000000..27ab2398f586a34bb3e0b4d1f2e08bc3738a3bb3 --- /dev/null +++ b/code/snapshot/workspace/rebuild/hierarchical_training_20261103/acceptance.py @@ -0,0 +1,67 @@ +"""Real full-batch GPU checks. Synthetic checks alone cannot activate training.""" +import argparse +from copy import deepcopy +import json +import time +import torch +from 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) diff --git a/code/snapshot/workspace/rebuild/hierarchical_training_20261103/check_all.py b/code/snapshot/workspace/rebuild/hierarchical_training_20261103/check_all.py new file mode 100644 index 0000000000000000000000000000000000000000..0abfcf04a0fca935f72fb00fbc666f816576b7f2 --- /dev/null +++ b/code/snapshot/workspace/rebuild/hierarchical_training_20261103/check_all.py @@ -0,0 +1,25 @@ +"""Supervised preflight for the four selected arms, never a training launcher.""" +import json +from pathlib import Path +import subprocess +import sys +import time +from 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() diff --git a/code/snapshot/workspace/rebuild/hierarchical_training_20261103/hierarchy.supervisor.conf b/code/snapshot/workspace/rebuild/hierarchical_training_20261103/hierarchy.supervisor.conf new file mode 100644 index 0000000000000000000000000000000000000000..6be12c6d653e1b2579fbef5bfeefe77102fc708b --- /dev/null +++ b/code/snapshot/workspace/rebuild/hierarchical_training_20261103/hierarchy.supervisor.conf @@ -0,0 +1,68 @@ +[program:specpartition-hierarchy-preflight] +command=/workspace/xj/SpecPartition-MS/.venv/bin/python -u /workspace/xj/SpecPartition-MS/rebuild/hierarchical_training_20261103/check_all.py +directory=/workspace/xj/SpecPartition-MS +environment=PROC_NAME="specpartition-hierarchy-preflight",OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1",CUBLAS_WORKSPACE_CONFIG=":4096:8" +autostart=false +autorestart=false +startsecs=1 +stopasgroup=true +killasgroup=true +stdout_logfile=/dev/stdout +stdout_logfile_maxbytes=0 +redirect_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_fine +directory=/workspace/xj/SpecPartition-MS +environment=PROC_NAME="specpartition-hierarchy-C03",OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1",CUBLAS_WORKSPACE_CONFIG=":4096:8" +autostart=false +autorestart=false +startsecs=10 +stopasgroup=true +killasgroup=true +stopwaitsecs=90 +stdout_logfile=/dev/stdout +stdout_logfile_maxbytes=0 +redirect_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_formula +directory=/workspace/xj/SpecPartition-MS +environment=PROC_NAME="specpartition-hierarchy-C06",OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1",CUBLAS_WORKSPACE_CONFIG=":4096:8" +autostart=false +autorestart=false +startsecs=10 +stopasgroup=true +killasgroup=true +stopwaitsecs=90 +stdout_logfile=/dev/stdout +stdout_logfile_maxbytes=0 +redirect_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_mass +directory=/workspace/xj/SpecPartition-MS +environment=PROC_NAME="specpartition-hierarchy-C07",OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1",CUBLAS_WORKSPACE_CONFIG=":4096:8" +autostart=false +autorestart=false +startsecs=10 +stopasgroup=true +killasgroup=true +stopwaitsecs=90 +stdout_logfile=/dev/stdout +stdout_logfile_maxbytes=0 +redirect_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_separate +directory=/workspace/xj/SpecPartition-MS +environment=PROC_NAME="specpartition-hierarchy-C08",OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1",CUBLAS_WORKSPACE_CONFIG=":4096:8" +autostart=false +autorestart=false +startsecs=10 +stopasgroup=true +killasgroup=true +stopwaitsecs=90 +stdout_logfile=/dev/stdout +stdout_logfile_maxbytes=0 +redirect_stderr=true diff --git a/code/snapshot/workspace/rebuild/hierarchical_training_20261103/kernels.py b/code/snapshot/workspace/rebuild/hierarchical_training_20261103/kernels.py new file mode 100644 index 0000000000000000000000000000000000000000..febcdc3eba1716b4a22091309f9cb87704787fa6 --- /dev/null +++ b/code/snapshot/workspace/rebuild/hierarchical_training_20261103/kernels.py @@ -0,0 +1,61 @@ +"""Equivalent base reductions and graph pooling, isolated from the live run.""" +import types +import numpy as np +import torch +from torch.nn import functional as F +from 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) + diff --git a/code/snapshot/workspace/rebuild/hierarchical_training_20261103/launch_record.json b/code/snapshot/workspace/rebuild/hierarchical_training_20261103/launch_record.json new file mode 100644 index 0000000000000000000000000000000000000000..f13b03a4914f466a13d2c26331c99fe336bba36f --- /dev/null +++ b/code/snapshot/workspace/rebuild/hierarchical_training_20261103/launch_record.json @@ -0,0 +1,104 @@ +{ + "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" + } +} diff --git a/code/snapshot/workspace/rebuild/hierarchical_training_20261103/managed.py b/code/snapshot/workspace/rebuild/hierarchical_training_20261103/managed.py new file mode 100644 index 0000000000000000000000000000000000000000..5d810156b17f6e4debf37c9e7536a18cc3408059 --- /dev/null +++ b/code/snapshot/workspace/rebuild/hierarchical_training_20261103/managed.py @@ -0,0 +1,31 @@ +"""Supervisor foreground entry with bounded recovery, no duplicate trainer.""" +import argparse +import fcntl +import json +from pathlib import Path +import subprocess +import sys +import time +from 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) diff --git a/code/snapshot/workspace/rebuild/hierarchical_training_20261103/objectives.py b/code/snapshot/workspace/rebuild/hierarchical_training_20261103/objectives.py new file mode 100644 index 0000000000000000000000000000000000000000..f7ce70fcf617e040043ca3c0f8a500d4add6c899 --- /dev/null +++ b/code/snapshot/workspace/rebuild/hierarchical_training_20261103/objectives.py @@ -0,0 +1,140 @@ +"""Joint base ranking plus genuine encoder-gradient coarse/fine auxiliaries.""" +from collections import Counter +import time +import torch +from torch.nn import functional as F +from 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.smiles1 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 + diff --git a/code/snapshot/workspace/rebuild/hierarchical_training_20261103/runtime_hier.py b/code/snapshot/workspace/rebuild/hierarchical_training_20261103/runtime_hier.py new file mode 100644 index 0000000000000000000000000000000000000000..82ee45f3cc61924ba3878794d9c958fbd1c3ab9f --- /dev/null +++ b/code/snapshot/workspace/rebuild/hierarchical_training_20261103/runtime_hier.py @@ -0,0 +1,85 @@ +"""Isolated four-arm runtime. Never writes to the accepted R09 source or run.""" +import contextlib +import fcntl +import hashlib +import json +import os +from pathlib import Path +import sys +import time + +HERE=Path(__file__).resolve().parent +ROOT=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.contextmanager +def 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() + diff --git a/code/snapshot/workspace/rebuild/hierarchical_training_20261103/sampling.py b/code/snapshot/workspace/rebuild/hierarchical_training_20261103/sampling.py new file mode 100644 index 0000000000000000000000000000000000000000..801d744dc53880bdca353ffd0397c3ebab0e6914 --- /dev/null +++ b/code/snapshot/workspace/rebuild/hierarchical_training_20261103/sampling.py @@ -0,0 +1,84 @@ +"""Formula / identity / real-record grouping with no within-source repetition.""" +from collections import deque,defaultdict +from functools import lru_cache +import hashlib +import 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) + diff --git a/code/snapshot/workspace/rebuild/hierarchical_training_20261103/test_runtime.py b/code/snapshot/workspace/rebuild/hierarchical_training_20261103/test_runtime.py new file mode 100644 index 0000000000000000000000000000000000000000..f14aff058b0bf2560bdf7ac0ac272afcac5c25f8 --- /dev/null +++ b/code/snapshot/workspace/rebuild/hierarchical_training_20261103/test_runtime.py @@ -0,0 +1,49 @@ +import unittest +from collections import Counter +import torch +from torch.nn import functional as F +from kernels import grouped_contrastive +from 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() diff --git a/code/snapshot/workspace/rebuild/hierarchical_training_20261103/train.py b/code/snapshot/workspace/rebuild/hierarchical_training_20261103/train.py new file mode 100644 index 0000000000000000000000000000000000000000..4eed3b75a919ae107083893e34d19f15a326b168 --- /dev/null +++ b/code/snapshot/workspace/rebuild/hierarchical_training_20261103/train.py @@ -0,0 +1,123 @@ +"""Managed resumable fine-tuning; real acceptance must precede training.""" +import argparse +from collections import deque +import fcntl +import json +import math +from pathlib import Path +import random +import shutil +import time +import traceback +import numpy as np +import torch +from torch.utils.data import DataLoader +from 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=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 + diff --git a/code/snapshot/workspace/rebuild/hierarchical_training_20261103/validation.py b/code/snapshot/workspace/rebuild/hierarchical_training_20261103/validation.py new file mode 100644 index 0000000000000000000000000000000000000000..c49eed30555137ff448e7569f8e8035ca07ab81d --- /dev/null +++ b/code/snapshot/workspace/rebuild/hierarchical_training_20261103/validation.py @@ -0,0 +1,181 @@ +"""Full official Validation pools; evaluation-only graph store, never training assets.""" +from collections import defaultdict, Counter +from concurrent.futures import ProcessPoolExecutor +from dataclasses import replace +from functools import lru_cache +import csv +import gzip +import hashlib +import json +import multiprocessing +import sqlite3 +import time +from runtime09 import * +from data09 import prepared_query +from 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 metrics diff --git a/code/snapshot/workspace/rebuild/intra_modal_extension/losses.py b/code/snapshot/workspace/rebuild/intra_modal_extension/losses.py new file mode 100644 index 0000000000000000000000000000000000000000..aa885a8d183d0d9d7c1e40e5639f5a9b6b649ded --- /dev/null +++ b/code/snapshot/workspace/rebuild/intra_modal_extension/losses.py @@ -0,0 +1,132 @@ +"""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, or +read 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 claim +about the original paper. Candidate-pool retrieval CE remains a separate loss. +""" +from dataclasses import dataclass +import math +from typing import Dict, Sequence + +import torch +from torch.nn import functional as F + + +@dataclass +class 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) diff --git a/code/snapshot/workspace/rebuild/intra_modal_extension/test_losses.py b/code/snapshot/workspace/rebuild/intra_modal_extension/test_losses.py new file mode 100644 index 0000000000000000000000000000000000000000..9d5ee86035f0666474bfebc855ec74b8ddfa3331 --- /dev/null +++ b/code/snapshot/workspace/rebuild/intra_modal_extension/test_losses.py @@ -0,0 +1,96 @@ +import unittest +import torch +from torch.nn import functional as F +from 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() diff --git a/code/snapshot/workspace/rebuild/post_training_evaluation_20261103/acceptance.py b/code/snapshot/workspace/rebuild/post_training_evaluation_20261103/acceptance.py new file mode 100644 index 0000000000000000000000000000000000000000..84824b2dee6c86eabf289ed816573ce9a4f339da --- /dev/null +++ b/code/snapshot/workspace/rebuild/post_training_evaluation_20261103/acceptance.py @@ -0,0 +1,60 @@ +"""Real Validation-only GPU parity; Test labels never select or tune weights.""" +from dataclasses import replace +import json +from 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() diff --git a/code/snapshot/workspace/rebuild/post_training_evaluation_20261103/eval_runtime.py b/code/snapshot/workspace/rebuild/post_training_evaluation_20261103/eval_runtime.py new file mode 100644 index 0000000000000000000000000000000000000000..cec9d81838890ff35cc6f0cce80d3ad860013425 --- /dev/null +++ b/code/snapshot/workspace/rebuild/post_training_evaluation_20261103/eval_runtime.py @@ -0,0 +1,102 @@ +"""Isolated post-training evaluation. Never imports training entry points.""" +import hashlib +import json +import os +from pathlib import Path +import 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().parent +ROOT = Path(os.environ.get('SPECPARTITION_ROOT', '/workspace/xj/SpecPartition-MS')) +sys.path.insert(0, str(ROOT / 'rebuild/training_r09')) +import runtime09 as legacy +from specpartition_ms.epoch_features import dumps, loads + +sha, save, readonly = legacy.sha, legacy.save, legacy.readonly +BASE = 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']) diff --git a/code/snapshot/workspace/rebuild/post_training_evaluation_20261103/evaluate.py b/code/snapshot/workspace/rebuild/post_training_evaluation_20261103/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..63706ea4e2e90321a7b7c201548f93afd54a71ce --- /dev/null +++ b/code/snapshot/workspace/rebuild/post_training_evaluation_20261103/evaluate.py @@ -0,0 +1,236 @@ +"""Full-pool, bounded-memory inference with identity-aligned restart files.""" +from collections import defaultdict, Counter +from dataclasses import replace +import fcntl +import gzip +import json +import math +import time +from 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) diff --git a/code/snapshot/workspace/rebuild/post_training_evaluation_20261103/evaluation.supervisor.conf b/code/snapshot/workspace/rebuild/post_training_evaluation_20261103/evaluation.supervisor.conf new file mode 100644 index 0000000000000000000000000000000000000000..38ecef5119bbffc87ca43738e5dab510019647c0 --- /dev/null +++ b/code/snapshot/workspace/rebuild/post_training_evaluation_20261103/evaluation.supervisor.conf @@ -0,0 +1,15 @@ +[program:specpartition-post-training-eval-20261103] +directory=/workspace/xj/SpecPartition-MS +command=/workspace/xj/SpecPartition-MS/.venv/bin/python -u /workspace/xj/SpecPartition-MS/rebuild/post_training_evaluation_20261103/managed.py +environment=OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1",CUBLAS_WORKSPACE_CONFIG=":4096:8",PYTHONHASHSEED="20261103" +autostart=true +autorestart=false +startsecs=5 +startretries=0 +stopasgroup=true +killasgroup=true +stopwaitsecs=30 +redirect_stderr=true +stdout_logfile=/workspace/xj/SpecPartition-MS/runs/post_training_evaluation_20261103/supervisor.log +stdout_logfile_maxbytes=20MB +stdout_logfile_backups=2 diff --git a/code/snapshot/workspace/rebuild/post_training_evaluation_20261103/launch_record.json b/code/snapshot/workspace/rebuild/post_training_evaluation_20261103/launch_record.json new file mode 100644 index 0000000000000000000000000000000000000000..e0930e39341911a5c3eb44a1f8cbcdd2298da306 --- /dev/null +++ b/code/snapshot/workspace/rebuild/post_training_evaluation_20261103/launch_record.json @@ -0,0 +1,29 @@ +{ + "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" +} diff --git a/code/snapshot/workspace/rebuild/post_training_evaluation_20261103/managed.py b/code/snapshot/workspace/rebuild/post_training_evaluation_20261103/managed.py new file mode 100644 index 0000000000000000000000000000000000000000..b4a097ef7e81f33d793ff9fedb862ca1e734d086 --- /dev/null +++ b/code/snapshot/workspace/rebuild/post_training_evaluation_20261103/managed.py @@ -0,0 +1,90 @@ +"""Registered training-completion dependencies, bounded concurrent evaluation.""" +import fcntl +import json +import os +import shutil +import subprocess +import sys +import time +from 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())) + raise diff --git a/code/snapshot/workspace/rebuild/post_training_evaluation_20261103/prepare.py b/code/snapshot/workspace/rebuild/post_training_evaluation_20261103/prepare.py new file mode 100644 index 0000000000000000000000000000000000000000..f3c7bf8ffb4afa1a28cd280a6829af9dfa001fe0 --- /dev/null +++ b/code/snapshot/workspace/rebuild/post_training_evaluation_20261103/prepare.py @@ -0,0 +1,172 @@ +"""Evaluation-only static assets; raw candidate entries are never filtered.""" +from collections import Counter +from concurrent.futures import ProcessPoolExecutor +import csv +import fcntl +import gzip +import json +import multiprocessing +import shutil +import sqlite3 +import time +from 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) diff --git a/code/snapshot/workspace/rebuild/training_r04/assets.supervisor.conf b/code/snapshot/workspace/rebuild/training_r04/assets.supervisor.conf new file mode 100644 index 0000000000000000000000000000000000000000..1bcb63bd2cc81cbf37af23a2e760ec502314b1b1 --- /dev/null +++ b/code/snapshot/workspace/rebuild/training_r04/assets.supervisor.conf @@ -0,0 +1,13 @@ +[program:specpartition-assets-r04] +directory=/workspace/xj/SpecPartition-MS/rebuild/training_r04 +command=/usr/bin/nice -n 15 /workspace/xj/SpecPartition-MS/.venv-data-r02/bin/python -u structure_assets.py +autostart=false +autorestart=false +startsecs=5 +stopasgroup=true +killasgroup=true +stdout_logfile=/workspace/xj/SpecPartition-MS/logs/structure_assets_r04.log +stderr_logfile=/workspace/xj/SpecPartition-MS/logs/structure_assets_r04.err.log +stdout_logfile_maxbytes=20MB +stderr_logfile_maxbytes=20MB +environment=OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1" diff --git a/code/snapshot/workspace/rebuild/training_r04/batch_pilot.supervisor.conf b/code/snapshot/workspace/rebuild/training_r04/batch_pilot.supervisor.conf new file mode 100644 index 0000000000000000000000000000000000000000..9f8762e0e1881a1bbcee68409fcb7f6e5e868892 --- /dev/null +++ b/code/snapshot/workspace/rebuild/training_r04/batch_pilot.supervisor.conf @@ -0,0 +1,13 @@ +[program:specpartition-sirius-r04-batch-pilot] +directory=/workspace/xj/SpecPartition-MS/rebuild/training_r04 +command=/usr/bin/nice -n 10 /workspace/xj/SpecPartition-MS/.venv-data-r02/bin/python -u sirius_batch.py --pilot +autostart=false +autorestart=false +startsecs=5 +stopasgroup=true +killasgroup=true +stdout_logfile=/workspace/xj/SpecPartition-MS/logs/sirius_r04_batch_pilot.log +stderr_logfile=/workspace/xj/SpecPartition-MS/logs/sirius_r04_batch_pilot.err.log +stdout_logfile_maxbytes=20MB +stderr_logfile_maxbytes=20MB +environment=OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1" diff --git a/code/snapshot/workspace/rebuild/training_r04/candidate_pilot.py b/code/snapshot/workspace/rebuild/training_r04/candidate_pilot.py new file mode 100644 index 0000000000000000000000000000000000000000..043bf0c7d9130d105157ea2bb597ce4f9bd79254 --- /dev/null +++ b/code/snapshot/workspace/rebuild/training_r04/candidate_pilot.py @@ -0,0 +1,32 @@ +import json +from pathlib import Path +from common import OUT, connect, save +from 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() diff --git a/code/snapshot/workspace/rebuild/training_r04/common.py b/code/snapshot/workspace/rebuild/training_r04/common.py new file mode 100644 index 0000000000000000000000000000000000000000..814f003ed98977c31b956e5bff4f5b269dee4c8a --- /dev/null +++ b/code/snapshot/workspace/rebuild/training_r04/common.py @@ -0,0 +1,146 @@ +"""Immutable source bindings and fail-closed training gates for the rebuild.""" +import hashlib +import json +import math +from pathlib import Path +import shutil +import sqlite3 +import 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')) diff --git a/code/snapshot/workspace/rebuild/training_r04/compact_candidates.py b/code/snapshot/workspace/rebuild/training_r04/compact_candidates.py new file mode 100644 index 0000000000000000000000000000000000000000..62cbce57f9936bfe04ee43bba51d845e693dec6f --- /dev/null +++ b/code/snapshot/workspace/rebuild/training_r04/compact_candidates.py @@ -0,0 +1,123 @@ +"""Lossless shared formula structures + per-spectrum indices (not duplicated SMILES). + +The original CID response is immutable. Structural validity is cached separately +from experimental m/z filtering. All stereo/CID aliases survive the 2D projection. +""" +from collections import Counter +import gzip +import json +from pathlib import Path +from common import C, OUT, digest, sha +from pubchem_stage import ADDUCTS,structure_record,utc + +PROTOCOL='r04_validity_neutral_formula_v1' + + +def read_gz(path): + with gzip.open(path,'rt') as f:return json.load(f) + + +def write_gz(path,r): + path=Path(path);path.parent.mkdir(parents=True,exist_ok=True);tmp=path.with_suffix('.partial') + with gzip.open(tmp,'wt',compresslevel=3) as f:json.dump(r,f,separators=(',',':'),allow_nan=False) + tmp.replace(path) + + +def usable_formula(client,formula): + raw,raw_path=client.formula(formula) + dest=client.root/'usable_formula_pools'/(formula+'.json.gz') + if dest.exists(): + out=read_gz(dest) + if (out['protocol']!=PROTOCOL or out['raw_records_sha256']!=raw['records_sha256'] + or digest(out['candidates'])!=out['content_sha256']): + raise ValueError('Usable formula artifact changed') + return out,dest + counts=Counter(raw=len(raw['records']));retained={} + for row in raw['records']: + item,reason=structure_record(row,formula) + if reason:counts[reason]+=1;continue + counts['structure_valid']+=1 + key=item['connectivity'] + if key not in retained:retained[key]={**item,'aliases':[]} + retained[key]['aliases'].append(item) + candidates=[retained[k] for k in sorted(retained)] + out={'protocol':PROTOCOL,'formula':formula,'raw_path':str(raw_path),'raw_sha256':sha(raw_path), + 'raw_records_sha256':raw['records_sha256'],'counts':dict(counts),'candidates':candidates, + 'content_sha256':digest(candidates),'experimental_mass_filter_applied':False,'completed_at':utc()} + write_gz(dest,out);return out,dest + + +def make_query(client,q,key,formulas,base): + dest=Path(base)/key[:2]/(key+'.json.gz') + if dest.exists(): + r=read_gz(dest) + if r['query_hash']!=key or r['formula_candidates']!=formulas or r['evidence_sha256']!=digest(q): + raise ValueError('Query artifact binding mismatch') + if digest(r['formula_indices'])!=r['indices_sha256']:raise ValueError('Query indices changed') + return r,dest + counts=Counter();per_formula={};indices=[];identities=set() + shift,z=ADDUCTS[q['adduct']] + for formula in formulas: + pool,path=usable_formula(client,formula);fc=Counter(pool['counts']);keep=[];ppm_values=[] + for i,candidate in enumerate(pool['candidates']): + passing=[] + for j,alias in enumerate(candidate['aliases']): + mz=(alias['neutral_exact_mass']+shift)/abs(z) + ppm=(mz-q['precursor_mz'])/q['precursor_mz']*1e6 + if abs(ppm)<=C['strict_ppm']:passing.append(j);ppm_values.append(ppm) + else:fc['outside_10ppm']+=1 + if passing: + keep.append({'index':i,'alias_indices':passing});identities.add(candidate['connectivity']) + fc['after_10ppm']+=len(passing);fc['connectivity']+=1 + per_formula[formula]=dict(fc);counts.update(fc) + indices.append({'formula':formula,'path':str(path),'sha256':sha(path),'kept':keep, + 'minimum_ppm':min(ppm_values) if ppm_values else None,'maximum_ppm':max(ppm_values) if ppm_values else None}) + counts['connectivity']=len(identities) + result={'format':'shared_formula_assets_with_per_query_alias_indices_v1','query_hash':key, + 'evidence_sha256':digest(q),'formula_candidates':formulas,'counts':dict(counts), + 'per_formula':per_formula,'formula_indices':indices,'indices_sha256':digest(indices), + 'candidate_identity_sha256':digest(sorted(identities)),'reference_injected':False, + 'negative_safety_complete':False,'training_ready':False,'completed_at':utc()} + write_gz(dest,result);return result,dest + + +def identities_from_query(result): + identities=set() + for ref in result['formula_indices']: + if sha(ref['path'])!=ref['sha256']:raise ValueError('Shared asset hash changed') + pool=read_gz(ref['path']) + for c in ref['kept']:identities.add(pool['candidates'][c['index']]['connectivity']) + if digest(sorted(identities))!=result['candidate_identity_sha256']:raise ValueError('Candidate identity resolution mismatch') + return identities + + +def validate_pilot(): + from pubchem_stage import Client + from common import connect,save + db=connect(readonly=True);client=Client();reports=[] + try: + for p in json.loads((OUT/'candidate_pilot.json').read_text())['results']: + key=p['query_hash'];q=json.loads(db.execute('SELECT body FROM queries WHERE query_hash=?',(key,)).fetchone()[0]) + full=read_gz(p['candidate_pool_path']) + compact,path=make_query(client,q,key,full['formula_candidates'],OUT/'compact_pilot') + assert identities_from_query(compact)=={c['connectivity'] for c in full['candidates']} + for metric in ('raw','after_10ppm','connectivity'): + assert compact['counts'][metric]==full['counts'][metric],metric + # Alias identities also have to match, not only the deduplicated set. + expected={(c['connectivity'],a['CID'],a['canonical_smiles']) for c in full['candidates'] for a in c['aliases']} + actual=set() + for ref in compact['formula_indices']: + pool=read_gz(ref['path']) + for entry in ref['kept']: + c=pool['candidates'][entry['index']] + for j in entry['alias_indices']: + a=c['aliases'][j];actual.add((c['connectivity'],a['CID'],a['canonical_smiles'])) + assert expected==actual,'CID/stereo alias loss' + reports.append({'query_hash':key,'identical_candidates':True,'identical_CID_aliases':True, + 'counts':compact['counts'],'path':str(path)}) + save(OUT/'compact_acceptance.json',{'passed':True,'results':reports,'source_sha256':sha(Path(__file__)), + 'training_started':False,'negative_safety_complete':False}) + finally:client.close();db.close() + + +if __name__=='__main__':validate_pilot() diff --git a/code/snapshot/workspace/rebuild/training_r04/config.json b/code/snapshot/workspace/rebuild/training_r04/config.json new file mode 100644 index 0000000000000000000000000000000000000000..3ee9eb6a942571af8f2fe7c8b256dae7fb8cf500 --- /dev/null +++ b/code/snapshot/workspace/rebuild/training_r04/config.json @@ -0,0 +1,41 @@ +{ + "release_id": "r04_joint_blind_candidates_20261031", + "root": "/workspace/xj/SpecPartition-MS", + "label_release": "data/derived/data_release_r03_val_test_casmi_20261031", + "output": "data/derived/training_candidates_r04_20261031", + "source_code": "archives/source_91bf888/historical/projects/specpartition-ms-scratch-v09", + "sirius": "tools/sirius-6.3.12/sirius/bin/sirius", + "sirius_version": "6.3.12", + "sirius_archive_sha256": "ea63fe2315c77938d9782921dfefa00b1495b0481576b1e22c20c31438fe5774", + "formula_top_k": 10, + "strict_ppm": 10.0, + "pubchem_requests_per_second_global": 3.0, + "pubchem_http_inflight": 1, + "pubchem_cid_property_batch": 200, + "formula_workers": 1, + "sirius_threads": 2, + "sirius_total_timeout_seconds": 900, + "reserve_disk_gib": 40, + "negative_safety": "R03 exact connectivity plus MCES<10 exclusion, pending is never safe", + "official_views": ["mass", "formula"], + "reference_injection": false, + "sirius_result_features": false, + "training": { + "initialization": "random", + "epochs": 6, + "odata_batch": 256, + "odata_microbatch": 32, + "msg_batch": 16, + "negative_draws_per_view": 128, + "sampling": "uniform_with_replacement_baseline", + "same_connectivity_false_negatives": false, + "both_msg_views_every_batch": true, + "learning_rate": 0.0001, + "loss_weights": {"formula": 1.0, "batch_bidirectional": 1.0, "final_pool": 1.0}, + "formula_gap_weight": 0.1, + "formula_gap_topk": 3, + "data_readiness_required": true, + "real_batch_acceptance_required": true, + "runtime_network_allowed": false + } +} diff --git a/code/snapshot/workspace/rebuild/training_r04/formula_queue.supervisor.conf b/code/snapshot/workspace/rebuild/training_r04/formula_queue.supervisor.conf new file mode 100644 index 0000000000000000000000000000000000000000..e8467dfec9b41a77d4b6fb453852ae28f84005f0 --- /dev/null +++ b/code/snapshot/workspace/rebuild/training_r04/formula_queue.supervisor.conf @@ -0,0 +1,13 @@ +[program:specpartition-sirius-r04-queue] +directory=/workspace/xj/SpecPartition-MS/rebuild/training_r04 +command=/usr/bin/nice -n 10 /workspace/xj/SpecPartition-MS/.venv-data-r02/bin/python -u sirius_batch.py --batch-size 32 +autostart=false +autorestart=false +startsecs=5 +stopasgroup=true +killasgroup=true +stdout_logfile=/workspace/xj/SpecPartition-MS/logs/sirius_r04_queue.log +stderr_logfile=/workspace/xj/SpecPartition-MS/logs/sirius_r04_queue.err.log +stdout_logfile_maxbytes=20MB +stderr_logfile_maxbytes=20MB +environment=OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1" diff --git a/code/snapshot/workspace/rebuild/training_r04/formula_recovery.before_timeout_fix_20261101.py b/code/snapshot/workspace/rebuild/training_r04/formula_recovery.before_timeout_fix_20261101.py new file mode 100644 index 0000000000000000000000000000000000000000..b1a937ffcbd6974eecb4b3e9a7e6de116710e231 --- /dev/null +++ b/code/snapshot/workspace/rebuild/training_r04/formula_recovery.before_timeout_fix_20261101.py @@ -0,0 +1,68 @@ +"""Bounded single-query replay of failed blind predictions; never invent results. + +The production batch worker keeps its code/process and successful artifacts. +Failures stay failed until a verified replay returns actual formulas. Each query +has at most four scientific attempts; infrastructure failures do not use this +budget. Failed computations receive a 900-second compound budget on replay. +""" +import argparse +import json +from pathlib import Path +import time +from common import OUT, disk_guard, save, sha +from queue_common import queue_db, lock_job, label_pipeline_blocked +from sirius_batch import run_batch + +MAX_SCIENTIFIC_ATTEMPTS=4 + + +def next_failed(db): + return db.execute('''SELECT q.query_hash,q.body,COALESCE(MAX(a.attempt),0) + FROM queries q LEFT JOIN formula_attempts a ON a.query_hash=q.query_hash + WHERE q.state='formula_failed' AND EXISTS(SELECT 1 FROM records r JOIN eligibility e + ON r.identity=e.identity WHERE r.query_hash=q.query_hash AND e.status='safe') + GROUP BY q.query_hash HAVING SUM(CASE WHEN a.status IN ('failed','completed') THEN 1 ELSE 0 END)=30: + report(db,registry,started,processed);last_report=time.monotonic() + + +if __name__=='__main__':main() diff --git a/code/snapshot/workspace/rebuild/training_r04/losses_r04.py b/code/snapshot/workspace/rebuild/training_r04/losses_r04.py new file mode 100644 index 0000000000000000000000000000000000000000..4addbcc0016a690b3b6873f38376f33cfb159aed --- /dev/null +++ b/code/snapshot/workspace/rebuild/training_r04/losses_r04.py @@ -0,0 +1,54 @@ +"""Three non-duplicated main objectives; reference identities are loss-only. + +Main structure task is connectivity. Molecule->MS uses all matching spectra as +uniform positive targets and averages across structures, not spectrum counts. +""" +import torch +from torch.nn import functional as F + + +def grouped_bidirectional(logits, spectrum_identities, molecule_identities): + if logits.shape != (len(spectrum_identities), len(molecule_identities)): + raise ValueError('Identity/logit shape mismatch') + if len(set(molecule_identities)) != len(molecule_identities): + raise ValueError('Molecule columns must be unique connectivity') + if not len(molecule_identities):raise ValueError('Empty positive universe') + lookup={k:i for i,k in enumerate(molecule_identities)} + targets=torch.tensor([lookup[k] for k in spectrum_identities],device=logits.device) + # With one identity there is no contrastive negative in either direction. + if len(lookup)<2: + zero=logits.sum()*0. + return zero,zero + ms_to_molecule=F.cross_entropy(logits.float(),targets) + reverse=logits.float().T.log_softmax(-1) + values=[] + for i,k in enumerate(molecule_identities): + mask=targets==i + if not bool(mask.any()):raise ValueError('Molecular batch identity has no MS positive') + values.append(-reverse[i,mask].mean()) + return ms_to_molecule,torch.stack(values).mean() + + +def final_pool_loss(scores, identities, truth, multiplicities=None): + if len(set(identities))!=len(identities):raise ValueError('Deduplicate connectivity first') + if truth not in identities or len(identities)<2: + return scores.sum()*0.,False + p=identities.index(truth) + if multiplicities is None: multiplicities=[1]*len(identities) + n=scores.new_tensor(multiplicities) + if n.shape!=scores.shape or not bool(torch.isfinite(n).all()) or bool((n<1).any()) or bool((n!=n.round()).any()): + raise ValueError('Invalid draw multiplicities') + if multiplicities[p]!=1:raise ValueError('Positive cannot be resampled as negative') + return torch.logsumexp(scores.float()+n.float().log(),0)-scores[p].float(),True + + +def formula_terms(scores, formulas, truth, gap_weight=.1, gap_topk=3, margin=.2): + if len(set(formulas))!=len(formulas):raise ValueError('Each formula must be one class') + if truth not in formulas or len(formulas)<2: + zero=scores.sum()*0. + return zero,zero,False + p=formulas.index(truth) + ce=torch.logsumexp(scores.float(),0)-scores[p].float() + neg=torch.cat((scores[:p],scores[p+1:])).float() + gap=F.softplus(neg.topk(min(gap_topk,len(neg))).values-scores[p].float()+margin).mean() + return ce,gap*gap_weight,True diff --git a/code/snapshot/workspace/rebuild/training_r04/negative_release.py b/code/snapshot/workspace/rebuild/training_r04/negative_release.py new file mode 100644 index 0000000000000000000000000000000000000000..ade548b261784a4aaabab1723d0995d2adb50f38 --- /dev/null +++ b/code/snapshot/workspace/rebuild/training_r04/negative_release.py @@ -0,0 +1,221 @@ +"""Publish MSP / MS2-SAN negative views only after complete upstream acceptance. + +This service never starts training, changes raw pools, or injects a reference. +All CID/SMILES remain in shared immutable formula assets. Per-record views bind +the exact experimental spectrum and exclude every same-connectivity alias from +the negative set. No preparation-time sampling/candidate cap is applied. +""" +import argparse +from collections import Counter +from functools import lru_cache +import gzip +import json +from pathlib import Path +import sqlite3 +import time +import ijson +from common import C, OUT, LABELS, POLICY_MODE, connect, digest, disk_guard, save, sha, label_release_complete +from compact_candidates import read_gz, write_gz +from queue_common import lock_job, label_pipeline_blocked + +SOURCES=('MSP_libraries','MS2_SAN_JSONL') +DEST=OUT/('negative_release_key14_v1' if POLICY_MODE=='inchikey14_exact' else 'negative_release_v1') +TERMINAL_UNSAFE={'near_heldout','heldout_exact'} + + +def load(path): + return json.loads(path.read_text()) if path.exists() else {} + + +def requirements(): + label=load(LABELS/'final_summary.json') + neg=load(OUT/'negative_safety_acceptance.json') + return { + 'final_labels':label_release_complete(label), + 'all_formulas':load(OUT/'sirius_queue_status.json').get('complete') is True, + 'all_pubchem':load(OUT/'pubchem_queue_status.json').get('complete') is True, + 'all_assets_ingested':load(OUT/'structure_asset_ingestion_status.json').get('ingestion_complete') is True, + 'all_negative_safety':neg.get('complete') is True and neg.get('pending')==0 and neg.get('errors')==0 + and bool(label.get('policy_sha256')) and neg.get('policy_sha256')==label.get('policy_sha256')} + + +def readonly_assets(): + db=sqlite3.connect(f'file:{OUT}/structure_assets.sqlite?mode=ro',uri=True,timeout=60) + db.execute('PRAGMA query_only=ON');return db + + +def lookup_graph(db,smiles): + row=db.execute('''SELECT s.graph_hash,s.identity,s.state,g.safety,g.feature_sha256, + g.feature_error,g.feature IS NOT NULL FROM smiles s LEFT JOIN graphs g ON g.graph_hash=s.graph_hash + WHERE s.smiles=?''',(smiles,)).fetchone() + if row is None:return {'state':'pending'} + key,identity,state,safety,feature,error,present=row + if state=='excluded':return {'state':'excluded'} + return {'state':safety,'graph_hash':key,'identity':identity,'feature_sha256':feature, + 'feature_present':bool(present),'error':error} + + +@lru_cache(maxsize=8) +def verified_pool(path,expected): + if sha(path)!=expected:raise ValueError('Formula asset hash changed') + p=read_gz(path) + if digest(p['candidates'])!=p['content_sha256']:raise ValueError('Formula candidate content changed') + return p + + +def project_query(query,get_pool,get_graph): + if query.get('reference_injected') is not False:raise ValueError('Reference injection/binding unknown') + if digest(query['formula_indices'])!=query['indices_sha256']:raise ValueError('Query indices changed') + raw=set();retained={};counts=Counter();pending=0 + for fi,ref in enumerate(query['formula_indices']): + pool=get_pool(ref['path'],ref['sha256']) + if pool['formula']!=ref['formula']:raise ValueError('Formula index binding changed') + for entry in ref['kept']: + candidate=pool['candidates'][entry['index']];identity=candidate['connectivity'];raw.add(identity) + for j in entry['alias_indices']: + alias=candidate['aliases'][j];g=get_graph(alias['canonical_smiles']);state=g['state'] + counts[state]+=1 + if state=='safe': + if g['identity']!=identity:raise ValueError('Graph/candidate identity mismatch') + if not g.get('feature_present') or not g.get('feature_sha256') or g.get('error'): + pending+=1;continue + item=retained.setdefault(identity,{'connectivity':identity,'formula':ref['formula'],'aliases':[]}) + item['aliases'].append({'formula_index':fi,'candidate_index':entry['index'],'alias_index':j, + 'graph_hash':g['graph_hash'],'feature_sha256':g['feature_sha256']}) + elif state not in TERMINAL_UNSAFE and state!='excluded':pending+=1 + if digest(sorted(raw))!=query['candidate_identity_sha256']:raise ValueError('Raw candidate identity mismatch') + values=[retained[k] for k in sorted(retained)] + return {'query_hash':query['query_hash'],'formula_candidates':query['formula_candidates'], + 'raw_candidate_identity_sha256':query['candidate_identity_sha256'],'raw_connectivity_count':len(raw), + 'safe_candidates':values,'safe_identity_sha256':digest(sorted(retained)), + 'safe_connectivity_count':len(values),'alias_safety_counts':dict(counts),'pending_aliases':pending, + 'complete':pending==0,'reference_injected':False,'candidate_cap':None, + 'reference_not_used_for_projection':True,'training_started':False} + + +def record_view(record,projection,reference_graph): + identity=record['structure']['connectivity'];formula=record['structure']['formula'] + candidates=projection.get('safe_candidates',[]) if projection else [] + formulas=projection.get('formula_candidates',[]) if projection else [] + positive=[i for i,c in enumerate(candidates) if c['connectivity']==identity] + negatives=len(candidates)-len(positive) + reference_ok=(reference_graph.get('state')=='safe' and reference_graph.get('identity')==identity + and reference_graph.get('feature_present') and bool(reference_graph.get('feature_sha256')) + and not reference_graph.get('error')) + complete=bool(projection and projection.get('complete')) + return {'record_id':record['record_id'],'source_id':record['source_id'],'ms':record['ms'], + 'reference_smiles':record['reference_smiles'],'reference_structure':record['structure'], + 'reference_graph_hash':reference_graph.get('graph_hash'), + 'candidate_count':len(candidates),'negative_connectivity_count':negatives, + 'positive_candidate_indices':positive,'negative_selection_rule':'all candidates with connectivity != reference connectivity', + 'truth_in_safety_filtered_pool':bool(positive),'truth_formula_in_blind_top10':formula in formulas, + 'candidate_pool_complete':complete,'reference_feature_ready':bool(reference_ok), + 'loss_eligibility':{ + 'independent_ms_structure_contrast':bool(reference_ok), + 'pool_infonce':bool(reference_ok and complete and positive and negatives>0), + 'formula_ce_has_positive_and_competitors':len(set(formulas))>1 and formula in formulas}, + 'sampling_deferred_to_training':True,'same_connectivity_never_negative':True, + 'reference_injected':False,'sirius_scores_are_model_features':False} + + +def status(db): + req=requirements();sources={} + for source in SOURCES: + sources[source]={ + 'records_before_final_MCES':db.execute('SELECT COUNT(*) FROM records WHERE source=?',(source,)).fetchone()[0], + 'formula_queries':dict(db.execute('''SELECT q.state,COUNT(DISTINCT q.query_hash) FROM queries q JOIN records r + ON q.query_hash=r.query_hash WHERE r.source=? GROUP BY q.state''',(source,))), + 'candidate_queries':dict(db.execute('''SELECT c.status,COUNT(DISTINCT c.query_hash) FROM candidate_jobs c JOIN records r + ON c.query_hash=r.query_hash WHERE r.source=? GROUP BY c.status''',(source,)))} + r={'stage':'waiting_for_complete_acceptance','requirements':req,'ready_to_publish':all(req.values()), + 'complete':False,'sources':sources,'training_started':False,'updated_unix':time.time()} + save(OUT/'negative_release_status.json',r);print(json.dumps(r),flush=True);return r + + +def publish(db,assets): + if not all(requirements().values()):raise RuntimeError('Incomplete upstream; cannot publish') + final=load(LABELS/'final_summary.json');path=Path(final['file']['path']) + if sha(path)!=final['file']['sha256']:raise ValueError('Final label release changed') + binding=json.loads(assets.execute("SELECT value FROM metadata WHERE key='binding'").fetchone()[0]) + if binding['policy_sha256']!=final['policy_sha256']:raise ValueError('Safety policy drift') + manifest_path=DEST/'manifest.json' + if manifest_path.exists(): + old=load(manifest_path) + if old['label_sha256']!=final['file']['sha256']:raise ValueError('Negative release label drift') + for f in old['files']: + if sha(f['path'])!=f['sha256']:raise ValueError('Published negative release modified') + return old + DEST.mkdir(parents=True,exist_ok=True) + files={s:DEST/(s+'.jsonl.gz') for s in SOURCES} + temporary={s:p.with_suffix('.partial') for s,p in files.items()} + streams={s:gzip.open(p,'wt',compresslevel=3) for s,p in temporary.items()} + counters={s:Counter() for s in SOURCES} + try: + with path.open('rb') as f: + for r in ijson.items(f,'item',use_float=True): + info=db.execute('SELECT source,query_hash FROM records WHERE record_id=?',(r['record_id'],)).fetchone() + if info is None:raise ValueError('Final record not in indexed staging') + source,key=info + if source not in SOURCES:continue + disk_guard();state,=db.execute('SELECT state FROM queries WHERE query_hash=?',(key,)).fetchone() + projection=None;projection_path=None;raw_identities=set() + if state=='formula_complete': + job=db.execute('SELECT status,result_path FROM candidate_jobs WHERE query_hash=?',(key,)).fetchone() + if job is None or job[0]!='completed':raise ValueError('Missing final candidate query') + query=read_gz(job[1]);projection_path=DEST/'query_views'/key[:2]/(key+'.json.gz') + if projection_path.exists(): + projection=read_gz(projection_path) + if projection['original_query_sha256']!=sha(job[1]):raise ValueError('Projection source drift') + else: + projection=project_query(query,verified_pool,lambda s:lookup_graph(assets,s)) + if not projection['complete']:raise RuntimeError('Pending negative encountered after acceptance') + projection['original_query_path']=job[1];projection['original_query_sha256']=sha(job[1]) + write_gz(projection_path,projection) + for ref in query['formula_indices']: + p=verified_pool(ref['path'],ref['sha256']) + raw_identities.update(p['candidates'][x['index']]['connectivity'] for x in ref['kept']) + elif state!='method_inapplicable':raise RuntimeError('Unresolved formula job in final labels') + ref=lookup_graph(assets,r['structure']['canonical_smiles']) + row=record_view(r,projection,ref) + if not row['reference_feature_ready']:raise RuntimeError('Final reference lacks safe features') + row.update(source=source,query_hash=key,formula_status=state, + truth_in_original_pool=r['structure']['connectivity'] in raw_identities, + shared_candidate_view_path=str(projection_path) if projection_path else None, + shared_candidate_view_sha256=sha(projection_path) if projection_path else None) + if state=='method_inapplicable':row['unavailable_reason']='SIRIUS_singly_charged_only' + streams[source].write(json.dumps(row,separators=(',',':'),allow_nan=False)+'\n') + counter=counters[source];counter['records']+=1;counter[state]+=1 + counter['truth_in_original_pool']+=row['truth_in_original_pool'] + counter['truth_in_safe_pool']+=row['truth_in_safety_filtered_pool'] + counter['candidate_occurrences']+=row['candidate_count'];counter['negative_occurrences']+=row['negative_connectivity_count'] + for task,enabled in row['loss_eligibility'].items():counter[task+'_eligible']+=enabled + finally: + for f in streams.values():f.close() + for s,p in temporary.items():p.replace(files[s]) + result={'complete':True,'scope':list(SOURCES),'label_sha256':final['file']['sha256'], + 'policy_sha256':final['policy_sha256'],'source_statistics':{s:dict(v) for s,v in counters.items()}, + 'files':[{'source':s,'path':str(p),'sha256':sha(p),'bytes':p.stat().st_size} for s,p in files.items()], + 'format':'one spectrum/reference per JSONL row; full candidate SMILES resolved losslessly through shared views', + 'candidate_cap':None,'reference_injected':False,'training_started':False, + 'training_requires_separate_full_feature_and_real_batch_acceptance':True,'finished_unix':time.time()} + save(manifest_path,result);save(OUT/'negative_release_status.json',result);return result + + +def main(): + p=argparse.ArgumentParser();p.add_argument('--once',action='store_true');p.add_argument('--probe',type=int,default=0) + a=p.parse_args();lock=lock_job('negative_release');db=connect(readonly=True);assets=readonly_assets() + if a.probe: + results=[] + for key,path in db.execute("SELECT query_hash,result_path FROM candidate_jobs WHERE status='completed' LIMIT ?",(a.probe,)): + q=read_gz(path);projection=project_query(q,verified_pool,lambda s:lookup_graph(assets,s)) + results.append({k:v for k,v in projection.items() if k!='safe_candidates'}) + print(json.dumps({'probe_only':True,'training_started':False,'results':results},indent=2));return + while True: + disk_guard();r=status(db) + if r['ready_to_publish']:print(json.dumps(publish(db,assets)),flush=True);return + if a.once:return + if label_pipeline_blocked():raise RuntimeError('Label safety blocked; no negative release/training') + time.sleep(300) + + +if __name__=='__main__':main() diff --git a/code/snapshot/workspace/rebuild/training_r04/negative_release.supervisor.conf b/code/snapshot/workspace/rebuild/training_r04/negative_release.supervisor.conf new file mode 100644 index 0000000000000000000000000000000000000000..3d7c08b49c4fc8e9b7f07e6ad6ab1810548816f4 --- /dev/null +++ b/code/snapshot/workspace/rebuild/training_r04/negative_release.supervisor.conf @@ -0,0 +1,13 @@ +[program:specpartition-negative-r04-release] +directory=/workspace/xj/SpecPartition-MS/rebuild/training_r04 +command=/usr/bin/nice -n 15 /workspace/xj/SpecPartition-MS/.venv-data-r02/bin/python -u negative_release.py +autostart=false +autorestart=false +startsecs=5 +stopasgroup=true +killasgroup=true +stdout_logfile=/workspace/xj/SpecPartition-MS/logs/negative_r04_release.log +stderr_logfile=/workspace/xj/SpecPartition-MS/logs/negative_r04_release.err.log +stdout_logfile_maxbytes=20MB +stderr_logfile_maxbytes=20MB +environment=OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1" diff --git a/code/snapshot/workspace/rebuild/training_r04/negative_safety.supervisor.conf b/code/snapshot/workspace/rebuild/training_r04/negative_safety.supervisor.conf new file mode 100644 index 0000000000000000000000000000000000000000..dc823335d09bcee1f52dda545290733b764b55a4 --- /dev/null +++ b/code/snapshot/workspace/rebuild/training_r04/negative_safety.supervisor.conf @@ -0,0 +1,13 @@ +[program:specpartition-negatives-r04-safety] +directory=/workspace/xj/SpecPartition-MS/rebuild/training_r04 +command=/usr/bin/nice -n 15 /workspace/xj/SpecPartition-MS/.venv-data-r02/bin/python -u structure_safety.py +autostart=false +autorestart=false +startsecs=5 +stopasgroup=true +killasgroup=true +stdout_logfile=/workspace/xj/SpecPartition-MS/logs/negative_safety_r04.log +stderr_logfile=/workspace/xj/SpecPartition-MS/logs/negative_safety_r04.err.log +stdout_logfile_maxbytes=20MB +stderr_logfile_maxbytes=20MB +environment=OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1" diff --git a/code/snapshot/workspace/rebuild/training_r04/pilot.supervisor.conf b/code/snapshot/workspace/rebuild/training_r04/pilot.supervisor.conf new file mode 100644 index 0000000000000000000000000000000000000000..ddab4427722fa75329410f315e586485c80e6009 --- /dev/null +++ b/code/snapshot/workspace/rebuild/training_r04/pilot.supervisor.conf @@ -0,0 +1,13 @@ +[program:specpartition-sirius-r04-pilot] +directory=/workspace/xj/SpecPartition-MS/rebuild/training_r04 +command=/usr/bin/nice -n 10 /workspace/xj/SpecPartition-MS/.venv-data-r02/bin/python -u sirius_stage.py --pilot +autostart=false +autorestart=false +startsecs=5 +stopasgroup=true +killasgroup=true +stdout_logfile=/workspace/xj/SpecPartition-MS/logs/sirius_r04_pilot.log +stderr_logfile=/workspace/xj/SpecPartition-MS/logs/sirius_r04_pilot.err.log +stdout_logfile_maxbytes=20MB +stderr_logfile_maxbytes=20MB +environment=OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1" diff --git a/code/snapshot/workspace/rebuild/training_r04/prepare_index.py b/code/snapshot/workspace/rebuild/training_r04/prepare_index.py new file mode 100644 index 0000000000000000000000000000000000000000..5b043a9135e72ad75a28746a89b981b411dfdd9d --- /dev/null +++ b/code/snapshot/workspace/rebuild/training_r04/prepare_index.py @@ -0,0 +1,87 @@ +"""Stream immutable inputs into an indexed staging area. This is NOT train-ready. + +Formula jobs share identical experimental spectra/precursors/adducts only, never +group on truth SMILES. Official pools remain raw and are not mass-filtered. +""" +from collections import Counter +import fcntl +import json +from pathlib import Path +import time +import ijson +from common import C, ROOT, OUT, LABELS, bind, connect, digest, disk_guard, has, save, sha, status, query_features + + +def run(): + OUT.mkdir(parents=True, exist_ok=True) + lock = (OUT/'index.lock').open('a+') + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + db = connect(); bind(db, 'config_sha256', sha(Path(__file__).with_name('config.json'))) + summary = json.loads((LABELS/'pre_mces_summary.json').read_text()) + source = Path(summary['file']['path']) + if sha(source) != summary['file']['sha256']: raise ValueError('R03 input hash mismatch') + bind(db, 'source', {'sha256':summary['file']['sha256'],'policy_sha256':summary['policy_sha256']}) + registry = json.loads((LABELS/'heldout_registry.json').read_text()) + forbidden = set(registry['union']) + source_map = {x['id']:x for x in json.loads((ROOT/'data/derived/data_release_r01_test_casmi_20261031/source_manifest.json').read_text())['sources']} + groups = Counter(); start = time.monotonic() + if not has(db, 'records_complete'): + with source.open('rb') as f: + for n,r in enumerate(ijson.items(f, 'item', use_float=True), 1): + group = source_map[r['source_id']]['group'] + if group not in ('MSP_libraries','MS2_SAN_JSONL','MSG_Train'): raise ValueError('Unexpected training source '+group) + st=r['structure'] + if st['connectivity'] in forbidden: raise ValueError('Heldout training label') + q=query_features(r) + key=digest({'sirius_version':C['sirius_version'],'top_k':C['formula_top_k'],'evidence':q}) + db.execute('INSERT OR IGNORE INTO records VALUES (?,?,?,?,?,?,?)', + (r['record_id'],group,st['connectivity'],r['reference_smiles'],st['formula'],key,json.dumps(r,separators=(',',':')))) + db.execute('INSERT OR IGNORE INTO structures(smiles) VALUES (?)',(r['reference_smiles'],)) + if group!='MSG_Train': + state='method_inapplicable' if abs(int(r['ms'].get('charge') or (2 if q['adduct'] in ('[M+2H]2+','[M-2H]2-') else 1)))!=1 else 'pending' + db.execute('INSERT OR IGNORE INTO queries(query_hash,body,state,error) VALUES (?,?,?,?)', + (key,json.dumps(q,separators=(',',':')),state,'SIRIUS singly-charged only' if state!='pending' else None)) + groups[group]+=1 + if n%10000==0: + db.commit();disk_guard();status('index_spectra',records=n,groups=dict(groups),seconds=time.monotonic()-start) + db.commit() + assert db.execute('SELECT COUNT(*) FROM records').fetchone()[0]==summary['records'] + bind(db,'records_complete',True) + targets={x[0] for x in db.execute("SELECT DISTINCT reference_smiles FROM records WHERE source='MSG_Train'")} + official=ROOT/'data/raw/massspecgym_v1_5' + manifest=json.loads((official/'source_manifest.json').read_text()) + # Candidate hashes are independently pinned from the verified official release. + expected={'mass':'9536a330cba24c399271364889119f90124579400dba14e9f78630c75c13c73a', + 'formula':'454636d2346aebb3cd87edc2efc3fa1bf91eb8e0219edff5880f02aa537ac954'} + for view in C['official_views']: + path=official/'data/molecules'/f'MassSpecGym1.5_retrieval_candidates_{view}.json' + if sha(path)!=expected[view]:raise ValueError('Official candidate hash mismatch') + bind(db,view+'_source',{'path':str(path),'sha256':expected[view]}) + if has(db,view+'_complete'):continue + seen=set();total=0 + with path.open('rb') as f: + for target,pool in ijson.kvitems(f,''): + if target not in targets:continue + if not isinstance(pool,list):raise ValueError('Unexpected official pool schema') + db.execute('INSERT OR IGNORE INTO official_pools VALUES (?,?,?,?)', + (view,target,json.dumps(pool,separators=(',',':')),digest(pool))) + db.executemany('INSERT OR IGNORE INTO structures(smiles) VALUES (?)',((s,) for s in pool)) + seen.add(target);total+=len(pool) + if len(seen)%200==0: + db.commit();disk_guard();status('index_official_'+view,targets=len(seen),candidate_entries=total) + db.commit() + if seen!=targets:raise ValueError('Missing official target pools: '+str(len(targets-seen))) + bind(db,view+'_complete',{'targets':len(seen),'entries':total}) + result={'stage':'indexed_not_training_ready','records':dict(db.execute('SELECT source,COUNT(*) FROM records GROUP BY source')), + 'blind_queries':dict(db.execute('SELECT state,COUNT(*) FROM queries GROUP BY state')), + 'official_pools':dict(db.execute('SELECT view,COUNT(*) FROM official_pools GROUP BY view')), + 'unique_structure_strings':db.execute('SELECT COUNT(*) FROM structures').fetchone()[0], + 'label_release_final':(LABELS/'final_summary.json').exists(),'negative_safety_complete':False, + 'training_started':False,'source_policy_sha256':registry['policy_sha256']} + save(OUT/'index_summary.json',result);status('index_complete',summary=result) + db.close();lock.close() + + +if __name__=='__main__': + try:run() + except Exception as e:status('index_failed',error=repr(e));raise diff --git a/code/snapshot/workspace/rebuild/training_r04/pubchem_pilot.supervisor.conf b/code/snapshot/workspace/rebuild/training_r04/pubchem_pilot.supervisor.conf new file mode 100644 index 0000000000000000000000000000000000000000..116496b57ca8ba211adc41af55573940d5dfaf8a --- /dev/null +++ b/code/snapshot/workspace/rebuild/training_r04/pubchem_pilot.supervisor.conf @@ -0,0 +1,13 @@ +[program:specpartition-pubchem-r04-pilot] +directory=/workspace/xj/SpecPartition-MS/rebuild/training_r04 +command=/usr/bin/nice -n 10 /workspace/xj/SpecPartition-MS/.venv-data-r02/bin/python -u candidate_pilot.py +autostart=false +autorestart=false +startsecs=5 +stopasgroup=true +killasgroup=true +stdout_logfile=/workspace/xj/SpecPartition-MS/logs/pubchem_r04_pilot.log +stderr_logfile=/workspace/xj/SpecPartition-MS/logs/pubchem_r04_pilot.err.log +stdout_logfile_maxbytes=20MB +stderr_logfile_maxbytes=20MB +environment=OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1" diff --git a/code/snapshot/workspace/rebuild/training_r04/pubchem_queue.py b/code/snapshot/workspace/rebuild/training_r04/pubchem_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..28a64f32cb75a93c37fb9708c0aede3cc68511ba --- /dev/null +++ b/code/snapshot/workspace/rebuild/training_r04/pubchem_queue.py @@ -0,0 +1,52 @@ +"""One global HTTP owner. Build all eligible blind pools; never start training.""" +import json +from pathlib import Path +import time +from common import OUT,LABELS,disk_guard,sha +from queue_common import queue_db,lock_job,eligible_query,progress,label_pipeline_blocked +from pubchem_stage import Client +from compact_candidates import make_query +import compact_candidates + + +def main(): + db=queue_db();lock=lock_job('pubchem_queue');client=Client() + a=json.loads((OUT/'compact_acceptance.json').read_text()) + if not a.get('passed') or a['source_sha256']!=sha(Path(compact_candidates.__file__)): + raise RuntimeError('Compact pool acceptance missing or stale') + db.execute("UPDATE candidate_jobs SET status='pending' WHERE status='running'");db.commit() + while True: + disk_guard() + rows=db.execute("""SELECT q.query_hash,q.body,q.formulas,COALESCE(c.attempts,0) + FROM queries q LEFT JOIN candidate_jobs c ON c.query_hash=q.query_hash + WHERE q.state='formula_complete' AND (c.status IS NULL OR c.status='pending' + OR (c.status='retry' AND c.attempts<3 AND c.updated=3 else 'retry',repr(e),time.time(),key));db.commit() + progress(db,'pubchem_queue',last_query=key,error=repr(e)) + disk_guard() + + +if __name__=='__main__':main() diff --git a/code/snapshot/workspace/rebuild/training_r04/pubchem_queue.supervisor.conf b/code/snapshot/workspace/rebuild/training_r04/pubchem_queue.supervisor.conf new file mode 100644 index 0000000000000000000000000000000000000000..009d9576441bbf2743006d6ad20a910695a097fb --- /dev/null +++ b/code/snapshot/workspace/rebuild/training_r04/pubchem_queue.supervisor.conf @@ -0,0 +1,13 @@ +[program:specpartition-pubchem-r04-queue] +directory=/workspace/xj/SpecPartition-MS/rebuild/training_r04 +command=/usr/bin/nice -n 10 /workspace/xj/SpecPartition-MS/.venv-data-r02/bin/python -u pubchem_queue.py +autostart=false +autorestart=false +startsecs=5 +stopasgroup=true +killasgroup=true +stdout_logfile=/workspace/xj/SpecPartition-MS/logs/pubchem_r04_queue.log +stderr_logfile=/workspace/xj/SpecPartition-MS/logs/pubchem_r04_queue.err.log +stdout_logfile_maxbytes=20MB +stderr_logfile_maxbytes=20MB +environment=OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1" diff --git a/code/snapshot/workspace/rebuild/training_r04/pubchem_stage.py b/code/snapshot/workspace/rebuild/training_r04/pubchem_stage.py new file mode 100644 index 0000000000000000000000000000000000000000..cffee8c551c3bbfad559b1894bceb89520b9037c --- /dev/null +++ b/code/snapshot/workspace/rebuild/training_r04/pubchem_stage.py @@ -0,0 +1,173 @@ +"""Shared formula cache, immutable raw responses, strict per-spectrum filtering. + +One process owns the HTTP lock; no per-worker rate multiplication. No fixed CID +cap, no truth injection. Candidate safety remains a separate required gate. +""" +from collections import Counter +from datetime import datetime, timezone +import fcntl +import gzip +import hashlib +from http.client import IncompleteRead, RemoteDisconnected +import json +from pathlib import Path +import time +from urllib.parse import quote, urlencode +from urllib.request import Request, urlopen +from urllib.error import HTTPError, URLError +from rdkit import Chem +from rdkit.Chem import Descriptors, rdMolDescriptors +from common import C, OUT, digest, save, sha, disk_guard + +BASE='https://pubchem.ncbi.nlm.nih.gov/rest/pug/' +ELECTRON=0.000548579909065 +PT=Chem.GetPeriodicTable() +H=PT.GetMostCommonIsotopeMass('H');N=PT.GetMostCommonIsotopeMass('N') +O=PT.GetMostCommonIsotopeMass('O');CARBON=12.;CL=PT.GetMostCommonIsotopeMass('Cl') +ADDUCTS={'[M+H]+':(H-ELECTRON,1),'[M-H]-':(-H+ELECTRON,-1), + '[M+Na]+':(22.989769282-ELECTRON,1),'[M+NH4]+':(N+4*H-ELECTRON,1), + '[M+Cl]-':(CL+ELECTRON,-1),'[M+FA-H]-':(CARBON+H+2*O+ELECTRON,-1)} +ELEMENTS={'C','H','N','O','P','S','F','Cl','Br','I','B','Si'} + + +def utc():return datetime.now(timezone.utc).isoformat() + + +class Client: + def __init__(self): + self.root=OUT/'pubchem';self.root.mkdir(parents=True,exist_ok=True) + self.lock=(self.root/'http.lock').open('a+') + fcntl.flock(self.lock,fcntl.LOCK_EX|fcntl.LOCK_NB) + self.next=0.;self.closed=False + + def close(self): + if not self.closed:self.lock.close();self.closed=True + + def request(self, suffix, data=None, allow_empty=False): + key=digest({'url':BASE+suffix,'body':data}) + path=self.root/'responses'/key[:2]/(key+'.json') + if path.exists(): + envelope=json.loads(path.read_text()) + if digest(envelope['response'])!=envelope['response_sha256']:raise ValueError('Raw response corruption') + return envelope['response'],{'path':str(path),'sha256':sha(path),'cached':True,'queried_at':envelope['queried_at']} + for attempt in range(6): + disk_guard();time.sleep(max(0,self.next-time.monotonic())) + self.next=time.monotonic()+1/C['pubchem_requests_per_second_global'] + body=urlencode(data).encode() if data else None + req=Request(BASE+suffix,data=body,headers={'User-Agent':'SpecPartition-MS academic training-candidate preparation', + 'Content-Type':'application/x-www-form-urlencoded'}) + started=utc();headers={};code=200 + try: + with urlopen(req,timeout=90) as response: + headers=dict(response.headers);result=json.load(response) + except HTTPError as e: + code=e.code + if e.code==404 and allow_empty: + raw=e.read() + fault=json.loads(raw) + if fault.get('Fault',{}).get('Code')!='PUGREST.NotFound':raise + result=fault + elif e.code in (429,500,502,503,504) and attempt<5: + time.sleep(min(60,2**(attempt+1)));continue + else:raise + except (URLError,TimeoutError,ConnectionError,IncompleteRead,RemoteDisconnected,json.JSONDecodeError) as e: + if attempt==5:raise + time.sleep(min(60,2**(attempt+1)));continue + load=str(next((v for k,v in headers.items() if k.lower()=='x-throttling-control'),'')) + delay=60 if 'Black' in load else 10 if 'Red' in load else 2 if 'Yellow' in load else 0 + self.next=max(self.next,time.monotonic()+delay) + envelope={'url':BASE+suffix,'request_body':data,'queried_at':started,'completed_at':utc(), + 'http_status':code,'headers':{k:v for k,v in headers.items() if k.lower() in ('date','last-modified','x-throttling-control')}, + 'response':result,'response_sha256':digest(result)} + save(path,envelope) + return result,{'path':str(path),'sha256':sha(path),'cached':False,'queried_at':started} + raise RuntimeError('HTTP retry exhaustion') + + def formula(self, formula): + if not formula or any(ch not in 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' for ch in formula): + raise ValueError('Unsafe formula string') + dest=self.root/'formula_pools'/(formula+'.json.gz') + if dest.exists(): + with gzip.open(dest,'rt') as f:cached=json.load(f) + if cached['formula']!=formula or digest(cached['records'])!=cached['records_sha256']: + raise ValueError('Formula pool integrity failure') + return cached,dest + result,prov=self.request('compound/fastformula/'+quote(formula,safe='')+'/cids/JSON',allow_empty=True) + ids=[] if result.get('Fault',{}).get('Code')=='PUGREST.NotFound' else result['IdentifierList']['CID'] + if any(type(x) is not int or x<=0 for x in ids):raise ValueError('Invalid CID') + raw_count=len(ids);ids=list(dict.fromkeys(ids));rows=[];requests=[prov] + batch_size=getattr(self,'property_batch_size',C['pubchem_cid_property_batch']) + for a in range(0,len(ids),batch_size): + batch=ids[a:a+batch_size] + props,p=self.request('compound/cid/property/MolecularFormula,IsomericSMILES,InChIKey,MonoisotopicMass,Charge/JSON', + {'cid':','.join(map(str,batch))}) + values=props['PropertyTable']['Properties'] + if len(values)!=len(batch) or {x['CID'] for x in values}!=set(batch): + raise ValueError('Incomplete or duplicate property response; never declare complete') + rows.extend(values);requests.append(p) + out={'formula':formula,'status':'completed','records':rows,'records_sha256':digest(rows), + 'cid_occurrences':raw_count,'unique_cids':len(ids),'duplicate_cids_removed':raw_count-len(ids), + 'database_version':'live PubChem PUG REST; no immutable release id supplied', + 'requests':requests,'completed_at':utc(),'empty_reason':'PUGREST.NotFound' if not ids else None} + dest.parent.mkdir(parents=True,exist_ok=True);tmp=dest.with_suffix('.partial') + with gzip.open(tmp,'wt',compresslevel=3) as f:json.dump(out,f,separators=(',',':')) + tmp.replace(dest);return out,dest + + +def structure_record(row,formula): + s=row.get('SMILES') or row.get('IsomericSMILES') or row.get('CanonicalSMILES') + if not s:return None,'missing_smiles' + m=Chem.MolFromSmiles(s) + if m is None:return None,'invalid_smiles' + if len(Chem.GetMolFrags(m))!=1:return None,'multifragment' + if row.get('Charge') is None:return None,'missing_pubchem_charge' + if row['Charge']!=0 or Chem.GetFormalCharge(m)!=0:return None,'nonneutral' + if any(a.GetIsotope() for a in m.GetAtoms()):return None,'isotope' + if any(a.GetSymbol() not in ELEMENTS for a in m.GetAtoms()):return None,'unsupported_element' + f=rdMolDescriptors.CalcMolFormula(m) + if f!=formula or row.get('MolecularFormula')!=formula:return None,'formula_mismatch' + key=Chem.MolToInchiKey(m) + if not key:return None,'identity_failure' + return {'CID':row['CID'],'smiles':s,'canonical_smiles':Chem.MolToSmiles(m,canonical=True), + 'inchikey':key,'connectivity':key.split('-')[0],'formula':formula, + 'neutral_exact_mass':Descriptors.ExactMolWt(m)},None + + +def filter_record(row,formula,q): + record,reason=structure_record(row,formula) + if reason:return None,reason + shift,z=ADDUCTS[q['adduct']] + mz=(record['neutral_exact_mass']+shift)/abs(z) + ppm=(mz-q['precursor_mz'])/q['precursor_mz']*1e6 + if abs(ppm)>C['strict_ppm']:return None,'outside_10ppm' + return {**record,'ppm':ppm},None + + +def query_pool(client,q,key,formulas,base): + dest=Path(base)/key/'candidate_pool.json.gz' + if dest.exists(): + with gzip.open(dest,'rt') as f:r=json.load(f) + if r['query_hash']!=key or r['formula_candidates']!=formulas:raise ValueError('Existing candidate binding mismatch') + if r.get('candidate_content_sha256') is not None and digest(r['candidates'])!=r['candidate_content_sha256']: + raise ValueError('Candidate content integrity failure') + if digest(sorted(x['connectivity'] for x in r['candidates']))!=r['candidate_identity_sha256']: + raise ValueError('Candidate identity integrity failure') + return r + counts=Counter();byformula={};retained={};raw_refs=[] + for formula in formulas: + pool,path=client.formula(formula);fc=Counter(raw=len(pool['records']));raw_refs.append({'formula':formula,'path':str(path),'sha256':sha(path)}) + for r in pool['records']: + x,reason=filter_record(r,formula,q) + if reason:fc[reason]+=1;continue + fc['after_10ppm']+=1;k=x['connectivity'] + if k in retained:retained[k]['aliases'].append(x) + else:retained[k]={**x,'aliases':[x]};fc['connectivity']+=1 + byformula[formula]=dict(fc);counts.update(fc) + result={'query_hash':key,'formula_candidates':formulas,'counts':dict(counts),'per_formula':byformula, + 'candidates':[retained[k] for k in sorted(retained)],'raw_pool_refs':raw_refs, + 'candidate_identity_sha256':digest(sorted(retained)), + 'candidate_content_sha256':digest([retained[k] for k in sorted(retained)]), 'negative_safety_complete':False, + 'reference_injected':False,'training_ready':False,'completed_at':utc()} + dest.parent.mkdir(parents=True,exist_ok=True);tmp=dest.with_suffix('.partial') + with gzip.open(tmp,'wt',compresslevel=3) as f:json.dump(result,f,separators=(',',':')) + tmp.replace(dest);return result diff --git a/code/snapshot/workspace/rebuild/training_r04/queue_common.py b/code/snapshot/workspace/rebuild/training_r04/queue_common.py new file mode 100644 index 0000000000000000000000000000000000000000..df352573cc425d752fc13ce1b7463c4731112dfd --- /dev/null +++ b/code/snapshot/workspace/rebuild/training_r04/queue_common.py @@ -0,0 +1,70 @@ +"""Preparation queues. Eligibility is independent of spectrum-derived proposals.""" +from collections import Counter +import fcntl +import json +from pathlib import Path +import time +from common import C, OUT, LABELS, bind, connect, digest, save + + +def queue_db(): + db=connect() + db.executescript(''' + CREATE TABLE IF NOT EXISTS eligibility(identity TEXT PRIMARY KEY,status TEXT,proof TEXT); + CREATE TABLE IF NOT EXISTS formula_attempts(query_hash TEXT,attempt INTEGER,status TEXT, + result_path TEXT,error TEXT,updated REAL,PRIMARY KEY(query_hash,attempt)); + CREATE TABLE IF NOT EXISTS candidate_jobs(query_hash TEXT PRIMARY KEY,status TEXT, + attempts INTEGER DEFAULT 0,result_path TEXT,error TEXT,updated REAL); + CREATE INDEX IF NOT EXISTS official_target ON official_pools(target); + ''') + return db + + +def lock_job(name): + f=(OUT/(name+'.lock')).open('a+') + fcntl.flock(f,fcntl.LOCK_EX|fcntl.LOCK_NB) + return f + + +def refresh_eligibility(db): + registry=json.loads((LABELS/'heldout_registry.json').read_text()) + policy=registry['policy_sha256'] + if registry.get('separation_method') == 'inchikey14_exact': + from key14_assets import load_label_eligibility + return load_label_eligibility(db, LABELS, registry) + known={x[0] for x in db.execute("SELECT identity FROM eligibility WHERE status IN ('safe','near_heldout')")} + added=Counter() + for p in (LABELS/'mces_results').glob('*.json'): + if p.stem in known:continue + r=json.loads(p.read_text()) + if r.get('status') not in ('safe','near_heldout'):continue + if r.get('policy_sha256')!=policy:raise ValueError('MCES policy drift') + variants=sorted({json.loads(x[0])['structure']['canonical_smiles'] for x in + db.execute('SELECT body FROM records WHERE identity=?',(p.stem,))}) + if not variants:raise ValueError('MCES identity not in staging') + if r.get('variant_sha256')!=digest(variants):raise ValueError('MCES graph variants do not match labels') + db.execute('INSERT OR REPLACE INTO eligibility VALUES (?,?,?)', + (p.stem,r['status'],json.dumps({'path':str(p),'policy_sha256':policy,'variant_sha256':r['variant_sha256']}))) + added[r['status']]+=1 + db.commit() + return dict(added) + + +def eligible_query(db,key): + return db.execute("""SELECT 1 FROM records r JOIN eligibility e ON r.identity=e.identity + WHERE r.query_hash=? AND e.status='safe' LIMIT 1""",(key,)).fetchone() is not None + + +def progress(db,stage,**extra): + result={'stage':stage,'updated_unix':time.time(),'training_started':False, + 'eligibility':dict(db.execute('SELECT status,COUNT(*) FROM eligibility GROUP BY status')), + 'formula_states':dict(db.execute('SELECT state,COUNT(*) FROM queries GROUP BY state')), + 'candidate_states':dict(db.execute('SELECT status,COUNT(*) FROM candidate_jobs GROUP BY status')), + 'label_release':str(LABELS),**extra} + save(OUT/(stage+'_status.json'),result) + print(json.dumps(result),flush=True) + + +def label_pipeline_blocked(): + p=LABELS/'pipeline_status.json' + return p.exists() and json.loads(p.read_text()).get('status')=='blocked' diff --git a/code/snapshot/workspace/rebuild/training_r04/readiness.py b/code/snapshot/workspace/rebuild/training_r04/readiness.py new file mode 100644 index 0000000000000000000000000000000000000000..ebb1dc34418cf9e841b25cd9a23a976e74b10265 --- /dev/null +++ b/code/snapshot/workspace/rebuild/training_r04/readiness.py @@ -0,0 +1,46 @@ +"""Read-only decision inputs; no launch path before COMPLETE acceptance. + +Writes a machine-readable decision, never interprets a pilot or partial success +as permission to train. A future launcher must independently verify these files. +""" +import json +from pathlib import Path +import time +from common import C,ROOT,OUT,LABELS,ACTIVE_POLICY,connect,save,sha,training_gate,label_release_complete + + +def load(path): + return json.loads(path.read_text()) if path.exists() else {} + + +def main(): + label=load(LABELS/'final_summary.json') + negatives=load(OUT/'negative_safety_acceptance.json') + features=load(OUT/'feature_acceptance.json') + formulas=load(OUT/'sirius_queue_status.json') + candidates=load(OUT/'pubchem_queue_status.json') + model=load(OUT/'real_batch_acceptance.json') + requirements={ + 'final_label_release':label_release_complete(label), + 'all_eligible_blind_formula_jobs':formulas.get('complete') is True, + 'all_eligible_pubchem_jobs':candidates.get('complete') is True, + 'all_negative_safety_and_features':training_gate(label,negatives,features), + 'real_batch_acceptance':model.get('passed') is True and model.get('feature_sha256')== + (sha(OUT/'feature_acceptance.json') if (OUT/'feature_acceptance.json').exists() else 'MISSING')} + report={'policy':'all_candidates_and_safety_before_training_no_partial_baseline', + 'requirements':requirements,'ready':all(requirements.values()),'training_started':False, + 'updated_unix':time.time(),'config_sha256':sha(Path(__file__).with_name('config.json')), + 'pending_steps':[k for k,v in requirements.items() if not v], + 'active_data_policy':ACTIVE_POLICY, + 'label_audit_snapshot':load(LABELS/('key14_acceptance.json' if ACTIVE_POLICY else 'mces_status.json')), + 'indexed_staging_not_final':load(OUT/'index_summary.json'), + 'formula_queue_snapshot':formulas,'candidate_queue_snapshot':candidates, + 'scope':{'msg_training_views':['mass','formula'],'evaluation':['MSG_Validation','MSG_Test','CASMI2022'], + 'candidate_caps_at_preparation':None,'reference_injection':False, + 'stereo_same_connectivity_as_negative':False,'sirius_scores_model_features':False}} + save(OUT/'TRAINING_READINESS.json',report) + save(ROOT/'reports/training_r04_readiness.json',report) + print(json.dumps(report,ensure_ascii=False),flush=True) + + +if __name__=='__main__':main()